full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/clinta_45246140f0ff7a577470_raw_c9b2cf3fdc5524ac0f58143389d8c9972c5d6080_ConvertFrom-RobocopyLog.ps1
clinta_45246140f0ff7a577470_raw_c9b2cf3fdc5524ac0f58143389d8c9972c5d6080_ConvertFrom-RobocopyLog.ps1
<# .Synopsis Parse robocopy log information .DESCRIPTION Parses robocopy logs into a collection of objects summarizing each robocopy operation .EXAMPLE onvertFrom-RobocopyLog C:\robocopy.log .EXAMPLE onvertFrom-RobocopyLog C:\robocopy.log | Export-CSV C:\RobocopySummary.csv #> function ConvertFrom-RobocopyLog { Param ( # Robocopy logfile to parse [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $LogFile ) Process { Get-Content $LogFile | foreach { if ($_ -like " ROBOCOPY :: Robust File Copy for Windows ") { $result = New-Object System.Object } if ($_ -like " Started : *") { $started = Get-Date $_.Replace(" Started : ","") $result | Add-Member -MemberType NoteProperty -Name Started -Value $started } if ($_ -like " Source = *") { $result | Add-Member -MemberType NoteProperty -Name Source -Value $_.Replace(" Source = ","") } if ($_ -like " Dest = *") { $result | Add-Member -MemberType NoteProperty -Name Dest -Value $_.Replace(" Dest = ","") } if ($_ -like " Files : *") { $result | Add-Member -MemberType NoteProperty -Name Files -Value $_.Replace(" Files : ","") } if ($_ -like " Options : *") { $result | Add-Member -MemberType NoteProperty -Name Options -Value $_.Replace(" Options : ","") } if ($_ -like " Dirs : *" -or $_ -like " Files : *" -or $_ -like " Bytes : *") { $resultIem = $($_[0..8] -join '').Trim() $result | Add-Member -MemberType NoteProperty -Name "Total $resultIem" -Value $($_[10..19] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") $result | Add-Member -MemberType NoteProperty -Name "Copied $resultIem" -Value $($_[20..29] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") $result | Add-Member -MemberType NoteProperty -Name "Skipped $resultIem" -Value $($_[30..39] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") $result | Add-Member -MemberType NoteProperty -Name "Mismatched $resultIem" -Value $($_[40..49] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") $result | Add-Member -MemberType NoteProperty -Name "FAILED $resultIem" -Value $($_[50..59] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") $result | Add-Member -MemberType NoteProperty -Name "Extra $resultIem" -Value $($_[60..69] -join '').Trim().Replace(" k","KB").Replace(" m","MB").Replace(" g","GB") } if ($_ -like " Ended : *") { $ended = Get-Date $_.Replace(" Ended : ","") $result | Add-Member -MemberType NoteProperty -Name Ended -Value $ended Write-Output $result } } } }
PowerShellCorpus/GithubGist/infralabo_7320636_raw_51b781695c4847706fdd21cc581fe6947ed62367_timer.ps1
infralabo_7320636_raw_51b781695c4847706fdd21cc581fe6947ed62367_timer.ps1
Function Get-CountDownTime([int]$seconds){ for ($time=$seconds;$time -ge 0;$time--){ $min = [math]::floor([int]$time/[int]60) $sec = $time % 60 if ($sec -lt 10){ $sec = "0$sec" } [string]"$min`:$sec" Start-Sleep -Seconds 1 Clear-Host } }# Get-CountDownTime 関数の終わり # *** スクリプトのエントリ ポイント *** get-CountDownTime 1800 [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [System.Windows.Forms.MessageBox]::Show("時間です!休憩してください。");
PowerShellCorpus/GithubGist/JonasGroeger_9077885_raw_581a416ad4d03c3cef35f3ac5869809733619362_Activate.ps1
JonasGroeger_9077885_raw_581a416ad4d03c3cef35f3ac5869809733619362_Activate.ps1
$workon_home_env__var_name = "WORKON_HOME" $venv_file_name = ".venv" $workon_home = $null # Test if env-var exists if(!(Test-Path Env:\$workon_home_env__var_name)) { $Host.UI.WriteErrorLine("You must set the environment variable '" + $workon_home_env__var_name + "'. It must point to your virtual environment folder.") Exit } # Test if env-var points to a existing folder if(!(Test-Path (Get-ChildItem Env:\$workon_home_env__var_name).Value)) { $Host.UI.WriteErrorLine("The the environment variable '" + $workon_home_env__var_name + "' does not point to an existing folder.") Exit } # Workon home is existing $workon_home = (Get-ChildItem Env:\$workon_home_env__var_name).Value # Test if venv file exists if(!(Test-Path $venv_file_name)) { $Host.UI.WriteErrorLine("You must have a file named '.venv' in this folder. It must contain the name of your virtual environment.") Exit } # TODO: Find $possible_venv_name in $folder_name = Split-Path (Get-Location) -leaf # venv file is existing, get content $possible_venv_name = (Get-Content $venv_file_name) $possible_venv_directory = (Join-Path $workon_home $possible_venv_name) if( # Empty file ($possible_venv_name -eq $null) -or # Spaces only file ($possible_venv_name.Trim() -eq "") -or # File pointing to non-existing folder !(Test-Path $possible_venv_directory) ) { $Host.UI.WriteErrorLine("The venv name inside '" + $venv_file_name + "' did not point to an existing virtual environment in '" + $workon_home + "'.") Exit } # Check if the folder is a virtual environment by looking for the Activate.ps1 file $activate_ps1 = (Join-Path $possible_venv_directory "Scripts\Activate.ps1") if(!(Test-Path $activate_ps1)) { $Host.UI.WriteErrorLine("Could not find a virtual environment inside '" + $possible_venv_directory + "'.") } else { # Activate the virtual environment . $activate_ps1 Write-Host("Activated virtual environment '" + $possible_venv_name + "'. Currently installed packages:") Write-Host("") pip freeze Write-Host("") Write-Host("Enter 'deactivate' to deactivate the active virtual environment.") }
PowerShellCorpus/GithubGist/davehope_6524592_raw_877769ac8724cd6de74cf2d3128bb1a13edc4ae0_Exchange%20-%20Mailbox%20Quotas%20Report.ps1
davehope_6524592_raw_877769ac8724cd6de74cf2d3128bb1a13edc4ae0_Exchange%20-%20Mailbox%20Quotas%20Report.ps1
# # Mailbox Size Reports. # ~~~~~~~~~~~~~~~~~~~~~ # # This script determines the effective mailbox quota and produces a # report for helpdesk staff. # # Changelog # ~~~~~~~~~ # 2012.04.25 Dave Hope Initial version. # 2013.09.11 Dave Hope Updated with new stylesheet and SendMail function. # # ====================================================================== $cfgWhiteSpace = 50; # MB that should be free $cfgMailFrom = "noreply@nwtraders.msft" $cfgMailServer = "LONDON" $cfgMailTo = @("Dave.hope@nwtraders.msft") # # Generate mailbox report. function getMailboxTable { Param( [string]$server = $(throw "A Server must be specified"), [int]$whiteSpace = $(throw "The amount of white space to be reported on must be spefified in MB") ) $output = "<html><head> <style type=""text/css""> body{font-family:'Bitstream Vera Sans','DejaVu Sans',Tahoma,sans-serif;font-size:13px;margin:0;background-color:#fff} table{border-color:#E8E8E8;border:1px solid #e8e8e8;width:100%;text-align:left;} th{color:#494949;font-size:1.0em;padding:8px;background-color:#F1F1F1;border-top:5px solid #E8E8E8} td{border-bottom:1px solid #E8E8E8} tbody tr td,tfoot tr td,tfoot tr th{padding:9px 8px 8px;font-size:0.9em;background:#fff} .bad td{background-color:#ffbbb6} .good td{background-color:#eee} .ok td{background-color:orange} </style> </head> <body> <h1>Mailbox Size Report</h1> <p>Report showing mailboxes with less than $($whiteSpace) MB of available space, generated at $((Get-Date).ToString())</p> <table cellpadding=""0"" cellspacing=""0""> <thead> <tr><th>Mailbox</th><th>Job Title</th><th>Space Left (MB)</th><th>Quota Status</th><th>Mailbox Size (MB)</th><th>Quota Warning (MB)</th></tr> </thead> <tbody>"; $outputGood = ""; $outputOk = ""; Write-Progress -Activity "Producing mailbox report" -Status "Getting list of mailboxes" -PercentComplete 0 $mboxs = get-mailbox -Server $server | select-object DisplayName, IssueWarningQuota, ProhibitSendQuota, ProhibitSendReceieveQuota, Database, DistinguishedName Write-Progress -Activity "Producing mailbox report" -Status "Getting list of mailboxes" -PercentComplete 0 $statTotal = $mboxs.count $statComplete = 0 foreach( $mbox in $mboxs ) { Write-Progress -Activity "Producing mailbox report" -Status "Getting mailbox infromation" -CurrentOperation "Total: $statTotal , Complete: $statComplete" -PercentComplete ($statComplete/$statTotal * 100) $mboxInfo = get-mailboxStatistics $mbox.DisplayName -WarningAction SilentlyContinue | Select-Object DisplayName,ServerName,StorageLimitStatus,TotalItemSize,LastLogonTime # Mailbox hasn't been logged into, lets bail. if ($mboxInfo.LastLogonTime -eq $null ) { continue; } # # If quota isn't set on the mailbox, lets examine the mailbox database. if ( $mbox.IssueWarningQuota -eq "unlimited" ) { $effectiveQuota = $(Get-MailboxDatabase $mbox.Database).IssueWarningQuota.Value.ToMB() } else { $effectiveQuota = $mbox.IssueWarningQuota.Value.ToMB() } # Calculate space remaining $mboxSize = $mboxInfo.TotalItemSize.Value.ToMB(); $spaceLeft = ($effectiveQuota - $mboxSize) # Job title $szPath = "LDAP://$($mbox.DistinguishedName)" $objADSI = [ADSI]$szPath $title = $objADSI.title.Value if( ($spaceLeft -gt $cfgWhiteSpace) -and ($mboxInfo.StorageLimitStatus -eq "BelowLimit")) { $outputGood += "<tr class=""good""><td>$($mboxInfo.DisplayName)</td><td>$($title)</td><td>$($spaceLeft)</td><td>$($mboxInfo.StorageLimitStatus)</td><td>$($mboxSize)</td><td>$($effectiveQuota)</td></tr>"; } elseif ( $mboxInfo.StorageLimitStatus -eq "MailboxDisabled" ) { $outputGood += "<tr class=""good""><td>$($mboxInfo.DisplayName)</td><td>$($title)</td><td>$($spaceLeft)</td><td>$($mboxInfo.StorageLimitStatus)</td><td>$($mboxSize)</td><td>$($effectiveQuota)</td></tr>"; } elseif ( $mboxInfo.StorageLimitStatus -eq "NoChecking" ) { $outputOk += "<tr class=""ok""><td>$($mboxInfo.DisplayName)</td><td>$($title)</td><td>$($spaceLeft)</td><td>$($mboxInfo.StorageLimitStatus)</td><td>$($mboxSize)</td><td>$($effectiveQuota)</td></tr>"; } else { $output += "<tr class=""bad""><td>$($mboxInfo.DisplayName)</td><td>$($title)</td><td>$($spaceLeft)</td><td>$($mboxInfo.StorageLimitStatus)</td><td>$($mboxSize)</td><td>$($effectiveQuota)</td></tr>"; } $statComplete++; } $output += $OutputOk; $output += $OutputGood; $output += "</tbody></table></body></html>"; return $output; } # # Send E-mail. # ====================================================================== function SendMail { Param( [string[]]$to = $(throw "Recipients required"), [string]$from = $(throw "Sender required"), [string]$server = $(throw "Server required"), [string]$subject = $(throw "Subject required."), [string]$body = $(throw "Message body required.") ) $mailMsg = new-object Net.Mail.MailMessage; $mailMsg.From = new-object Net.Mail.MailAddress( $from ) foreach ($recipient in $to) { $mailMsg.To.Add( $recipient ) } $mailmsg.Subject = $subject $mailMsg.Body = $body $mailMsg.IsBodyHtml = $true; $smtp = new-object Net.Mail.SmtpClient( $server ) $smtp.Send( $mailMsg ); } $output = getMailboxTable -Server $cfgMailServer -whiteSpace $cfgWhiteSpace SendMail -to $cfgMailTo -from "noreply@mccarthyandstone.co.uk" -server "mccshomml701.ad.mccarthyandstone.co.uk" -subject "Mailbox Report" -body $output
PowerShellCorpus/GithubGist/chrwei_3724873_raw_0ac7a6c13b26ae2a4fe3eb5f3a1269a106dec365_fix-align.ps1
chrwei_3724873_raw_0ac7a6c13b26ae2a4fe3eb5f3a1269a106dec365_fix-align.ps1
if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "VMware.VimAutomation.Core" } Connect-VIServer 'vcenter' $vmlist = @() $vmlist += "vncproxy" $vmlist += "vma" $valignervm = "valigner" $valignerip = "10.212.0.17" $method = "align" #check_alignemnt, align, space_reclaim $targetalign=2048.0 #in 512B blocks, 2048 is 1MB $hashType = @{} $hashType."align" = 1 $hashType."check_alignment" = 4 $hashType."space_reclaim" = 5 function uberaligner_rest { param ($method,$type,$send,$valignerip,$d=$false) if($d) { Write-Host "J1" } # since using system.net.webclient, this will stop malformed header errors $netAssembly = [Reflection.Assembly]::GetAssembly([System.Net.Configuration.SettingsSection]) IF($netAssembly) { $bindingFlags = [Reflection.BindingFlags] "Static,GetProperty,NonPublic" $settingsType = $netAssembly.GetType("System.Net.Configuration.SettingsSectionInternal") $instance = $settingsType.InvokeMember("Section", $bindingFlags, $null, $null, @()) if($instance) { $bindingFlags = "NonPublic","Instance" $useUnsafeHeaderParsingField = $settingsType.GetField("useUnsafeHeaderParsing", $bindingFlags) if($useUnsafeHeaderParsingField) { $useUnsafeHeaderParsingField.SetValue($instance, $true) | out-null } } } $URL="http://$valignerip/uberalign"+$method if($d) { Write-Host "J2 sending $URL" } $webclient = New-Object System.Net.WebClient $webclient.Headers.Add("Content-Type","application/json") if($d) { Write-Host "J3" } if($type -eq "POST") { if($d) { Write-Host "J4" } if(!$webclient.UploadString([string]$URL,"POST",$send)) { if($d) { Write-Host "J4f" } return $false } else { if($d) { Write-Host "J4t" } return $webclient } } else{ if($d) { Write-Host "J5" } return $webclient.DownloadString([string]$URL) } } function hashToJSON { param ($hash) [string]("{"+(( $hash.keys | %{ if($hash.$_.gettype().toString() -eq "System.String") { '"'+$_+'":"'+$hash.$_+'"' } elseif($hash.$_.gettype().toString() -eq "System.Double") { if($hash.$_ -eq [math]::round($hash.$_,0)) { '"'+$_+'":'+$hash.$_+".0" } else { '"'+$_+'":'+$hash.$_ } } else { '"'+$_+'":'+$hash.$_ } } ) -join ",")+"}") } function serverGuid { get-wmiobject win32_computersystemproduct | %{ $_.uuid } } function serverHostname { get-wmiobject win32_computersystemproduct | %{ $_.__SERVER } } function formatOut { param($tmpText,$state) if($tmpText.length -ge 65) { $tmpText = $tmpText.substring(0,65) } if($state -eq $true) { $state = "OK" } else { $state = "FAILED" } $len = 70 - $tmpText.length "{0,0} {1,$len}" -f $tmpText,"[ $state ]" } function initOut { param($tmpText) ($tmpText | %{ $_ -split "(\[)|(\])" } | %{ if($_ -eq " OK ") { write-host -f "green" -nonewline $_ } elseif ($_ -eq " FAILED "){ write-host -f "red" -nonewline $_} else { write-host -nonewline $_ }}) -join "" } function docleanup { param($vm) initOut(formatOut("Start Cleanup") $true) initOut(formatOut(" Removing hard disk from aligner") $true) get-vm $vm | Get-HardDisk | where {$_.Persistence -eq "Persistent"} | %{$_.Filename} | %{ $df=$_;get-vm $valignervm | get-harddisk | where {$_.filename -eq $df } | remove-harddisk -confirm:$false} | out-null # initOut(formatOut(" Remove snap on $vm") $true) # Get-Snapshot -VM $vm | Remove-Snapshot -Confirm:$false | out-null initOut(formatOut(" Powering on $vm") $true) Get-VM $vm | Start-VM -Confirm:$false | out-null } # set up timer to keep the Lock on the aligner $timer = new-object timers.timer $timer.Interval = 15000 #15 seconds [string]$SessLockSend = hashToJSON @{"guid"=$serverGuid;"ip"=serverHostname;"timestamp"=0;"locked"="false";"secondsleft"=0} $sessionlockaction = { $tmpResp = uberaligner_rest -type "POST" -method "/api/session/lock" -send $SessLockSend -valignerip $valignerip if(!$tmpResp) { initOut(formatOut("submit lock request") $false) $timer.stop() Unregister-Event sesslocktimer } # if($tmpResp.responseheaders.get("/session/LockStatus") -eq 400) { # Write-Host -ForegroundColor Blue "JOB::Lock granted" # } else { # Write-Host -ForegroundColor Blue "JOB::Possible problem with lock" # } } Register-ObjectEvent -InputObject $timer -EventName elapsed –SourceIdentifier sesslocktimer -Action $sessionlockaction $assembly = [Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions") $transmogrifer = New-Object System.Web.Script.Serialization.JavaScriptSerializer $serverGuid = serverGuid # Check to see if valigner is responsive $tmpHttp = uberaligner_rest -type "GET" -method "/api/job/current" -valignerip $valignerip if($tmpHttp -eq "null") { initOut(formatOut("Checked to see if aligner is responsive") $false) exit } initOut(formatOut("Checked to see if aligner is responsive") $true) # Check the valigner and see if it is locked, and if not start job to keep it locked initOut(formatOut("Check to see if aligner $valignervm is locked") $true) $tmpHttp = uberaligner_rest -type "GET" -method "/api/session" -valignerip $valignerip [psobject]$tmpState = $transmogrifer.DeserializeObject($tmpHttp) if($tmpState.locked -eq "true" -and $tmpState.guid -ne (serverGuid)) { initOut(formatOut(" Aligner is locked by "+$tmpState.ip+" with "+$tmpState.secondsleft+" seconds remaining on lock") $false) exit } elseif ($tmpState.locked -match "true|false") { if($tmpState.guid -eq ($serverGuid)) { initOut(formatOut(" I own the current lock, issuing new lock request") $true) } $timer.start() #start lock timer } #setup reconfig spec $vmview = Get-View (Get-VM $valignervm).ID $Cntrlkey = get-vm $valignervm | get-view | %{$_.config.hardware.device} | where{$_.deviceInfo.label -eq "SCSI controller 0"} | %{ $_.key } $spec = New-Object VMware.Vim.VirtualMachineConfigSpec $spec.deviceChange = @() $spec.deviceChange += New-Object VMware.Vim.VirtualDeviceConfigSpec $spec.deviceChange[0].operation = "add" :loop1 foreach($targetvm in $vmlist) { try { initOut(formatOut("Checking for specified VM $targetvm existence") $true) get-vm -name $targetvm -erroraction stop | out-null initOut(formatOut(" VM $targetvm found") $true) } catch { initOut(formatOut(" VM $targetvm notfound") $false);continue loop1 } # Check the valigner and see if it is in ready state (0,9) initOut(formatOut("Checking to see if aligner is busy") $true) $time = 0 #timeout in 60 seconds Write-Host "Waiting: " -NoNewline do { sleep 1 $time = $time + 1 Write-Host $time " " -NoNewline $tmpHttp = uberaligner_rest -type "GET" -method "/api/state" -valignerip $valignerip } until ((@(0,9) -contains $transmogrifer.DeserializeObject($tmpHttp).state) -or ($time -gt 59)) Write-Host "" #clear the -NoNewline above if ($time -gt 59) { #bail initOut(formatOut(" Aligner is not busy") $fasle) initOut(formatOut("Removing background job to lock aligner") $true) $timer.stop() Unregister-Event sesslocktimer exit } initOut(formatOut(" Aligner is not busy") $true) initOut(formatOut("Checking to see if VM $targetvm is powered off") $true) if (get-vm -name $targetvm | where {$_.PowerState -ne "PoweredOff"}) { initOut(formatOut(" VM $targetvm powered off") $false) Get-VM $targetvm | Shutdown-VMGuest -Confirm:$false | out-null initOut(formatOut(" Waiting for power off") $true) do { Start-Sleep -s 1 #update objects and Check the power status $objvm = Get-VM -Name $targetvm $status = $objvm.PowerState }until($status -eq "PoweredOff") } initOut(formatOut(" VM $targetvm powered off") $true) #expand disks Get-VM $targetvm | get-harddisk | %{ Set-HardDisk -CapacityKB ($_.CapacityKB + 1024) -Confirm:$false } # Take a VMware snapshot of VM try { get-vm $targetvm | new-snapshot -name psuberaligner -description "Failback snapshot by PSUberAligner" -erroraction stop -Quiesce:$true -Memory:$false | out-null initOut(formatOut("Took snapshot") $true) } catch { initOut(formatOut("Took snapshot") $false) write-host -f "red" $error[0] docleanup($targetvm) continue loop1 } $hddlist = get-vm $targetvm | get-view | %{ $_.config.hardware.device } | where {$_.deviceInfo.label -like "Hard disk*" -and $_.Backing.DiskMode -eq "persistent" } foreach($device in $hddlist) { initOut(formatOut("Starting hard disk "+$device.Backing.FileName+" to aligner") $true) $spec.deviceChange[0].device = $device $spec.deviceChange[0].device.key = 2001 $spec.deviceChange[0].device.UnitNumber = 1 $spec.deviceChange[0].device.controllerKey = $CntrlKey $taskMoRef = $vmview.ReconfigVM_Task($spec) do { $task = Get-View $taskMoRef if($task.info.state -eq "error") { initOut(formatOut(" Adding hard disk "+$device.Backing.FileName+" to aligner") $false) docleanup($targetvm) continue loop1 } } until ($task.info.state -eq "success" -or $task.info.state -eq "error") # Send job to aligner $jobGuid = [System.Guid]::NewGuid().toString() [string]$tmpSend = hashToJSON @{"type"=$hashType."$method";"offset"=$targetalign;"id"=$jobGuid;"name"=$targetvm+' / '+$device.DeviceInfo.Label ;"guid"=$serverGuid} #$tmpSend if($tmpHttp = uberaligner_rest -type "POST" -method "/api/job/new" -send $tmpSend -valignerip $valignerip) { initOut(formatOut("Sending job to aligner") $true) } else { initOut(formatOut("Sending job to aligner") $false) docleanup($targetvm) continue loop1 } initOut(formatOut("Waiting for job to begin") $true) #timeout in 60 seconds $time = 0 Write-Host "Waiting: " -NoNewline do { sleep 5 $time = $time + 5 Write-Host $time " " -NoNewline $tmpHttp = uberaligner_rest -type "GET" -method "/api/job/current" -valignerip $valignerip } until (($transmogrifer.DeserializeObject($tmpHttp).id -eq $jobGuid) -or ($time -gt 59)) Write-Host "" #clear the -NoNewline above if ($time -gt 59) { #bail initOut(formatOut(" job responded") $false) docleanup($targetvm) initOut(formatOut("Removing background job to lock aligner") $true) $timer.stop() Unregister-Event sesslocktimer exit } initOut(formatOut(" Job has started, waiting for job to finish") $true) do { if($method -eq "align") { $tmpHttp = uberaligner_rest -type "GET" -method "/api/job/current" -valignerip $valignerip $jobDetails = $transmogrifer.DeserializeObject($tmpHttp) [array]$tmpDesc = ($jobDetails.currentstep -split "(\d{1,3})\%")[0] -split "\s{1,4}","" -replace ":","" if($tmpPerc = ($jobDetails.currentstep -split "(\d{1,3})\%")[1]) { $tmpStatus = ($tmpDesc[1]+" "+[math]::round(([double]($tmpPerc/100)*([double]$jobDetails.diskdetails._totalsectors * 512 / 1GB)),1)+"/"+[math]::round(([double]$jobDetails.diskdetails._totalsectors * 512 / 1GB),1)+" GB") write-progress -activity $tmpDesc[0] -percentcomplete $tmpPerc -status $tmpStatus } } sleep 5 $tmpHttp = uberaligner_rest -type "GET" -method "/api/state" -valignerip $valignerip } until (@(0,9) -contains $transmogrifer.DeserializeObject($tmpHttp).state) if($transmogrifer.DeserializeObject($tmpHttp).state -eq 0) { initOut(formatOut(" Job has finished") $true) } else { initOut(formatOut(" Job has finished") $false) #no need to clean up here since it's the last step } $tmpHttp = uberaligner_rest -type "GET" -method "/api/state" -valignerip $valignerip #$transmogrifer.DeserializeObject($tmpHttp) $tmpHttp = uberaligner_rest -type "GET" -method "/api/job/current" -valignerip $valignerip $transmogrifer.DeserializeObject($tmpHttp) #$transmogrifer.DeserializeObject($tmpHttp).diskdetails #$transmogrifer.DeserializeObject($tmpHttp).partitions initOut(formatOut(" Removing hard disk from aligner") $true) get-vm $targetvm | Get-HardDisk | where {$_.Persistence -eq "Persistent"} | %{$_.Filename} | %{ $df=$_;get-vm $valignervm | get-harddisk | where {$_.filename -eq $df } | remove-harddisk -confirm:$false} | out-null } #done with this vm docleanup($targetvm) } initOut(formatOut("Removing background job to lock aligner") $true) $timer.stop() Unregister-Event sesslocktimer
PowerShellCorpus/GithubGist/jstangroome_1945943_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
jstangroome_1945943_raw_ae9898129bc470a4d66f8a0113e892063d84f6a6_clean-merged-branches.ps1
$dontcare = git fetch origin --prune $branches = git branch -a --merged | ?{$_ -match "remotes\/origin"} | ?{$_ -notmatch "\/master"} | %{$_.Replace("remotes/origin/", "").Trim() } if (-not $branches) { echo "No merged branches detected" exit 0 } echo $branches $title = "Delete Merged Branches" $message = "Do you want to delete the already-merged remote branches displayed above??" $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", ` "Delete the remote branches listed." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", ` "Leave the branches alone." $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) $result = $host.ui.PromptForChoice($title, $message, $options, 1) if ($result -eq 1) { exit 0 } $branches | %{ git push origin ":$_" }
PowerShellCorpus/GithubGist/mdnmdn_1493541_raw_dcfd2f87fbec6b5d447bf077a1e1c83a41071f75_uploadfile.ps1
mdnmdn_1493541_raw_dcfd2f87fbec6b5d447bf077a1e1c83a41071f75_uploadfile.ps1
$siteUrl = "http://sharepoint/" $listName = "Site Assets" $fileName = "OfferApp.xap" $filePath = "OfferApp.Web\ClientBin\" + $fileName [system.reflection.assembly]::LoadWithPartialName("Microsoft.Sharepoint") $site = New-Object Microsoft.SharePoint.SPSite($siteUrl) $web = $site.OpenWeb() $list = $web.Lists[$listName] $fileCollection = $list.RootFolder.Files $file = Get-Item $filePath $stream = $file.OpenRead() $uploaded = $fileCollection.Add($file.Name, $stream, $TRUE) "Uploaded " + $file.Name if ($stream) {$stream.Dispose()} #$files = get-childItem -Exclude *.ps1 #foreach ($file in $files) #{ # $stream = $file.OpenRead() # $uploaded = $fileCollection.Add($file.Name, $stream, $TRUE) # "Uploaded " + $file.Name # if ($stream) {$stream.Dispose()} #} if ($web) {$web.Dispose()} if ($site) {$site.Dispose()}
PowerShellCorpus/GithubGist/Blacksly_0490082e5f197aec462f_raw_b8ec30bc8620eeea3207ef47810626b27a2d66f7_gistfile1.ps1
Blacksly_0490082e5f197aec462f_raw_b8ec30bc8620eeea3207ef47810626b27a2d66f7_gistfile1.ps1
127.0.0.1 localhost www.kpi.com
PowerShellCorpus/GithubGist/guitarrapc_9802b36076aee80fa033_raw_82f92a3369365e5bef0b717055d362475cf48e01_MultiPartUpload.ps1
guitarrapc_9802b36076aee80fa033_raw_82f92a3369365e5bef0b717055d362475cf48e01_MultiPartUpload.ps1
# (Get-Item c:\Tools\FileName.zip).Length # Size -> 118073855 # Upload with default -> 10 concurrent connection Write-S3Object -BucketName bucketname -Key FileName.zip -File C:\Tools\FileName.zip
PowerShellCorpus/GithubGist/jonschoning_3432382_raw_27d9911ea9b48d045ff1994115369acfd069d01e_TextReview.ps1
jonschoning_3432382_raw_27d9911ea9b48d045ff1994115369acfd069d01e_TextReview.ps1
# This script extracts all the string literals from a source code tree # so the strings can be examined in a spell checker. # # Author: John D. Cook # http://www.johndcook.com # If path is not provided as an argument, the script searches the current directory. param($srcRoot=(pwd)) # Make an array of file names in the directory matching source file extensions $sourceExtensions = "\.(cs|vb|aspx|resx|cpp|rc|h|js|xml)$" $files = (dir -recurse $srcRoot | %{$_.FullName}) -match $sourceExtensions # Process each file foreach ($file in $files) { $allLines = (get-content $file) $linesToKeep = @() $lineNumber = 0 # Process each line in a file foreach ($line in $allLines) { $lineNumber++ # Exclude C++ header includes if ($line -match "^#include") { continue } # Extract quoted strings # Process each literal on each line $pattern = '"[^"]*"' # a quoted string " $literals = ([regex]::matches($line, $pattern) | %{$_.value}) foreach ($literal in $literals) { $literal = ($literal -replace '\\[a-z]', " ") # get rid of \n etc. $literal = ($literal -replace "&(?=\w)", "") # remove amperands followed immediately by letters, as in menu shortcut notation if ($literal -notmatch "\w") { continue # no word characters in literal } if ($literal -match " ") { # Literals containing no spaces are often code rather than blocks of prose. # We reduced our false positive rate quite a bit when we limited # the script to only report strings containing at least one space. $linesToKeep += "$lineNumber`t $literal" } } } # Print report for files that have literals that haven't been filtered out if ($linesToKeep.Length -gt 0) { $file " " $linesToKeep "___________________________________________" " " } # Parse XML files again, looking for text not contained in quotes but contained inside XML elements if ($file -match "\.(xml|aspx|resx)$") { $lineNumber = 0 $linesToKeep = @() foreach ($line in $allLines) { $lineNumber++ $line = ($line -replace "<[^>]*>", " ") # strip XML tags $line = ($line -replace "&nbsp;", " ") # get rid of space entities if ($line -match "\w") # There's some text left after the above processing { $line = $line.trim() $linesToKeep += "`t$lineNumber $line" } } if ($linesToKeep.Length -gt 0) { $file " " $linesToKeep "___________________________________________" " " } } }
PowerShellCorpus/GithubGist/jeng1111_5606706_raw_f834f855534f6d7ce1184e63aaf3d8bff8c73720_gistfile1.ps1
jeng1111_5606706_raw_f834f855534f6d7ce1184e63aaf3d8bff8c73720_gistfile1.ps1
#thanks to: http://blog.newslacker.net/2012/03/powershell-executing-net-web-request.html # // first argument is mapped to $url #param($url) $url = "https://www.lds.org/general-conference/sessions/2014/04?cid=HPSU040614654&lang=eng" [int]$DownloadCount = 0 #download files to a subfolder in your documents folder $basedir = [environment]::getfolderpath("mydocuments") + "\Conference mp3s" #create folder if it doesn't exist: $check = Test-Path -PathType Container $basedir if($check -eq $false){ New-Item $basedir -type Directory } # // create a request [Net.HttpWebRequest] $req = [Net.WebRequest]::create($url) $req.Method = "GET" $req.Timeout = 60000 [Net.HttpWebResponse] $result = $req.GetResponse() [IO.Stream] $stream = $result.GetResponseStream() [IO.StreamReader] $reader = New-Object IO.StreamReader($stream) #Here we get the text source of the web page: [string] $inputdata = $reader.readToEnd() $stream.flush() $stream.close() $output_file = "$basedir\results.txt" if (test-path $output_file) {remove-item $output_file; write-host $output_file removed.} $regex = '(?!.*0{3}.*)http:[a-z0-9A-Z\.\/-]*\.mp3' $inputdata | select-string -Pattern $regex -AllMatches | % { $_.Matches } | % {$_.Value} | out-file -FilePath $output_file -width 4000 -append #$a gets all the mp3 links from the file $a = get-content $output_file remove-item $output_file #download! for ($i=0; $i -lt $a.count; $i++) { $source = $a[$i] #extract the filename: $b = $source.split('/') $filename = $b[$b.count - 1] $destination = "$basedir\$filename" #Do not download file if it already exists: if (!(test-path -path $destination -pathtype leaf)) { write-host "Downloading $source to $destination" $wc = New-Object System.Net.WebClient #Get file size before downloading $req = [Net.WebRequest]::create($source) $resp = $req.GetResponse() $fileSize = $resp.ContentLength $resp.Close() $req.abort() #if you do not abort the request, it will stall this loop # Limit download file size if you wish. 20000000 is about 19MB if ($filesize -lt 20000000) { $wc.DownloadFile($source, $destination) } else { write-host "DID NOT DOWNLOAD FILE, IT WAS TOO BIG!" } $wc.Dispose() write-host "Download complete: $destination" $DownloadCount += 1 } else { Write-Host "FILE ALREADY EXISTS ($destination). Did not download $source" } } write-host "All done! Downloaded $DownloadCount file(s)." write-host "Files have been saved to $basedir"
PowerShellCorpus/GithubGist/robertchong_3c36357dd8366cae60d5_raw_59643e697d03b2f951854a23b724270b31850f15_LocateExpiredCACerts.ps1
robertchong_3c36357dd8366cae60d5_raw_59643e697d03b2f951854a23b724270b31850f15_LocateExpiredCACerts.ps1
# # LocateExpiredCACerts # Source: http://blogs.technet.com/b/heyscriptingguy/archive/2012/05/17/3386232.aspx # $store=new-object System.Security.Cryptography.X509Certificates.X509Store("\\<COMPUTER_NAME>\CA","LocalMachine") $store.open("ReadOnly") $store.certificates | % { If ($_.NotAfter -lt (Get-Date)) { $_ | Select Issuer, Subject, @{Label="ExpiredOn";Expression={$_.NotAfter}} } }
PowerShellCorpus/GithubGist/Gordon-Beeming_e06d0ab7f121bf0121cd_raw_fae08531ef6d355852380aad072e4bd6c1b77647_upgrade-tfs-2013-process-templates.ps1
Gordon-Beeming_e06d0ab7f121bf0121cd_raw_fae08531ef6d355852380aad072e4bd6c1b77647_upgrade-tfs-2013-process-templates.ps1
# Copyright © Microsoft Corporation. All Rights Reserved. # This code released under the terms of the # Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) # #config $server = "MyTfsServer" $port = 8080 $virtualDirectory = "tfs" $CollectionName = "DefaultCollection" $TeamProjectNames = @("Team Project 1", "Team Project 2", "Team Project 7", "Sample Scrum Project 1") $ProcessTemplateRoot = "C:\templates\Microsoft Visual Studio Scrum 2013.3" $CollectionUrl = "http://$($server)$(if ($port -ne 80) { ":$port" })$(if (![string]::IsNullOrEmpty($virtualDirectory)) { "/$virtualDirectory" })/$($CollectionName)" $API_Version = "12.0" #---------------------------- # don't edit below this line #---------------------------- #get a reference to the witadmin executable path for the current api version $WitAdmin = "${env:ProgramFiles(x86)}\Microsoft Visual Studio $API_Version\Common7\IDE\witadmin.exe" #if there is a file with the name GlobalLists-ForImport.xml import it as Global List info for the current collection if (Test-Path "$ProcessTemplateRoot\GlobalLists-ForImport.xml") { Write-Host "Importing GlobalLists-ForImport.xml" & $WitAdmin importgloballist /collection:$CollectionUrl /f:"$ProcessTemplateRoot\GlobalLists-ForImport.xml" } #get a reference to all work item type definitions $wit_TypeDefinitions = Get-ChildItem "$ProcessTemplateRoot\WorkItem Tracking\TypeDefinitions\*.*" -include "*.xml" #get a reference to all work item link types $witd_LinkTypes = Get-ChildItem "$ProcessTemplateRoot\WorkItem Tracking\LinkTypes\*.*" -include "*.xml" #import each Link Type for the $CollectionName foreach($witd_LinkType in $witd_LinkTypes) { Write-Host "Importing $($witd_LinkType.Name)" & $WitAdmin importlinktype /collection:$CollectionUrl /f:$($witd_LinkType.FullName) } foreach ($TeamProjectName in $TeamProjectNames) { Write-Host "Upgrading $TeamProjectName." #import each Type Definition for the $TeamProjectName foreach($wit_TypeDefinition in $wit_TypeDefinitions) { Write-Host "Importing $($wit_TypeDefinition.Name)" & $WitAdmin importwitd /collection:$CollectionUrl /p:$TeamProjectName /f:$($wit_TypeDefinition.FullName) } #import work item categories for the $TeamProjectName & $WitAdmin importcategories /collection:$CollectionUrl /p:$TeamProjectName /f:"$ProcessTemplateRoot\WorkItem Tracking\Categories.xml" #import work item process configuration for the $TeamProjectName & $WitAdmin importprocessconfig /collection:$CollectionUrl /p:$TeamProjectName /f:"$ProcessTemplateRoot\WorkItem Tracking\Process\ProcessConfiguration.xml" } Write-Host "Done upgrading team projects"
PowerShellCorpus/GithubGist/jarek-przygodzki_59606741d9668b3eadc1_raw_d4b80da1c2686051ffdb1643d781429bc79f1e99_update-submodules.ps1
jarek-przygodzki_59606741d9668b3eadc1_raw_d4b80da1c2686051ffdb1643d781429bc79f1e99_update-submodules.ps1
$GIT_CMD = '/path/to/git.exe' & $GIT_CMD submodule update --remote $difference = & $GIT_CMD status --porcelain $git_update_count = [regex]::matches($differences, "^M+").count if($git_update_count -ne 0) { & $GIT_CMD commit -m "Aktualizacja wersji submodułów" & $GIT_CMD push origin }
PowerShellCorpus/GithubGist/jirrick_2474503_raw_975f94626c37486e52e330f5d89b2a3fcf691a8c_wifiap.ps1
jirrick_2474503_raw_975f94626c37486e52e330f5d89b2a3fcf691a8c_wifiap.ps1
$wifi = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wifi_card_identificator_goes_here*"} $miniport = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -eq "Microsoft Virtual WiFi Miniport Adapter"} | Select-Object -first 1 if ( $miniport.MACAddress.Length -lt 17) { Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 0 -currentOperation "Disabling WiFi Miniport" $miniport.Disable() > $null Start-Sleep 2 Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 20 -currentOperation "Disabling WiFi Card" $wifi.Disable() > $null Start-Sleep 2 Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 40 -currentOperation "Enabling WiFi Card" $wifi.Enable() > $null Start-Sleep 2 Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 60 -currentOperation "Enabling WiFi Miniport" $miniport.Enable() > $null Start-Sleep 2 Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 80 -currentOperation "(Re)staring hostednetwork" } Write-Output "`r`n`r`n`r`n`r`n`r`n`r`n`r`n`r`n`r`n`r`n" netsh wlan stop hostednetwork Start-Sleep 1 netsh wlan set hostednetwork mode=allow ssid=some_ssid_here key=some_key_here keyUsage=persistent Start-Sleep 1 netsh wlan start hostednetwork Write-Progress -activity "(Re)starting virtual WiFi AP" -status 'Progress' -percentcomplete 100 -currentOperation "Script finished"
PowerShellCorpus/GithubGist/kouphax_1150019_raw_60fc6382fc8ad5f73d8d1655d18257ab16d31af4_default.ps1
kouphax_1150019_raw_60fc6382fc8ad5f73d8d1655d18257ab16d31af4_default.ps1
# Declare default task Task Default -depends Build,Test
PowerShellCorpus/GithubGist/PaulStovell_9522828_raw_7f7163682bc3d87b1b03ccdb78d7512f7b43893e_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
PaulStovell_9522828_raw_7f7163682bc3d87b1b03ccdb78d7512f7b43893e_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
## -------------------------------------------------------------------------------------- ## Configuration ## -------------------------------------------------------------------------------------- $ConfirmPreference = "None" $isEnabled = $OctopusParameters["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] if (!$isEnabled -or ![Bool]::Parse($isEnabled)) { exit 0 } $WebSiteName = $OctopusParameters["Octopus.Action.IISWebSite.WebSiteName"] $ApplicationPoolName = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolName"] $bindingString = $OctopusParameters["Octopus.Action.IISWebSite.Bindings"] $appPoolFrameworkVersion = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] $webRoot = $OctopusParameters["Octopus.Action.IISWebSite.WebRoot"] $enableWindows = $OctopusParameters["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] $enableBasic = $OctopusParameters["Octopus.Action.IISWebSite.EnableBasicAuthentication"] $enableAnonymous = $OctopusParameters["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] $applicationPoolIdentityType = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] $applicationPoolUsername = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolUsername"] $applicationPoolPassword = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolPassword"] if (! $webRoot) { $webRoot = "." } $maxFailures = $OctopusParameters["Octopus.Action.IISWebSite.MaxRetryFailures"] if ($maxFailures -Match "^\d+$") { $maxFailures = [int]$maxFailures } else { $maxFailures = 5 } $sleepBetweenFailures = $OctopusParameters["Octopus.Action.IISWebSite.SleepBetweenRetryFailuresInSeconds"] if ($sleepBetweenFailures -Match "^\d+$") { $sleepBetweenFailures = [int]$sleepBetweenFailures } else { $sleepBetweenFailures = Get-Random -minimum 1 -maximum 4 } if ($sleepBetweenFailures -gt 60) { Write-Host "Invalid Sleep time between failures. Setting to max of 60 seconds" $sleepBetweenFailures = 60 } # Helper to run a block with a retry if things go wrong function Execute-WithRetry([ScriptBlock] $command) { $attemptCount = 0 $operationIncomplete = $true while ($operationIncomplete -and $attemptCount -lt $maxFailures) { $attemptCount = ($attemptCount + 1) if ($attemptCount -ge 2) { Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..." Start-Sleep -s $sleepBetweenFailures Write-Output "Retrying..." } try { & $command $operationIncomplete = $false } catch [System.Exception] { if ($attemptCount -lt ($maxFailures)) { Write-Output ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message) } else { throw } } } } $webRoot = (resolve-path $webRoot) $wsbindings = new-object System.Collections.ArrayList # Each binding string consists of a protocol/binding information (IP, port, hostname)/SSL thumbprint/enabled # Binding strings are pipe (|) separated to allow multiple to be specified $bindingString.Split("|") | foreach-object { $bindingParts = $_.split("/") $skip = $false if ($bindingParts.Length -ge 4) { if (![String]::IsNullOrEmpty($bindingParts[3]) -and [Bool]::Parse($bindingParts[3]) -eq $false) { $skip = $true } } if ($skip -eq $false) { $wsbindings.Add(@{ protocol=$bindingParts[0];bindingInformation=$bindingParts[1];thumbprint=$bindingParts[2] }) | Out-Null } else { Write-Host "Ignore binding: $_" } } Import-Module WebAdministration # For any HTTPS bindings, ensure the certificate is configured for the IP/port combination $wsbindings | where-object { $_.protocol -eq "https" } | foreach-object { $sslCertificateThumbprint = $_.thumbprint.Trim() Write-Host "Finding SSL certificate with thumbprint $sslCertificateThumbprint" $certificate = Get-ChildItem Cert:\LocalMachine -Recurse | Where-Object { $_.Thumbprint -eq $sslCertificateThumbprint -and $_.HasPrivateKey -eq $true } | Select-Object -first 1 if (! $certificate) { throw "Could not find certificate under Cert:\LocalMachine with thumbprint $sslCertificateThumbprint. Make sure that the certificate is installed to the Local Machine context and that the private key is available." } Write-Host ("Found certificate: " + $certificate.Subject) $bindingInfo = $_.bindingInformation $bindingParts = $bindingInfo.split(':') $ipAddress = $bindingParts[0] if ((! $ipAddress) -or ($ipAddress -eq '*')) { $ipAddress = "0.0.0.0" } $port = $bindingParts[1] $sslBindingsPath = ("IIS:\SslBindings\" + $ipAddress + "!" + $port) Execute-WithRetry { $sslBinding = get-item $sslBindingsPath -ErrorAction SilentlyContinue if (! $sslBinding) { New-Item $sslBindingsPath -Value $certificate | Out-Null } else { Set-Item $sslBindingsPath -Value $certificate | Out-Null } } } ## -------------------------------------------------------------------------------------- ## Run ## -------------------------------------------------------------------------------------- pushd IIS:\ $appPoolPath = ("IIS:\AppPools\" + $ApplicationPoolName) Execute-WithRetry { $pool = Get-Item $appPoolPath -ErrorAction SilentlyContinue if (!$pool) { Write-Host "Application pool `"$ApplicationPoolName`" does not exist, creating..." new-item $appPoolPath -confirm:$false $pool = Get-Item $appPoolPath } else { Write-Host "Application pool `"$ApplicationPoolName`" already exists" } } Execute-WithRetry { Write-Host "Set application pool identity: $applicationPoolIdentityType" if ($applicationPoolIdentityType -eq "SpecificUser") { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="SpecificUser"; username="$applicationPoolUsername"; password="$applicationPoolPassword"} } else { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="$applicationPoolIdentityType"} } } Execute-WithRetry { Write-Host "Set .NET framework version: $appPoolFrameworkVersion" Set-ItemProperty $appPoolPath managedRuntimeVersion $appPoolFrameworkVersion } $sitePath = ("IIS:\Sites\" + $webSiteName) Execute-WithRetry { $site = Get-Item $sitePath -ErrorAction SilentlyContinue if (!$site) { Write-Host "Site `"$WebSiteName`" does not exist, creating..." $id = (dir iis:\sites | foreach {$_.id} | sort -Descending | select -first 1) + 1 new-item $sitePath -bindings @{protocol="http";bindingInformation=":81:od-temp.example.com"} -id $id -physicalPath $webRoot -confirm:$false } else { Write-Host "Site `"$WebSiteName`" already exists" } } $cmd = { Write-Host "Assigning website to application pool..." Set-ItemProperty $sitePath -name applicationPool -value $ApplicationPoolName } Execute-WithRetry -Command $cmd Execute-WithRetry { Write-Host ("Home directory: " + $webRoot) Set-ItemProperty $sitePath -name physicalPath -value "$webRoot" } Execute-WithRetry { Write-Host "Assigning bindings to website..." Clear-ItemProperty $sitePath -name bindings for ($i = 0; $i -lt $wsbindings.Count; $i = $i+1) { Write-Host ("Binding: " + ($wsbindings[$i].protocol + " " + $wsbindings[$i].bindingInformation + " " + $wsbindings[$i].thumbprint)) New-ItemProperty $sitePath -name bindings -value ($wsbindings[$i]) } } try { Execute-WithRetry { Write-Host "Anonymous authentication enabled: $enableAnonymous" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/anonymousAuthentication -name enabled -value "$enableAnonymous" -location $WebSiteName -PSPath "IIS:\" } Execute-WithRetry { Write-Host "Basic authentication enabled: $enableBasic" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/basicAuthentication -name enabled -value "$enableBasic" -location $WebSiteName -PSPath "IIS:\" } Execute-WithRetry { Write-Host "Windows authentication enabled: $enableWindows" Set-WebConfigurationProperty -filter /system.webServer/security/authentication/windowsAuthentication -name enabled -value "$enableWindows" -location $WebSiteName -PSPath "IIS:\" } } catch [System.Exception] { Write-Output "Authentication options could not be set. This can happen when there is a problem with your application's web.config. For example, you might be using a section that requires an extension that is not installed on this web server (such as URL Rewrtiting). It can also happen when you have selected an authentication option and the appropriate IIS module is not installed (for example, for Windows authentication, you need to enable the Windows Authentication module in IIS/Windows first)" throw } # It can take a while for the App Pool to come to life (#490) Start-Sleep -s 1 Execute-WithRetry { $state = Get-WebAppPoolState $ApplicationPoolName if ($state.Value -eq "Stopped") { Write-Host "Application pool is stopped. Attempting to start..." Start-WebAppPool $ApplicationPoolName } } Execute-WithRetry { $state = Get-WebsiteState $WebSiteName if ($state.Value -eq "Stopped") { Write-Host "Web site is stopped. Attempting to start..." Start-Website $WebSiteName } } popd Write-Host "IIS configuration complete"
PowerShellCorpus/GithubGist/whataride_7638409_raw_29225d8e219b765e7abc29da7e6a3b032da56f36_Operators.ps1
whataride_7638409_raw_29225d8e219b765e7abc29da7e6a3b032da56f36_Operators.ps1
# Arithmatic operators # Comparison operators # -eq, -lt, -gt, -ge, -le, -ne # Logical operators # -not, ! (the same as -not), -and, -or # Conditional operators # -Match (-NotMatch for negative), -Like (-NotLike, -CLike that force case sensitivity) # -Contains, -NotIn $Guy ="Guy Thomas 1949" $Guy -Match "Th" # Result PS> True # one can use wild card ? and * $Guy ="Guy Thomas 1949" $Guy -Match "19?9" # Result PS> True Get-WmiObject -List | Where {$_.name -Match "cim*"} # -Match operator can also work on character classes; think of any regex expression # \w matches any word character, meaning letters and numbers. # \s matches any white space character, such as tabs, spaces, and so forth. # \d matches any digit character. $Guy ="Guy Thomas 1949" $Guy -Match "\w" # Result PS> True # -Like check if two strings are the same $Guy ="Guy Thomas 1949" $Guy -Like "Th" # Result PS> False $Guy ="Guy Thomas 1949" $Guy -Like "Guy*" # Result PS> True $Guy ="Guy Thomas 1949" $Guy -Like "*Th*" # Result PS> True
PowerShellCorpus/GithubGist/belotn_7751191_raw_dc9e98282df81e02590cf234bfc9455f219abbe5_not_using_farmserverlicence.ps1
belotn_7751191_raw_dc9e98282df81e02590cf234bfc9455f219abbe5_not_using_farmserverlicence.ps1
get-xaserver | get-xaserverconfiguration |? {! $_.LicenseServerUseFarmSettings } | select ServerName
PowerShellCorpus/GithubGist/andy-mcknight_195079110ed51ecfaa63_raw_98cfaed2e55b17db3214b3bcd10b7f939e9eea4e_Check-ShadowCopies.ps1
andy-mcknight_195079110ed51ecfaa63_raw_98cfaed2e55b17db3214b3bcd10b7f939e9eea4e_Check-ShadowCopies.ps1
# This script lists Shadow Copies on specified servers created over past 7 days # # Author: Andy McKnight # Created: 08/12/2014 # Last Edit: 08/12/2014 # $servers = "SERVER1", "SERVER2", "SERVER3" # etc, etc $daystocheck = 7 #region CheckShadowCopies # Uses WMI Win32_Volume to get drive letter from device id Function Get-DriveLetters($server) { $volumes = @{} $allvolumes = Get-WmiObject win32_volume -ComputerName $server -Property DeviceID, Name foreach ($v in $allvolumes) { $volumes.add($v.DeviceID, $v.Name) } $volumes } Function Check-ShadowCopies { <# .SYNOPSIS Checks Shadow Copy Status of specified servers for past 7 days. .DESCRIPTION Checks Shadow Copy Status on specified servers for past 7 days. Script designed to be ran as a scheduled task. .EXAMPLE powershell.exe Check-ShadowCopies.ps1 No parameters required. Run the script to return the content of the various backup locations. #> $allshadowcopies = @() Foreach ($server in $servers) { $driveletters = Get-DriveLetters $server $shadowcopies = Get-WmiObject -Class "Win32_ShadowCopy" -ComputerName $server -Property InstallDate, VolumeName Foreach ($copy in $shadowcopies) { $shadowcopy = New-Object System.Object $date = [datetime]::ParseExact($copy.InstallDate.Split(".")[0], "yyyyMMddHHmmss", $null) $shadowcopy | Add-Member -Type NoteProperty -Name Server -Value $server $shadowcopy | Add-Member -Type NoteProperty -Name Date -Value $date $shadowcopy | Add-Member -Type NoteProperty -Name Drive -Value $driveletters.Item($copy.VolumeName) If ($date -gt (Get-Date).AddDays(-$daystocheck)) { $allshadowcopies += $shadowcopy } } } $allshadowcopies | Sort-Object Date -Descending } #endregion CheckShadowCopies
PowerShellCorpus/GithubGist/fzed51_10022078_raw_5b5fcdb93d367d13310ba76823025efee4f1d41f_Format-ANSI.ps1
fzed51_10022078_raw_5b5fcdb93d367d13310ba76823025efee4f1d41f_Format-ANSI.ps1
<# .Synopsis Formate une sortie console ANSI .DESCRIPTION Cette commande interprête les commande ansi ESC[PL;PcH ESC[PL;Pcf ESC[PnA ESC[PnB ESC[PnC ESC[PnD ESC[s ESC[u ESC[2J ESC[K ESC[Ps;...;Psm .EXAMPLE "←[H←[7mCoucou!!!" | Format-ANSI .EXAMPLE composer --ansi | Format-ANSI #> [CmdletBinding()] Param ( [Parameter(ValueFromPipeline=$true, Position=0)] [string] $in = '' ) Begin { $DefautForegroundColor = $Host.ui.RawUI.ForegroundColor $DefautBackgroundColor = $Host.ui.RawUI.BackgroundColor } Process { [Collections.ArrayList]$BackupPosX = @() [Collections.ArrayList]$BackupPosY = @() [int]$PosX = 0 [int]$PosY = 0 $fore = $DefautForegroundColor $back = $DefautBackgroundColor $in.Split([char]27+'←') | % { [int]$x = $host.UI.RawUI.CursorPosition.X [int]$y = $host.UI.RawUI.CursorPosition.Y switch -Regex ($_) { "^\[((\d+);(\d))?H(.*)" { if ( $Matches[1] -ne $null ){ $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates([int]$Matches[2],[int]$Matches[3])) } else { $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates(0,0)) } Write-Host $Matches[4] -no -fo $fore -ba $back } "^\[((\d+);(\d))?f(.*)" { if ( $Matches[1] -ne $null ){ $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates([int]$Matches[2],[int]$Matches[3])) } else { $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates(0,0)) } Write-Host $Matches[4] -no -fo $fore -ba $back } "^\[(\d+)A(.*)" { $y = [Math]::Max(0, ($y-[int]$Matche[1])) $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) Write-Host $Matches[2] -no -fo $fore -ba $back } "^\[(\d+)B(.*)" { $y = $y+[int]$Matche[1] $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) Write-Host $Matches[2] -no -fo $fore -ba $back } "^\[(\d+)C(.*)" { $x = [Math]::Min(([int]$host.ui.RawUI.WindowSize.Width - 1), ($y + [int]$Matche[1])) $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) Write-Host $Matches[2] -no -fo $fore -ba $back } "^\[(\d+)D(.*)" { $x = [Math]::Max(0, ($y-[int]$Matche[1])) $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) Write-Host $Matches[2] -no -fo $fore -ba $back } "^\[s(.*)" { $BackupPosX.Insert(0,$x) $BackupPosY.Insert(0,$y) Write-Host $Matches[1] -no -fo $fore -ba $back } "^\[u(.*)" { if( $BackupPosX.Count -gt 0 ){ $x = $BackupPosX[0] $y = $BackupPosY[0] $BackupPosX.Remove(0,1) $BackupPosY.Remove(0,1) $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) } Write-Host $Matches[1] -no -fo $fore -ba $back } "^\[2J(.*)" { Clear-Host Write-Host $Matches[1] -no -fo $fore -ba $back } "^\[K(.*)" { $l = $host.ui.RawUI.WindowSize.Width -1 - $x Write-Host " " * $l -no -fo $fore -ba $back $host.UI.RawUI.CursorPosition = $(New-Object Management.Automation.Host.Coordinates($x,$y)) Write-Host $Matches[1] -no -fo $fore -ba $back } "^\[([0-9;]+)m(.*)" { $Matches[1].split(';') | % { switch ($_) { '0' { $fore = $DefautForegroundColor $back = $DefautBackgroundColor } '7' { $fore, $back = $back, $fore } '30' { $fore = 'Black' } '31' { $fore = 'Red' } '32' { $fore = 'Green' } '33' { $fore = 'Yellow' } '34' { $fore = 'Blue' } '35' { $fore = 'Magenta' } '36' { $fore = 'Cyan' } '37' { $fore = 'White' } '40' { $back = 'Black' } '41' { $back = 'Red' } '42' { $back = 'Green' } '43' { $back = 'Yellow' } '44' { $back = 'Blue' } '45' { $back = 'Magenta' } '46' { $back = 'Cyan' } '47' { $back = 'White' } } Write-Host $Matches[2] -no -fo $fore -ba $back } } Default {Write-Host $_ -no -fo $fore -ba $back} } Remove-Variable x, y } Write-Host } End { $Host.ui.RawUI.ForegroundColor = $DefautForegroundColor $Host.ui.RawUI.BackgroundColor = $DefautBackgroundColor }
PowerShellCorpus/GithubGist/PierreMage_6890664_raw_bc2c936c96398afb80d0734f21d2ecf219dc38d2_PowerShell-profile.ps1
PierreMage_6890664_raw_bc2c936c96398afb80d0734f21d2ecf219dc38d2_PowerShell-profile.ps1
# http://technet.microsoft.com/en-us/library/ee692685.aspx # F7 = history # Alt+F7 = history -c # F8 = Ctrl+R Set-Location C: # Easier navigation Set-Alias o start function oo {start .} function .. {Set-Location ..} function ... {Set-Location ..\..} function .... {Set-Location ..\..\..} function ..... {Set-Location ..\..\..\..} # function google ($q) {start http://www.google.com/?#q=$q} function so ($q) {start http://stackoverflow.com/search?q=$q} # Maven # Requires M2_HOME\bin to be added to the Path environment variable # -rf --resume-from <project> function mci {mvn clean install} function mcis {mvn clean install '-Dmaven.test.skip'} function mcp {mvn clean package} function mcps {mvn clean prepare-package war:exploded '-Dmaven.test.skip'} function mct {mvn clean test}
PowerShellCorpus/GithubGist/TearTheSky_f5d39df867b278eb5555_raw_4dc7e7b3c5235630118e398e8bcf1af7438d535c_Get-MultiCellValues.ps1
TearTheSky_f5d39df867b278eb5555_raw_4dc7e7b3c5235630118e398e8bcf1af7438d535c_Get-MultiCellValues.ps1
#引数定義 Param ( [string]$pathName = "", [int]$targetSheetNumber = -1, [string]$targetCollumn = "", [int]$targetRow = -1 ) #****************************************************************************** # 機能 : Excel起動 # # 機能説明 : Excelを起動する。 # # 引数 : なし # # 戻り値 : Excelオブジェクト #****************************************************************************** function OpenExcel { [void] ([Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel")) $excel = New-Object "Microsoft.Office.Interop.Excel.ApplicationClass" return $excel } #****************************************************************************** # 機能 : ワークブック起動 # # 機能説明 : 指定したExcelファイルを開く。 # # 引数 : $excel Excelオブジェクト # $filePath Excelファイルのフルパスファイル名 # # 戻り値 : ワークブックオブジェクト #****************************************************************************** function OpenWorkbook($excel, $filePath) { $workbook = $excel.Workbooks.Open($filePath) return $workbook } #****************************************************************************** # 機能 : Excel終了 # # 機能説明 : Excelを終了する。 # # 引数 : $excel Excelオブジェクト # # 戻り値 : なし #****************************************************************************** function CloseExcel($excel) { if ($excel -ne $null) { $excel.Quit() $excel = $null [GC]::Collect([GC]::MaxGeneration) } return } #****************************************************************************** # 機能 : ワークブック終了 # # 機能説明 : 指定したワークブックを閉じる。 # # 引数 : $workbook ワークブックオブジェクト # # 戻り値 : なし #****************************************************************************** function CloseWorkbook($workbook) { if ($workbook -ne $null) { $workbook.Close($false) $workbook = $null } return } #****************************************************************************** # 機能 : Excelカラム番号変換 # # 機能説明 : Excelカラム名を番号へ変換する。 # # 引数 : $columnName Excelカラム名 # # 戻り値 : カラム番号 #****************************************************************************** function ConvertExcelColumnNo($columnName) { $columnValue = 0 for ($i = 0; $i -lt $columnName.Length; $i++) { $columnValue += ((([int] $columnName.ToUpper().Chars($i)) - 64) ` * ([math]::pow(26, $columnName.Length - $i - 1))) } return [int]$columnValue } #****************************************************************************** # 機能 : 項目値読み取り # # 機能説明 : 指定したシート、セル(単一項目)の設定値を読み取る。 # # 引数 : $workbook ワークブックオブジェクト # $sheetNo シート番号(1オリジン) # $rowNo 行番号(1オリジン) # $columnName 列名 # # 戻り値 : Excelセル設定値 #****************************************************************************** function ReadExcelItem($workbook, $sheetNo, $rowNo, $columnName) { $worksheet = $workbook.Worksheets.Item($sheetNo) $columnNo = ConvertExcelColumnNo $columnName $value = $worksheet.Cells.Item($rowNo, $columnNo).Text.Trim() $worksheet = $null return $value trap { Write-Debug "ReadExcelItem():exception" $worksheet = $null break } } #----------------------------------------------------------------------------------------------------- # - - - 処理の流れについて - - - # #全部のExcelファイルを取得する(.xlsと.xlsx) #各ファイルについて # 開く #指定されたセルの値を取得する #その値を返す #キーが0個の連想配列を作成しておく #戻ってきた値について  #0ならキーを追加する  #キーに対して値を1増やす #配列のキーが1個以上なら #そのキーがすでに存在するかを確認する #存在していたらそのキーに対して値を1増やす   #キーがが存在しないならキーを追加する    #そのキーに対して値を1増やす # 最後にわかりやすく標準出力する。 #----------------------------------------------------------------------------------------------------- if($pathName -eq "") { #フォルダ選択ダイアログの表示 $shell = New-Object -com Shell.Application $folderPath = $shell.BrowseForFolder(0,"対象フォルダーを選択してください",0,"0") if($folderPath -eq $null){exit} $myFolderPath = $folderPath.Self.Path } else { [string]$myFolderPath = $pathName } #変数準備 $excelObject = OpenExcel $excelFiles = @() $answers = @{} #Excelファイルを取得 Set-Location $myFolderPath $excelFiles += Get-ChildItem -Name "*.xlsx" $excelFiles += Get-ChildItem -Name "*.xls" # 取得対象セルを特定 if($targetSheetNumber -eq -1) { Write-Output "値を知りたいセルがあるシートの番号(左から数えて何個目のシートか、たとえば3個目なら3)を入力してください。" [int]$targetSheetNumber = Read-Host } if($targetCollumn -eq "") { Write-Output "値を知りたいセルの列名(A5ならA)を入力してください。" [string]$targetCollumn = Read-Host } if($targetRow -eq -1) { Write-Output "値を知りたいセルの行名(A5なら5)を入力してください。" [int]$targetRow = Read-Host } #各Excelファイルのそのセルから値を取得 foreach($aFile in $excelFiles) { $filePath = ( [string](Get-Location)+ "\" +$aFile) $workbookObject = OpenWorkbook $excelObject $filePath $targetValue = ReadExcelItem $workbookObject $targetSheetNumber $targetRow $targetCollumn if( ($answers.Contains($targetValue) ) -eq $false ) { $answers.Add($targetValue, 1) } else { $answers[$targetValue] += 1 } CloseWorkbook } CloseExcel $answers
PowerShellCorpus/GithubGist/grantcarthew_7002208_raw_0bae4e8cea578315c84de52cf02104a2e2cbf07f_Initialize-SPWeb.ps1
grantcarthew_7002208_raw_0bae4e8cea578315c84de52cf02104a2e2cbf07f_Initialize-SPWeb.ps1
<# .Synopsis Invokes a standard web request against all the sites in SharePoint. .Description There are some dependencies to run this script as follows; The account used to run this script will need read access to all sites for the initialization to fully succeed. This script is required to be run on a SharePoint server or a machine with the Microsoft.SharePoint.PowerShell dll registered. Requires PowerShell v3.0. #> [CmdletBinding()] Param () "Importing the PowerShell cmdlets." $ver = $host | select version if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"} Add-PsSnapin Microsoft.SharePoint.PowerShell "Creating an Internet Explorer object for navigation." $ie = New-Object -ComObject InternetExplorer.Application "Enumerate the SharePoint sites." $Webs = Get-SPWebApplication -IncludeCentralAdministration | Get-SPSite | Get-SPWeb "Navigating to all $($Webs.Count) sites." foreach ($Web in $Webs) { "Initializing $($Web.URL)" try { $ie.Navigate($Web.URL) while ($ie.Busy) { Start-Sleep -Seconds 1 } "Title: $($ie.Document.title)" } catch { Write-Host -Object ("Status: " + $Error[0].Exception.Message) -ForegroundColor Yellow } } $ie.Quit() "SPWeb Initialization Complete."
PowerShellCorpus/GithubGist/threecourse_7852959_raw_f894a4d5e06660e7ba3d264bdaa3e2a90ee59d45_CSharpCompileRun.ps1
threecourse_7852959_raw_f894a4d5e06660e7ba3d264bdaa3e2a90ee59d45_CSharpCompileRun.ps1
# --------------------------------------------------------------------- # PowershellからC#コードをコンパイル・実行するサンプル # # (参考) # http://codezine.jp/article/detail/5007 # # (注意点) # .NET Frameworkの制約上、Add-Typeによる型の追加を再実行するには、Powershellのセッションを切る必要がある。 # そのため、Powershellのプロセスを立ち上げ、その中でコンパイル・実行するようにしている。 # --------------------------------------------------------------------- # 引数の取得 # Python風に、トップレベルであれば$moduleに"__main__"が入るようにしている。 # 他のPowershellプロセスを立ち上げるときには、$moduleに"called"を入れるようにする。 param([string]$module) if($module -eq ""){ $module = "__main__"} # コンパイル・実行を行う関数の定義 function ComplieAndRun(){ # CSharpコードのソース $source=@" public class SampleClass{ public static string SayHello(string Name) { return "Hello " + Name; } } "@ # CSharpコードのコンパイル Add-Type -Language CSharpVersion3 -TypeDefinition $Source # CSharpコードの実行 [SampleClass]::SayHello("World") } # トップレベルでない場合のみ、コンパイル・実行を行う。 if($module -ne "__main__"){ ComplieAndRun [Console]::ReadKey() | Out-Null # 実行後入力を待つ } # トップレベルの場合は、別のPowershellプロセスを立ち上げ、自身のスクリプトを呼び出す。 if($module -eq "__main__"){ $path = '"' + $Script:MyInvocation.MyCommand.Path + '"' start-process powershell.exe -ArgumentList @("-File", $path, "called") }
PowerShellCorpus/GithubGist/yun2dot0_47f02634b06c28b03238_raw_b2152a7646ad083fa6bc048c641768c142dc6f2f_profile.ps1
yun2dot0_47f02634b06c28b03238_raw_b2152a7646ad083fa6bc048c641768c142dc6f2f_profile.ps1
# UTF-16で保存すること # タイトルバーを見た目よくする $(Get-Host).UI.RawUI.WindowTitle = ` ([Security.Principal.WindowsIdentity]::GetCurrent().name -replace "^(.*?)\\(.*?)$", "`$2@`$1")` + " - Windows PowerShell"` + $(if((([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole] "Administrator"))){" [管理者として実行]"}) # プロンプトの設定 function prompt(){ Write-Host ("[{0}]" -f (Split-Path(Get-Location) -Leaf)) -NoNewline -ForegroundColor Yellow return "> " } # Alias sal Hidemaru "C:\Program Files (x86)\Hidemaru\Hidemaru.exe" # 秀丸エディタ
PowerShellCorpus/GithubGist/nakaji_3445423_raw_91c03e318ad4093c5f68bb8d14c56630da76cac0_gistfile1.ps1
nakaji_3445423_raw_91c03e318ad4093c5f68bb8d14c56630da76cac0_gistfile1.ps1
# 指定されたディレクトリ配下のファイルに対して、MD5チェックサムを取得する # # 下記ブログを参考に作成 # PowerShell でハッシュ値を計算する(http://blogs.gine.jp/taka/archives/1369) param($path) function GetMD5{ param($fileName) $stream = New-Object IO.StreamReader $fileName # MD5ハッシュ値を計算する $md5 = [System.Security.Cryptography.MD5]::Create() $hash = $md5.ComputeHash($stream.BaseStream); $result = [System.BitConverter]::ToString($hash).Replace("-","").ToLower() $result } Get-ChildItem $path | ?{ !$_.PSIsContainer } | %{ echo ($_.Name + "`t" + (GetMD5 $_.FullName)) }
PowerShellCorpus/GithubGist/dfinke_3923295_raw_9d9f05c1790d6e1581483e3c2a5f4750edb95b14_InvokeCompileAllTS.ps1
dfinke_3923295_raw_9d9f05c1790d6e1581483e3c2a5f4750edb95b14_InvokeCompileAllTS.ps1
function Invoke-CompileAllTS { <# .Synopsis Recursively searches for TypeScript files and invokes the compiler on the target .Example Invoke-CompileAllTS #> ls . -Recurse *.ts | ForEach {tsc $_.fullname} }
PowerShellCorpus/GithubGist/rpunt_5134907_raw_4316fee30d222cb2b708c66616a954dd1232e8ef_Verify%20User%20Credentials.ps1
rpunt_5134907_raw_4316fee30d222cb2b708c66616a954dd1232e8ef_Verify%20User%20Credentials.ps1
[CmdletBinding()] param ( [parameter(Mandatory=$true)][string]$adminuser, [parameter(Mandatory=$true)][string]$adminpassword ) $computer = gc env:computername # did you enter valid credentials for a local user? [Reflection.Assembly]::LoadFile('C:\Windows\assembly\GAC_MSIL\System.DirectoryServices\2.0.0.0__b03f5f7f11d50a3a\System.DirectoryServices.dll') Add-Type -assemblyname system.DirectoryServices.accountmanagement $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine) if ($DS.ValidateCredentials($adminuser, $adminpassword)) { # yay! } else { # boo! }
PowerShellCorpus/GithubGist/vinadm_0fd14cd7b748ae1a23ad_raw_b9cfa71e9821d85fe3752ea5808e4bec915aea88_gistfile1.ps1
vinadm_0fd14cd7b748ae1a23ad_raw_b9cfa71e9821d85fe3752ea5808e4bec915aea88_gistfile1.ps1
# Uses Quest Active Roles # Free to download http://www.quest.com/powershell/activeroles-server.aspx # # Special Thanks to Mladen Milunovic for his comments that improved the Script! # # List all computers that have been # Inactive in "Active Directory"(Boy THERE'S a play on words!) # for a specified Number of Days # # New version exports the Data to a CSV file and removes limit # on number of Computers listed (default is 1000) # $COMPAREDATE=GET-DATE # # DO NOT RUN THIS IN PRODUCTION. TEST IT FIRST and use it as # a REFERENCE tool. AUTO PURGING OF COMPUTER ACCOUNTS is # DANGEROUS and SILLY. # # But this little query might help you weed out accounts # of potentially dead systems in Active Directory # # # Number of Days to see if account has been active # Within # $NumberDays=90 # $CSVFileLocation='C:\TEMP\OldComps.CSV' # # GET-QADCOMPUTER -SizeLimit 0 -IncludedProperties LastLogonTimeStamp | where { ($CompareDate-$_.LastLogonTimeStamp).Days -gt $NumberDays } | Select-Object Name, LastLogonTimeStamp, OSName, ParentContainerDN | Sort-Object ModificationDate, Name | Export-CSV $CSVFileLocation # #
PowerShellCorpus/GithubGist/breezhang_6610058_raw_cdeea142168ea13583fc34dc0812e0783dd5f2d4_a.ps1
breezhang_6610058_raw_cdeea142168ea13583fc34dc0812e0783dd5f2d4_a.ps1
function Get-IniContent ($filePath) { $ini = @{} switch -regex -file $FilePath { "^\[(.+)\]" # Section { $section = $matches[1] $ini[$section] = @{} $CommentCount = 0 } "^(;.*)$" # Comment { # $value = $matches[1] # $CommentCount = $CommentCount + 1 # $name = "Comment" + $CommentCount # $ini[$section][$name] = $value } "(.+?)\s*=(.*)" # Key { $name,$value = $matches[1..2] $ini[$section][$name] = $value } } return $ini }
PowerShellCorpus/GithubGist/pbabcock_6034350_raw_3b516d2639682aceb6880641a51a0f190e0c33ae_envdemo.ps1
pbabcock_6034350_raw_3b516d2639682aceb6880641a51a0f190e0c33ae_envdemo.ps1
$tempPath = $(get-location) Write-Output "Current directory: $($tempPath)" [Environment]::SetEnvironmentVariable("DevPath", "$($tempPath)\Dev", "User") Write-Output "Value of DevPath $($tempPath)\Dev"
PowerShellCorpus/GithubGist/hsiboy_bfed1d445e936c4773fa_raw_bee66eef37b1b3471a908d402c175f69a73ec69c_install.ps1
hsiboy_bfed1d445e936c4773fa_raw_bee66eef37b1b3471a908d402c175f69a73ec69c_install.ps1
#set up vars $computername = Get-Content 'server_list.txt' $msiname = "NewRelicAgent_x86_3.4.24.0.msi" $licenseKey = "aaaaabbbbbbcccccdddddeeeeeffffggggghhhhh" $destinationFolder = "\\$computer\C$\temp\install" $payload = $destinationFolder + "\" + $msiname foreach ($computer in $computername) { #This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it. if (!(Test-Path -path $destinationFolder)) { New-Item $destinationFolder -Type Directory } Copy-Item -Path $sourcefile -Destination $destinationFolder #stop IIS Invoke-Command -ComputerName $computer { iisreset.exe /stop } $exitCode =Invoke-Command -ComputerName $computer -ScriptBlock { msiexec.exe /i $payload /qn NR_LICENSE_KEY=$licenseKey} if($exitCode -eq 0) { Write-Host "Installation successful!" -ForegroundColor Green } else { Write-Host "Installation unsuccessful. Exitcode: $exitCode" -ForegroundColor Red } }
PowerShellCorpus/GithubGist/sunnyc7_9579625_raw_aa58dae2428d4c479053a4e45f0d23c1c120c990_get-continiouscounterpoll.ps1
sunnyc7_9579625_raw_aa58dae2428d4c479053a4e45f0d23c1c120c990_get-continiouscounterpoll.ps1
# Author: Sunny Chakraborty. 2014 (@sunnyc7) # BasedOn: Matt Graeber's beautiful work with Powershell Lambda functions. # Powershell Magazine Source: http://www.powershellmagazine.com/2013/12/23/simplifying-data-manipulation-in-powershell-with-lambda-functions/ # Code: get-continiouscounterpoll.ps1 # Source: https://gist.github.com/9579625 <# You can copy list of counters in counter-paths.txt. Please avoid using * based counter paths. Instead use (_total) Content of counter-paths.txt \Processor(_Total)\% User Time \Processor(_Total)\% Privileged Time \Processor(_Total)\Interrupts/sec \Processor(_Total)\DPCs Queued/sec \Processor(_Total)\% Processor Time \Memory\Available MBytes \Memory\Pages/sec \Memory\Pool Nonpaged Bytes \Memory\% Committed Bytes In Use \Synchronization(_Total)\Spinlock Contentions/sec #> $counters = Get-Content .\counter-paths.txt Function Map-Counter { param ( [Parameter(Mandatory)] [ValidateScript({ $_.Ast.ParamBlock.Parameters.Count -eq 1 })] [Scriptblock] $Expression, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [Object[]] $Sequence ) foreach ($member in $Sequence) { $hash = @{} $hash.Add("$member",(Invoke-Expression (&$Expression $member))) $hash } } $cookedValue = { param($x) (Get-Counter $x).CounterSamples.CookedValue } for (;;) { Map-Counter $cookedValue $counters }
PowerShellCorpus/GithubGist/ringe_7579356_raw_5b088396be9fae814534929e13e95061b815a959_logoff_sessions.ps1
ringe_7579356_raw_5b088396be9fae814534929e13e95061b815a959_logoff_sessions.ps1
$timeout = 300 $message = "Please save your work. You will be logged off in "+ $timeout/60 +" minutes" $sessions = @() # Collect session IDs and warn users query session | select-string "wdica" | %{$_ -replace " {2,27}"," "} | foreach {$_.ToString().split(" ")[3]} | foreach { $sessions += $_ msg $_ /TIME:$timeout $message } # Wait for timeout sleep $timeout # Log off sessions $sessions | foreach { logoff $_ }
PowerShellCorpus/GithubGist/rdrobinson3_5707787_raw_90a37fe63a1c6bb43b782eaa7d69f220b47ded50_AddSiteColumnsToContentTypes.ps1
rdrobinson3_5707787_raw_90a37fe63a1c6bb43b782eaa7d69f220b47ded50_AddSiteColumnsToContentTypes.ps1
# # Description: # # This script adds Site Columns to the appropriate Content Types as listed in # the AddSiteColumnsToContentTypes.csv. The .CSV needs to be saved to # "C:\PowerShell\" directory. If this directory does not exist, you will need to create it. # # Running this script requires running PowerShell with elevated privileges so right # click the SharePoint 2010 Management Shell and select "Run as administrator" then use # change directory commands and tabs to run the PS1 from its directory. # Reference the CSV holding the Content Type values and begin the loop $create = Import-Csv -path c:\PowerShell\AddSiteColumnsToContentTypes.csv $create | ForEach-Object { # Get the Site where the Site Columns will be added to Content Types $site = Get-SPSite -Identity $($_.'SiteCollectionURL') $web = $site.RootWeb # Add Site Columns to Content Types $ct=$web.ContentTypes["$($_.'ContentType')"]; $fieldAdd=$web.Fields["$($_.'SiteColumn')"] $fieldLink=New-Object Microsoft.SharePoint.SPFieldLink($fieldAdd) $ct.FieldLinks.Add($fieldLink); $ct.Update() # Dispose of the Web and Site objects and close the loop $web.Dispose() $site.Dispose() }
PowerShellCorpus/GithubGist/GuruAnt_7197673_raw_1623cf9eeb7b8dc6323ea71884509b52fa0d43c4_Get-AppSenseLogonTimes.ps1
GuruAnt_7197673_raw_1623cf9eeb7b8dc6323ea71884509b52fa0d43c4_Get-AppSenseLogonTimes.ps1
Function Get-AppSenseLogonTimes { <# .Synopsis Returns information about AppSense logon events as recorded by the AppSense event log .Description Returns, via the AppSense Event log, the Logon Time, Node Name, Action, Start Time and Duration of AppSense logon actions. Useful for tuning and optimising AppSense logons. The Policy Configuration item "Send events to the Appsense event log" should be enabled for this to work. .Parameter ComputerName The target computer name. .Example Gets AppSense Logon times from Server1 Get-AppSenseLogonTimes -ComputerName "Server1" .Notes Ben Neise 28/10/2013 #> Param ( [String] $ComputerName = $env:localhost ) Try { Get-Eventlog -ComputerName $ComputerName -LogName AppSense | Select-Object `     @{Name="Logon Time";Expression={@($_.ReplacementStrings[0])}},     @{Name="Node Name";Expression={@($_.ReplacementStrings[1])}},     @{Name="Action";Expression={@($_.ReplacementStrings[2])}},     @{Name="Start Time";Expression={@($_.ReplacementStrings[3])}},     @{Name="Duration";Expression={[int]$_.ReplacementStrings[4]}} } Catch { Write-Error "Can't get AppSense logs from $ComputerName" } }
PowerShellCorpus/GithubGist/mnzk_c317848463ce0f2e391e_raw_3594a2ac881e449d76b5e2e55ec064a938c1f658_primes.ps1
mnzk_c317848463ce0f2e391e_raw_3594a2ac881e449d76b5e2e55ec064a938c1f658_primes.ps1
# # 既知の素数リストを保存しているファイルを読み込み # 続きから素数を列挙する # # 素数リストファイルは # primes000.txt, primes001.txt, primes002.txt ... # と複数ファイルに分割されていても良い。 # ファイル番号の順に内容を連結した時、素数が昇順に並んでいること。 # 新たな素数は、ファイル番号最大+1のファイル名で保存します。 # # ファイルが1つもない場合、初めにprimes000.txt を生成します。 # # [実行例] # 下記スクリプトを読みこんだ後、 # # > enumerate-prime-numbers 100000 # # # $path : 作業フォルダ # $test_count : 何回素数テストを行うか # function enumerate-prime-numbers($test_count) { $path = "S:\temp\primes2" function floor($n){ [long][Math]::Floor($n) } $files = ls (Join-Path $path "primes*.txt") | sort $next_file_number = &{ if($null -eq $files){ 0 }else{ $f = $files[$files.Length-1] 1 + ($f.Name -replace "[^\d]","") } } $next_filename = Join-Path $path ("primes{0:d3}.txt" -f $next_file_number) if($next_file_number -eq 0){ echo 2,3 > $next_filename $files = @($next_filename) } [System.Collections.Generic.List[long]]` $primes_list = New-Object System.Collections.Generic.List[long] [void]$primes_list.AddRange([long[]](cat $files)) $primes_counter = $primes_list.Count $last_prime = $primes_list[$primes_counter - 1] [void]$primes_list.RemoveAt(0) # 2を削除 (奇数のみテストするため) 1 .. (floor ($test_count / 2)) | % { $x=$last_prime } { $x += 2 $test_limit = floor([Math]::Sqrt($x)) $is_prime = $true foreach($p in $primes_list){ if($p -gt $test_limit){ break } if($x % $p -eq 0){ $is_prime = $false; break } } if($is_prime){ echo $x >> $next_filename [void]$primes_list.Add($x) $primes_counter++ echo "$primes_counter : $x" } } }
PowerShellCorpus/GithubGist/agileguy_1476823_raw_43e0d9304d76865cbfeafae0acd3806656199375_sudo.ps1
agileguy_1476823_raw_43e0d9304d76865cbfeafae0acd3806656199375_sudo.ps1
$file, [string]$arguments = $args; if([System.IO.File]::Exists("$(get-location)\$file")) { $file = "$(Get-Location)\$file"; } $psi = new-object System.Diagnostics.ProcessStartInfo $file; $psi.Arguments = $arguments; $psi.Verb = "runas"; [System.Diagnostics.Process]::Start($psi);
PowerShellCorpus/GithubGist/patrickmslatteryvt_11196973_raw_8f2c0be3cb6615381ab4427e82a00ec1c8172105_create_zol_vm.ps1
patrickmslatteryvt_11196973_raw_8f2c0be3cb6615381ab4427e82a00ec1c8172105_create_zol_vm.ps1
# Stops the client whining about certs Set-PowerCLIConfiguration -InvalidCertificateAction ignore # Edit these values to suit your environment Connect-VIServer -server vcenter.dev.acme.com -User root -Password ******************* # VM host we will create the VM on $VS5_Host = "10.10.10.2" # Name of VM we want to create $vmName1 = "ZOL_CentOS" # How many vCPUs in the VM $vm_cpu = 2 # How much RAM in the VM (in MB) $vmRAM = 4096 # The public network the VM will talk on $public_network_name = "VMs" # The datastore that the boot drive (EXT4) will reside on $osstore = "RAID0" # Size of the boot drive (in GB) $osstore_size_GB = 8 # The datastore that the 8 HDDS will be created in $hddstore = "RAID0" # Size of the HDDs (in GB) $hddstore_size_GB = 10 # The datastore that the 2 SSDs (for ZIL and L2ARC) will be created in $ssdstore = "SSD" # Size of the SSDs (in GB) $ssdstore_size_GB = 8 # NEEDS A CD AND AN ATTACHED ISO # Don't edit below the line #=============================================================================== # Create the basic VM $VM1 = new-vm ` -Host "$VS5_Host" ` -Name $vmName1 ` -Datastore (get-datastore "$osstore") ` -Location "ZOL" ` -GuestID rhel6_64Guest ` -MemoryMB $vmRAM ` -DiskMB $osstore_size_MB ` -NetworkName "$public_network_name" ` -DiskStorageFormat "Thin" ` -Version "v8" ` -NumCpu $vm_cpu ` -Confirm:$false # Create first HDD on HBA #2 $New_Disk1 = New-HardDisk -vm($VM1) -CapacityGB $hddstore_size_GB -StorageFormat Thin -datastore "$hddstore" $New_SCSI_1_1 = $New_Disk1 | New-ScsiController -Type VirtualLsiLogicSAS -Confirm:$false # Add 7 more HDDs on HBA #2 foreach ($id in 1,2,3,4,5,6,8) { $New_Disk1 = New-HardDisk -vm($VM1) -CapacityGB $hddstore_size_GB -StorageFormat Thin -datastore "$hddstore" set-harddisk -Confirm:$false -harddisk $New_Disk1 -controller $New_SCSI_1_1 } # Create first SSD on HBA #3 $New_Disk1 = New-HardDisk -vm($VM1) -CapacityGB $ssdstore_size_GB -StorageFormat Thin -datastore "$ssdstore" $New_SCSI_1_1 = $New_Disk1 | New-ScsiController -Type VirtualLsiLogicSAS -Confirm:$false # Add one more SSD on HBA #3 $New_Disk1 = New-HardDisk -vm($VM1) -CapacityGB $ssdstore_size_GB -StorageFormat Thin -datastore "$ssdstore" set-harddisk -Confirm:$false -harddisk $New_Disk1 -controller $New_SCSI_1_1 # http://blogs.microsoft.co.il/scriptfanatic/2009/08/27/force-a-vm-to-enter-bios-setup-screen-on-next-reboot/ filter Set-VMBIOSSetup { param( [switch]$Disable, [switch]$PassThru ) if($_ -is [VMware.VimAutomation.Types.VirtualMachine]) { trap { throw $_ } $vmbo = New-Object VMware.Vim.VirtualMachineBootOptions $vmbo.EnterBIOSSetup = $true if($Disable) { $vmbo.EnterBIOSSetup = $false } $vmcs = New-Object VMware.Vim.VirtualMachineConfigSpec $vmcs.BootOptions = $vmbo ($_ | Get-View).ReconfigVM($vmcs) if($PassThru) { Get-VM $_ } } else { Write-Error "Wrong object type. Only virtual machine objects are allowed." } } # Set VM to boot from BIOS on first boot so that we can disable the floppy/serial/parallel ports etc. Get-VM $vmName1 | Set-VMBIOSSetup -PassThru # Set any additional VM params that are useful # Based on: https://github.com/rabbitofdeath/vm-powershell/blob/master/vsphere5_hardening.ps1 $ExtraOptions = @{ # Creates /dev/disk/by-id in Linux "disk.EnableUUID"="true"; # Disable virtual disk shrinking "isolation.tools.diskShrink.disable"="true"; "isolation.tools.diskWiper.disable"="true"; # 5.0 Prevent device removal-connection-modification of devices "isolation.tools.setOption.disable"="true"; "isolation.device.connectable.disable"="true"; "isolation.device.edit.disable"="true"; # Disable copy/paste operations to/from VM "isolation.tools.copy.disable"="true"; "isolation.tools.paste.disable"="true"; "isolation.tools.dnd.disable"="false"; "isolation.tools.setGUIOptions.enable"="false"; # Disable VMCI "vmci0.unrestricted"="false"; # Log Management "tools.setInfo.sizeLimit"="1048576"; "log.keepOld"="10"; "log.rotateSize"="100000"; # Limit console connections - choose how many consoles are allowed #"RemoteDisplay.maxConnections"="1"; "RemoteDisplay.maxConnections"="2"; # 5.0 Disable serial port "serial0.present"="false"; # 5.0 Disable parallel port "parallel0.present"="false"; # 5.0 Disable USB "usb.present"="false"; # Disable VIX Messaging from VM "isolation.tools.vixMessage.disable"="true"; # ESXi 5.x+ "guest.command.enabled"="false"; # ESXi 4.x # Disable logging #"logging"="false"; # 5.0 Disable HGFS file transfers [automated VMTools Upgrade] "isolation.tools.hgfsServerSet.disable"="false"; # Disable tools auto-install; must be manually initiated. "isolation.tools.autoInstall.disable"="false"; # 5.0 Disable VM Monitor Control - VM not aware of hypervisor #"isolation.monitor.control.disable"="true"; # 5.0 Do not send host information to guests "tools.guestlib.enableHostInfo"="false"; } # build our configspec using the hashtable from above. $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec # note we have to call the GetEnumerator before we can iterate through Foreach ($Option in $ExtraOptions.GetEnumerator()) { $OptionValue = New-Object VMware.Vim.optionvalue $OptionValue.Key = $Option.Key $OptionValue.Value = $Option.Value $vmConfigSpec.extraconfig += $OptionValue } # Change our VM settings $vmview=get-vm $vmName1 | get-view $vmview.ReconfigVM_Task($vmConfigSpec)
PowerShellCorpus/GithubGist/mkropat_85ac76202a72839d955f_raw_1e0244a89dccf43a65368e6e14c0b3ad12bbc221_set-ie-proxy.ps1
mkropat_85ac76202a72839d955f_raw_1e0244a89dccf43a65368e6e14c0b3ad12bbc221_set-ie-proxy.ps1
$setProxy = { param($proxy) Set-Location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' Set-ItemProperty . ProxyServer $proxy Set-ItemProperty . ProxyOverride '<local>' Set-ItemProperty . ProxyEnable 1 } # You can run $setProxy as another user like so: # # Start-Job -Credential (Get-Credential) -ScriptBlock $setProxy -ArgumentList '1.2.3.4:1337'
PowerShellCorpus/GithubGist/jakeballard_9019658_raw_375bbfe9e572402826e5fe6ffef92d2528069c11_Get-PrintSpoolerCrashes.ps1
jakeballard_9019658_raw_375bbfe9e572402826e5fe6ffef92d2528069c11_Get-PrintSpoolerCrashes.ps1
param( $ComputerList = ("$env:COMPUTERNAME"), $Cred = $(Get-Credential "$env:USERDOMAIN\$env:USERNAME") ) $Result1 = Invoke-Command -ComputerName $ComputerList -Credential $Cred -ScriptBlock { $Win32_OperatingSystem = Get-WmiObject -Class 'Win32_OperatingSystem' $LastBootUpTime = $Win32_OperatingSystem.ConvertToDateTime($Win32_OperatingSystem.LastBootUpTime) $Win32_PrinterDriver = get-wmiobject -class 'Win32_PrinterDriver' -namespace 'root\CIMV2' $PrinterDriverFiles = ForEach ($Printer in $Win32_PrinterDriver) { $Printer.DependentFiles | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } if ($Printer.ConfigFile) { $Printer.ConfigFile | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } } if ($Printer.DataFile) { $Printer.DataFile | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } } if ($Printer.DriverPath) { $Printer.DriverPath | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } } if ($Printer.FilePath) { $Printer.FilePath | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } } if ($Printer.HelpFile) { $Printer.HelpFile | ForEach-Object { [pscustomobject] @{ "Printer" = $Printer.Name "FullName" = $_ "Name" = Split-Path -Path $_ -Leaf } } } } Get-WinEvent -FilterHashtable @{logname="application"; providername="Application Error"; data="spoolsv.exe","PrintIsolationHost.exe","splwow64.exe"} ` | where {$_.timecreated -ge $LastBootUpTime} ` | Select-Object ` TimeCreated, ` @{Name='ProcessName';Expression={$_.Properties[0].Value}}, ` @{Name='FaultingDLL';Expression={$_.Properties[11].Value}}, ` @{Name='Printer_Driver';Expression={$FaultingDLL = $_.Properties[11].Value; $($PrinterDriverFiles | where {($_.FullName -eq $FaultingDLL) -or ($_.Name -eq $FaultingDLL)}).Printer}} } | Sort-Object TimeCreated -Descending $Result1 | Out-GridView -Title "Print Spooler Crashes - Since Last Boot" $Result2 = Invoke-Command -ComputerName $ComputerList -Credential $Cred -ScriptBlock { $null = New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS Get-ChildItem hku: | where name -NotLike '*_Classes' | ForEach-Object { if ($(test-path $( Join-Path $_ 'Printers\Connections'))) { $UserName = (New-Object System.Security.Principal.SecurityIdentifier($_.PSChildName)).Translate( [System.Security.Principal.NTAccount]) Get-ChildItem $( Join-Path $_ 'Printers\Connections' ) | select -expandproperty PSChildName | ForEach-Object { [pscustomobject] @{ 'User' = $UserName 'Printer' = $(Join-path $_.Split(',')[2].ToUpper() $_.Split(',')[3].ToUpper()) 'Driver' = (gwmi -ComputerName $($_.Split(',')[2]) -query "Select DriverName FROM Win32_Printer WHERE DeviceID='$($_.Split(',')[3])'").DriverName } } } } } $Result2 | Out-GridView -Title "Connected Printers"
PowerShellCorpus/GithubGist/Mierdin_11362400_raw_941433296b024d4d5f56c2f361134cb0bf1c10e4_StorageTrueUp.ps1
Mierdin_11362400_raw_941433296b024d4d5f56c2f361134cb0bf1c10e4_StorageTrueUp.ps1
<# Name: StorageTrueUp.ps1 Author: Matthew Oswalt Created: 4/27/2014 Description: Storage True-Up Currently only tested and verified with the following platforms: Hardware Platforms: *NetApp Release 8.2P2 Cluster-Mode *Cisco UCSM Platform Emulator 2.2(1b)PE1 *Nexus 5596UP running 6.0(2)N2(2) Minimum Software Versions: *Powershell 3.0 *Cisco PowerTool 1.1.1.0 *Netapp PowerShell Toolkit 3.0.0.90 #> Import-Module CiscoUcsPs Import-Module DataONTAP #region VARs #Netapp Variables $NAipAddr = "10.12.0.70" $NAusername = "admin" $NApassword = "Password1!" $NAportset = "fcoe_pset_1" $NAvserver = "VSERVER_TEST" $NAbootVol = "/vol/BOOT_VOL/" #Needs to be of this format, including the forward slashes. LUN will be appended without any slashes #UCS Variables $UCSipAddr = "192.168.17.159" $UCSusername = "config" $UCSpassword = "config" $UCSbootpolicy = "BFS-ESX" $organization = "ORG_TEST" #Place the location $ConfigFile = "C:\temp\config.txt" #endregion #region Establish Connections #Connect to Netapp, suppressing prompt $NASecPass = ConvertTo-SecureString $NApassword -AsPlainText -Force $NAcred = New-Object System.Management.Automation.PSCredential($NAusername, $NASecPass) Connect-NcController $NAipAddr -credential $NAcred #Connect to UCSM, suppressing prompt $UCSSecPass = ConvertTo-SecureString $UCSpassword -AsPlainText -Force $ucsmCreds = New-Object System.Management.Automation.PSCredential($UCSusername, $UCSSecPass) Disconnect-Ucs Connect-Ucs $UCSipAddr -Credential $ucsmCreds #endregion <# .SYNOPSIS "Trues up" the BFS configuration on a Netapp array to work with Cisco UCS. .DESCRIPTION Reaches into a Cisco UCS Instance, and iterates through every service profile, creating Netapp initiator groups for each one, and then putting each service profile's vHBA's WWPNs in the respective initiator groups. It can run whether or not the various LUNs or IGROUPs exist - it will "true up" the configuration as necessary. .EXAMPLE Simply run - just run the cmdlet Update-NetappCiscoBFS #> function Update-NetappCiscoBFS { #Get SPs, not templates $serviceProfiles = Get-UcsServiceProfile -Type instance -Org $organization #Iterate through Service Profiles, creating boot luns and igroups, mapping as you go foreach ($SP in $serviceProfiles) { #create path to LUN $LUNPath = $NAbootVol + $SP.name + "_boot" #check to see if lun by this path already exists if (Get-NcLun -path $LUNPath -Vserver $NAvserver) { Write-Host "LUN already exists: " $SP.Name } Else { #Need to finish flushing out this line New-NcLun -path $LUNPath -Size 10g -OsType vmware -Unreserved -vserver $NAvserver } #Populate array with existing vHBAs on this service profile $vHBAs = $SP | Get-UcsVhba #check to see if igroup by this name already exists if (Get-NcIgroup -name $SP.Name) { Write-Host "igroup already exists: " $SP.Name } Else { #Create the igroup first Write-Host "Creating igroup named " + $SP.Name $newIgroup = New-NcIgroup -name $sp.Name -protocol fcp -portset $NAportset -type VMware -vserver $NAvserver #Iterate through each vHBA, and add each WWPN to this igroup foreach ($vHBA in $vHBAs) { Write-Host "Adding WWPN " $vHBA.Addr Add-NcIgroupInitiator -Initiator $vHBA.Addr -Name $SP.Name -vserver $NAvserver } #Adds the mapping at the tail end. Kept inside this if statement so it only ran on igroups that were created by this script, not existing ones Add-NcLunMap -Path $LUNPath -InitiatorGroup $newIgroup.Name -vserver $NAvserver } } } <# .SYNOPSIS Creates a Cisco NX-OS configuration snippet for zoning and aliases .DESCRIPTION This script will generate fibre channel configuration for NX-OS based on an existing Cisco UCS configuration. Zones will be created on a one-to-many basis. --Each zone will contain a single WWPN representing either the A-side or B-side vHBA of a UCS service profile. --Each zone will also contain up to two additional target WWPNs, derived from the boot policy attached to the service profile. --Alternatively, the "FabBWWPNs and FabBWWPNs" arguments may be supplied if you wish to bypass this feature and provide arrays containing your desired targers (i.e. if Boot-from-SAN is not being used) .PARAMETER FabAVSAN Provide a string array of all WWPNs on fabric A that you wish to include as targets in each zone. .PARAMETER FabBWWPNs Provide a string array of all WWPNs on fabric B that you wish to include as targets in each zone. .PARAMETER SPfilter Provide the name of a service profile template here to only include service profiles spawned from that template in the zoning configuration. If you wish to include all service profiles, omit this argument. .PARAMETER $FabATargets A simple string array containing all WWPNs you wish to use as targets in each zone for Fabric A. This argument is optional, but if supplied, this script will not derive targets from Cisco UCS, and instead rely on this supplied array. This argument is optional, but if supplied: --This script will not derive targets from Cisco UCS, and instead rely on this supplied array. --You must also provide the sister argument, FabBTargets. If you only supply one of these, an error will be raised when the script attempts to iterate through these. .PARAMETER $FabBTargets A simple string array containing all WWPNs you wish to use as targets in each zone for Fabric B. This argument is optional, but if supplied: --This script will not derive targets from Cisco UCS, and instead rely on this supplied array. --You must also provide the sister argument, FabATargets. If you only supply one of these, an error will be raised when the script attempts to iterate through these. .EXAMPLE Generate configuration based on existing Boot-from-SAN policy in UCS. Generate-FCSwitchConfig -FabAVSAN "10" -FabBVSAN "20" .EXAMPLE Generate configuration based on existing Boot-from-SAN policy in UCS, but only for service profiles that were created from the referenced service profile template Generate-FCSwitchConfig -FabAVSAN "10" -FabBVSAN "20" -SPfilter "SPT-ESX" .EXAMPLE Generate configuration, only referencing UCS to create initiator WWPN entry. Targets derived from supplied arguments. Generate-FCSwitchConfig -FabAVSAN "10" -FabBVSAN "20" -FabATargets ["50:00:00:00:00:AA:00:01", "50:00:00:00:00:AA:00:02"] -FabBTargets ["50:00:00:00:00:BB:00:01", "50:00:00:00:00:BB:00:02"] #> function Generate-FCSwitchConfig { param( [parameter(Mandatory=${true})][string]$FabAVSAN, [parameter(Mandatory=${true})][string]$FabBVSAN, [parameter(Mandatory=${false})][string]$SPfilter, [parameter(Mandatory=${false})][string[]]$FabATargets, [parameter(Mandatory=${false})][string[]]$FabBTargets ) #Reset VSANTable dictionary back to default $VSANTable = $null $VSANTable = @{} #This dictionary will keep our Fabric-to-VSAN mapping nice and clean. The "key" is the fabric ID, and the value is the corresponding VSAN ID. $VSANTable.Add("A", $FabAVSAN) $VSANTable.Add("B", $FabBVSAN) #Pull down list of FcpAdapters from filer - unused right now, may use this later as a third method of deriving targets #$targetAdapters = Get-NcFcpPortName -Vserver $NAvserver if ($SPfilter) { #If the optional $SPfilter argument was provided, use it to only retrieve service profiles created from that SP Template $serviceProfiles = Get-UcsServiceProfile -Type instance -Org $organization -SrcTemplName $SPfilter } else { #No SPfilter argument was provided - retrieve all service profile instances $serviceProfiles = Get-UcsServiceProfile -Type instance -Org $organization } New-Item -ItemType file $ConfigFile -Force foreach ($VSANKey in $VSANTable.Keys | Sort-Object) { $WWPNTable = $null $WWPNTable = @{} #Iterate through Service Profiles, creating boot luns and igroups, mapping as you go foreach ($SP in $serviceProfiles) { #Populate array with existing vHBAs on this service profile $vHBAs = $SP | Get-UcsVhba #Iterate through each vHBA, and add each WWPN to this igroup foreach ($vHBA in $vHBAs) { #Adding WWPN and name to hash table for later config generation if($vHBA.SwitchId -eq $VSANKey) { $WWPNTable.Add($SP.Name + "_" + $vHBA.Name, $vHBA.Addr) } } } Add-Content $ConfigFile "!Fabric $VSANKey Configuration" #Create Device Alias Database configuration (matches SP+VHBA combo to WWPN) Add-Content $ConfigFile "device-alias database" foreach ($WWPNKey in $WWPNTable.Keys | Sort-Object) { $configLine = (" device-alias name " + $WWPNKey + " pwwn " + $WWPNTable[$WWPNKey]) Add-Content $ConfigFile $configLine } Add-Content $ConfigFile "device-alias commit" Add-Content $ConfigFile "!" #create zones foreach ($WWPNKey in $WWPNTable.Keys | Sort-Object) { Add-Content $ConfigFile ("zone name " + $WWPNKey + "_TO_NTAP vsan " + $VSANTable[$VSANKey]) Add-Content $ConfigFile (" member pwwn " + $WWPNTable[$WWPNKey]) #If the user decided to provide their own targets, use this info instead of pulling from UCS boot policy if ($FabATargets -is [system.array] -and $FabBTargets -is [system.array]){ if ($VSANKey -eq "A") { foreach ($target in $FabATargets) { Add-Content $ConfigFile (" member pwwn " + $target) } } else { foreach ($target in $FabBTargets) { Add-Content $ConfigFile (" member pwwn " + $target) } } } else { #Runs if the user decided to pull targets from each service profile's boot policy. If such a policy is not connected to a service profile, this portion will fail. $spname = $WWPNKey $spname = $spname.substring(0, $spname.indexof('_')) #Ugly, but best way to get SP name out of SP_VHBA combo right now. May revise to keep SP and VHBA in separate params later, but right now it keeps them together nicely $thisSP = Get-UcsServiceProfile -Name $spname $bootpolicy = Get-UcsBootPolicy -Name $thisSP.BootPolicyName #Ugly but necessary. Don't believe there's any other way to refer to boot policy right now if ($VSANKey -eq "A") { $targets = $bootpolicy | Get-UcsLsbootSan | Get-UcsLsbootSanCatSanImage -Type "primary" | Get-UcsLsbootSanCatSanImagePath $targets = $targets.Wwn } else { $targets = $bootpolicy | Get-UcsLsbootSan | Get-UcsLsbootSanCatSanImage -Type "secondary" | Get-UcsLsbootSanCatSanImagePath $targets = $targets.Wwn } foreach ($target in $targets) { Add-Content $ConfigFile (" member pwwn " + $target) } } } Add-Content $ConfigFile "!" #create zoneset Add-Content $ConfigFile ("zoneset name ZONESET_VSAN_" + $VSANTable[$VSANKey] + " vsan " + $VSANTable[$VSANKey]) #add zones to zoneset foreach ($WWPNKey in $WWPNTable.Keys | Sort-Object) { Add-Content $ConfigFile (" member " + $WWPNKey) } Add-Content $ConfigFile "!" Add-Content $ConfigFile ("zoneset activate name ZONESET_VSAN_" + $VSANTable[$VSANKey] + " vsan " + $VSANTable[$VSANKey]) Add-Content $ConfigFile "!" } } Update-NetappCiscoBFS #Generate-FCSwitchConfig -FabAVSAN "10" -FabBVSAN "11" -FabATargets "50:00:00:00:00:AA:00:01", "50:00:00:00:00:AA:00:02" -FabBTargets "50:00:00:00:00:BB:00:01", "50:00:00:00:00:BB:00:02" Generate-FCSwitchConfig -FabAVSAN "10" -FabBVSAN "11"
PowerShellCorpus/GithubGist/rjattrill_3057564_raw_060dd107a2616d5c70cc3c38210fe7cc487649b7_TestPort.ps1
rjattrill_3057564_raw_060dd107a2616d5c70cc3c38210fe7cc487649b7_TestPort.ps1
1443 | % { echo ((new-object Net.Sockets.TcpClient).Connect("192.168.75.11",$_)) "server listening on TCP port $ _" }
PowerShellCorpus/GithubGist/thlorenz_525571_raw_e35b39187593ce2f7d4f23cc4fd117e9b1be837e_git_svn_ps_prompt.ps1
thlorenz_525571_raw_e35b39187593ce2f7d4f23cc4fd117e9b1be837e_git_svn_ps_prompt.ps1
# See http://gist.github.com/180853 for gitutils.ps1. . (Resolve-Path ~/Documents/WindowsPowershell/gitutils.ps1) function prompt { writeUserLocation if (isCurrentDirectoryGitRepository) { writeGitInfo } elseif(Test-Path .svn) { writeSvnInfo } Write-Host("`n$") -nonewline -foregroundcolor Green return " " } function writeUserLocation { Write-Host($pwd) -nonewline -foregroundcolor Green } function writeShortenedUserLocation { $path = "" $pathbits = ([string]$pwd).split("\", [System.StringSplitOptions]::RemoveEmptyEntries) if($pathbits.length -eq 1) { $path = $pathbits[0] + "\" } else { $path = $pathbits[$pathbits.length - 1] } $userLocation = $env:username + '@' + [System.Environment]::MachineName + ' ../' + $path $host.UI.RawUi.WindowTitle = $userLocation Write-Host($userLocation) -nonewline -foregroundcolor Green } function writeGitInfo { $status = gitStatus $currentBranch = $status["branch"] Write-Host(' [') -nonewline -foregroundcolor Yellow if ($status["ahead"] -eq $FALSE) { # We are not ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Cyan } else { # We are ahead of origin Write-Host($currentBranch) -nonewline -foregroundcolor Red } Write-Host(' +' + $status["added"]) -nonewline -foregroundcolor Yellow Write-Host(' ~' + $status["modified"]) -nonewline -foregroundcolor Yellow Write-Host(' -' + $status["deleted"]) -nonewline -foregroundcolor Yellow if ($status["untracked"] -ne $FALSE) { Write-Host(' !') -nonewline -foregroundcolor Yellow } Write-Host(']') -nonewline -foregroundcolor Yellow } function writeSvnInfo { $untracked=$deleted=$added=$modified=0 switch -regex (svn st) { "^\?" {$untracked+=1} "^D" {$deleted+=1} "^A" {$added+=1} "^M" {$modified+=1} } $prompt_string = " [svn +$added ~$modified -$deleted" if ($untracked -eq 0) { $prompt_string += "]" } else { $prompt_string += " !]" } Write-Host ($prompt_string) -nonewline -foregroundcolor yellow }
PowerShellCorpus/GithubGist/mrdrbob_4111019_raw_2cae2e025b170cde39480e2216e052d075191530_Script-Database.ps1
mrdrbob_4111019_raw_2cae2e025b170cde39480e2216e052d075191530_Script-Database.ps1
function global:Script-Database([string]$server, [string]$dbname, [string]$filename) { add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" | out-null add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" | out-null add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" | out-null $SMOserver = New-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $server $db = $SMOserver.databases[$dbname] $opts = New-Object ('Microsoft.SqlServer.Management.Smo.ScriptingOptions') $opts.AppendToFile = $True $opts.ScriptSchema = $True $opts.ScriptData = $True $opts.ScriptDrops = $False $opts.TargetServerVersion = [Microsoft.SqlServer.Management.Smo.SqlServerVersion]::Version105 $opts.Triggers = $True $opts.ClusteredIndexes = $True $opts.NonClusteredIndexes = $True $opts.Indexes = $True $opts.FullTextIndexes = $True $opts.DriAll = $True $opts.ToFileOnly = $True $opts.FileName = $filename echo '' | Out-File $opts.FileName foreach($tb in $db.Tables | where {!($_.IsSystemObject)}) { echo $tb.Name $tb.EnumScript($opts) } }
PowerShellCorpus/GithubGist/MichaelPaulukonis_72a03ad6bc3df5492490_raw_873ea153d55cf93e1c7fc9aaedb7280e30ce3899_copy.setup.ps1
MichaelPaulukonis_72a03ad6bc3df5492490_raw_873ea153d55cf93e1c7fc9aaedb7280e30ce3899_copy.setup.ps1
$sourceDir = "\\path\to\source\" $destDir = "\\path\to\dest\" # NOTE: this WILL overwrite existing docs (unless open) Copy-Item $sourceDir*.docx $destDir # delete (hidden, leftover) office temp files # usually caused by killing processes Remove-Item ~*.docx -force
PowerShellCorpus/GithubGist/aggieben_3643522_raw_34a05e3668642b1a3765b75bbc009c50d83e245d_TestEmail.ps1
aggieben_3643522_raw_34a05e3668642b1a3765b75bbc009c50d83e245d_TestEmail.ps1
$mail = New-Object System.Net.Mail.SmtpClient("smtp.geusnet.com", 25) $mail.Send("aggieben@gmail.com", "bcollins@praecoemailtest.cloudap...", "testing kato", "blah")
PowerShellCorpus/GithubGist/sumhat_d2a6d491e0df5943cead_raw_85326b673ec950d1063fbdc69e4d863cd7288263_gistfile1.ps1
sumhat_d2a6d491e0df5943cead_raw_85326b673ec950d1063fbdc69e4d863cd7288263_gistfile1.ps1
Function Get-Data { Param ( [int] $data = -1 ) return $data; }
PowerShellCorpus/GithubGist/andreaswasita_bb862f9fbcfa9c305236_raw_fa46c303d5ba6a6cdfb07c24cba446b3589951e8_New-AzureVMStaticDIP.ps1
andreaswasita_bb862f9fbcfa9c305236_raw_fa46c303d5ba6a6cdfb07c24cba446b3589951e8_New-AzureVMStaticDIP.ps1
cls Import-module Azure $subscription = Read-Host -Prompt 'Microsoft Azure Subscription:' $storage = Read-Host -Prompt 'Storage Account Name:' Set-azuresubscription -SubscriptionName $subscription -CurrentStorageAccountName $storage #Get the latest Windows Server 2012 Datacenter image $images = Get-AzureVMImage ` | where { $_.ImageFamily -eq “Windows Server 2012 Datacenter” } ` | Sort-Object -Descending -Property PublishedDate $latestImage = $images[0] $latestImage $myimage = Read-Host -Prompt 'Azure Image Name:' $service = Read-Host -Prompt 'Azure Service Name:' $name = Read-Host -Prompt 'Azure VM Name:' $instance = Read-Host -Prompt 'Instance Size:' $username = Read-Host -Prompt 'Admin User Name:' $password = Read-Host -Prompt 'Password:' $VIP = Read-Host -Prompt 'Reserved VIP Name:' $location = Read-Host -Prompt 'Azure Location:' $myVM = New-AzureVMConfig -Name $name -InstanceSize $instance -ImageName $myimage -DiskLabel "OS" ` | Add-AzureProvisioningConfig -Windows -Password $password -AdminUsername $username -DisableAutomaticUpdates New-AzureVM -ServiceName $service -VMs $myVM -ReservedIPName $VIP -Location $location
PowerShellCorpus/GithubGist/rdingwall_2953197_raw_773fba3ef6f628e512a699301da6e003e21ba7c4_StripAuthorXMLComments.ps1
rdingwall_2953197_raw_773fba3ef6f628e512a699301da6e003e21ba7c4_StripAuthorXMLComments.ps1
# Powershell to recursively strip all <author> XML comments out of *.cs files. # See 'collective code ownership' for why we do not want to encourage individual # developers claiming/marking sections of code # http://jamesshore.com/Agile-Book/collective_code_ownership.html. # # (And if for some reason you really want to know who worked on a class, SVN # blame will give you a MUCH better picture anyway). dir -recurse -filter *.cs $src | foreach ($_) { $file = $_.fullname echo $file (get-content $file) | where {$_ -notmatch "^.*\///.*\<author\>.*$" } | out-file $file }
PowerShellCorpus/GithubGist/wictorwilen_d3c082852a81b051ca07_raw_7317262d24ab2849a741fb53f0fd34cbb4fc667f_gistfile1.ps1
wictorwilen_d3c082852a81b051ca07_raw_7317262d24ab2849a741fb53f0fd34cbb4fc667f_gistfile1.ps1
# Copy the current entry to a new (called No Hyper-V) bcdedit /copy {current} /d "No Hyper-V" # Note the Id from the command result above bcdedit /set <ID> hypervisorlaunchtype off # Set the default one to the newly created entry bcdedit /default /ID <ID>
PowerShellCorpus/GithubGist/GuruAnt_7559974_raw_5b736d21aed2fdee3860d5b0d5b1f7524f625189_Invoke-SubversionScript.ps1
GuruAnt_7559974_raw_5b736d21aed2fdee3860d5b0d5b1f7524f625189_Invoke-SubversionScript.ps1
Function Invoke-SubversionScript { <# .Synopsis Runs a script directly from Subversion. .Description Given a valid Subversion URL and credentials (Basic authentication) invokes the script on the local machine. .Parameter Url The URL of the script. Should be a valid URL, and end in PS1 .Parameter Username The username used to access Subversion (Basic authentication). .Parameter Password The password for the account used to access Subversion (Basic authentication). .Example Runs the script at the specified URL. Invoke-SubversionScript -Url "http://subversion/svn/repository/folder/SCOM2012Functions.ps1" -Username "Domain\Username" -Password "Password1" .Notes Ben Neise 18/11/2013 #> Param ( [ValidateScript({$_ -Match '^(?:http)(?:s)?(?:://)(?:www\.)?(?:[^\ ]*).ps1$'})] [Parameter(Mandatory=$true,Position=0)] [String] $Url, [Parameter(Mandatory=$false,Position=1)] [String] $Username = "", [Parameter(Mandatory=$false,Position=2)] [String] $Password = "" ) Process { $strAuthentication = 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Username + ":" + $Password )) $objWebClient = New-Object System.Net.WebClient $objWebClient.Headers.Add("Content-Type", "application/xml") $objWebClient.Headers.Add("Accept", "application/xml") $objWebClient.Headers.Add("Authorization", $strAuthentication ) Try { $strCommand = $objWebClient.DownloadString($Url) } Catch { Write-Error -Message "Can't read URL" Exit } } End { Invoke-Expression -Command $strCommand } }
PowerShellCorpus/GithubGist/xinmyname_917733_raw_431c62252610c65332b4b73ed75bc51264fb9c8f_set-svnignore.ps1
xinmyname_917733_raw_431c62252610c65332b4b73ed75bc51264fb9c8f_set-svnignore.ps1
svn -R --depth immediates propset svn:ignore -F <path-to-svn-ignore-txt> <path-to-svn-repository>
PowerShellCorpus/GithubGist/Sakuramochi_5227075_raw_96ed0b55c496c1c9b76c1d534eed860ac92f2f1b_webclient_downloaddata.ps1
Sakuramochi_5227075_raw_96ed0b55c496c1c9b76c1d534eed860ac92f2f1b_webclient_downloaddata.ps1
# Yahoo Japanへお遣いにいってトピックスをもぎってくるスクリプト # 言語 # Windows Powershell # 書式 # test_webclient # オプション # なし $access_url = "http://www.yahoo.co.jp" # ここからwebclient方式 $client = New-Object System.Net.WebClient $enc = [Text.Encoding]::GetEncoding("utf-8") $html_data = $enc.GetString( $client.DownloadData( $access_url ) ) Write-host "====getvalues====" $c_RH = $client.ResponseHeaders "Connection" + "`t[" + $c_RH.GetValues("Connection") + "]" "Pragma" + "`t`t[" + $c_RH.GetValues("Pragma") + "]" "Transfer-Encoding" + "[" + $c_RH.GetValues("Transfer-Encoding") + "]" "Cache-Control" + "`t[" + $c_RH.GetValues("Cache-Control") + "]" "Content-Type" + "`t[" + $c_RH.GetValues("Content-Type") + "]" "Date" + "`t`t`t[" + $c_RH.GetValues("Date") + "]" "Expires" + "`t`t[" + $c_RH.GetValues("Expires") + "]" "Server" + "`t`t[" + $c_RH.GetValues("Server") + "]" Write-host "========" Write-Debug $html_data # ここまでwebclient方式 # パターンマッチでのデータ抽出 if ($html_data -match "<strong>トピックス</strong>(.*?)<table (.*?)>(.*?)</table>") { # トピックテーブル取得 $topics_table = $Matches[3] Write-Debug $topics_table # マッチしたパターンをすべて取得 $regex = [regex] "<td>(.*?)</td>" $topics = $regex.Matches( $topics_table ) Write-Host "Yahoo Japan トピックス " (Get-Date -Format "yyyy年M月dd日") foreach ($_ in $topics) { # タグの削除 $_.value -replace "<(.*?)>", "" } }
PowerShellCorpus/GithubGist/objectx_5781757_raw_0b3cbd584aa770dfb41187b7806c966f71850436_indynize.ps1
objectx_5781757_raw_0b3cbd584aa770dfb41187b7806c966f71850436_indynize.ps1
# # indynize.ps1: InvokeDynamic enabler for Groovy on windows. # # AUTHOR(S): Masashi Fujita <objectxtreme@gmail.com> # param ([switch]$WhatIf = $false, [switch]$Verbose = $false) $groovydir = Split-Path -parent $MyInvocation.MyCommand.Path | Split-Path -parent $libdir = Join-Path $groovydir "lib" $orig_libdir = "$libdir.orig" $indy_dir = Join-Path $groovydir "indy" if (-not $(Test-Path $orig_libdir)) { Move-Item -WhatIf:$WhatIf -Verbose:$Verbose $libdir $orig_libdir } else { Remove-Item -WhatIf:$WhatIf -Verbose:$Verbose -Recurse -Force $libdir } $null = New-Item -ItemType Directory -WhatIf:$WhatIf -Verbose:$Verbose $libdir foreach ($indy in Get-ChildItem "$indy_dir\*.jar") { $t = $(Split-Path -leaf $indy) -replace "-indy.jar",".jar" Copy-Item -WhatIf:$WhatIf -Verbose:$Verbose $indy $(Join-Path $libdir $t) } foreach ($orig in Get-ChildItem "$orig_libdir\*.jar") { $dst = Join-Path $libdir $(Split-Path -leaf $orig) if (Test-Path $dst) { if ($Verbose) { Write-Host -ForegroundColor yellow "Skip copying $orig" } } else { Copy-Item -WhatIf:$WhatIf -Verbose:$Verbose $orig $dst } } exit 0
PowerShellCorpus/GithubGist/stknohg_5d8f6c4c250a5545c696_raw_4d19632bee9591679230ec0a88c8c1954f925f8f_pronama_calendar.ps1
stknohg_5d8f6c4c250a5545c696_raw_4d19632bee9591679230ec0a88c8c1954f925f8f_pronama_calendar.ps1
# # プロ生ちゃん #カレンダープログラミング プチコンテスト用カレンダーPowerShell版 # 日曜始まりの当月のカレンダーを表示します。 # 土曜日は青色、日曜日は赤色で表示されます。 # $Today = (Get-Date).Date; $Year = $Today.Year; $Month = $Today.Month; $CharWidth = 2; $SpaceWidth = 1; $DefaultColor= 'White'; Write-Host ( "{0:yyyy/MM}" -F $Today).PadLeft(($CharWidth * 7 + $SpaceWidth * 6) / 2 + 4 ) -ForegroundColor:$DefaultColor; Write-Host "".PadLeft(($CharWidth + $SpaceWidth) * (Get-Date -Year $Year -Month $Month -Day 1).DayOfWeek) -NoNewline; 1..[DateTime]::DaysInMonth($Year, $Month) | ForEach-Object { $Params = @{ 'SpaceWidth' = $SpaceWidth; 'NoNewLine' = $true; 'ForeColor' = $DefaultColor; } Switch ( (Get-Date -Year $Year -Month $Month -Day $_).DayOfWeek ) { Saturday { $Params.SpaceWidth = 0; $Params.NoNewLine = $false; $Params.ForeColor = 'Blue'; } Sunday { $Params.SpaceWidth = $SpaceWidth; $Params.NoNewLine = $true; $Params.ForeColor = 'Red'; } Default { $Params.SpaceWidth = $SpaceWidth; $Params.NoNewLine = $true; $Params.ForeColor = $DefaultColor; } } Write-Host ("{0,$CharWidth}" -F $_ ).PadRight($CharWidth + $Params.SpaceWidth) -NoNewline:$Params.NoNewLine -ForegroundColor:$Params.ForeColor; } Write-Host -NoNewline:(!$Params.NoNewLine);
PowerShellCorpus/GithubGist/wiking-at_47da5610e895e8b51aae_raw_516c8d1f935d4ed448fceda877203261b35be5de_migrate-inidb-to-extdb.ps1
wiking-at_47da5610e895e8b51aae_raw_516c8d1f935d4ed448fceda877203261b35be5de_migrate-inidb-to-extdb.ps1
$VerbosePreference = "SilentlyContinue" $ErrorActionPreference= 'silentlycontinue' Function Get-IniContent { <# .Synopsis Gets the content of an INI file .Description Gets the content of an INI file and returns it as a hashtable .Notes Author : Oliver Lipkau <oliver@lipkau.net> Blog : http://oliver.lipkau.net/blog/ Date : 2014/06/23 Version : 1.1 #Requires -Version 2.0 .Inputs System.String .Outputs System.Collections.Hashtable .Parameter FilePath Specifies the path to the input file. .Example $FileContent = Get-IniContent "C:\myinifile.ini" ----------- Description Saves the content of the c:\myinifile.ini in a hashtable called $FileContent .Example $inifilepath | $FileContent = Get-IniContent ----------- Description Gets the content of the ini file passed through the pipe into a hashtable called $FileContent .Example C:\PS>$FileContent = Get-IniContent "c:\settings.ini" C:\PS>$FileContent["Section"]["Key"] ----------- Description Returns the key "Key" of the section "Section" from the C:\settings.ini file .Link Out-IniFile #> [CmdletBinding()] Param( [ValidateNotNullOrEmpty()] [ValidateScript({(Test-Path $_) -and ((Get-Item $_).Extension -eq ".ini")})] [Parameter(ValueFromPipeline=$True,Mandatory=$True)] [string]$FilePath ) Begin {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"} Process { Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath" $ini = @{} switch -regex -file $FilePath { "^\[(.+)\]$" # Section { $section = $matches[1] $ini[$section] = @{} $CommentCount = 0 } "^(;.*)$" # Comment { if (!($section)) { $section = "No-Section" $ini[$section] = @{} } $value = $matches[1] $CommentCount = $CommentCount + 1 $name = "Comment" + $CommentCount $ini[$section][$name] = $value } "(.+?)\s*=\s*(.*)" # Key { if (!($section)) { $section = "No-Section" $ini[$section] = @{} } $name,$value = $matches[1..2] $ini[$section][$name] = $value } } Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $path" Return $ini } End {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"} } Function Get-BattlEyeGUID ([string]$steamID64) { Try { $beBytes = [System.Text.Encoding]::ASCII.GetBytes("BE") $idBytes = [System.BitConverter]::GetBytes([Int64]::Parse($steamID64)) $sb = New-Object System.Text.StringBuilder $md5 = New-Object System.Security.Cryptography.MD5CryptoServiceProvider $md5.ComputeHash($beBytes + $idBytes) | %{ [void] $sb.Append($_.ToString("x2")) } Return $sb.ToString() } Catch { Return "" } } Set-Location F:\Server1\db $filter='Bankmoney="' $query = (dir -include *.ini -recurse | select-string $filter ) $files = $query.Path | Get-Unique #loop for the sql-script Foreach ($file in $files) { $iniconent = Get-IniContent $file $uid = $iniconent["Playerinfo"]["UID"].Replace("`"","") $name = $iniconent["Playerinfo"][“Name”].Replace("`"","") $name2= '\"'+$name+'\"' $bankmoney = 0 [int]$bankmoney = ($iniconent["Playerinfo"][“BankMoney”]).Replace("`"","") $cmoney = 0 [int]$cmoney = ($iniconent["PlayerSave"][“Money”]).Replace("`"","") $fullmoney = $bankmoney + $cmoney $Beguid = Get-BattlEyeGUID $uid $Beguid2 = '\"'+$Beguid+'\"' if ($fullmoney -gt 10000) { #INSERT INTO `PlayerInfo` VALUES ('76561197964070402','\"Torndeco\"','WEST',0,'\"9d5a2241429129715f8b262f8fddb2e9\"'); "INSERT INTO `PlayerInfo` VALUES ('$uid','$name2','WEST',$fullmoney,'$Beguid2');" | Out-File D:\wiking\user-import-final.sql -Append #"UPDATE `PlayerInfo` SET BattlEyeGUID = '$Beguid2' WHERE UID ='$UID';" | Out-File D:\wiking\update-beguid.sql -Append } }
PowerShellCorpus/GithubGist/nskerl_8985365_raw_844828bb13f5c2946a2a33a8cc14e568cb3ddf0b_Deploy.ps1
nskerl_8985365_raw_844828bb13f5c2946a2a33a8cc14e568cb3ddf0b_Deploy.ps1
# the service params (Octo can/should pass these in) $serviceName = "MyCompany.MyService" $serviceExe = "MyService.exe" $fullPath = Join-Path -Path $OctopusPackageDirectoryPath -ChildPath $serviceExe # resolve service context $service = Get-Service MyCompany.MyService -ErrorAction SilentlyContinue if (! $service) { Write-Host "Installing as a new service..." & $fullPath "install" | Write-Host } else { Write-Host "Stopping service..." Stop-Service $service.Name -Force Write-Host "Reconfiguring service..." & "sc.exe" config $service.Name binPath= $fullPath start= demand | Write-Host Write-Host "Restarting service..." Start-Service $service.Name }
PowerShellCorpus/GithubGist/z0c_9780385_raw_9a274d024ecb45f6530497ce04d069c8dead669b_Psake-Build.ps1
z0c_9780385_raw_9a274d024ecb45f6530497ce04d069c8dead669b_Psake-Build.ps1
Properties { $baseDir = Resolve-Path . $project = Split-Path $baseDir -Leaf $artifactDir = "$baseDir\Build\Packages" $version = "1.0.1" } Task Default -Depends Build Task Clean { if (Test-Path "$baseDir\build") { Remove-Item "$baseDir\Build" -Recurse -Force -ErrorAction Stop } } Task RestorePackages { Exec { .\.nuget\NuGet restore -PackagesDirectory .\packages } } Task UpdateAssemblyInfo { (Get-ChildItem -Path $baseDir -Filter AssemblyInfo.cs -Recurse) | Foreach-Object { (Get-Content $_.FullName) | Foreach-Object { $_ -replace 'AssemblyVersion.+$',"AssemblyVersion(`"$version`")]" ` -replace 'AssemblyFileVersion.+$',"AssemblyFileVersion(`"$version`")]" } | Out-File $_.FullName } } Task Build -Depends Clean,RestorePackages,UpdateAssemblyInfo { Exec { msbuild "$project.sln" /p:Configuration=Release /t:"Clean,Build" } } Task Package -Depends Build { if (!(Test-Path($artifactDir))) { New-Item -ItemType Directory -Force -Path $artifactDir | Out-Null } Exec { .\.nuget\NuGet pack $baseDir\$project\$project.csproj -OutputDirectory $artifactDir -Properties Configuration=Release -Version $version } } Task Publish -Depends Package { Exec { .\.nuget\NuGet push "$artifactDir\$project.$version.nupkg" } }
PowerShellCorpus/GithubGist/ecki_6725537_raw_e46d1eea3ea0d97799c3a24061eee5aa3be42e24_openantrag-j2c.ps1
ecki_6725537_raw_e46d1eea3ea0d97799c3a24061eee5aa3be42e24_openantrag-j2c.ps1
# # This will format http://openantrag.de/api/proposal/ID/gettop/100 JSON files into CSV # $list = @() foreach($file in Get-ChildItem -Filter proposal-*.json .) { $list += ((Get-Content -Encoding UTF8 $file) -join "`n" | ConvertFrom-Json) } # Inspect Result graphically: PS1> $list | Out-GridView # Inspect Possible Columns: PS1> $list | Get-Member # See full Object: PS1> $list | fc -Depth 3 $list | select Key_Representation, Id, Title, CreatedAt, ID_CurrentProposalStep, IsAbuse | ConvertTo-Csv > file.csv
PowerShellCorpus/GithubGist/g-un--_4111309_raw_74b391943ee52db760f95108672d173c16101227_GroupRegexReplace.ps1
g-un--_4111309_raw_74b391943ee52db760f95108672d173c16101227_GroupRegexReplace.ps1
"Test 1.1.1.1" -replace "(?<first>\d+\.\d+\.\d+\.)\d+", '${1}2'
PowerShellCorpus/GithubGist/sunnyone_5610762_raw_97f8a2ea5ac432a642dd42c0421ea6244af1d972_screenshot.ps1
sunnyone_5610762_raw_97f8a2ea5ac432a642dd42c0421ea6244af1d972_screenshot.ps1
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") function Get-ScreenShot($Path, [Drawing.Rectangle]$Bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds) { $bmp = New-Object Drawing.Bitmap $bounds.width, $bounds.height $graphics = [Drawing.Graphics]::FromImage($bmp) $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size) $bmp.Save($Path, [Drawing.Imaging.ImageFormat]::Png) $graphics.Dispose() $bmp.Dispose() } #$bounds = [Drawing.Rectangle]::FromLTRB(0, 0, 1920, 1080) for ($i = 0; $i -lt 10; $i++) { $date = Get-Date -Format "yyyyMMddHHmmss" Get-ScreenShot "C:\temp\scrtest\screenshot-$date.png" echo $date sleep -Seconds 1 }
PowerShellCorpus/GithubGist/vgrem_9763560fc9a5fd273ea0_raw_055bfc3521daa623e3a928c0e993b7ef0ec70577_Print-SPOSites.ps1
vgrem_9763560fc9a5fd273ea0_raw_055bfc3521daa623e3a928c0e993b7ef0ec70577_Print-SPOSites.ps1
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" $AdminUrl = "https://tenant-admin.sharepoint.com/" $UserName = "username@tenant.onmicrosoft.com" $Password = "password" $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force $Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword $SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword) function Get-SPOWebs(){ param( $Url = $(throw "Please provide a Site Collection Url"), $Credential = $(throw "Please provide a Credentials") ) $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url) $context.Credentials = $Credential $web = $context.Web $context.Load($web) $context.Load($web.Webs) $context.ExecuteQuery() foreach($web in $web.Webs) { Get-SPOWebs -Url $web.Url -Credential $Credential $web } } #Retrieve all site collection infos Connect-SPOService -Url $AdminUrl -Credential $Credentials $sites = Get-SPOSite #Retrieve and print all sites foreach ($site in $sites) { Write-Host 'Site collection:' $site.Url $AllWebs = Get-SPOWebs -Url $site.Url -Credential $SPOCredentials $AllWebs | %{ Write-Host $_.Title } Write-Host '-----------------------------' } $AllWebs = Get-SPOWebs -Url 'https://tenant.sharepoint.com' -Credential $SPOCredentials $AllWebs | %{ Write-Host $_.Title }
PowerShellCorpus/GithubGist/jballe_5fdd11cdacd540781105_raw_a49f20f3da23dfc9b3c2577eeeaef804142a28db_install.ps1
jballe_5fdd11cdacd540781105_raw_a49f20f3da23dfc9b3c2577eeeaef804142a28db_install.ps1
#chocolatey (iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')))>$null 2>&1 # now install cinst javaruntime-preventasktoolbar cinst javaruntime cinst git cinst hg cinst microsoft-build-tools cinst Thoughtworks.Go.Server -source 'https://www.myget.org/F/jballe-chocolatey/' cinst Thoughtworks.Go.Agent -source 'https://www.myget.org/F/jballe-chocolatey/'
PowerShellCorpus/GithubGist/PaulStovell_b3e18ede1bf1cfe173b3_raw_b87b91c8b34fd80a823664f9063be29059b27196_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
PaulStovell_b3e18ede1bf1cfe173b3_raw_b87b91c8b34fd80a823664f9063be29059b27196_Octopus.Features.IISWebSite_BeforePostDeploy.ps1
## -------------------------------------------------------------------------------------- ## Configuration ## -------------------------------------------------------------------------------------- $isEnabled = $OctopusParameters["Octopus.Action.IISWebSite.CreateOrUpdateWebSite"] if (!$isEnabled -or ![Bool]::Parse($isEnabled)) { exit 0 } $WebSiteName = $OctopusParameters["Octopus.Action.IISWebSite.WebSiteName"] $ApplicationPoolName = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolName"] $bindingString = $OctopusParameters["Octopus.Action.IISWebSite.Bindings"] $appPoolFrameworkVersion = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolFrameworkVersion"] $webRoot = $OctopusParameters["Octopus.Action.IISWebSite.WebRoot"] $enableWindows = $OctopusParameters["Octopus.Action.IISWebSite.EnableWindowsAuthentication"] $enableBasic = $OctopusParameters["Octopus.Action.IISWebSite.EnableBasicAuthentication"] $enableAnonymous = $OctopusParameters["Octopus.Action.IISWebSite.EnableAnonymousAuthentication"] $applicationPoolIdentityType = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolIdentityType"] $applicationPoolUsername = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolUsername"] $applicationPoolPassword = $OctopusParameters["Octopus.Action.IISWebSite.ApplicationPoolPassword"] if (! $webRoot) { $webRoot = "." } $maxFailures = $OctopusParameters["Octopus.Action.IISWebSite.MaxRetryFailures"] if ($maxFailures -Match "^\d+$") { $maxFailures = [int]$maxFailures } else { $maxFailures = 5 } $sleepBetweenFailures = $OctopusParameters["Octopus.Action.IISWebSite.SleepBetweenRetryFailuresInSeconds"] if ($sleepBetweenFailures -Match "^\d+$") { $sleepBetweenFailures = [int]$sleepBetweenFailures } else { $sleepBetweenFailures = Get-Random -minimum 1 -maximum 4 } if ($sleepBetweenFailures -gt 60) { Write-Host "Invalid Sleep time between failures. Setting to max of 60 seconds" $sleepBetweenFailures = 60 } # Helper to run a block with a retry if things go wrong function Execute-WithRetry([ScriptBlock] $command) { $attemptCount = 0 $operationIncomplete = $true while ($operationIncomplete -and $attemptCount -lt $maxFailures) { $attemptCount = ($attemptCount + 1) if ($attemptCount -ge 2) { Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..." Start-Sleep -s $sleepBetweenFailures Write-Output "Retrying..." } try { & $command $operationIncomplete = $false } catch [System.Exception] { if ($attemptCount -lt ($maxFailures)) { Write-Output ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message) } else { throw } } } } $webRoot = (resolve-path $webRoot).ProviderPath $wsbindings = new-object System.Collections.ArrayList # Each binding string consists of a protocol/binding information (IP, port, hostname)/SSL thumbprint/enabled # Binding strings are pipe (|) separated to allow multiple to be specified $bindingString.Split("|") | foreach-object { $bindingParts = $_.split("/") $skip = $false if ($bindingParts.Length -ge 4) { if (![String]::IsNullOrEmpty($bindingParts[3]) -and [Bool]::Parse($bindingParts[3]) -eq $false) { $skip = $true } } if ($skip -eq $false) { $wsbindings.Add(@{ protocol=$bindingParts[0];bindingInformation=$bindingParts[1];thumbprint=$bindingParts[2] }) | Out-Null } else { Write-Host "Ignore binding: $_" } } Add-PSSnapin WebAdministration -ErrorAction SilentlyContinue Import-Module WebAdministration -ErrorAction SilentlyContinue # For any HTTPS bindings, ensure the certificate is configured for the IP/port combination $wsbindings | where-object { $_.protocol -eq "https" } | foreach-object { $sslCertificateThumbprint = $_.thumbprint.Trim() Write-Host "Finding SSL certificate with thumbprint $sslCertificateThumbprint" $certificate = Get-ChildItem Cert:\LocalMachine -Recurse | Where-Object { $_.Thumbprint -eq $sslCertificateThumbprint -and $_.HasPrivateKey -eq $true } | Select-Object -first 1 if (! $certificate) { throw "Could not find certificate under Cert:\LocalMachine with thumbprint $sslCertificateThumbprint. Make sure that the certificate is installed to the Local Machine context and that the private key is available." } Write-Host ("Found certificate: " + $certificate.Subject) $bindingInfo = $_.bindingInformation $bindingParts = $bindingInfo.split(':') $ipAddress = $bindingParts[0] if ((! $ipAddress) -or ($ipAddress -eq '*')) { $ipAddress = "0.0.0.0" } $port = $bindingParts[1] $sslBindingsPath = ("IIS:\SslBindings\" + $ipAddress + "!" + $port) Execute-WithRetry { $sslBinding = get-item $sslBindingsPath -ErrorAction SilentlyContinue if (! $sslBinding) { New-Item $sslBindingsPath -Value $certificate | Out-Null } else { Set-Item $sslBindingsPath -Value $certificate | Out-Null } } } ## -------------------------------------------------------------------------------------- ## Run ## -------------------------------------------------------------------------------------- pushd IIS:\ $appPoolPath = ("IIS:\AppPools\" + $ApplicationPoolName) Execute-WithRetry { $pool = Get-Item $appPoolPath -ErrorAction SilentlyContinue if (!$pool) { Write-Host "Application pool `"$ApplicationPoolName`" does not exist, creating..." new-item $appPoolPath -confirm:$false $pool = Get-Item $appPoolPath } else { Write-Host "Application pool `"$ApplicationPoolName`" already exists" } } Execute-WithRetry { Write-Host "Set application pool identity: $applicationPoolIdentityType" if ($applicationPoolIdentityType -eq "SpecificUser") { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="SpecificUser"; username="$applicationPoolUsername"; password="$applicationPoolPassword"} } else { Set-ItemProperty $appPoolPath -name processModel -value @{identitytype="$applicationPoolIdentityType"} } } Execute-WithRetry { Write-Host "Set .NET framework version: $appPoolFrameworkVersion" Set-ItemProperty $appPoolPath managedRuntimeVersion $appPoolFrameworkVersion } $sitePath = ("IIS:\Sites\" + $webSiteName) Execute-WithRetry { $site = Get-Item $sitePath -ErrorAction SilentlyContinue if (!$site) { Write-Host "Site `"$WebSiteName`" does not exist, creating..." $id = (dir iis:\sites | foreach {$_.id} | sort -Descending | select -first 1) + 1 new-item $sitePath -bindings @{protocol="http";bindingInformation=":81:od-temp.example.com"} -id $id -physicalPath $webRoot -confirm:$false } else { Write-Host "Site `"$WebSiteName`" already exists" } } $cmd = { Write-Host "Assigning website to application pool..." Set-ItemProperty $sitePath -name applicationPool -value $ApplicationPoolName } Execute-WithRetry -Command $cmd Execute-WithRetry { Write-Host ("Home directory: " + $webRoot) Set-ItemProperty $sitePath -name physicalPath -value "$webRoot" } Execute-WithRetry { Write-Host "Assigning bindings to website..." Clear-ItemProperty $sitePath -name bindings for ($i = 0; $i -lt $wsbindings.Count; $i = $i+1) { Write-Host ("Binding: " + ($wsbindings[$i].protocol + " " + $wsbindings[$i].bindingInformation + " " + $wsbindings[$i].thumbprint)) New-ItemProperty $sitePath -name bindings -value ($wsbindings[$i]) } } $appCmdPath = $env:SystemRoot + "\system32\inetsrv\appcmd.exe" if ((Test-Path $appCmdPath) -eq $false) { throw "Could not find appCmd.exe at $appCmdPath" } try { Execute-WithRetry { Write-Host "Anonymous authentication enabled: $enableAnonymous" & $appCmdPath set config "$WebSiteName" -section:"system.webServer/security/authentication/anonymousAuthentication" /enabled:"$enableAnonymous" /commit:apphost } Execute-WithRetry { Write-Host "Basic authentication enabled: $enableBasic" & $appCmdPath set config "$WebSiteName" -section:"system.webServer/security/authentication/basicAuthentication" /enabled:"$enableAnonymous" /commit:apphost } Execute-WithRetry { Write-Host "Windows authentication enabled: $enableWindows" & $appCmdPath set config "$WebSiteName" -section:"system.webServer/security/authentication/windowsAuthentication" /enabled:"$enableAnonymous" /commit:apphost } } catch [System.Exception] { Write-Output "Authentication options could not be set. This can happen when there is a problem with your application's web.config. For example, you might be using a section that requires an extension that is not installed on this web server (such as URL Rewrtiting). It can also happen when you have selected an authentication option and the appropriate IIS module is not installed (for example, for Windows authentication, you need to enable the Windows Authentication module in IIS/Windows first)" throw } # It can take a while for the App Pool to come to life (#490) Start-Sleep -s 1 Execute-WithRetry { $state = Get-WebAppPoolState $ApplicationPoolName if ($state.Value -eq "Stopped") { Write-Host "Application pool is stopped. Attempting to start..." Start-WebAppPool $ApplicationPoolName } } Execute-WithRetry { $state = Get-WebsiteState $WebSiteName if ($state.Value -eq "Stopped") { Write-Host "Web site is stopped. Attempting to start..." Start-Website $WebSiteName } } popd Write-Host "IIS configuration complete"
PowerShellCorpus/GithubGist/dotps1_709bf487ba5f9967b45f_raw_27b817006e03db3b87dca5f4cf72a32cde2da2f6_Convert-MACAddressDelimiter.ps1
dotps1_709bf487ba5f9967b45f_raw_27b817006e03db3b87dca5f4cf72a32cde2da2f6_Convert-MACAddressDelimiter.ps1
function Convert-MACAddressDelimiter { [CmdletBinding()] [OutputType([String])] Param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateScript({$patterns = @( '^([0-9a-f]{2}:){5}([0-9a-f]{2})$' '^([0-9a-f]{2}-){5}([0-9a-f]{2})$' '^([0-9a-f]{4}.){2}([0-9a-f]{4})$' '^([0-9a-f]{12})$' ) if ($_ -match ($patterns -join '|')){ $true } else { throw "The argument '$_' does not match a valid MAC address format." } })] [string] $MacAddress, [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateSet(':', '-', '.', $null)] [string] $Delimiter = ':' ) $rawAddress = $MacAddress -replace '\W' switch ($Delimiter) { { $_ -match ':|-' } { for ($i = 2; $i -le 14; $i += 3) { $result = $rawAddress = $rawAddress.Insert($i, $_) } break } '.' { for ($i = 4; $i -le 9; $i += 5) {$result = $rawAddress = $rawAddress.Insert($i, $_) } break } default { $result = $rawAddress } } return $result }
PowerShellCorpus/GithubGist/janikvonrotz_8285809_raw_76a315da273d9360725a5ac15768665ef9d55dd8_Map-GroupMembershipByUsersDepartment.ps1
janikvonrotz_8285809_raw_76a315da273d9360725a5ac15768665ef9d55dd8_Map-GroupMembershipByUsersDepartment.ps1
Import-Module activedirectory $Groups = @( @{ Department = "Fahrdienst A" Group = "Fahrdienst A - Weickart Markus Gruppe" DistGroup = "Fahrdienst A - Weickart Markus" }, @{ Department = "Fahrdienst B" Group = "Fahrdienst B - Nietlispach Marco Gruppe" DistGroup = "Fahrdienst B - Nietlispach Marco" }, @{ Department = "Fahrdienst C" Group = "Fahrdienst C - Habegger Rolf Gruppe" DistGroup = "Fahrdienst C - Habegger Rolf" }, @{ Department = "Fahrdienst D" Group = "Fahrdienst D - Wechsler Josef Gruppe" DistGroup = "Fahrdienst D - Wechsler Josef" }, @{ Department = "Fahrdienst E" Group = "Fahrdienst E - Brunner Ronald Gruppe" DistGroup = "Fahrdienst E - Brunner Ronald" }, @{ Department = "Fahrdienst F" Group = "Fahrdienst F - Bieri René Gruppe" DistGroup = "Fahrdienst F - Bieri René" } ) $Groups | %{ Remove-ADGroupMember -Identity $_.Group -Members $(Get-ADGroupMember -Identity $_.Group) -Confirm:$false Remove-ADGroupMember -Identity $_.DistGroup -Members $(Get-ADGroupMember -Identity $_.DistGroup) -Confirm:$false } Get-ADUser -SearchScope OneLevel -SearchBase "OU=Fahrdienst,OU=Betrieb,OU=vblusers2,DC=vbl,DC=ch" -filter * -properties department, Enabled | sort department | where{$_.Enabled} | %{ $User = $_ $Result = $true $Groups | where{$_.Department -eq $User.Department -or (($User.Department).trimend(" ") -eq $_.Department)} | %{ [char[]]$Department = $User.Department if($Department[($Department).Length -1] -eq " "){ Set-ADUser -Identity $User -Department ($User.Department).trimend(" ") } $_.Department Add-ADGroupMember -Identity $_.Group -Members $User Add-ADGroupMember -Identity $_.DistGroup -Members $User $Result = $false } if($Result){throw "Problem with User: $($_.Name)"} }
PowerShellCorpus/GithubGist/adoprog_5606784_raw_2b0f5513260f8838ff996aa5a32176c04cc99dc5_gistfile1.ps1
adoprog_5606784_raw_2b0f5513260f8838ff996aa5a32176c04cc99dc5_gistfile1.ps1
$buildFolder = Resolve-Path .. $sourcePath = "$buildFolder\Output\LaunchSitecore.Build.12345.zip"
PowerShellCorpus/GithubGist/guitarrapc_9523d3c7dbb04b6bac71_raw_538b4afad3ce9513023b752dfb0b61fe0a6fcbe0_Foreach-Object%E3%81%A8Foreach%E3%81%AE%E7%BD%A0.ps1
guitarrapc_9523d3c7dbb04b6bac71_raw_538b4afad3ce9513023b752dfb0b61fe0a6fcbe0_Foreach-Object%E3%81%A8Foreach%E3%81%AE%E7%BD%A0.ps1
#region return の罠 1..3 | %{ return $_ } <# 1 2 3 #> foreach ($x in (1..3)) { return $x } <# 1 #> #endregion #region continue の罠 1..3 | %{ $_ continue } <# 1 #> foreach ($x in (1..3)) { $x continue } <# 1 2 3 #> #endregion #region break はふつー 1..3 | %{ $_ break } <# 1 #> foreach ($x in (1..3)) { $x break } <# 1 #> #endregion
PowerShellCorpus/GithubGist/dfinke_6c4a7064651e66a4713d_raw_f5297b4dc6e0ed6867ce2970bfef45cabade0230_Get-GithubEmojis.ps1
dfinke_6c4a7064651e66a4713d_raw_f5297b4dc6e0ed6867ce2970bfef45cabade0230_Get-GithubEmojis.ps1
workflow Get-GithubEmojis { param($TargetPath="c:\temp\emojis") if(!(Test-Path -Path $TargetPath)) { $null= New-Item -ItemType Directory -Path $TargetPath } $emojis = Invoke-RestMethod -Uri https://api.github.com/emojis $names = ($emojis | Get-Member -MemberType NoteProperty).name $records = $names | ForEach { $target=$emojis.$PSItem [PSCustomObject]@{ FileName=(Split-Path -Leaf $target) -replace "\?v5", "" Url=$target } } ForEach -Parallel ($record in $records) { try { Invoke-RestMethod -Uri $record.Url -OutFile (Join-Path -Path $TargetPath -ChildPath $record.FileName) } catch {} } }
PowerShellCorpus/GithubGist/johndacosta_6080418_raw_14aaa2cc6c8f35413298ccacc1a8d51a4760b017_get-diskspace.ps1
johndacosta_6080418_raw_14aaa2cc6c8f35413298ccacc1a8d51a4760b017_get-diskspace.ps1
Get-WmiObject win32_volume | Select-Object SystemName,Name, BlockSize, Capacity, FreeSpace, DriveLetter , @{Name="CapacityGB";Expression={[math]::round($_.Capacity/1GB,2)}}, @{Name="FreeSpaceGB";Expression={[math]::round($_.FreeSpace/1GB,2)}} , @{Name="FreeSpacePercent";Expression={[math]::round(($_.FreeSpace/($_.Capacity*1.00))*100.00,2)}} , @{Name="Date";Expression={$(Get-Date -f s)}}| Sort-Object Name | Convertto-JSON # This format will allow you to filter on drive name and select a remote computer. # Get-WmiObject win32_volume -ComputerName ServerName | Where-Object {$_.label -match "S\:.*"} | Select-Object SystemName,Name, BlockSize, Capacity, FreeSpace, DriveLetter , @{Name="CapacityGB";Expression={[math]::round($_.Capacity/1GB,2)}}, @{Name="FreeSpaceGB";Expression={[math]::round($_.FreeSpace/1GB,2)}} , @{Name="FreeSpacePercent";Expression={[math]::round(($_.FreeSpace/($_.Capacity*1.00))*100.00,2)}} , @{Name="Date";Expression={$(Get-Date -f s)}}| Sort-Object Name | Convertto-JSON
PowerShellCorpus/GithubGist/YoungjaeKim_4eb6359dd6076f3f74f7_raw_3583f1fe1129d018d1656c622df71ec90c0b2813_teamcity_azure_worker_role.ps1
YoungjaeKim_4eb6359dd6076f3f74f7_raw_3583f1fe1129d018d1656c622df71ec90c0b2813_teamcity_azure_worker_role.ps1
#Modified and simplified version of https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/ #Modified and treat error-terminating of http://weblogs.asp.net/srkirkland/ci-deployment-of-azure-web-roles-using-teamcity $ErrorActionPreference = "Stop" $subscription = "[Your Subscription Name]" $service = "[Your Azure Service Name]" $slot = "staging" #staging or production $package = "[ProjectName]\bin\[BuildConfigName]\app.publish\[ProjectName].cspkg" $configuration = "[ProjectName]\bin\[BuildConfigName]\app.publish\ServiceConfiguration.Cloud.cscfg" $timeStampFormat = "g" $deploymentLabel = "ContinuousDeploy to $service v%build.number%" Write-Output "Running Azure Imports" Import-AzurePublishSettingsFile "C:\TeamCity\[Your PublishSettings Filename].publishsettings" function Publish(){ Write-Output "$(Get-Date -f $timeStampFormat) - Publising Azure Deployment..." $deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue if ($a[0] -ne $null) { Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. " } if ($deployment.Name -ne $null) { #Update deployment inplace (usually faster, cheaper, won't destroy VIP) Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $service. Upgrading deployment." UpgradeDeployment } else { 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" $opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID" } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress" # perform Update-Deployment $setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID" } #Azure Publish Execution try{ Set-AzureSubscription -CurrentStorageAccount [Your Storage Account Name] -SubscriptionName $subscription Publish }catch{ throw #Rethrow to detect failed build status. Check "an erorr message is logged by build runner" in TeamCity Bulid configuration Failure Conditions menu Break }
PowerShellCorpus/GithubGist/guitarrapc_a45f070be3301d27eb78_raw_8c80453e3395f4d50837c489dc75868550618517_break.ps1
guitarrapc_a45f070be3301d27eb78_raw_8c80453e3395f4d50837c489dc75868550618517_break.ps1
1..3 | %{ $_ break $_ } <# 1 #> foreach ($x in (1..3)) { $x break $x } <# 1 #>
PowerShellCorpus/GithubGist/mynameiscoffey_7002093_raw_19ed21ddcc03b1cbe4719a133f7b259dce540acb_deploy.ps1
mynameiscoffey_7002093_raw_19ed21ddcc03b1cbe4719a133f7b259dce540acb_deploy.ps1
#Modified and simplified version of https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/ $subscription = "[Your Subscription Name]" $service = "[Your Azure Service Name]" $slot = "staging" #staging or production $package = "[ProjectName]\bin\[BuildConfigName]\app.publish\[ProjectName].cspkg" $configuration = "[ProjectName]\bin\[BuildConfigName]\app.publish\ServiceConfiguration.Cloud.cscfg" $timeStampFormat = "g" $deploymentLabel = "ContinuousDeploy to $service v%build.number%" Write-Output "Running Azure Imports" Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.psd1" Import-AzurePublishSettingsFile "C:\TeamCity\[PSFileName].publishsettings" Set-AzureSubscription -CurrentStorageAccount $service -SubscriptionName $subscription function Publish(){ $deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue if ($a[0] -ne $null) { Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. " } if ($deployment.Name -ne $null) { #Update deployment inplace (usually faster, cheaper, won't destroy VIP) Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } else { 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" $opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID" } function UpgradeDeployment() { write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress" # perform Update-Deployment $setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force $completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot $completeDeploymentID = $completeDeployment.deploymentid write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete" Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID" } Write-Output "Create Azure Deployment" Publish
PowerShellCorpus/GithubGist/p0w3rsh3ll_a4e606996150b63ae54b_raw_46728caf493e5e8cdf81ec04784131809ee6d761_ProxyURL.ps1
p0w3rsh3ll_a4e606996150b63ae54b_raw_46728caf493e5e8cdf81ec04784131809ee6d761_ProxyURL.ps1
# Define a proxy URL for a configuration script Configuration ProxyURL { Registry ProxyPerMachinePolicy { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings' ValueName = 'ProxySettingsPerUser' Ensure = 'Present' ValueData = '0' ValueType = 'Dword' Force = $true } Registry ProxyPerMachineWinHttPSettings { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' ValueName = 'WinHttPSettings' Ensure = 'Absent' Force = $true } Registry ProxyPerMachineDefaultConnectionSettings { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' ValueName = 'DefaultConnectionSettings' Ensure = 'Present' ValueType = 'Binary' ValueData = '46000000040000000500000000000000000000001D000000687474703A2F2F6D7970726F78792E6671646E2F70726F78792E7061630000000000000000000000000000000000000000000000000000000000000000' Force = $true } Registry ProxyPerMachineSavedLegacySettings { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' ValueName = 'SavedLegacySettings' Ensure = 'Present' ValueType = 'Binary' ValueData = '46000000090000000500000000000000000000001D000000687474703A2F2F6D7970726F78792E6671646E2F70726F78792E7061630000000000000000000000000000000000000000000000000000000000000000' Force = $true } Registry ProxyPerMachineProxyEnable { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' ValueName = 'ProxyEnable' Ensure = 'Present' ValueData = '0' ValueType = 'Dword' Force = $true } Registry ProxyPerMachineProxyServer { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' ValueName = 'ProxyServer' Ensure = 'Absent' Force = $true } Registry ProxyPerMachineProxyOverride { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' ValueName = 'ProxyOverride' Ensure = 'Absent' Force = $true } Registry ProxyPerMachineAutoConfigURL { Key = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings' ValueName = 'AutoConfigURL' Ensure = 'Present' ValueData = 'http://myproxy.fqdn/proxy.pac' ValueType = 'String' Force = $true } Registry ProxyPerMachineLockAutoConfig { Key = 'HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Control Panel' ValueName = 'Autoconfig' Ensure = 'Present' ValueData = '1' ValueType = 'Dword' Force = $true } Registry ProxyPerMachineLockProxy { Key = 'HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Internet Explorer\Control Panel' ValueName = 'Proxy' Ensure = 'Present' ValueData = '1' ValueType = 'Dword' Force = $true } }
PowerShellCorpus/GithubGist/andreaswasita_0386c773b9873e7cca88_raw_dd7029d8d27c3c6ec4187e29d6141b3d164c9450_Remove-AzureAntiMalware.ps1
andreaswasita_0386c773b9873e7cca88_raw_dd7029d8d27c3c6ec4187e29d6141b3d164c9450_Remove-AzureAntiMalware.ps1
$servicename = "MyAzureVMAntiMalware" $name = "MyAzureVM01" Get-AzureVM -ServiceName $servicename -Name $name | Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -Uninstall | Update-AzureVM
PowerShellCorpus/GithubGist/belotn_6867957_raw_9f37f62cd12396ae786391d159b330860179a787_Disbale-GPOUnusedPart.ps1
belotn_6867957_raw_9f37f62cd12396ae786391d159b330860179a787_Disbale-GPOUnusedPart.ps1
Get-ADOrganizationalUnit -Filter 'OU -like "*Citrix*"' -SearchBase 'dc=fabrikam,dc=com' -Properties * |% { $_.gpLink -split ']' } |? { $_ -match '[0,2]$'} |% { (($_ -replace '\[','').split(';')[0]) -replace 'LDAP://',''} |% { get-adobject $_ -properties * } | sort -Unique DisplayName |% { if( $_.Flags -ne 3 ){ if([bool]( gci "$($_.gPCFileSysPath)\User") -eq $false){ if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){ (get-gpo -Name $_.DisplayName).GpoStatus = "AllSettingsDisabled" }else{ (get-gpo -Name $_.DisplayName).GpoStatus = "UserSettingsDisabled" } }else { if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){ (get-gpo -Name $_.DisplayName).GpoStatus = "ComputerSettingsDisabled" }ELSE{ #do nothing } } } }
PowerShellCorpus/GithubGist/toddb_1133511_raw_45404dbfa3c115ced13c44aa7a91b41e87177f34_build-tasks.ps1
toddb_1133511_raw_45404dbfa3c115ced13c44aa7a91b41e87177f34_build-tasks.ps1
<# Basic build tasks for SharePoint (or other projects) - using 7zip and GacUtil $framework = '4.0x64' . .\scripts\build-tasks.ps1 properties { $project = "Sites" $environment = "" # handed in commmand line $revision = "0" # handed in commmand line $version = "1.0.0." # problem with version as substitution at this level $platform = "x64" $config = "Release" $base_dir = resolve-path . $configuration = "bin\$platform\$config" $lib_dir = "$base_dir\lib" $tools_dir = "$base_dir\tools" $test_dir = "$base_dir\src\$project\$configuration" $release_dir = "$base_dir\CodeToDeploy\Releases" $extract_dir = "$base_dir\CodeToDeploy\Deploy" $buildartifacts_dir = "$build_dir\CodeToDeploy\Publish" $binaries_root = "$base_dir\src\Ui" $wsp_root = "$binaries_root\bin\$config" $sln_file = "$base_dir\src\$project.sln" $wsp_proj = "$base_dir\src\$project\UI-$project.csproj" } Task Compile { exec { msbuild $sln_file /t:build "/p:Configuration=$config" "/p:Platform=$platform" } } Task PackageWsp { exec { msbuild $wsp_proj /t:package "/p:Configuration=$config" "/p:Platform=$platform" "/p:OutDir=$wsp_root\" } "Error msbuild $wsp_proj /t:package p:Configuration=$config /p:Platform=$platform /p:OutDir=$wsp_root\" } Task Version -Description "Version the assemblies" { Update-AssemblyInfoFiles $version$revision $assemblyinfo_excludes } Task Version-Reset -Description "Returns the version of the assemblies to 1.0.0.0" { Reset-AssemblyInfoFiles } Task Publish -Description "Copies the necessary files into the publishing folder" { Clobber-Directory $buildartifacts_dir CopyTo-Directory $base_dir\here.cmd $buildartifacts_dir CopyTo-Directory $base_dir\scripts\deploy\default.ps1 $buildartifacts_dir CopyTo-Directory $base_dir\scripts\deploy\Install.bat $buildartifacts_dir CopyTo-Directory $base_dir\scripts\deploy\Migrate.bat $buildartifacts_dir CopyTo-Directory $base_dir\scripts\psake.psm1 $buildartifacts_dir\scripts CopyTo-Directory $base_dir\scripts\sharepoint-tasks.ps1 $buildartifacts_dir\scripts CopyTo-Directory $base_dir\scripts\build-tasks.ps1 $buildartifacts_dir\scripts CopyTo-Directory $base_dir\scripts\migrations-tasks.ps1 $buildartifacts_dir\scripts CopyTo-Directory $wsp_root\Infrastructure.dll $buildartifacts_dir\lib\migratordotnet CopyTo-Directory $wsp_root\Domain.dll $buildartifacts_dir\lib\migratordotnet CopyTo-Directory $wsp_root\$project.dll $buildartifacts_dir\lib\migratordotnet CopyTo-Directory $lib_dir\migratordotnet\* $buildartifacts_dir\lib\migratordotnet CopyTo-Directory $lib_dir\wsp\* $buildartifacts_dir\wsp CopyTo-Directory $wsp_root\$solution $buildartifacts_dir\wsp Create-VersionFile $buildartifacts_dir\$version$revision } Task Extract -Description "Unzips the packing zip archive" { Extract-Zip $release_dir\$project-$version$revision.zip $extract_dir } Task Zip -Description "Unzips the packing zip archive" { Create-Zip $release_dir\$project-$version$revision.zip $buildartifacts_dir } Task Deploy -Description "Runs the Install.bat file under the deploy user credentials" { exec { cd $extract_dir; dir; runas /savecred /user:$site_owner "$extract_dir\Install.bat $extract_dir $application $environment" } "If this command fails, through command line do this: runas /savecred /user:$site_owner cmd - and rerun -> this will save the creds " } Task Gac -Description "Add all assemblies to GAC" { AddTo-Gac $wsp_root $project } Task Gac-Uninstall -Description "Remove all assemblies from the GAC" { Clean-Gac $wsp_root $project } #> $7z_exe = ".\lib\7z\7z.exe" $gac_exe = "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64\gacutil.exe" function Writeable-AssemblyInfoFile($filename){ sp $filename IsReadOnly $false } function ReadOnly-AssemblyInfoFile($filename){ sp $filename IsReadOnly $true } function CopyTo-Directory($files, $dir){ Create-Directory $dir cp $files $dir -recurse -container } function Clobber-Directory($dir){ if (Test-Path -path $dir) { rmdir $dir -recurse -force } } function Create-Directory($dir){ if (!(Test-Path -path $dir)) { new-item $dir -force -type directory} } function Create-VersionFile($file){ New-Item $file -type file } function Create-Zip($file, $dir, $7z){ if ($7z -eq $null) { $7z = $7z_exe } if (Test-Path -path $file) { remove-item $file } Create-Directory $dir exec { & $7z a -tzip $file $dir\* } } function Extract-Zip($file, $extract_dir, $7z){ if ($7z -eq $null) { $7z = $7z_exe } Clobber-Directory $extract_dir Create-Directory $extract_dir exec { & $7z x $file -aoa "-o$extract_dir"} } function Clean-Gac($dir, $include, $gac){ if ($gac -eq $null) { $gac = $gac_exe } get-childitem $dir -filter *.$include*.dll | % { exec { & $gac /u $_.basename } } } function AddTo-Gac($dir, $include, $gac){ if ($gac -eq $null) { $gac = $gac_exe } get-childitem $dir -filter *.$include*.dll | % { exec { & $gac /i $_.fullname } } } function Update-AssemblyInfoFiles ([string] $version, [System.Array] $excludes = $null, $make_writeable = $false) { #------------------------------------------------------------------------------- # Update version numbers of AssemblyInfo.cs # adapted from: http://www.luisrocha.net/2009/11/setting-assembly-version-with-windows.html #------------------------------------------------------------------------------- if ($version -notmatch "[0-9]+(\.([0-9]+|\*)){1,3}") { Write-Error "Version number incorrect format: $version" } $versionPattern = 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)' $versionAssembly = 'AssemblyVersion("' + $version + '")'; $versionFilePattern = 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)' $versionAssemblyFile = 'AssemblyFileVersion("' + $version + '")'; Get-ChildItem -r -filter AssemblyInfo.cs | % { $filename = $_.fullname $update_assembly_and_file = $true # set an exclude flag where only AssemblyFileVersion is set if ($excludes -ne $null) { $excludes | % { if ($filename -match $_) { $update_assembly_and_file = $false } } } # We are using a source control (TFS) that requires to check-out files before # modifying them. We don't want checkins so we'll just toggle # the file as writeable/readable if ($make_writable) { Writeable-AssemblyInfoFile($filename) } # see http://stackoverflow.com/questions/3057673/powershell-locking-file # I am getting really funky locking issues. # The code block below should be: # (get-content $filename) | % {$_ -replace $versionPattern, $version } | set-content $filename $tmp = ($file + ".tmp") if (test-path ($tmp)) { remove-item $tmp } if ($update_assembly_and_file) { (get-content $filename) | % {$_ -replace $versionFilePattern, $versionAssemblyFile } | % {$_ -replace $versionPattern, $versionAssembly } > $tmp write-host Updating file AssemblyInfo and AssemblyFileInfo: $filename --> $versionAssembly / $versionAssemblyFile } else { (get-content $filename) | % {$_ -replace $versionFilePattern, $versionAssemblyFile } > $tmp write-host Updating file AssemblyInfo only: $filename --> $versionAssemblyFile } if (test-path ($filename)) { remove-item $filename } move-item $tmp $filename -force if ($make_writable) { ReadOnly-AssemblyInfoFile($filename) } } } function Reset-AssemblyInfoFiles(){ Update-AssemblyInfoFiles ("1.0.0.0") }
PowerShellCorpus/GithubGist/mrlesmithjr_7954983_raw_c07172bce60ac13fedddd87e16919ea4ea7e19d1_Get_VM_Network.ps1
mrlesmithjr_7954983_raw_c07172bce60ac13fedddd87e16919ea4ea7e19d1_Get_VM_Network.ps1
#Provided by @mrlesmithjr #EveryThingShouldBeVirtual.com # # Set variable for all VMs that are powered on $vms = Get-vm | where { $_.PowerState -eq “PoweredOn”} # Capture default info Get-VMGuestNetworkInterface $vms # Capture more details - Only works for Windows VMs Get-VMGuestNetworkInterface $vms | Select VM, Name, IPPolicy, Ip, Dns, DefaultGateway, DnsPolicy
PowerShellCorpus/GithubGist/xinhuang_11347412_raw_9a20ec3374212ee6cd114ff4a4011b489cbee8a3_rc.ps1
xinhuang_11347412_raw_9a20ec3374212ee6cd114ff4a4011b489cbee8a3_rc.ps1
param( [switch]$install ) function Try-ImportModule($module, [ScriptBlock]$onError) { try { Import-Module $module -ErrorAction Stop } catch { & $onError Import-Module $module } } Try-ImportModule 'PsGet' -OnError { (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex } Try-ImportModule 'PsReadLine' -OnError { Install-Module PsReadLine } function prompt { $_locationStackDepthString = New-Object string ([char] '+'), (Get-Location -Stack).Count $color = 'Yellow' Write-Host '>> ' -nonewline -ForegroundColor $color Write-Host $(Get-Date -Format T) -ForegroundColor 'Green' -NoNewLine Write-Host " " $PWD.Path -ForegroundColor 'Cyan' Write-Host ($_locationStackDepthString + '>') -nonewline -ForegroundColor $color return " " } function Write-Callstack([System.Management.Automation.ErrorRecord]$ErrorRecord=$null, [int]$Skip=1) { Write-Host # blank line if ($ErrorRecord) { Write-Host -ForegroundColor Red "$ErrorRecord $($ErrorRecord.InvocationInfo.PositionMessage)" if ($ErrorRecord.Exception) { Write-Host -ForegroundColor Red $ErrorRecord.Exception } if ((Get-Member -InputObject $ErrorRecord -Name ScriptStackTrace) -ne $null) { #PS 3.0 has a stack trace on the ErrorRecord; if we have it, use it & skip the manual stack trace below Write-Host -ForegroundColor Red $ErrorRecord.ScriptStackTrace return } } Get-PSCallStack | Select -Skip $Skip | % { Write-Host -ForegroundColor Yellow -NoNewLine "! " Write-Host -ForegroundColor Red $_.Command $_.Location $(if ($_.Arguments.Length -le 80) { $_.Arguments }) } } try { if ($install) { if ($PsVersionTable.PsVersion.Major -lt 4) { Write-Error "This runtime config file requires PowerShell minimum version 4.0." return } $thisFile = $MyInvocation.MyCommand.Path $sourceMeLine = ". $thisFile" if (Test-Path $profile -PathType Leaf) { $sourcedMe = Get-Content $profile | % { $_.Trim() } | ? { $_ -eq $sourceMeLine } } else { $sourcedMe = $False } if (-Not $sourcedMe) { "`n$sourceMeLine`n" | Out-File $profile -Append } iex $sourceMeLine } } catch { Write-Callstack $Error[0] Write-Callstack $Error[0] }
PowerShellCorpus/GithubGist/Rodske_0898e6b36b6ce4c84585_raw_a693c0538b8b5a463ae84e139b15b59f74856cc0_GenerateSqlObjects.ps1
Rodske_0898e6b36b6ce4c84585_raw_a693c0538b8b5a463ae84e139b15b59f74856cc0_GenerateSqlObjects.ps1
# Adapted from http://www.simple-talk.com/sql/database-administration/automated-script-generation-with-powershell-and-smo/ <# .SYNOPSIS Generate file-per-object scripts of specified server and database. .DESCRIPTION Generate file-per-object scripts of specified server and database to specified directory. Attempts to create specified directory if not found. .PARAMETER ServerName Specifies the database server hostname. .PARAMETER Database Specifies the name of the database you want to script as objects to files. .PARAMETER SavePath Specifies the directory where you want to store the generated scripts. #> [CmdletBinding()] Param( [Parameter(Mandatory = $true, Position = 1)] [string]$ServerName, [Parameter(Mandatory = $true, Position = 2)] [string]$Database, [Parameter(Mandatory = $true, Position = 3)] [string]$SavePath ) # Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended library $v = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') { [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null } [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null Set-PSDebug -strict # catch a few extra bugs $ErrorActionPreference = "continue" $srv = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $ServerName #attach to the server if ($srv.ServerType -eq $null) # check to see if we found a server { throw "Unable to connect to server '$ServerName' " } # Loop through the databases and do a case insensitive search for .Name # Doing this instead of $srv.Databases[$Database] because it can change the character case # of the .Name property (i.e. 'ENTERPRISE' becomes 'enterprise') of the located Database object. $db = $null # initialize empty variable foreach ($finddb in $srv.Databases) { if ($finddb.Name -eq $Database) { $db = $finddb break } } if ($db -eq $null) { throw "Unable to find database '$Database'" } # create scripter object (used by the function ScriptOutDbObj()) $scripter = New-Object ("Microsoft.SqlServer.Management.Smo.Scripter") $srv #create the scripter $scripter.Options.AllowSystemObjects = $false $scripter.Options.AnsiFile = $true $scripter.Options.AnsiPadding = $true # true = SET ANSI_PADDING statements $scripter.Options.Default = $true $scripter.Options.DriAll = $true $scripter.Options.Encoding = New-Object ("System.Text.ASCIIEncoding") $scripter.Options.ExtendedProperties = $true $scripter.Options.IncludeDatabaseContext = $true # true = USE <databasename> statements $scripter.Options.IncludeHeaders = $false $scripter.Options.Indexes = $true $scripter.Options.NoCollation = $true # true = don't script verbose collation info in table scripts $scripter.Options.SchemaQualify = $true $scripter.Options.ScriptDrops = $false $scripter.Options.ToFileOnly = $true $scripter.Options.Triggers = $true $scripter.Options.WithDependencies = $false # create the directory if necessary (SMO doesn't). if (!(Test-Path -Path $SavePath)) { Write-Verbose "Creating directory at '$SavePath'" try { New-Item $SavePath -Type Directory | Out-Null } catch [System.Exception] { throw "Error while creating '$SavePath'" } } ################################################################################ # Function Script Out Database Object # # Function that accepts a Smo.Database-related object or an object with a valid # Urn property, then calls the already instantiated Scripter object to write # sql script to file. # # Args: $inObj = Database object from either a "list" (generated by EnumObjects # method) or a database object with a Urn property (i.e. Table, # StoredProcedure, etc) ################################################################################ Function ScriptOutDbObj($inObj) { # Create a single element URN array $UrnCollection = New-Object ("Microsoft.SqlServer.Management.Smo.UrnCollection") $UrnCollection.Add($inObj.Urn) # get the valid Urn.Type string for the file name $typeName = $UrnCollection.Item(0).Type # tell the scripter object where to write it $SavePath = Resolve-Path $SavePath # get the full path of passed in argument (for scripter object's benefit) $scripter.Options.Filename = Join-Path $SavePath "$($inObj.Schema + '.' -Replace '^\.','')$($inObj.Name -Replace '[\\\/\:]',' ').$typeName.sql" # a bit of progress reporting... Write-Verbose $scripter.Options.FileName #and write out the object to the specified file $scripter.Script($UrnCollection) } # End of Function ScriptOutDbObj ################################################################################ ## MAIN PROGRAM LOGIC ## # now get all the object types except extended stored procedures and a few others we don't want # by creating a "bitmap" of the DatabaseObjectTypes enum: $objectTypeFlags = [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::All -bxor ( [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::Certificate + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::DatabaseRole + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ExtendedStoredProcedure + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::MessageType + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ServiceBroker + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ServiceContract + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ServiceQueue + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::ServiceRoute + [long][Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::SqlAssembly) #and we store them in a datatable $d = New-Object ("System.Data.DataTable") #get everything except the information schema, system views, and some other extra items $d = $db.EnumObjects($objectTypeFlags) | Where-Object { $_.Schema -ne "sys" -and $_.Name -ne "sys" -and $_.Schema -ne "information_schema" -and $_.Name -ne "information_schema" -and $_.Schema -notlike "db_*" -and $_.Name -notlike "db_*" -and $_.Name -notlike "sp_*diagram*" -and $_.Name -ne "fn_diagramobjects" -and $_.Name -ne "sysdiagrams" -and $_.Schema -ne "guest" -and $_.Name -ne "guest" } #and write out each scriptable object as a file in the directory you specify $d | ForEach-Object { #for every object we have in the datatable. ScriptOutDbObj $_ } # Next, script out Database Triggers (DatabaseDdlTrigger) separately because they are not returned by Database.EnumObjects() foreach ($t in $db.Triggers) { ScriptOutDbObj $t } # also script out the database definition itself ScriptOutDbObj $db Write-Verbose "Done!"
PowerShellCorpus/GithubGist/tcshao_3797240_raw_abd040954c15390d8d52f21109d7da757aaf42f6_DeleteOldTextFiles.ps1
tcshao_3797240_raw_abd040954c15390d8d52f21109d7da757aaf42f6_DeleteOldTextFiles.ps1
<# Deleting *.txt files from 'c:\temp' and subdirectories more than 5 days old #> Get-ChildItem 'C:/temp' -Recurse -Include '*txt' | WHERE { ($_.CreationTime -le $(Get-Date).AddDays(-5)) } | Remove-Item
PowerShellCorpus/GithubGist/CodeAndLoathing_37be9c54b545eb93b1fc_raw_f5c712103e3981c5f6a58ef69fdc419d682edf23_AD-verifyUserOrGroupExists.ps1
CodeAndLoathing_37be9c54b545eb93b1fc_raw_f5c712103e3981c5f6a58ef69fdc419d682edf23_AD-verifyUserOrGroupExists.ps1
# query list of usernames and/or groups and determine if they exist in specified AD domain or not # tested against Powershell 4.0 # parameters $domain = "example.com" $userList = @('username1','username2','username3...') $groupList = @('groupname1','groupname2','groupname3...') # result vars $unknownUserList = @() $unknownGroupList = @() # foreach($user in $userList){ #Try retrieve user $ADUser = Get-ADUser -Filter {SamAccountName -eq $user} -Server $domain #Test to see if the user exists if($ADUser) { #user exists } else { #user does not exist Write-host "$($User) does not Exist" $unknownUserList += $user } } foreach ($group in $groupList){ #Try retrieve group $ADGroup = Get-ADGroup -Filter {SamAccountName -eq $group} -Server $domain #Test to see if the group exists if($ADGroup) { #group exists } else { #group does not exist Write-host "$($Group) does not Exist" $unknownGroupList += $group } }
PowerShellCorpus/GithubGist/nich0s_6104726_raw_8bebfd8b0a77ad64deec5b46b374f50e70a08a6f_gui_form_template.ps1
nich0s_6104726_raw_8bebfd8b0a77ad64deec5b46b374f50e70a08a6f_gui_form_template.ps1
<# name: gui_form_template.ps1 auth: nich0s desc: Template for building GUIs in PowerShell. #> # Imports Import-Module SomethingWindowsy # Main function function GenerateForm { [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null $formMain = New-Object System.Windows.Forms.Form $btnButton = New-Object System.Windows.Forms.Button $rtbRichTextBox = New-Object System.Windows.Forms.RichTextBox $lvListView = New-Object System.Windows.Forms.ListView $cbCheckBox = New-Object System.Windows.Forms.CheckBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState # onClick btnButton function btnButtonOnClick { $btnButton.Text = "Working..." $selectedItemsInListView = '$lvListView.SelectedItems | %{$_.Text}' $itemQuery = Invoke-Expression $selectedItemsInListView ForEach ($item in $itemQuery) { $itemInfo = Get-Something $item -Property * ForEach ($prop in $itemInfo.PropertyNames) { $rtbRichTextBox.Text += "`n ${prop}: " $rtbRichTextBox.Text += $itemInfo.$prop } } $btnButton.Text = "Original Text" } function checkBoxAction1 { # Checkbox stateChange event } function checkBoxAction2 { # Checkbox stateChange event } function onLoad { checkBoxAction2 } $onFormLoad = {$formMain.WindowState = $InitialFormWindowState} # Correct the initial state of the form to prevent the .Net maximized form issue # Form "Main" $formMain.Text = "Title" $formMain.Name = "formMain" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 512 $System_Drawing_Size.Height = 512 $formMain.ClientSize = $System_Drawing_Size $formMain.DataBindings.DefaultDataSourceUpdateMode = 0 $formMain.AutoScaleMode = 0 # List Box $lvListView.Text = "" $lvListView.Name = "lvListView" $lvListView.UseCompatibleStateImageBehavior = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 128 $System_Drawing_Size.Height = 256 $lvListView.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 0 $System_Drawing_Point.Y = 0 $lvListView.Location = $System_Drawing_Point $lvListView.View = 1 $lvListView.Columns.Add("Items", 96) | out-null $lvListView.FullRowSelect = $True $lvListView.TabIndex = 0 $lvListView.DataBindings.DefaultDataSourceUpdateMode = 0 $formMain.Controls.Add($lvListView) # Rich Text Box $rtbRichTextBox.Text = "" $rtbRichTextBox.Name = "rtbRichTextBox" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 128 $System_Drawing_Point.Y = 0 $rtbRichTextBox.Location = $System_Drawing_Point $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 384 $System_Drawing_Size.Height = 512 $rtbRichTextBox.Size = $System_Drawing_Size $rtbRichTextBox.TabIndex = 1 $rtbRichTextBox.DataBindings.DefaultDataSourceUpdateMode = 0 $formMain.Controls.Add($rtbRichTextBox) # Button "Button" $btnButton.Text = "Button" $btnButton.Name = "btnButton" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 96 $System_Drawing_Size.Height = 24 $btnButton.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 16 $System_Drawing_Point.Y = 256 $btnButton.Location = $System_Drawing_Point $btnButton.TabIndex = 2 $btnButton.DataBindings.DefaultDataSourceUpdateMode = 0 $btnButton.UseVisualStyleBackColor = $True $btnButton.add_Click({btnButtonOnClick}) $formMain.Controls.Add($btnButton) # CheckBox "CheckBox" $cbCheckBox.Text = "CheckBox" $cbCheckBox.Name = "cbCheckBox" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 96 $System_Drawing_Size.Height = 24 $cbCheckBox.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 16 $System_Drawing_Point.Y = 304 $cbCheckBox.Location = $System_Drawing_Point $cbCheckBox.TabIndex = 4 $cbCheckBox.DataBindings.DefaultDataSourceUpdateMode = 0 $cbCheckBox.UseVisualStyleBackColor = $True $cbCheckBox.Add_CheckStateChanged({ If ($cbCheckBox.Checked) { checkBoxAction1 } Else { checkBoxAction2 } }) $formMain.Controls.Add($cbCheckBox) # Finish Building Form $InitialFormWindowState = $formMain.WindowState $formMain.add_Load($onFormLoad) $formMain.add_Load({onLoad}) $formMain.ShowDialog()| Out-Null } GenerateForm
PowerShellCorpus/GithubGist/guitarrapc_77c1b0dc0ab0564c46d9_raw_606bb001d69a0eb87da5f5047e95b2bba9a2fa4d_PartialExpression.ps1
guitarrapc_77c1b0dc0ab0564c46d9_raw_606bb001d69a0eb87da5f5047e95b2bba9a2fa4d_PartialExpression.ps1
#3. $() でくくる。部分式扱いなので、先行評価、展開される "$($hoge.hoge)"
PowerShellCorpus/GithubGist/justFen_2782653_raw_153e0a724b27f57f7eabf2913867eff416343e28_AutoVM.ps1
justFen_2782653_raw_153e0a724b27f57f7eabf2913867eff416343e28_AutoVM.ps1
param ( [string]$vmName = (Read-Host "Provide VM Name"), [string]$Template = (Read-Host "What Template do you want Vanilla/Web/Gravis?") [string]$Template = (Read-Host "Disk size 40/80?") ) # Import Configuration . (Join-Path -Path (Split-Path -parent $MyInvocation.MyCommand.Definition) -ChildPath "configuration.ps1") # Load VMware Module if ((Get-PSSnapin | Where-Object { $_.Name -eq "VMware.VimAutomation.Core" }) -eq $null) { Add-PSSnapin VMware.VimAutomation.Core } # Connect to vCenter Connect-VMHost ### Variables ### $domainName = "hihihih.justfen.co.uk" $fqdn = $vmName.$domainName # Highest amount of disk space required for VM $RequiredDisk = 80000 $Pool = Get-ResourcePool "TRON" # Will calculate Datastore with most free space, useful until Storage DRS setup $DataStore = Get-Datastore | Where { $_.FreespaceMB -gt $RequiredDisk } | Sort-Object FreeSpaceMB -Descending | Select -First 1 if (!$Datastore) { throw "No Datastore could be found with $RequiredDisk MB free space." } # Will chose ESX host with least CPU utilization, maybe RAM would be a better choice $ESXHost = Get-VMHost | Sort $_.CPuUsageMhz | Select -First 1 $OSCustomizationSpec = get-OSCustomizationSpec "Windows" if (!$OSCustomizationSpec) { throw "OSCustomizationSpec Windows was not found"} New-VM -vmhost $ESXHost ` -Name $vmName ` -Template $Template ` -ResourcePool $Pool ` -Datastore $DataStore ` -OSCustomizationSpec $OSCustomizationSpec Start-VM -VM $vmName
PowerShellCorpus/GithubGist/akimboyko_4258647_raw_a6643cf56090e1101598fdb5259cbeebf8f22f8d_gistfile1.ps1
akimboyko_4258647_raw_a6643cf56090e1101598fdb5259cbeebf8f22f8d_gistfile1.ps1
Write-Host 'throw' try { try { throw "exception" } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace throw } } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace Write-Host $err } Write-Host 'throw (exception)' try { try { $exception = New-Object System.Exception ("test") throw $exception } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace throw } } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace Write-Host $err } Write-Host 'throw $_' try { try { $exception = New-Object System.Exception ("test") throw $exception } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace throw $_ } } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace Write-Host $err } Write-Host 'throw $_.Exception' try { try { $exception = New-Object System.Exception ("test") throw $exception } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace throw $_.Exception } } catch { Write-Host $_ Write-Host $_.GetType() Write-Host $_.Exception Write-Host $_.Exception.StackTrace Write-Host $err }
PowerShellCorpus/GithubGist/minakuchiya_5459133_raw_f93daed8a8f6de1a25dd5fb0b976a0ba7b1714d5_Waei.ps1
minakuchiya_5459133_raw_f93daed8a8f6de1a25dd5fb0b976a0ba7b1714d5_Waei.ps1
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") function waei($value) { $value = [Web.HttpUtility]::UrlEncode($value) ie http://dictionary.goo.ne.jp/srch/je/$value/m0u/ }
PowerShellCorpus/GithubGist/philipmat_8a292387dcef0bad9404_raw_9f9bf1b4d470e9bd67b871d52915ef16e43d68fa_recover.ps1
philipmat_8a292387dcef0bad9404_raw_9f9bf1b4d470e9bd67b871d52915ef16e43d68fa_recover.ps1
# Usage: (execute in the .git/objects folder) # recover.ps1 -startDate "8/13/2014 1:22:00pm" -endDate "8/13/2014 8:00:00pm" > borked_files.txt [CmdletBinding()] Param( [string]$startDate, [string]$endDate ) $start = [datetime]::Today if ($startDate) { $start = [datetime]::Parse($startDate) } $end = $start.AddDays(1) if ($endDate) { $end = [datetime]::Parse($endDate) } Write-Host "Searching for git objects created between $start and $end" $files = Get-ChildItem -recurse | where {$_.CreationTime -gt $start -and $_.CreationTime -lt $end} $sha_length = "fe19a805b91c63cca33f53c56499fa53b2436303".Length $count_files = $files.Length Write-Host "Files: $count_files" $i = 0 foreach ($file in $files) { $composed = $file.Directory.BaseName + $file.BaseName if ($composed.Length -eq $sha_length) { Write-Output "----=====SHA1: $composed" git show $composed $i++ Write-Host -NoNewline "." if ($i % 50 -eq 0) { Write-Host -ForegroundColor Green "= $i/$count_files" } } else { Write-Host -ForegroundColor DarkRed "Ignoring: $composed" } }
PowerShellCorpus/GithubGist/timheuer_3422592_raw_d2acb885b7a73d73bf27a997c897ed83944a8f92_gistdiff.ps1
timheuer_3422592_raw_d2acb885b7a73d73bf27a997c897ed83944a8f92_gistdiff.ps1
# ask the user for a gist name param ( [string]$gistname = "$(Read-Host 'Enter a name for the gist')" ) # constant $gistapi = "https://api.github.com/gists" $filename = $gistname + '.diff' $teststring = "`{`"description`": `"the description for this gist`",`"public`": true,`"files`": `{`"file1.txt`": `{`"content`": `"String file contents`"`}`}`}" # get the diff from the current session $diff = git diff # build up the json object data $data = (New-Object PSObject | Add-Member -PassThru NoteProperty description $gistname | Add-Member -PassThru NoteProperty public true | Add-Member -PassThru NoteProperty files (New-Object PSObject | Add-Member -PassThru NoteProperty $filename (New-Object PSObject | Add-Member -PassThru NoteProperty content "testing" ) | ConvertTo-Json -Compress ) | ConvertTo-Json -Compress ) | ConvertTo-Json -Compress # get the byte[] for the POST #$bytes = [System.Text.Encoding]::ASCII.GetBytes($data) Write-Host $data # create the web client to post $wc = New-Object System.Net.WebClient $wc.Headers.Add("Content-Type", "application/vnd.github.beta+json") $resp = $wc.UploadString($gistapi, $data) # temp: write out the response # ideally this would parse response, write out the resulting URI to the gist Write-Host ([System.Text.Encoding]::ASCII).GetString($resp)
PowerShellCorpus/GithubGist/RamblingCookieMonster_558007250a0380b94ac4_raw_33026e7e0516ecb7eb509446982c8777ae314d0b_Test-Pipeline.ps1
RamblingCookieMonster_558007250a0380b94ac4_raw_33026e7e0516ecb7eb509446982c8777ae314d0b_Test-Pipeline.ps1
<# This function and following examples illustrate the implementation of two helpful scenarios: Pipeline input, with verbose output describing the values and types within the Begin, Process, and End blocks ShouldProcess support, with friendly bypass handling using a Force switch. #> Function Test-Pipeline { [cmdletbinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] param( [parameter( Mandatory = $false, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] [string[]]$ComputerName = "$env:computername", [switch]$Force ) Begin { $RejectAll = $false $ConfirmAll = $false Write-Verbose "BEGIN Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" } Process { Write-Verbose "PROCESS Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" foreach($Computer in $ComputerName) { if($PSCmdlet.ShouldProcess( "Processed the computer '$Computer'", "Process the computer '$Computer'?", "Processing computer" )) { if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to process '$Computer'?", "Processing '$Computer'", [ref]$ConfirmAll, [ref]$RejectAll)) { Write-Verbose "----`tPROCESS Block, FOREACH LOOP - processed item is a $(try{$computer.GetType()} catch{$null}) with value $computer`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" } } } } End { Write-Verbose "END Block - `$ComputerName is a $(try{$ComputerName.GetType()} catch{$null}) with value $ComputerName`nPSBoundParameters is `t$($PSBoundParameters |Format-Table -AutoSize | out-string )" } } #Define some computer names we will test with $Computers = "Computer1", "Computer2" # Test this using pipeline input $Computers | Test-Pipeline -verbose #Test this using named parameters Test-Pipeline -ComputerName $Computers -Verbose #Test this using force with named parameters Test-Pipeline -ComputerName $Computers -Force -Verbose #ShouldProcess implementation borrowed from Jaykul's Demo-ShouldProcess - http://poshcode.org/3291
PowerShellCorpus/GithubGist/mortenya_ffd155fb325958076312_raw_952d39561d33010672aa17a7a2f320482866524b_Get-LoggedOnUserSession.ps1
mortenya_ffd155fb325958076312_raw_952d39561d33010672aa17a7a2f320482866524b_Get-LoggedOnUserSession.ps1
function get-loggedonuser ($computername){ #mjolinor 3/17/10 $regexa = '.+Domain="(.+)",Name="(.+)"$' $regexd = '.+LogonId="(\d+)"$' $logontype = @{ "0"="Local System" "2"="Interactive" #(Local logon) "3"="Network" # (Remote logon) "4"="Batch" # (Scheduled task) "5"="Service" # (Service account logon) "7"="Unlock" #(Screen saver) "8"="NetworkCleartext" # (Cleartext network logon) "9"="NewCredentials" #(RunAs using alternate credentials) "10"="RemoteInteractive" #(RDP\TS\RemoteAssistance) "11"="CachedInteractive" #(Local w\cached credentials) } $logon_sessions = @(gwmi win32_logonsession -ComputerName $computername) $logon_users = @(gwmi win32_loggedonuser -ComputerName $computername) $session_user = @{} $logon_users |% { $_.antecedent -match $regexa > $nul $username = $matches[1] + "\" + $matches[2] $_.dependent -match $regexd > $nul $session = $matches[1] $session_user[$session] += $username } $logon_sessions |%{ $starttime = [management.managementdatetimeconverter]::todatetime($_.starttime) $loggedonuser = New-Object -TypeName psobject $loggedonuser | Add-Member -MemberType NoteProperty -Name "Session" -Value $_.logonid $loggedonuser | Add-Member -MemberType NoteProperty -Name "User" -Value $session_user[$_.logonid] $loggedonuser | Add-Member -MemberType NoteProperty -Name "Type" -Value $logontype[$_.logontype.tostring()] $loggedonuser | Add-Member -MemberType NoteProperty -Name "Auth" -Value $_.authenticationpackage $loggedonuser | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $starttime $loggedonuser } }
PowerShellCorpus/GithubGist/smasterson_9141216_raw_b5c35083d9c532f2584fc0854ed3ecbccb69960a_ChangePwd.ps1
smasterson_9141216_raw_b5c35083d9c532f2584fc0854ed3ecbccb69960a_ChangePwd.ps1
# # ChangePwd # # Author: Shawn Masterson # Created: June 2013 # Version: 1 # # Purpose: Change local Windows account passwords on remote systems located in a vSphere folder # # # Arguments: # -vCenter - vCenter Server FQDN or IP # -VMFolder - vCenter folder containing VMs to update # -Flush - Clears current share connections (\\computer\share$) # # Examples: # .\ChangePwd.ps1 # .\ChangePwd.ps1 -Flush # .\ChangePwd.ps1 -vCenter vcenterserver -VMFolder "My VMs" # # Notes: # You can right click on script and 'Run from Powershell' # The -Flush parameter will run the following command on start-up - net use * /d /y (understand what this does before using!) # If you have multiple folders with the same name, VMs in all folders will be updated # # Supported OS's: # Windows Servers 03/03x64/08/08x64/08R2/2012 # # Requirements: # vCenter (Server list to be updated is gathered from vCenter - only tested on 5.x) # Script host must have PowerCLI (only tested on 5.x) # Script host needs WMI/RPC access to servers being updated # VMware Tools must be installed and running on the Windows VMs # Must be able to resolve DNS names of systems as seen in vCenter # # Disclaimer: # There is absolutely zero error catching built into this script! # USE AT YOUR OWN RISK # # # #-------------------------------------------------------------------- # Parameters (Arguments) # param ( $vcenter, $VMFolder, [switch]$Flush ) # # #-------------------------------------------------------------------- # User Denifed Variables # # vSphere folder to exclude (notmatch) $skipFolder = "Clone" # #-------------------------------------------------------------------- # Load Snap-ins # # Add VMware snap-in if required if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) {add-pssnapin VMware.VimAutomation.Core} # # #-------------------------------------------------------------------- # Main Procedures # # Flush share connections if -Flush is used If ($Flush) {net use * /d /y | Out-Null} # cls Write-Host "ChangePwd " (Get-Date) -foregroundcolor "Yellow" Write-Host "`nThis script will change the password of a user account on remote VMs" -foregroundcolor "Yellow" Write-Host "VMs are gathered from a choosen vSphere folder`n`n`n" -foregroundcolor "Yellow" # # Ask for vCenter address (if not provided) If ($vcenter -eq $Null) {$vcenter = Read-Host "Enter vCenter server FQDN or IP"} Write-Host # # Connect to vCenter server Try { Write-Host "Connecting to vCenter -" $vcenter -foregroundcolor "Yellow" Connect-VIServer $vcenter -EA Stop } Catch { Write-Host "`r`n`r`nUnable to connect to" $vcenter -backgroundcolor Red Write-Host "Exiting...`r`n`r`n" -foregroundcolor "Yellow" Exit } # # Ask for vSphere folder to get VMs from (if not provided) Write-Host "`n" If ($VMFolder -eq $Null) {$VMFolder = Read-Host "Enter vSphere folder to query"} # # Grab all Windows VM guest hostnames that are Powered On in the supplied vSphere folder Write-Host "`n" Write-Host "Querying All Running Windows VMs in Folder(s) -" $VMFolder -foregroundcolor "Yellow" $vms = Get-Folder $VMFolder | Get-VM | Where-Object {$_.Guest.OSFullName -like "*Windows*" -and $_.PowerState -eq "PoweredOn" -and $_.Folder.Name -notmatch $skipFolder} | ` Sort -Property Name | foreach { $_.Guest.Hostname } # # Confirm vSphere Folder exists If ($vms -eq $Null) { Write-Host "`r`n`r`nFolder does not exists or no VMs in Folder to scan" -backgroundcolor Red Write-Host "Exiting...`r`n`r`n" -foregroundcolor "Yellow" Exit} # Write-Host "`nFound" $vms.Count "systems`n" -foregroundcolor "Yellow" # # Write-Host "`n`n" If ($Account -eq $Null) {$Account = Read-Host "Enter Windows account to update password"} If ($Newpwd -eq $Null) {$Newpwd = Read-Host 'Enter NEW password for' $Account} # # # Write-Host "`n`n" Write-Host "Credentials are needed to connect to the Windows Servers being updated`n" -foregroundcolor "Yellow" If ($Username -eq $Null) {$Username = Read-Host "Enter Windows Admin username"} If ($Password -eq $Null) {$Password = Read-Host 'Enter Windows password for' $Username} Write-Host "`n`n" Write-Host "Process started..." -foregroundcolor "Yellow" Write-Host # # # Update account password on each VM foreach ($vm in $vms) { Write-Host "`nUpdating" $vm -foregroundcolor "Yellow" Try { $remote = New-Object System.DirectoryServices.DirectoryEntry("WinNT://$vm/$account,user",$username,$password) $remote.SetPassword($Newpwd) } Catch { Write-Host "FAILED" -backgroundcolor Red $error[0] $fails = $fails + "`n" + $vm } } # # # # #-------------------------------------------------------------------- # Close Connections # # Disconnect vCenter Disconnect-VIServer -Server $vcenter -Force -Confirm:$false # #-------------------------------------------------------------------- # Outputs # Write-Host "`n`n" Write-Host "Update Complete`n" -foregroundcolor "Yellow" If ($fails -ne $Null) {Write-Host "The following servers failed to update:" $fails -backgroundcolor Red} # # Prompt to exit script Write-Host "`n`n" Write-Host "Press any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
PowerShellCorpus/GithubGist/pcgeek86_945f327819dedc2378c3_raw_b2bcb0e9f32e032e58bb19734867dcf054d9c638_DSC-NewAzureVM.ps1
pcgeek86_945f327819dedc2378c3_raw_b2bcb0e9f32e032e58bb19734867dcf054d9c638_DSC-NewAzureVM.ps1
#region Subscription $SubscriptionName = 'Visual Studio Ultimate with MSDN'; Select-AzureSubscription -SubscriptionName $SubscriptionName; #endregion #region Affinity Group $AffinityGroup = @{ Name = 'powershelldsc'; Location = 'North Central US'; }; if (!(Get-AzureAffinityGroup -Name $AffinityGroup.Name -ErrorAction SilentlyContinue)) { [void](New-AzureAffinityGroup @AffinityGroup); } Read-Host -Prompt '#Region Affinity Group completed!'; #endregion #region Storage Account $StorageAccount = @{ StorageAccountName = 'powershelldsc'; AffinityGroup = $AffinityGroup.Name; } if (!(Get-AzureStorageAccount -StorageAccountName $StorageAccount.StorageAccountName -ErrorAction SilentlyContinue)) { [void](New-AzureStorageAccount @StorageAccount); } Set-AzureSubscription -SubscriptionName $SubscriptionName -CurrentStorageAccountName $StorageAccount.StorageAccountName; # Get the storage account keys, and then create a storage context $StorageKey = Get-AzureStorageKey -StorageAccountName $StorageAccount.StorageAccountName; $Context = New-AzureStorageContext -StorageAccountName $StorageAccount.StorageAccountName -StorageAccountKey $StorageKey.Primary; Read-Host -Prompt '#Region Storage Account completed!'; #endregion #region DSC Configuration $DSCConfig = @{ ConfigurationPath = '{0}\DSC-DSCWave.ps1' -f $PSScriptRoot; ConfigurationArchive = '{0}\DSC-DSCWave.zip' -f $PSScriptRoot; } Publish-AzureVMDscConfiguration -ConfigurationPath $DSCConfig.ConfigurationPath -ConfigurationArchivePath $DSCConfig.ConfigurationArchive -Force; Publish-AzureVMDscConfiguration -ConfigurationPath $DSCConfig.ConfigurationPath -StorageContext $Context -Force; Read-Host -Prompt '#Region DSC Configuration completed!'; #endregion #region Cloud Service $Service = @{ ServiceName = 'powershelldsc'; AffinityGroup = $AffinityGroup.Name; Description = 'Contains VMs used for PowerShell DSC testing.'; }; if (!(Get-AzureService -ServiceName $Service.ServiceName -ErrorAction SilentlyContinue)) { [void](New-AzureService @Service); } Read-Host -Prompt '#Region Cloud Service completed!'; #endregion #region Virtual Machine #$ImageList = Get-AzureVMImage; #$ImageList.Where({ $PSItem.ImageName -match '2012-R2' }).ImageName; $VMConfig = @{ Name = 'powershelldsc'; InstanceSize = 'Medium'; ImageName = 'a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201407.01-en.us-127GB.vhd'; }; # Create the VM configuration $VM = New-AzureVMConfig @VMConfig; $VMProvisioningConfig = @{ Windows = $true; Password = 'P@ssw0rd!'; AdminUsername = 'Trevor'; VM = $VM; }; # Add the Windows provisioning details to the VM configuration [void](Add-AzureProvisioningConfig @VMProvisioningConfig); $VMDscExtension = @{ ConfigurationArchive = '{0}.zip' -f (Split-Path -Path $DSCConfig.ConfigurationPath -Leaf); ConfigurationName = 'DSCWave'; VM = $VM; }; [void](Set-AzureVMDscExtension @VMDscExtension); # Create the Azure Virtual Machine [void](New-AzureVM -ServiceName $Service.ServiceName -VMs $VM); Write-Host -Object '#Region Virtual Machine completed!'; return; #endregion #region Cleanup Remove-AzureService -ServiceName $Service.ServiceName -DeleteAll -Force; Remove-AzureStorageAccount -StorageAccountName $StorageAccount.StorageAccountName; Remove-AzureAffinityGroup -Name $AffinityGroup.Name; #endregion #region Helper stuff # RDP into the Azure VM Get-AzureRemoteDesktopFile -ServiceName $Service.ServiceName -Name $VMConfig.Name -Launch; # Update the DSC extension on the target AzureVM $AzureVM = Get-AzureVM -ServiceName $Service.ServiceName -Name $VMConfig.Name; $AzureVMNew = Set-AzureVMDscExtension -VM $AzureVM -ConfigurationArchive $VMDscExtension.ConfigurationArchive -ConfigurationName VisualStudio2013Express; $AzureVMNew | Update-AzureVM; # Stop/start the VM (use on-demand) $AzureVM | Stop-AzureVM -Force; $AzureVM | Start-AzureVM; $AzureVM | Update-AzureVM; $AzureVM | Remove-AzureVM -DeleteVHD; #endregion
PowerShellCorpus/GithubGist/anderssonjohan_4738733_raw_02e02488679b99f32922cef516af1cc4f99f10a5_testargs.ps1
anderssonjohan_4738733_raw_02e02488679b99f32922cef516af1cc4f99f10a5_testargs.ps1
param( [string] $foo, [int] $bar ) $arguments = "" # Change to $PSBoundParameters.. $MyInvocation.BoundParameters.Keys | %{ Write-Host "key $_" # $MyInvocation.BoundParameters.Item( string key ) fails in PowerShell 3.0: # $paramValue = $MyInvocation.BoundParameters.Item( $_ ) # # Exception getting "Item": "The given key was not present in the dictionary." # At C:\temp\testargs.ps1:8 char:2 # + $paramValue = $MyInvocation.BoundParameters.Item( $_ ) # + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + CategoryInfo : NotSpecified: (:) [], GetValueInvocationException # + FullyQualifiedErrorId : ExceptionWhenGetting # This works in both PowerShell 2.0 and 3.0 # Conclusion: Do not use $MyInvocation.BoundParameters - it will have the keys but not the values? # $PSBoundParameters has both keys and values on v2 and v3. $paramValue = $PSBoundParameters.Item( $_ ) if( $paramValue -match "\s" ) { $paramValue = """$paramValue""" } $arguments += " -$_ $paramValue" } Write-Host $arguments
PowerShellCorpus/GithubGist/AmrEldib_3581c3aff5aee81dc2f9_raw_9031f8537e6b49b0aeb5eeec40772662944155fc_GetChildItem.ps1
AmrEldib_3581c3aff5aee81dc2f9_raw_9031f8537e6b49b0aeb5eeec40772662944155fc_GetChildItem.ps1
Get-ChildItem | out-file "D:\MyOutputFile.txt" -Append -Force
PowerShellCorpus/GithubGist/trondhindenes_948ee0aa0ef99b5ee1d7_raw_4aeeba05b28a01686e64d40c54e44fbcac1dc89a_generateDBs.ps1
trondhindenes_948ee0aa0ef99b5ee1d7_raw_4aeeba05b28a01686e64d40c54e44fbcac1dc89a_generateDBs.ps1
$Folders = get-childitem *db* -path "D:\MDB" -Recurse foreach ($folder in $folders) { $DBName = $folder.Name $ExchangeServer = $DBName.split("-")[0] $LogFolderPath = $folder.Fullname.Replace("DB","LOG") $edbfilepath = "$($folder.FullName)\$DBName.edb" if (!(get-mailboxdatabase $DBName -erroraction 0)) { New-mailboxdatabase -server $ExchangeServer -name $dbname -LogFolderPath $LogFolderPath } }
PowerShellCorpus/GithubGist/belotn_6827958_raw_8ca6659a8b6502128faa7885b901b3d1069eb96c_get-emptygpo2.ps1
belotn_6827958_raw_8ca6659a8b6502128faa7885b901b3d1069eb96c_get-emptygpo2.ps1
Get-ADObject -Filter 'ObjectClass -eq "groupPolicyContainer"' -SearchBase 'CN=Policies,CN=System,DC=fabrikam,DC=com' |% { Get-Adobject $_.distinguishedName -properties * } |?{ [bool]( gci "$($_.gPCFileSysPath)\User") -eq $false -and [bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false } | select DisplayName
PowerShellCorpus/GithubGist/jonschoning_5306402_raw_a2c6198dc394bd6c9a56b7cd3b51b83d1187730b_select-not-match.ps1
jonschoning_5306402_raw_a2c6198dc394bd6c9a56b7cd3b51b83d1187730b_select-not-match.ps1
Function select-not-match ($filter, $pattern) { Get-ChildItem -Filter $filter -Recurse | Where-Object { !(Select-String -Path $_.fullname -Pattern $pattern -SimpleMatch -Quiet) } | select fullname }