full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Get-ShortenedURL.ps1
Get-ShortenedURL.ps1
Function Get-ShortenedURL { <# .SYNOPSIS Get-ShortenedURL Author: Chris Campbell (@obscuresec) License: BSD 3-Clause .DESCRIPTION A function that returns the actual URL from a http redirect. .PARAMETER $ShortenedURL Specifies the shortened URL. .EXAMPLE PS C:\\> Get-ShortenedURL -ShortenedURL http://goo.gl/V4PKq PS C:\\> Get-ShortenedURL -ShortenedURL http://goo.gl/V4PKq,http://bit.ly/IeWSIZ PS C:\\> Get-Content C:\\urls.txt | Get-ShortenedURL PS C:\\> Get-ShortenedURL -ShortenedURL (Get-Content C:\\urls.txt) .LINK http://obscuresecurity.blogspot.com/2013/01/Get-ShortenedURL.html https://github.com/obscuresec/random/blob/master/Get-ShortenedURL #> [CmdletBinding()] Param( [Parameter(Mandatory=$True,ValueFromPipeline=$True)] [string[]] $ShortenedURL ) BEGIN {} PROCESS { Try { #Loop through each URL in the array Foreach ($URL in $ShortenedURL) { #Create the WebClient Object and request $WebClientObject = New-Object System.Net.WebClient $WebRequest = [System.Net.WebRequest]::create($URL) $WebResponse = $WebRequest.GetResponse() #Parse out redirected URL $ActualDownloadURL = $WebResponse.ResponseUri.AbsoluteUri #Create custom object to store results $ObjectProperties = @{ 'Shortened URL' = $URL; 'Actual URL' = $ActualDownloadURL} $ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties #Output the results Write-Output $ResultsObject #Close the webclient connection $WebResponse.Close() } } Catch {} } END {} }
PowerShellCorpus/PoshCode/Report-RecipientCounts.ps1
Report-RecipientCounts.ps1
<# .SYNOPSIS Report-RecipientCounts.ps1 Keep a running total of daily recipient count distribution. .DESCRIPTION Keep a running total of daily recipient count distribution. .PARAMETER Days The number of days back to examine logs. Default = 1 (Yesterday) .EXAMPLE Report-RecipientCounts.ps1 Get the report for yesterday. .EXAMPLE Report-RecipientCounts.ps1 -Days 3 Get the report for 3 days ago, which was missed .NOTES Original framework for this report came from: http://www.msexchange.org/kbase/ExchangeServerTips/ExchangeServer2010/Monitoring/E-mailRecipientNumberDistribution.html I modified the script slightly so we can have a running history and a quick view web page. #> param( [int]$Days= 1 ) # set the time period for the report - default is yesterday $Days = $Days * (-1) $Start = get-date $((get-date).adddays($Days)) -hour 00 -minute 00 -second 00 $End = get-date $((get-date).adddays($Days)) -hour 23 -minute 59 -second 59 #=====> TO DO -- change <webserver> to a location in your environment $HistoryFile = '\\\\<webserver>\\RecipientCounts.CSV' $HTMLOutFile = '\\\\<webserver>\\RecipientCounts.htm' $RecipientCounts = @() If (Test-Path$HistoryFile){$RecipientCounts = Import-Csv $HistoryFile} # Create a new object to hold today's finding $NewCountObj = New-ObjectPSObject $NewCountObj | Add-Member -typeNoteProperty-name Date -value (get-date $Start -Format yyyyMMdd) $NewCountObj | Add-Member -typeNoteProperty-name '1' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '2' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '5' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '10' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '30' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '50' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '75' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '100' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '150' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '200' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '250' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '300' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '350' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '400' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '500' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '600' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '700' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '800' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '900' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '1000' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '3000' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name '5000' -value (0) $NewCountObj | Add-Member -typeNoteProperty-name 'Big' -value (0) Get-TransportServer | Get-MessageTrackingLog -ResultSize Unlimited -EventID RECEIVE -Start $Start -End $End | ? {$_.Source -eq "STOREDRIVER"} | Select RecipientCount | ForEach { If ($_.RecipientCount-eq 1) {$NewCountObj.'1'++ } If ($_.RecipientCount-eq 2) {$NewCountObj.'2'++ } If ($_.RecipientCount-gt 2 -and $_.RecipientCount -le 5) {$NewCountObj.'5'++ } If ($_.RecipientCount-gt 5 -and $_.RecipientCount -le 10) {$NewCountObj.'10'++ } If ($_.RecipientCount-gt 10 -and $_.RecipientCount -le 30) {$NewCountObj.'30'++ } If ($_.RecipientCount-gt 30 -and $_.RecipientCount -le 50) {$NewCountObj.'50'++ } If ($_.RecipientCount-gt 50 -and $_.RecipientCount -le 75) {$NewCountObj.'75'++ } If ($_.RecipientCount-gt 75 -and $_.RecipientCount -le 100) {$NewCountObj.'100'++ } If ($_.RecipientCount-gt 100 -and $_.RecipientCount -le 150) {$NewCountObj.'150'++ } If ($_.RecipientCount-gt 150 -and $_.RecipientCount -le 200) {$NewCountObj.'200'++ } If ($_.RecipientCount-gt 200 -and $_.RecipientCount -le 250) {$NewCountObj.'250'++ } If ($_.RecipientCount-gt 250 -and $_.RecipientCount -le 300) {$NewCountObj.'300'++ } If ($_.RecipientCount-gt 300 -and $_.RecipientCount -le 350) {$NewCountObj.'350'++ } If ($_.RecipientCount-gt 350 -and $_.RecipientCount -le 400) {$NewCountObj.'400'++ } If ($_.RecipientCount-gt 400 -and $_.RecipientCount -le 500) {$NewCountObj.'500'++ } If ($_.RecipientCount-gt 500 -and $_.RecipientCount -le 600) {$NewCountObj.'600'++ } If ($_.RecipientCount-gt 600 -and $_.RecipientCount -le 700) {$NewCountObj.'700'++ } If ($_.RecipientCount-gt 700 -and $_.RecipientCount -le 800) {$NewCountObj.'800'++ } If ($_.RecipientCount-gt 800 -and $_.RecipientCount -le 900) {$NewCountObj.'900'++ } If ($_.RecipientCount-gt 900 -and $_.RecipientCount -le 1000) {$NewCountObj.'1000'++ } If ($_.RecipientCount-gt 1000 -and $_.RecipientCount -le 3000) {$NewCountObj.'3000'++ } If ($_.RecipientCount-gt 3000 -and $_.RecipientCount -le 5000) {$NewCountObj.'5000'++ } If ($_.RecipientCount-gt 5000) {$NewCountObj.Big++ } } $NewCounts= @() if ($RecipientCounts) { $NewCounts = @($RecipientCounts) + @($NewCountObj) }Else { $NewCounts = $NewCountObj } $NewCounts=$NewCounts | Sort Date-Descending $NewCounts | Export-Csv $HistoryFile -NoTypeInformation # Simple Headers $Header1 = '<h2><font Color = #151b8d><p style="text-align: center;"><b>Recipient Counts History Report</b></p></font></h2>' $Header2 = '<h4><font Color = #151b8d><p style="text-align: center;"><b>(Updated Daily via[' + $(split-path $MyInvocation.InvocationName -Leaf) + '])</b></p></Font></h4>' $Header3 = '<h3><font Color = #800517><p style="text-align: center;">' + $(Get-Date) + '</font></H3></p>' $a = "<style>" $a = $a + "BODY{background-color:LightCyan;text-align: center;}" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;text-align: center;}" $a = $a + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:Bisque}" $a = $a + "TD{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:AntiqueWhite}" $a = $a + "</style>" $NewCounts | ConvertTo-Html -Head ($A,$Header1,$Header2,$Header3) | out-file $HTMLOutFile -Force
PowerShellCorpus/PoshCode/Services Auto NotRunning_1.ps1
Services Auto NotRunning_1.ps1
#LazyWinAdmin.com Get-WmiObject Win32_Service -ComputerName . |` where {($_.startmode -like "*auto*") -and ` ($_.state -notlike "*running*")}|` select DisplayName,Name,StartMode,State|ft -AutoSize
PowerShellCorpus/PoshCode/Begin Block.ps1
Begin Block.ps1
Begin { #VMware VM Host (ESX) UUID $VMHost_UUID = @{ Name = "VMHost_UUID" Expression = { $_.Summary.Hardware.Uuid } } #XenServer Host UUID $XenHost_UUID = @{ Name = "XenHost_UUID" Expression = { $_.Uuid } } }
PowerShellCorpus/PoshCode/ConvertTo-Hex_6.ps1
ConvertTo-Hex_6.ps1
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx param ( [string]$SidString ) # Create SID .NET object using SID string provided $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring # Create a byte array of the proper length $sidBytes = New-Object byte[] $sid.BinaryLength #Convert to bytes $sid.GetBinaryForm( $sidBytes, 0 ) # Iterate through bytes, converting each to the hexidecimal equivalent $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } # Join the hex array into a single string for output $hexArr -join ''
PowerShellCorpus/PoshCode/Convert-ToCHexString_5.ps1
Convert-ToCHexString_5.ps1
function Convert-ToCHexString { param ([String] $str) $ans = '' [System.Text.Encoding]::ASCII.GetBytes($str) | % { $ans += "0x{0:X2}, " -f $_ } return $ans.Trim(' ',',') }
PowerShellCorpus/PoshCode/Timespan SMTP Headers.ps1
Timespan SMTP Headers.ps1
$hdr_txt = gc ./hdr.txt $rec_hdr_regex = [regex]"^Received\\:\\sfrom\\s(.+?)\\sby\\s(.+?)\\;\\s(.+?\\d\\d\\:\\d\\d\\:\\d\\d\\s[+|-]\\d{4})" $from_hdr = $hdr_txt | select-string "^From\\:\\s.+$" $rec_block = $hdr_txt[0..$($from_hdr.linenumber -2)] $rec_lines = $rec_block | select-string "^Received\\:\\sfrom" $sent_hdr = $hdr_txt | select-string "^Date\\:\\s.+$" $sent_hdr.line -match "^Date\\:\\s(.+)$" > $nul $sent_ts = [datetime]$matches[1] foreach ($rec_line in $rec_lines[1..$($rec_lines.count -1)]){$rec_block[$rec_line.linenumber -1] = "~" + $rec_line.line} $rec_hdrs = $([string]$rec_block).split("~") Write-host "`nMessage sent $($sent_ts)`n" $i = $rec_hdrs.count -1 $last_ts = $sent_ts while ($i -ge 0) { $rec_hdrs[$i] -match $rec_hdr_regex > $nul $rec_ts = [datetime]$matches[3] $latency = $rec_ts - $last_ts $last_ts = $rec_ts write-host "latency is $($latency.totalseconds) seconds`n" write-host $matches[1] $i-- } Write-host "`nMessage received $($last_ts)" write-host "Total time is $($($last_ts - $sent_ts).seconds) seconds.`n"
PowerShellCorpus/PoshCode/Pause_1.ps1
Pause_1.ps1
function Pause ($Message = "Press any key to continue...") { Write-Host -NoNewline $Message $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Write-Host "" }
PowerShellCorpus/PoshCode/Select-Random v2.0.ps1
Select-Random v2.0.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Joel "Jaykul" Bennett ### </Author> ### <Description> ### Selects a random element from the collection either passed as a parameter or input via the pipeline. ### If the collection is passed in as an argument, we simply pick a random number between 0 and count-1 ### for each element you want to return, but when processing pipeline input we want to keep memory use ### to a minimum, so we use a "reservoir sampling" algorithm[1]. ### ### [1] http://gregable.com/2007/10/reservoir-sampling.html ### ### The script stores $count elements (the eventual result) at all times. It continues processing ### elements until it reaches the end of the input. For each input element $n (the count of the inputs ### so far) there is a $count/$n chance that it becomes part of the result. ### * For each previously selected element, there is a $count/($n-1) chance of it being selected ### * For the ones selected, there's a ($count/$n * 1/$count = 1/$n) chance of it being replaced, so a ### ($n-1)/$n chance of it remaining ... thus, it's cumulative probability of being among the selected ### elements after the nth input is processed is $count/($n-1) * ($n-1)/$n = $count/$n, as it should be. ### ### </Description> ### <Usage> ### $arr = 1..5; Select-Random $arr ### 1..10 | Select-Random -Count 2 ### </Usage> ### <Version>2.0.0.0</Version> ### </Script> param([int]$count=1, [array]$inputObject=$null) BEGIN { if ($args -eq '-?') { @" Usage: Select-Random [[-Count] <int>] [-inputObject] <array> (from pipeline) [-?] Parameters: -Count : The number of elements to select. -Collection : The collection from which to select a random element. -? : Display this usage information and exit Examples: PS> $arr = 1..5; Select-Random $arr PS> 1..10 | Select-Random -Count 2 "@ exit } elseif ($inputObject) { ### If you're accepting $args, you need to pass those in... # Write-Output $io | &($MyInvocation.InvocationName) $args; Write-Output $inputObject | &($MyInvocation.InvocationName) -Count $count break; } else { $seen = 0 $selected = new-object object[] $count $rand = new-object Random } } PROCESS { if($_) { $seen++ if($seen -lt $count) { $selected[$seen-1] = $_ } ## For each input element $n there is a $count/$n chance that it becomes part of the result. elseif($rand.NextDouble() -gt $count/$seen) { ## For the ones previously selected, there's a 1/$n chance of it being replaced $selected[$rand.Next(0,$count)] = $_ } } } END { if (-not $inputObject) { ## DO ONCE: (only on the re-invoke, not when using -inputObject) Write-Verbose "Selected $count of $seen elements" Write-Output $selected # foreach($el in $selected) { Write-Output $el } } }
PowerShellCorpus/PoshCode/FTP upload_5.ps1
FTP upload_5.ps1
@charset "utf-8"; /* Credit:http://www.templatemo.com */ body { margin: 0px; padding: 0px; color: #c2bead; font-family: Tahoma, Geneva, sans-serif; font-size: 12px; line-height: 1.5em; background-color: #2f2e28; background-image: url(images/templatemo_body.jpg); background-repeat: repeat-y; background-position: left; } a, a:link, a:visited { color: #34baf9; text-decoration: none; } a:hover { color: #CCFF00; text-decoration: underline; } p { margin: 0 0 10px 0; padding: 0; } img { border: none; } h1, h2, h3, h4, h5, h6 { color: #e2c934; } h1 { font-size: 24px; font-weight: normal; margin: 0 0 30px 0; padding: 5px 0; } h2 { font-size: 20px; font-weight: normal; margin: 0 0 30px 0; font-weight: normal; } h3 { font-size: 16px; margin: 0 0 15px 0; padding: 0; padding: 0; font-weight: normal; } h4 { font-size: 14px; margin: 0 0 15px 0; padding: 0; } .cleaner { clear: both; width: 100%; height: 0px; font-size: 0px; } .cleaner_h10 { clear: both; width:100%; height: 10px; } .cleaner_h20 { clear: both; width:100%; height: 20px; } .cleaner_h30 { clear: both; width:100%; height: 30px; } .cleaner_h40 { clear: both; width:100%; height: 40px; } .cleaner_h50 { clear: both; width:100%; height: 50px; } .cleaner_h60 { clear: both; width:100%; height: 60px; } .float_l { float: left; } .float_r { float: right; } .image_wrapper { display: inline-block; border: 1px solid #000; background: #333; padding: 4px; margin-bottom: 10px; } .image_fl { float: left; margin: 3px 15px 0 0; } .image_fr { float: right; margin: 3px 0 0 15px; } blockquote { font-style: italic; margin: 0 0 0 10px;} cite { font-weight: bold; color:#333; } cite span { color: #666; } em { color: #f9a834; } .tmo_list { margin: 20px 0 20px 20px; padding: 0; list-style: none; } .tmo_list li { background: transparent url(images/templatemo_list.png) no-repeat; margin:0 0 20px; padding: 0 0 0 20px; line-height: 1em; } .tmo_list li a { color: #fff; } .tmo_list li a:hover { color: #ff4301; } .btn_more a { display: inline-block; font-weight: bold; color: #dcd9cb; } .btn_more a span { font-size: 16px; } .btn_more a:hover { color: #CCFF00; text-decoration: none; } .service_list { margin: 40px 0 0 30px; padding: 0; list-style: none; } .service_list li { margin: 0; padding: 0; } .service_list li a { display: block; height: 25px; margin-bottom: 20px; padding-left: 35px; } .service_list li .service_one { background: url(images/onebit_08.png) center left no-repeat; } .service_list li .service_two { background: url(images/onebit_11.png) center left no-repeat; } .service_list li .service_three { background: url(images/onebit_17.png) center left no-repeat; } .service_list li .service_four { background: url(images/onebit_21.png) center left no-repeat; } .service_list li .service_five { background: url(images/onebit_12.png) center left no-repeat; } #contact_form { padding: 0; } #contact_form form { margin: 0px; padding: 0px; } #contact_form form .input_field { width: 440px; padding: 8px; background: #333028; border: 1px solid #886; color: #FFF; } #contact_form form label { display: block; width: 100px; margin-right: 10px; font-size: 14px; margin-bottom: 3px; } #contact_form form textarea { width: 440px; height: 120px; padding: 8px; background: #333028; font-family: Arial, Helvetica, sans-serif; border: 1px solid #886; color: #FFF; } #contact_form form .submit_btn { color: #886; background: #333028; border: 1px solid #886; padding: 10px 20px; margin-right: 140px; font-size: 15px; } #gallery_container { clear: both; margin-top: 30px; padding-right: 40px; width: 480px; height: 320px; overflow: auto; } #gallery_container .gallery_box { clear: both; display: block; padding: 0; margin: 0 0 40px 0; } .gallery_box img { float: left; width: 120px; height: 100px; padding: 4px; background: #fff; border: 1px solid #ccc; margin: 3px 30px 0 0; } #templatemo_footer { clear: both; width: 600px; padding: 20px 0; text-align: center; }/* CSS Document */
PowerShellCorpus/PoshCode/Edit-RDP.ps1
Edit-RDP.ps1
######################################################################################################################## # NAME # Edit-RDP # # SYNOPSIS # Opens a RDP file for editing. # # SYNTAX # Edit-RDP [-Path] <string> # # DETAILED DESCRIPTION # The Edit-RDP cmdlet opens an existing RDP file for editing using the Microsoft Terminal Services Client. # # PARAMETERS # -Path <string> # Specifies the path to the RDP file. # # Required? true # Position? 1 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # INPUT TYPE # # # RETURN TYPE # # # NOTES # # -------------------------- EXAMPLE 1 -------------------------- # # C:\\PS>Edit-RDP -Path C:\\myserver.rdp # # # This command opens the specified RDP file for edit in Terminal Services Client. # # #Function global:Edit-RDP { param( [string]$Path = (throw "A path to a RDP file is required.") ) if (Test-Path $path) { mstsc.exe /edit $path } else { throw "Path does not exist." } #}
PowerShellCorpus/PoshCode/Lead Systems Engineer.ps1
Lead Systems Engineer.ps1
<# Author: Matt Schmitt Date: 11/28/12 Version: 1.0 From: USA Email: ithink2020@gmail.com Website: http://about.me/schmittmatt Twitter: @MatthewASchmitt Description A script for forwarding and unforwarding email for users in Office 365. #> Import-Module ActiveDirectory Write-Host "" Write-Host "PowerShell AD Password Tool" Write-Host "" Write-Host "This tool displays the Exparation Date of a user's Password and thier Lockedout" Write-Host "Status. It will then allow you to unlock and/or reset the password." Write-Host "" Write-Host "" #Counts how many locked account there are on the local DC and sets it to $count $count = Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Measure-Object | Select-Object -expand Count #If there are locked accounts (other than Administrator and Guest), then this will display who is locked out. If ( $count -gt 0 ) { Write-Host "Current Locked Out Accounts on your LOCAL Domain Controller:" Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Select-Object SamAccountName, LastLogonDate | Format-Table -AutoSize }else{ # Write-Host "There are no locked out accounts on your local Domain Controller." } Write-Host "" #Asks for the username $user = Read-Host "Enter username of the employee you would like to check or [ Ctrl+c ] to exit" Write-Host "" Write-Host "" [datetime]$today = (get-date) #Get pwdlastset date from AD and set it to $passdate $searcher=New-Object DirectoryServices.DirectorySearcher $searcher.Filter="(&(samaccountname=$user))" $results=$searcher.findone() $passdate = [datetime]::fromfiletime($results.properties.pwdlastset[0]) #Set password Age to $PwdAge $PwdAge = ($today - $passdate).Days If ($PwdAge -gt 90){ Write-Host "Password for $user is EXPIRED!" Write-Host "Password for $user is $PwdAge days old." }else{ Write-Host "Password for $user is $PwdAge days old." } Write-Host "" Write-Host "" Write-Host "Checking LockedOut Status on defined Domain Controllers:" #Get Lockedout status and display # ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls switch (Get-ADUser -server DC01.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC01: Not Locked"} "True" {"DC01: LOCKED"}} switch (Get-ADUser -server DC02.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC02: Not Locked"} "True" {"DC02: LOCKED"}} # ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs. Write-Host "" Write-Host "" [int]$y = 0 $option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?" cls While ($y -eq 0) { switch ($option) { "1" { # ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls Write-Host "Unlocking account on DC01" Unlock-ADAccount -Identity $user -server DC01.your.domain.com Write-Host "Unlocking account on DC02" Unlock-ADAccount -Identity $user -server DC02.your.domain.com # ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs. #Get Lockedout status and set it to $Lock $Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) Write-Host "" #Depending on Status, tell user if the account is locked or not. switch ($Lock) { "False" { Write-Host "$user is unlocked." } "True" { Write-Host "$user is LOCKED Out." } } Write-Host "" Write-Host "Press any key to Exit." $y += 1 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } "2" { $newpass = (Read-Host -AsSecureString "Enter user's New Password") Write-Host "" Write-Host "Resetting Password on local DC..." Write-Host "" Set-ADAccountPassword -Identity $user -NewPassword $newpass Write-Host "" Write-Host "Resetting Password on DC02" Write-Host "" # ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass # ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs. Write-Host "" Write-Host "Press any key to Exit." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $y += 1 } "3" { $newpass = (Read-Host -AsSecureString "Enter user's New Password") Write-Host "" Write-Host "Resetting Password on Local DC..." Write-Host "" Set-ADAccountPassword -Identity $user -NewPassword $newpass Write-Host "" Write-Host "Resetting Password on DC02" Write-Host "" # ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass # ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs. Write-Host "" Write-Host "Password for $user has been reset." Write-Host "" # ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls Write-Host "Unlocking account on DC01" Unlock-ADAccount -Identity $user -server DC01.your.domain.com Write-Host "Unlocking account on DC02" Unlock-ADAccount -Identity $user -server DC02.your.domain.com # ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs. #Get Lockedout status and set it to $Lock $Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) Write-Host "" #Depending on Status, tell user if the account is locked or not. switch ($Lock) { "False" { Write-Host "$user is unlocked." } "True" { Write-Host "$user is LOCKED Out." } } Write-Host "" Write-Host "Press any key to Exit." $y += 1 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } "4" { #exit code $y += 1 } default { Write-Host "You have entered and incorrect number." Write-Host "" $option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?" } } }
PowerShellCorpus/PoshCode/Download DefragTools _1.ps1
Download DefragTools _1.ps1
#requires -version 2.0 <# .Synopsis Downloads Channel 9 Defrag Tool Episode Video .DESCRIPTION Downloads Channel 9 Defrag Tool Episode Video in the format selected and to a given path. .EXAMPLE Downloads all shows in WMV format to the default Downloads Folder for the user. Get-DefragToolsShow -All -VideoType wmv .EXAMPLE Downloads only the last show of the series in MP4 format Get-DefragToolsShow -Last -VideoType MP4 .NOTES Author: Carlos Perez carlos_perez[at]darkoperator.com #> function Get-DefragToolsShow { [CmdletBinding()] Param ( [Parameter(Mandatory=$false, Position=0)] $Path = "$($env:USERPROFILE)\\downloads", [Parameter(Mandatory=$false, ParameterSetName="All")] [switch]$All = $true, [Parameter(Mandatory=$false, ParameterSetName="Last")] [switch]$Last = $true, [Parameter(Mandatory=$false)] [ValidateSet("MP4HD","MP4","WMVHD","WMV")] [string]$VideoType = "MP4HD" ) Begin { $WebClient = New-Object System.Net.WebClient $Global:downloadComplete = $false $eventDataComplete = Register-ObjectEvent $WebClient DownloadFileCompleted ` -SourceIdentifier WebClient.DownloadFileComplete ` -Action {$Global:downloadComplete = $true} $eventDataProgress = Register-ObjectEvent $WebClient DownloadProgressChanged ` -SourceIdentifier WebClient.DownloadProgressChanged ` -Action { $Global:DPCEventArgs = $EventArgs } # Lets change to the proper path Set-Location (Resolve-Path $Path).Path } Process { switch ($PsCmdlet.ParameterSetName) { "All"{$all = $true} "Last"{$all = $false} } switch ($VideoType) { "MP4HD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4high"} "MP4" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4"} "WMVHD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmvhigh"} "WMV" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmv"} } $feed = [xml]$WebClient.DownloadString($feedURL) if ($All) { foreach ($episode in $feed.rss.channel.Item) { # Create a proper URI for parsing $episodeURL = [System.Uri]$episode.enclosure.url # Get the episode file name $file = $episodeURL.Segments[-1] #Check if the file exists if it does skip it if (!(Test-Path $file)) { Write-Progress -Activity 'Downloading file' -Status $file $WebClient.DownloadFileAsync($episodeURL,$file) while (!($Global:downloadComplete)) { $pc = $Global:DPCEventArgs.ProgressPercentage if ($pc -ne $null) { Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc } } $Global:downloadComplete = $false } } } else { $episodeURL = [System.Uri]$feed.rss.channel.Item[0].enclosure.url # Get the episode file name $file = $episodeURL.Segments[-1] #Check if the file exists if it does skip it if (!(Test-Path $file)) { Write-Progress -Activity 'Downloading file' -Status $file $WebClient.DownloadFileAsync($episodeURL,$file) # Lets wait for it to finish while (!($Global:downloadComplete)) { $pc = $Global:DPCEventArgs.ProgressPercentage if ($pc -ne $null) { Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc } } } } } End { Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete $Global:downloadComplete = $null $Global:DPCEventArgs = $null [GC]::Collect() } }
PowerShellCorpus/PoshCode/Find-Abbreviation.ps1
Find-Abbreviation.ps1
# Name : Find-Abbreviation.ps1 # Author: David "Makovec" Moravec # Web : http://www.powershell.cz # Email : powershell.cz@googlemail.com # # Description: Finds meaning of given abbreviation # : Uses HttpRest http://poshcode.org/787 # # Version: 0.1 # History: # v0.1 - (add) basic functionality # # Usage: Find-Abbreviation itmu # ################################################################# function Find-Abbreviation { $url = "http://acronyms.thefreedictionary.com/$args" Invoke-Http get $url | Receive-Http Text "//tr[@cat]//td[2]" }
PowerShellCorpus/PoshCode/Start-BootsTimer_1.ps1
Start-BootsTimer_1.ps1
function Start-BootsTimer { #.Syntax # Creates a stay-on-top countdown timer #.Description # A WPF borderless count-down timer, with audio/voice alarms and visual countdown + colored progress indication #.Parameter EndMessage # The message to be spoken by a voice when the time is up... #.Parameter StartMessage # A message to be spoken at start up (just to let you know, audibly, what's up). #.Parameter Minutes # Some minutes to add to the timer #.Parameter Seconds # Some seconds to add to the timer #.Parameter Hours # Some hours to add to the timer #.Parameter SoundFile # A .wav file to play as the alarm #.Parameter FontSize # The size of the timer text #.Parameter SingleAlarm # Only sound the alarm once #.Example # Start-BootsTimer 180 "The three minute egg is ready!" # # Starts a three minute timer with the specified voice alert at the end # #.Example # Start-BootsTimer -End "The three minute egg is ready!" -Minute 3 # # Starts a three minute timer with the specified voice alert at the end # #.Example # Start-BootsTimer "Your turn is over!" -Minutes 10 -Single -FontSize 18 # # Starts a 10 minute timer that only plays the alert once at the end, and has a small font, which would fit over the task bar or a window title bar... [CmdletBinding(DefaultParameterSetName="Times")] PARAM( [Parameter(Position=2,ParameterSetName="Times",Mandatory=$false)] [Parameter(Position=1,ParameterSetName="Reasons", Mandatory=$true)] [string]$EndMessage , [Parameter(Position=2,ParameterSetName="Reasons", Mandatory=$false)] [string]$StartMessage , [Parameter(Position=3,ParameterSetName="Reasons", Mandatory=$false)] [int]$minutes = 0 , [Parameter(Position=4,ParameterSetName="Reasons", Mandatory=$false)] [Parameter(Position=1,ParameterSetName="Times", Mandatory=$true)] [int]$seconds = 0 , [Parameter()] [int]$hours = 0 , [Parameter()] $SoundFile = "$env:SystemRoot\\Media\\notify.wav" , [Parameter()] $FontSize = 125 , [Parameter()] [Switch]$SingleAlarm ) # Default to 10 seconds ... without adding 5 seconds when people specify minutes if(($seconds + $Minutes + $hours) -eq 0) { $seconds = 10 } $start = [DateTime]::Now ## We have to store all this stuff, because the powerboots window lasts longer than the script $TimerStuff = @{} $TimerStuff["seconds"] = [Math]::Abs($seconds) + [Math]::Abs([int]($minutes*60)) + [Math]::Abs([int]($hours*60*60)) $TimerStuff["TimerEnd"] = $start.AddSeconds( $TimerStuff["seconds"] ) $TimerStuff["SingleAlarm"] = $SingleAlarm ## Take care of as much overhead as we can before we need it... if(Test-Path $soundFile) { $TimerStuff["Sound"] = new-Object System.Media.SoundPlayer $TimerStuff["Sound"].SoundLocation=$SoundFile } if($EndMessage -or $StartMessage) { $TimerStuff["Voice"] = new-object -com SAPI.SpVoice } ## Create and store a scriptblock to figure out the remaining time and format it $TimerStuff["NowFunction"] = { $diff = $BootsTimer.Tag["TimerEnd"] - [DateTime]::Now; $diff.TotalSeconds if($diff.Ticks -ge 0) { ([DateTime]$diff.Ticks).ToString(" HH:mm.ss") } else { ([DateTime][Math]::Abs($diff.Ticks)).ToString("-HH:mm.ss") } } ## Create and store a scriptblock to sound the alarm $TimerStuff["AlarmFunction"] = { if($BootsTimer.Tag["Sound"]) { $BootsTimer.Tag["Sound"].Play() } else { [System.Media.SystemSounds]::Exclamation.Play() } if($BootsTimer.Tag["EndMessage"]) { $null = $BootsTimer.Tag["Voice"].Speak( $BootsTimer.Tag["EndMessage"], 1 ) } } ## Store the "EndMessage" message if($EndMessage) { $TimerStuff["EndMessage"] = $EndMessage } ## If they provided a second status message, read it out loud if($StartMessage) { $null = $TimerStuff["Voice"].Speak( $StartMessage, 1 ) } ## Make the window ... $Global:BootsTimer = boots -WindowStyle None -AllowsTransparency $true -Topmost $true { TextBlock "" -FontSize $FontSize -FontFamily Impact -margin 20 ` -BitmapEffect $(OuterGlowBitmapEffect -GlowColor White -GlowSize 15) ` -Foreground $(LinearGradientBrush -Start "1,1" -End "0,1" { GradientStop -Color Black -Offset 0.0 GradientStop -Color Black -Offset 0.95 GradientStop -Color Red -Offset 1.0 GradientStop -Color Red -Offset 1.0 }) # -TextDecorations ([System.Windows.TextDecorations]::Underline) } -On_MouseDown { if($_.ChangedButton -eq "Left") { $this.DragMove() } } -On_Close { $this.Tag["Timer"].Stop() Remove-BootsWindow $this } -Async -Popup -Passthru -Background Transparent -ShowInTaskbar $False -Tag $TimerStuff ## Now we need to call that scriptblock on a timer. That's easy, but it ## must be done on the window's thread, so we use Invoke-BootsWindow. ## Notice the first argument is the window we want to run the script in Invoke-BootsWindow $BootsTimer { ## We'll create a timer $BootsTimer.Tag["Timer"] = new-object System.Windows.Threading.DispatcherTimer $BootsTimer.Tag["Timer"].Interval = [TimeSpan]"0:0:0.05" ## And will invoke the $updateBlock $BootsTimer.Tag["Timer"].Add_Tick( { trap { write-host "Error: $_" -fore Red write-host $($_.Exception.StackTrace | Out-String) -fore Red } $remain, $BootsTimer.Content.Text = & $BootsTimer.Tag["NowFunction"] $remain = $remain / $BootsTimer.Tag["seconds"] ## Move the gradient a little bit each time. $BootsTimer.Content.Foreground.GradientStops[2].Offset = [Math]::Max(0.0, $remain) $BootsTimer.Content.Foreground.GradientStops[1].Offset = [Math]::Max(0.0, $remain - 0.05) ## When we get to the end ... make a few changes if($remain -le 0) { ## The first time we hit the end, we want to add a mouse click handler... if($this.Interval.Seconds -eq 0) { ## Which will now only fire every few seconds ## So it's easier to close the window ;) $this.Interval = [TimeSpan]"0:0:2" ## If you click on the finished window, it just goes away $BootsTimer.Add_MouseDown( { $BootsTimer.Close() } ) ## But if they chose -SingleAlarm, they don't neeto bother if($BootsTimer.Tag["SingleAlarm"]) { $BootsTimer.Close() } } & $BootsTimer.Tag["AlarmFunction"] } } ) ## Now start the timer running $BootsTimer.Tag["Timer"].Start() } }
PowerShellCorpus/PoshCode/Get_Set Signature 2.4.ps1
Get_Set Signature 2.4.ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping) #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## Get all the signatures ## ## ls | Select-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 2.4 - Added a -Module parameter to the Set-AuthenticodeSignature ## It will recursively sign all the signable files in a module... ## - Tweaked Get-AuthenticodeCertificate to first search Cert:\\CurrentUser\\My ## 's much faster on my home PC this way ## 2.3 - Reworked Get-UserCertificate and Get-AuthenticodeCertificate for better behavior ## 2.2 - Added sorting and filtering the displayed certs, and the option to save your choice ## 2.1 - Added some extra exports and aliases, and included my Start-AutoSign script... ## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support ## 1.7 - Modified the reading of certs to better support people who only have one :) ## 1.6 - Converted to work with CTP 3, and added function help comments ## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file ## Note: If you get this off PoshCode, you'll have to create it yourself, see below: ## 1.4 - Moved the default certificate setting into an external psd1 file. ## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-AuthenticodeSigned ## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned ## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files ## It's important to remember that the signatures are NOT checked by PowerShell yet... ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## #################################################################################################### function Get-UserCertificate { <# .SYNOPSIS Gets the user's default signing certificate so we don't have to ask them over and over... .DESCRIPTION The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can be reused without re-querying for the location and/or password ... .RETURNVALUE An X509Certificate2 suitable for code-signing #> [CmdletBinding()] param ( $Name ) begin { if($Name) { $Script:UserCertificate = Get-AuthenticodeCertificate $Name } } end { ## If they don't have a cert, or they haven't stored it... if(!(Test-Path Variable:Script:UserCertificate) -or $Script:UserCertificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2] -or $Script:UserCertificate.Thumbprint -ne $ExecutionContext.SessionState.Module.PrivateData ) { ## Verbose output if($VerbosePreference -gt "SilentlyContinue") { if(!(Test-Path Variable:Script:UserCertificate)) { Write-Verbose "Loading User Certificate from Module Config: $($ExecutionContext.SessionState.Module.PrivateData)" } else { Write-Verbose "Saving User Certificate to Module Config: ($($Script:UserCertificate.Thumbprint) -ne $($ExecutionContext.SessionState.Module.PrivateData))" } } Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)" ## If they don't have a cert if(!(Test-Path Variable:Script:UserCertificate) -or $Script:UserCertificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $Script:UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData } Write-Verbose "Confirming Certificate: $($Script:UserCertificate.Thumbprint)" ## If their cert isn't stored at least temporarily... if($Script:UserCertificate -and (!$ExecutionContext.SessionState.Module.PrivateData -or ($ExecutionContext.SessionState.Module.PrivateData -ne $Script:UserCertificate.Thumbprint))) { ## Store it temporarily ... $ExecutionContext.SessionState.Module.PrivateData = $Script:UserCertificate.Thumbprint ## And ask them if they want to store it permanently Write-Verbose "Updating Module Metadata" if($Host.UI -and $Host.UI.PromptForChoice -and (0 -eq $Host.UI.PromptForChoice("Keep this certificate for future sessions?", $Script:UserCertificate, [Management.Automation.Host.ChoiceDescription[]]@("&Yes","&No"), 0)) ) { $mVersion = $PSCmdlet.MyInvocation.MyCommand.Module.Version Write-Verbose "Version: $mVersion" if($MVersion -le "2.2") { $MVersion = 2.2 } New-ModuleManifest $PSScriptRoot\\Authenticode.psd1 ` -ModuleToProcess Authenticode.psm1 ` -Author 'Joel Bennett' -Company 'HuddledMasses.org' ` -ModuleVersion $MVersion ` -PowerShellVersion '2.0' ` -Copyright '(c) 2008-2010, Joel Bennett' ` -Desc 'Function wrappers for Authenticode Signing cmdlets' ` -Types @() -Formats @() -RequiredModules @() ` -RequiredAssemblies @() -FileList @() -NestedModules @() ` -PrivateData $Script:UserCertificate.Thumbprint $null = Sign $PSScriptRoot\\Authenticode.psd1 -Cert $Script:UserCertificate } } } return $Script:UserCertificate } } function Get-AuthenticodeCertificate { [CmdletBinding()] param ( $Name = $(Get-UserCertificate) ) end { $Certificate = $Name # Until they get a cert, or hit ENTER without any input while($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { trap { Write-Host "The authenticode module requires a code-signing certificate, and can't find yours!" Write-Host Write-Host "If this is the first time you've seen this error, please run Get-AuthenticodeCertificate by hand and specify the full path to your PFX file, or the Thumbprint of a cert in your OS Cert store -- and then answer YES to save that cert in the 'PrivateData' of the Authenticode Module metadata." Write-Host Write-Host "If you have seen this error multiple times, you may need to manually create a module manifest for this module with the path to your cert, and/or specify the certificate name each time you use it." Write-Error $_ continue } ## If they haven't specified the name, prompt them: if(!$Name) { $certs = @(Get-ChildItem Cert:\\ -Recurse -CodeSign | Sort NotAfter) if($certs.Count) { Write-Host "You have $($certs.Count) code signing certificates in your local certificate storage which you can specify by partial Thumbprint, or you may specify the path to a .pfx file:" -fore cyan $certs | Out-Host } $Name = $(Read-Host "Please specify a user certificate (wildcards allowed)") if(!$Name) { return } } Write-Verbose "Certificate Path: $Name" ## Check "CurrentUsers\\My" first, because it's MOST LIKELY there, and it will be MUCH faster in some cases. $ResolvedPath = Get-ChildItem Cert:\\CurrentUser\\My -Recurse -CodeSign | Where {$_.ThumbPrint -like $Name } | Select -Expand PSPath if(!$ResolvedPath) { ## We have to at least check the other folders too, if we didn't find it. $ResolvedPath = Get-ChildItem Cert:\\ -Recurse -CodeSign | Where {$_.ThumbPrint -like $Name } | Select -Expand PSPath } if(!$ResolvedPath) { Write-Verbose "Not a Certificate path: $Path" $ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue" | Where { Test-Path $_ -PathType Leaf -ErrorAction "SilentlyContinue" } } if(!$ResolvedPath) { Write-Verbose "Not a full or legit relative path Path: $ResolvedPath" $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" | Where { Test-Path $_ -PathType Leaf -ErrorAction "SilentlyContinue" } Write-Verbose "Resolved File Path: $ResolvedPath" } if(@($ResolvedPath).Count -gt 1) { throw "You need to specify enough of the name to narrow it to a single certificate. '$Name' returned $(@($ResolvedPath).Count):`n$($ResolvedPath|Out-String)" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } $Name = $Null # Blank it out so we re-prompt them } Write-Verbose "Certificate: $($Certificate | Out-String)" return $Certificate } } function Test-AuthenticodeSignature { <# .SYNOPSIS Tests a script signature to see if it is valid, or at least unaltered. .DESCRIPTION The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it is Valid, OR **unaltered** and signed by the user's certificate .PARAMETER Signature Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature. .PARAMETER ForceValid Switch parameter, forces the signature to be valid -- otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate). Aliases Valid .EXAMPLE ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_} To get the signature reports for all the scripts that we consider safely signed. .EXAMPLE ls | ? { gas $_ | Test-AuthenticodeSignature } List all the valid signed scripts (or scripts signed by our cert) .NOTES Test-AuthenticodeSignature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate. .INPUTTYPE System.Management.Automation.Signature .RETURNVALUE Boolean value representing whether the script's signature is valid, or YOUR certificate #> [CmdletBinding()] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint) ) ) } #################################################################################################### function Set-AuthenticodeSignature { <#.SYNOPSIS Adds an Authenticode signature to a Windows PowerShell script or other file. .DESCRIPTION The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed. .NOTES After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script. When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate To sign all of the files with the specified certificate .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate. .EXAMPLE Set-AuthenticodeSignature -Module PSCX Signs the whole PSCX module at once (all the ps1, psm1, psd1, dll, exe, and ps1xml files, etc.). .INPUTTYPE String. You can pipe a file path to Set-AuthenticodeSignature. .PARAMETER FilePath Specifies the path to a file that is being signed. Aliases Path, FullName .PARAMETER ModuleName Specifies a module name (or path) to sign. When you specify a module name, all of the files in that folder and it's subfolders are signed (if they're signable). .PARAMETER Certificate Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails. .PARAMETER Force Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions. .Parameter HashAlgorithm Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm. Files that are signed with a different hashing algorithm might not be recognized on other systems. .PARAMETER IncludeChain Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default. Valid values are: -- Signer: Includes only the signer's certificate. -- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority. --All: Includes all the certificates in the certificate chain. .PARAMETER TimestampServer Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string. Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing. .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding(DefaultParameterSetName="File")] param ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, ParameterSetName="File")] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]]$FilePath , [Parameter(Position=1, Mandatory=$true, ParameterSetName="Module")] [ValidateScript({ Write-Verbose $_ if(!(Get-Module -List $_)) { throw "Cannot find a module by that name: '$_'" } return $true })] [string[]]$ModuleName , [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) , [Switch]$Force , [ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")] [String]$HashAlgorithm #="SHA1" , [ValidateSet("Signer","NotRoot","All")] [String]$IncludeChain #="NotRoot" , [String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll" ) begin { if($PSCmdlet.ParameterSetName -eq "Module"){ Write-Verbose ($ModuleName -join ", ") $FilePath = Get-Module -List $ModuleName | Split-Path | Get-ChildItem -Recurse | Where { !$_.PsIsContainer } | Select -Expand FullName $FilePath | Write-Verbose $null = $PSBoundParameters.Remove("ModuleName") } if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $Certificate = Get-AuthenticodeCertificate $Certificate } $PSBoundParameters["Certificate"] = $Certificate } process { Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)" $PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath) if(Test-Path $FilePath -Type Leaf) { Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters } else { Write-Warning "Cannot sign folders: '$FilePath'" } } } #################################################################################################### function Get-AuthenticodeSignature { <#.SYNOPSIS Gets information about the Authenticode signature in a file. .DESCRIPTION The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE Get-AuthenticodeSignature script.ps1 To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] param ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string[]] $FilePath ) process { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath } } #################################################################################################### function Select-AuthenticodeSigned { <#.SYNOPSIS Select files based on the status of their Authenticode Signature. .DESCRIPTION The Select-AuthenticodeSigned function filters files on the pipeline based on the state of their authenticode signature. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1,*.ps[dm]1 | Select-AuthenticodeSigned To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] param ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter()] # Return only files that are signed with the users' certificate (as returned by Get-UserCertificate). [switch]$MineOnly , [Parameter()] # Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate). [switch]$NotMineOnly , [Parameter()] [Alias("HashMismatch")] # Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match). [switch]$BrokenOnly , [Parameter()] # Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate). # # That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly) [switch]$TrustedOnly , [Parameter()] # Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate. [switch]$ValidOnly , [Parameter()] # Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate). [switch]$InvalidOnly , [Parameter()] # Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed. [switch]$UnsignedOnly ) process { if(!(Test-Path -PathType Leaf $FilePath)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$FilePath'" # } } else { foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) { # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $FilePath" return } # Trusted only returns ONLY things which are Valid if($ValidOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $FilePath" return } # AllValid returns only things that are SIGNED and not HashMismatch if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $FilePath" return } # InvalidOnly returns things that are Either NotSigned OR HashMismatch ... if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $FilePath" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $FilePath" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint)))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" return } # NotMine returns only things that were NOT signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint)))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Signed: $FilePath" return } get-childItem $sig.Path }} } } function Start-AutoSign { # .Synopsis # Start a FileSystemWatcher to automatically sign scripts when you save them # .Description # Create a FileSystemWatcher with a scriptblock that uses the Authenticode script Module to sign anything that changes # .Parameter Path # The path to the folder you want to monitor # .Parameter Filter # A filter to select only certain files: by default, *.ps* (because we can only sign .ps1, .psm1, .psd1, and .ps1xml # .Parameter Recurse # Whether we should also watch autosign files in subdirectories # .Parameter CertPath # The path or name of a certain certificate, to override the defaults from the Authenticode Module # .Parameter NoNotify # Whether wo should avoid using Growl to notify the user each time we sign something. # .NOTE # Don't run this on a location where you're going to be generating dozens or hundreds of files ;) param($Path=".", $Filter= "*.ps*", [Switch]$Recurse, $CertPath, [Switch]$NoNotify) if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) { Import-Module Growl Register-GrowlType AutoSign "Signing File" -ErrorAction 0 } else { $NoNotify = $false } $realItem = Get-Item $Path -ErrorAction Stop if (-not $realItem) { return } $Action = { ## Files that can't be signed show up as "UnknownError" with this message: $InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider" ## Files that are signed with a cert we don't trust also show up as UnknownError, but with different messages: # $UntrustedCert = "A certificate chain could not be built to a trusted root authority" # $InvalidCert = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider" # $ExpiredCert = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file" ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature | Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } | Select-Object -ExpandProperty Path ) { if(!$NoNotify) { Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file" } if($CertPath) { Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath } else { Set-AuthenticodeSignature -FilePath $file } } } $watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse } Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null } Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias slas Select-AuthenticodeSigned -Description "Authenticode Module Alias" Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias" Export-ModuleMember -Alias gas,sas,slas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate, Get-AuthenticodeCertificate, Start-AutoSign # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUC4C60rGhPPdTPlUyDeAeKODK # jwCggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp # Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy # dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw # MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp # BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV # BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 # IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J # 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj # Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR # ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU # TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC # pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV # uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD # VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk # QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0 # YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl # IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y # aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo # dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg # KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG # IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3 # BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv # bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj # b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG # SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl # IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA # UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF # pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q # qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h # fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B # UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5 # 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1 # pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4 # npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV # 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki # 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp # 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR # MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD # b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln # bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk # aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB # qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0 # IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh # dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW # GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP # ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC # rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD # dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0 # U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2 # R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU # Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC # MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE # AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ # yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq # t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw # KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD # VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud # IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC # AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg # c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g # Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG # JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0 # dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB # BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j # bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j # b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A # 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb # E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27 # zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n # FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j # RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D # dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT # DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj # YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ # bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3 # AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBTFKf1cSPkl # 8ThxS25yfCxeBJI+FTANBgkqhkiG9w0BAQEFAASCAQDGsdmxOr6tj6tPsk4X4d04 # nbUU/xjjMDsS6UN+PxQ/Evje850K12JXv0XhXwpLofxrXLo7cHIaGN4sNZ0eLLTi # QC9vCWaowDdD2kyJGwYugaaspk3B4Ll7wc+OZmgIHzlJa/kM7n0oEinXNyf1KDlX # KIUOhtzHyddvnN487r+9Z3ZBA3FHowYWGfcjK+XHFAmdsd3GikmBf1+yZFlbPbVs # HJOu7lDRR7K4y0bbKeP4H8bzGZ4ZlDdpcf6yN+c7uspdvXqWUiMqQBk6sHpRj0l5 # 0CgzwS7DKBWWhTDwrhh4Ejg3mGu5j4aDsgZaZ72LzUQP5xNZayre2xaPAkLX4Gg0 # SIG # End signature block
PowerShellCorpus/PoshCode/c0b827b7-ab4f-4cce-93be-c140388d2469.ps1
c0b827b7-ab4f-4cce-93be-c140388d2469.ps1
################################################################################################################ # # NAME # Copy-Data # # SYNOPSIS # Copy Data between Folders including a Progressbar # # SYNTAX # Copy-Data [Source <PathToSource>] [Destination <PathToDestination>] [-Confirm] [-Recurse] # # # DETAILED DESCRIPTION # The Copy-Data cmdlet copies an item from one location to another in a namespace. Copy-Data does not # delete the items being copied. # # PARAMETERS # -Confirm <SwitchParameter> # Prompts you for confirmation before executing the command. # # Required? false # Position? named # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Recurse <SwitchParameter> # Specifies a recursive copy. # # Required? false # Position? named # Default value # Accept pipeline input? false # Accept wildcard characters? false # # # INPUT TYPE # # # RETURN TYPE # Shows a progressbar where you can see the progress # # NOTES # # -------------------------- EXAMPLE 1 -------------------------- # # C:\\PS>copy-Data C:\\Wabash\\Logfiles\\mar1604.log.txt C:\\Presentation # # # # -------------------------- EXAMPLE 2 -------------------------- # # C:\\PS>copy-Data C:\\Wabash\\Logfiles\\*.txt C:\\Presentation function copy-data { param( [string]$file = "", [string]$dest = "", [switch]$Recurse, [switch]$Confirm ) $copy = cp $file $dest for ($a=1; $a -lt 100; $a++) { Write-Progress -Activity “Copying...” -SecondsRemaining $a -Status "% Complete:" -percentComplete $a } } set-Alias cpd copy-data
PowerShellCorpus/PoshCode/Exch07 Snd_Rec Report.ps1
Exch07 Snd_Rec Report.ps1
# Get the start date for the tracking log search $Start = (Get-Date -Hour 00 -Minute 00 -Second 00).AddDays(-1) # Get the end date for the tracking log search $End = (Get-Date -Hour 23 -Minute 59 -Second 59).AddDays(-1) #Create a date for the csv file that this will get spit into $date = get-date -Format MM-dd-yyyy # Declare an array to store the results $Results = @() # Get the SEND events from the message tracking logs $Sent = Get-MessageTrackingLog -Server <Server Name Ommited Needs Updated> -Start $Start -End $End -resultsize unlimited | Where { $_.EventID -eq 'Send' -or $_.EventID -eq 'Deliver' } # Get the RECEIVE events from the message tracking logs $Received = Get-MessageTrackingLog -Server <Server Name Ommited Needs Updated> -Start $Start -End $End -resultsize unlimited | Where { $_.EventID -eq 'Receive' -or $_.EventID -eq 'TRANSFER' } # Get the mailboxes we want to report on #For in case I need to one day work with multiple DB's: $Mailboxes = Get-Mailbox -Database "EXCHANGE01\\SG1\\DB1" $Mailboxes = Get-Mailbox # Set up the counters for the progress bar $Total = $Mailboxes.Count $Count = 1 # Sort the mailboxes and pipe them to a For-Each loop $Mailboxes | Sort-Object DisplayName | ForEach-Object { # Update the progress bar $PercentComplete = $Count / $Total * 100 Write-Progress -Activity "Message Tracking Log Search" -Status "Processing mailboxes" -percentComplete $PercentComplete # Declare a custom object to store the data $Stats = "" | Select-Object Name,Sent,Received # Get the email address for the mailbox $Email = $_.WindowsEmailAddress.ToString() # Set the Name property of our object to the mailbox's display name $Stats.Name = $_.DisplayName # Set the Sent property to the number of messages sent $Stats.Sent = ($Sent | Where-Object { ($_.EventId -eq "Send" -or $_.EventID -eq "Deliver") -and ($_.Sender -eq $email) }).Count # Set the Received property to the number of messages received $Stats.Received = ($Received | Where-Object { ($_.EventId -eq "RECEIVE") -and ($_.Recipients -match $email) }).Count # Add the statistics for this mailbox to our results array $Results += $Stats # Increment the progress bar counter $Count += 1 } # Output the results $Results | Export-CSV C:\\Net_Admin_Stuff\\usage_reports\\send_receive_log\\send_receive_log-$date.csv -NoType
PowerShellCorpus/PoshCode/Start-Encryption_4.ps1
Start-Encryption_4.ps1
## Start-Encryption ################################################################################################## ## Rijndael symmetric key encryption ... with no passes on the key. Very lazy. ## USAGE: ## $encrypted = Encrypt-String "Oisin Grehan is a genius" "P@ssw0rd" ## Decrypt-String $encrypted "P@ssw0rd" ## ## You can choose to return an array by passing -arrayOutput to Encrypt-String ## I chose to use Base64 encoded strings because they're easier to save ... [Reflection.Assembly]::LoadWithPartialName("System.Security") function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key", [switch]$arrayOutput) { $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $c = $r.CreateEncryptor() $ms = new-Object IO.MemoryStream $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write" $sw = new-Object IO.StreamWriter $cs $sw.Write($String) $sw.Close() $cs.Close() $ms.Close() $r.Clear() [byte[]]$result = $ms.ToArray() if($arrayOutput) { return $result } else { return [Convert]::ToBase64String($result) } } function Decrypt-String($Encrypted, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key") { if($Encrypted -is [string]){ $Encrypted = [Convert]::FromBase64String($Encrypted) } $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [System.Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $d = $r.CreateDecryptor() $ms = new-Object IO.MemoryStream @(,$Encrypted) $cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read" $sr = new-Object IO.StreamReader $cs Write-Output $sr.ReadToEnd() $sr.Close() $cs.Close() $ms.Close() $r.Clear() }
PowerShellCorpus/PoshCode/Audit NTFS on Shares_2.ps1
Audit NTFS on Shares_2.ps1
$Excel = New-Object -Com Excel.Application $Excel.visible = $True $Excel = $Excel.Workbooks.Add() $wSheet = $Excel.Worksheets.Item(1) $wSheet.Cells.item(1,1) = "Folder Path:" $wSheet.Cells.Item(1,2) = "Users/Groups:" $wSheet.Cells.Item(1,3) = "Permissions:" $wSheet.Cells.Item(1,4) = "Permissions Inherited:" $WorkBook = $wSheet.UsedRange $WorkBook.Interior.ColorIndex = 8 $WorkBook.Font.ColorIndex = 11 $WorkBook.Font.Bold = $True ####Change the path to the folder or share you want NTFS perms on#### $dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true} $intRow = 1 foreach ($dir in $dirToAudit) { $colACL = Get-Acl -Path $dir.FullName foreach ($acl in $colACL) { $intRow++ $wSheet.Cells.Item($intRow,1) = $dir.FullName foreach ($accessRight in $acl.Access) { $wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)" $wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)" $wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected $intRow++ } } } $WorkBook.EntireColumn.AutoFit()
PowerShellCorpus/PoshCode/Start-ISE.ps1
Start-ISE.ps1
function Start-ISE () { <# .synopsis Load some file into ISE .Description Load some file into ISE .Parameter fileObjOrFileName file to be loaded .ReturnValue $null .Notes Author: bernd kriszio e-mail: bkriszio@googlemail.com Created: 2008-12-28 Requires: V2 CTP 3 Todo: I do not see the solution using advanced functions for a variable number of arguments Start-ISE .\\foo.ps1 .\\bar.ps1 fails. .Example Start-ISE $profile .Example get-childitem *.ps1 | Start-ISE .Example 'foo.ps1', 'bar.ps1' | Start-ISE #> param( [Parameter(Position = 0, Mandatory=$false, ValueFromPipeline=$True)] $fileObjOrFileName ) PROCESS { if ($fileObjOrFileName -ne $null){ if ($fileObjOrFileName.gettype().Name -eq 'String'){ $fileObject = Get-item $fileObjOrFileName } else { $fileObject = $fileObjOrFileName } } & "$PSHome/powershell_ise.exe" $fileObject.Fullname } <# End{ foreach ($file in $args) { if ($file.gettype().Name -eq 'FileInfo'){ & "$PSHome/powershell_ise.exe" $file.Fullname } elseif ($file.gettype().Name -eq 'String') { & "$PSHome/powershell_ise.exe" "$(pwd)\\$file" } } } #> }
PowerShellCorpus/PoshCode/Compare-Drive.ps1
Compare-Drive.ps1
param($ComputerName1,$ComputerName2) $a = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName1 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} $b = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName2 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}} Compare-Object -ReferenceObject $a -DifferenceObject $b -Property name,capacity -PassThru | select-object name, @{n='ComputerName1';e={$ComputerName1}}, @{n='ComputerName2';e={$ComputerName2}}, @{n='Capacity1';e={$name = $_.name; $drive = $a | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }}, @{n='Capacity2';e={$name = $_.name; $drive = $b | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }} | Sort-Object -Property name -Unique #get-content .\\serverpairs.txt | %{$servers = $_ -split ','; .\\compare-drive.ps1 $servers[0] $servers[1] } | ogv
PowerShellCorpus/PoshCode/Get-LeaderBoard_3.ps1
Get-LeaderBoard_3.ps1
<# .SYNOPSIS Pulls down the leaderboards for the 2011 Scripting Games .DESCRIPTION Quick and dirty script to pull down the leaderboards for the 2011 scripting games. Can choose either beginner or advanced via a command line switch. To see the output in a table, you must pipe to "format-table -autosize" or "out-gridview" .PARAMETER Level The leaderboard to parse .EXAMPLE Get-LeaderBoard -Level Beginner Retrieves the beginner leaderboard. .EXAMPLE Get-LeaderBoard -Level Advanced Retrieves the advanced leaderboard .EXAMPLE Get-LeaderBoard Advanced | Format-Table -Autosize Retrieves the advanced leaderboard and returns values in a table .EXAMPLE Get-LeaderBoard Advanced | Format-Table -Autosize Retrieves the advanced leaderboard and displays a table. .EXAMPLE Get-LeaderBoard Advanced | where { $_.UserName -eq "My Name" } Retrieves status for user "My Name" .NOTES NAME: Get-LeaderBoard VERSION: 1.01 AUTHOR: Alex McFarland LASTEDIT: 04/23/2011 -Added rankings to output. This unfortunately requires use of ft - auto to get decent looking output. -Incorporated regex changes to to issues points out by Scott Alvarino. Was missing foreign language characters and periods. #> function Get-LeaderBoard { param( [Parameter( Position = 0, Mandatory = $true, HelpMessage = "Leaderboard to parse. Advanced, or Beginner")] [ValidateSet("Advanced","Beginner")] [String]$Level="Advanced" ) # create a webclient $WebClient = New-Object System.Net.WebClient # download the page $LeaderPage = $WebClient.DownloadString("http://2011sg.poshcode.org/Reports/TopUsers?filter=$Level") # create a horrific looking regular expression $RegEx = '<a href="/Scripts/By/\\d{1,3}">(?<UserName>[\\w\\s\\S]*)</a>\\s*</td>\\s*<td>\\s*(?<TotalPoints>\\d{1,2}\\.\\d{1,2})\\s*</td>\\s*<td>\\s*(?<ScriptsRated>\\d*)' # initialize counter for ratings $i = 1 # split the page into seperate objects so we can parse each invidual $LeaderPage -split "<tr>" | ForEach { # match the regex $_ -match $RegEx | Out-Null # create a new PSObject, supply a hashtable with the properties if (-not $Matches.UserName -eq "") { New-Object PSObject -Property @{ "Ranking" = $i++ "UserName" = $Matches.UserName "ScriptsRated" = $Matches.ScriptsRated "TotalPoints" = $Matches.TotalPoints "AverageRating" = if ($Matches.ScriptsRated -gt 0) { # get average round to two decimal places "{0:N2}" -f ($Matches.TotalPoints / $Matches.ScriptsRated) } } } # clear matches if ($Matches) { $Matches.Clear() } # get our objects in a specific order. } | select -Unique Ranking,UserName,ScriptsRated,AverageRating,TotalPoints }
PowerShellCorpus/PoshCode/Trace-Route.ps1
Trace-Route.ps1
function Trace-Route { param( # The URL to trace [Parameter(Mandatory=$true)] [Uri]$Url, # The timeout for the request, in milliseconds [Timespan]$Timeout = "0:0:0.25", # The maximum number of hops for the trace route [Int]$MaximumHops = 32 ) process { Invoke-Expression "tracert -w $($timeOut.TotalMilliseconds) -h $MaximumHops $url" | Where-Object { if ($_ -match "[.+]") { $destination try { $destination = [IpAddress]$_.Split("[]",[StringSplitOptions]"RemoveEmptyEntries")[-1] } catch { return $false } } $true } | Where-Object { if ($_ -like "*Request timed out.*") { throw "Request timed Out" } return $true } | Foreach-Object { if ($_ -like "*ms*" ) { $chunks = $_ -split " " | Where-Object { $_ } $destAndip = $chunks[-1] $dest, $ip = $destAndip.Replace("[", "").Replace("]","") -split " " if (-not $ip) { $ip = $dest $dest = "" } $ip = @($ip)[0].Trim() -as [IPAddress] if ($chunks[1] -eq '*' -and $chunks[2] -eq '*' -and $chunks[3] -eq '*') { Write-Error "Request Timed Out" return } $trace = New-Object Object $time1 = try { [Timespan]::FromMilliseconds($chunks[1].Replace("<","").Replace(" ms", ""))} catch {} $time2 = try { [Timespan]::FromMilliseconds($chunks[1].Replace("<","").Replace(" ms", ""))} catch {} $time3 = try { [Timespan]::FromMilliseconds($chunks[1].Replace("<","").Replace(" ms", ""))} catch {} $trace | Add-Member NoteProperty HopNumber ($chunks[0].Trim() -as [uint32]) -PassThru | Add-Member NoteProperty Time1 $time1 -PassThru | Add-Member NoteProperty Time2 $time2 -PassThru | Add-Member NoteProperty Time3 $time3 -PassThru | Add-Member NoteProperty Ip $ip -PassThru | Add-Member NoteProperty Host $dest -PassThru | Add-Member NoteProperty DestinationUrl $url -PassThru | Add-Member NoteProperty DestinationIP $destination -PassThru } } } }
PowerShellCorpus/PoshCode/Get-EventLogBackup.ps1
Get-EventLogBackup.ps1
Param($BackupLocation,$list,$FromAD,[switch]$clear) # For more info read the following blog entry # http://www.bsonposh.com/modules/wordpress/?p=41 function Get-ADComputers{ $filter = "(&(objectcategory=computer))" $root = [ADSI]"" $props = "dNSHostName","sAMAccountName" $Searcher = new-Object System.DirectoryServices.DirectorySearcher($root,$filter,$props) $Searcher.PageSize = 1000 $Computers = $Searcher.findAll() | %{$_.properties['dnshostname']} $Computers } function Ping-Server { Param([string]$server) $pingresult = Get-WmiObject win32_pingstatus -f "address='$Server'" if($pingresult.statuscode -eq 0) {$true} else {$false} } if($FromAD){$computers = Get-ADComputers} else{if($list){$computers = get-Content $list}else{Write-Host "Please Provide List";return}} foreach($computer in $computers) { if(ping-server $computer) { $Folder = "{1}-Logs-{0:MMddyymm}" -f [DateTime]::now,$computer Write-Host "+ Processing Server $Computer" New-Item "$backupLocation\\$folder" -type Directory -force | out-Null If(!(Test-Path "\\\\$computer\\c$\\LogBackups")){New-Item "\\\\$computer\\c$\\LogBackups" -type Directory -force | out-Null} $Eventlogs = Get-WmiObject Win32_NTEventLogFile -ComputerName $computer Foreach($log in $EventLogs) { $path = "\\\\{0}\\c$\\LogBackups\\{1}.evt" -f $Computer,$log.LogFileName $result = ($log.BackupEventLog($path)).ReturnValue Copy-Item $path -dest "$backupLocation\\$folder" -force if($clear) { $log.clear() } } } }
PowerShellCorpus/PoshCode/SharpSsh 3.ps1
SharpSsh 3.ps1
#requires -version 2.0 ## A simple SSH Scripting module for PowerShell ## History: ## v1 - Initial Script ## v2 - Capture default prompt in New-SshSession ## v3 - Update to advanced functions, require 2.0, and add basic help ## USING the binaries from: ## http://downloads.sourceforge.net/sharpssh/SharpSSH-1.1.1.13.bin.zip [void][reflection.assembly]::LoadFrom( (Resolve-Path "~\\Documents\\WindowsPowerShell\\Libraries\\Tamir.SharpSSH.dll") ) Function ConvertTo-SecureString { #.Synopsis # Helper function which converts a string to a SecureString Param([string]$input) $result = new-object System.Security.SecureString foreach($c in $input.ToCharArray()) { $result.AppendChar($c) } $result.MakeReadOnly() return $result } Function ConvertTo-PSCredential { #.Synopsis # Helper function which converts a NetworkCredential to a PSCredential Param([System.Net.NetworkCredential]$Credential) $result = new-object System.Security.SecureString foreach($c in $input.ToCharArray()) { $result.AppendChar($c) } $result.MakeReadOnly() New-Object System.Management.Automation.PSCredential "$($Credential.UserName)@$($Credential.Domain)", (ConvertTo-SecureString $Credential.Password) } ## NOTE: These are still bare minimum functions, and only cover ssh, not sftp or scp (see here: http://poshcode.org/1034) ## IMPORTANT: if you "expect" something that does NOT get output, you'll be completely stuck and unable to 'break' ## ## As a suggestion, the best way to handle the output is to "expect" your prompt, and then do ## select-string matching on the output that was captured before the prompt. function New-SshSession { <# .Synopsis Create an SSH session to a remote server .Description Connect to a specific SSH server with the specified credentials. Supports RSA KeyFile connections. .Parameter HostName The server to SSH into .Parameter UserName The user name to use for login .Parameter Password The Password for login (Note: you really should pass this as a System.Security.SecureString, but it will accept a string instead) .Parameter KeyFile An RSA keyfile for ssh secret key authentication (INSTEAD of username/password authentication). .Parameter Credentials A PSCredential object containing all the information needed to log in. The login name should be in the form user@host .Parameter Passthru If passthru is specified, the new SshShell is returned. .Example New-SshSession Microsoft.com BillG Micr050ft Description ----------- Creates a new ssh session with the ssh server at Microsoft.com using the 'BillG' as the login name and 'Micr050ft' as the password (please don't bother trying that). .Example New-SshSession Microsoft.com -Keyfile BillGates.ppk Description ----------- Creates a new ssh session with the ssh server at Microsoft.com using the credentials supplied in the BillGates.ppk private key file. .Example $MSCred = Get-Credential BillG@Microsoft.com # prompts for password New-SshSession $MSCred Description ----------- Creates a new ssh session based on the supplied credentials. Uses the output of $MsCred.GetNetworkCredential() for the server to log into (domain) and the username and password. #> [CmdletBinding(DefaultParameterSetName='NamePass')] Param( [Parameter(Position=0,Mandatory=$true,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)] [Parameter(Position=0,Mandatory=$true,ParameterSetName="RSAKeyFile",ValueFromPipelineByPropertyName=$true)] [string]$HostName , [Parameter(Position=1,Mandatory=$false,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)] [string]$UserName , [Parameter(Position=2,Mandatory=$false,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)] $Password , [Parameter(Position=1,Mandatory=$true,ParameterSetName="RSAKeyFile",ValueFromPipelineByPropertyName=$true)] [string]$KeyFile , [Parameter(Position=0,Mandatory=$true,ParameterSetName="PSCredential",ValueFromPipeline=$true)] [System.Management.Automation.PSCredential]$Credentials , [switch]$Passthru ) process { switch($PSCmdlet.ParameterSetName) { 'RSAKeyFile' { $global:LastSshSession = new-object Tamir.SharpSsh.SshShell $HostName, $UserName $global:LastSshSession.AddIdentityFile( (Convert-Path (Resolve-Path $KeyFile)) ) } 'NamePass' { if(!$UserName -or !$Password) { $Credentials = $Host.UI.PromptForCredential("SSH Login Credentials", "Please specify credentials in user@host format", "$UserName@$HostName","") } else { if($Password -isnot [System.Security.SecureString]) { $Password = ConvertTo-SecureString $Password } $Credentials = New-Object System.Management.Automation.PSCredential "$UserName@$HostName", $Password } } } if($Credentials) { $global:LastSshSession = new-object Tamir.SharpSsh.SshShell ` $Credentials.GetNetworkCredential().Domain, $Credentials.GetNetworkCredential().UserName, $Credentials.GetNetworkCredential().Password } $global:LastSshSession.Connect() $global:LastSshSession.RemoveTerminalEmulationCharacters = $true if($Passthru) { return $global:LastSshSession } $global:LastSshSession.WriteLine("") sleep -milli 500 $global:defaultSshPrompt = [regex]::Escape( $global:LastSshSession.Expect().Split("`n")[-1] ) } } function Remove-SshSession { <# .Synopsis Exits the open SshSession #> Param([Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession) $SshShell.WriteLine( "exit" ) sleep -milli 500 if($SshShell.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." } $SshShell.Close() $SshShell = $null } function Invoke-Ssh { <# .Synopsis Executes an SSH command and Receives output .Description Invoke-Ssh is basically the same as a Send-Ssh followed by a Receive-Ssh, except that Expect defaults to $defaultSshPrompt (which is read in New-SshSession) .Parameter Command The command to send .Parameter Expect A regular expression for expect. The ssh session will wait for a line that matches this regular expression to be output before returning, and will return all the text up to AND INCLUDING the line that matches. Defaults .Parameter SshShell The shell to invoke against. Defaults to the LastSshSession #> Param( [string]$Command , [regex]$Expect = $global:defaultSshPrompt ## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } } function Send-Ssh { <# .Synopsis Executes an SSH command without receiving input .Description Sends a command to an ssh session .Parameter Command The command to send .Parameter SshShell The shell to send to. Defaults to the LastSshSession #> Param( [string]$command , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) } else { throw "The ssh shell isn't open!" } } function Receive-Ssh { <# .Synopsis Receives output from an SSH session .Description Retrieves output from an SSH session until the text matches the Expect pattern .Parameter Expect A regular expression for expect. The ssh session will wait for a line that matches this regular expression to be output before returning, and will return all the text up to AND INCLUDING the line that matches. .Parameter SshShell The shell to wait for. Defaults to the LastSshSession #> Param( [RegEx]$expect ## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } }
PowerShellCorpus/PoshCode/Get-ADGroupMembers_1.ps1
Get-ADGroupMembers_1.ps1
Function Get-ADGroupMembers { <# .SYNOPSIS Return a collection of users in an ActiveDirectory group. .DESCRIPTION This function returns an object that contains all the properties of a user object. This function works for small groups as well as groups in excess of 1000. .PARAMETER UserGroup The name of the group to get membership from. .PARAMETER UserDomain The LDAP URL of the domain that the group resides in. .EXAMPLE Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn name distinguishedName cn ---- ----------------- -- {Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts} {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple} ... Description ----------- This example shows passing in a group name, but leaving the default domain name in place. .NOTES The context under which this script is run must have rights to pull infromation from ActiveDirectory. .LINK http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers #> Param ( $UserGroup = "Domain Users", [ADSI]$UserDomain = ("LDAP://DC=company,DC=com") ) Begin { $DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path) $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher $LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))" $DirectorySearcher.SearchRoot = $DirectoryEntry $DirectorySearcher.PageSize = 1000 $DirectorySearcher.Filter = $LDAPFilter $DirectorySearcher.SearchScope = "Subtree" $SearchResult = $DirectorySearcher.FindAll() $UserAccounts = @() } Process { foreach ($Item in $SearchResult) { $Group = $Item.GetDirectoryEntry() $Members = $Group.member If ($Members -ne $Null) { foreach ($User in $Members) { $UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)") If ($UserObject.objectCategory.Value.Contains("Group")) { } Else { $ThisUser = New-Object -TypeName PSObject -Property @{ cn = $UserObject.cn distinguishedName = $UserObject.distinguishedName name = $UserObject.name nTSecurityDescriptor = $UserObject.nTSecurityDescriptor objectCategory = $UserObject.objectCategory objectClass = $UserObject.objectClass objectGUID = $UserObject.objectGUID objectSID = $UserObject.objectSID showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly } } $UserAccounts += $ThisUser } } } } End { Return $UserAccounts } }
PowerShellCorpus/PoshCode/Chassis Type_2.ps1
Chassis Type_2.ps1
$system = Get-WMIObject -class Win32_systemenclosure $type = $system.chassistypes Switch ($Type) { "1" {"Chassis type is: $Type - Other"} "2" {"Chassis type is: $type - Virtual Machine"} "3" {"Chassis type is: $type - Desktop"} "4" {"Chassis type is: $type - Low Profile Desktop"} "5" {"Chassis type is: $type - Pizza Box"} "6" {"Chassis type is: $type - Mini Tower"} "7" {"Chassis type is: $type - Tower"} "8" {"Chassis type is: $type - Portable"} "9" {"Chassis type is: $type - Laptop"} "10" {"Chassis type is: $type - Notebook"} "11" {"Chassis type is: $type - Handheld"} "12" {"Chassis type is: $type - Docking Station"} "13" {"Chassis type is: $type - All-in-One"} "14" {"Chassis type is: $type - Sub-Notebook"} "15" {"Chassis type is: $type - Space Saving"} "16" {"Chassis type is: $type - Lunch Box"} "17" {"Chassis type is: $type - Main System Chassis"} "18" {"Chassis type is: $type - Expansion Chassis"} "19" {"Chassis type is: $type - Sub-Chassis"} "20" {"Chassis type is: $type - Bus Expansion Chassis"} "21" {"Chassis type is: $type - Peripheral Chassis"} "22" {"Chassis type is: $type - Storage Chassis"} "23" {"Chassis type is: $type - Rack Mount Chassis"} "24" {"Chassis type is: $type - Sealed-Case PC"} Default {"Chassis type is: $type - Unknown"} }
PowerShellCorpus/PoshCode/Invoke-SqlCmd_4.ps1
Invoke-SqlCmd_4.ps1
####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() $ds.Tables }
PowerShellCorpus/PoshCode/Get-Scope.ps1
Get-Scope.ps1
function Get-Scope { #.Synopsis # Determine the scope of execution (are you in a module? how many scope layers deep are you?) #.Parameter Invocation # In order to correctly determine the scope, this function requires that you pass in the $MyInvocation variable when you call it. #.Parameter ToHost # If you just want to *see* the value in the console to debug something, you can pass this switch (and optionally, set the foreground/background colors) #.Parameter Foreground # The Foreground color of host output #.Parameter Background # The Background color of host output #.Example # $scope = Get-Scope $MyInvocation # # Description # ----------- # Call Get-Scope and store the output so you can test if you're in module scope, etc. #.Example # Get-Scope $MyInvocation -ToHost Magenta DarkBlue # # Description # ----------- # Call Get-Scope and write the output to host, specifying the foreground and background colors [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true)] [System.Management.Automation.InvocationInfo]$Invocation , [Parameter(ParameterSetName="Debugging",Mandatory=$true)] [Switch]$ToHost , [Parameter(Position=1,ParameterSetName="Debugging")] [ConsoleColor]$Foreground = "Cyan" , [Parameter(Position=2,ParameterSetName="Debugging")] [ConsoleColor]$Background = "Black" ) end { function Get-ScopeDepth { trap { continue } $depth = 0 do { Set-Variable scope_test -Scope (++$depth) } while($?) return $depth - 1 } $depth = Get-ScopeDepth Remove-Variable scope_test New-Variable scope_test $PSScope = New-Object PSObject -Property @{ IsModuleScope = [bool]$Invocation.MyCommand.Module IsGlobalScope = [bool](Get-Variable scope_test -Scope global -ea 0) IsScriptScope = [bool](Get-Variable scope_test -Scope script -ea 0) ScopeDepth = $depth PipelinePosition = $Invocation.PipelinePosition PipelineLength = $Invocation.PipelineLength StackDepth = (Get-PSCallStack).Count - 1 Invocation = $Invocation CallStack = Get-PSCallStack } if($ToHost) { &{ $PSScope, $PSScope.Invocation | Out-String } | Write-Host -Foreground $Foreground -Background $Background } else { $PSScope } }}
PowerShellCorpus/PoshCode/Out-Report.ps1
Out-Report.ps1
#Depends on Microsoft Report Viewer Redistributable and ReportExporters #ReportExporters available at http://www.codeproject.com/KB/reporting-services/ReportExporters_WinForms.aspx #Download demo version of ReportExporters for compiled dlls #Tested with Microsoft Report Viewer 2008 SP1 Redistributable, although 2005 and base 2008 version should work #Visual Studio installations as well as SQL Server Reporting Services may already include Microsoft Report Viewer #Microsoft Report Viewer Redist available at http://www.microsoft.com/downloads/details.aspx?familyid=BB196D5D-76C2-4A0E-9458-267D22B6AAC6&displaylang=en #EXAMPLES #get-alias | ./out-report.ps1 "c:\\users\\u00\\bin\\aliases.xls" xls #get-alias | ./out-report.ps1 "c:\\users\\u00\\bin\\aliases.pdf" pdf #get-alias | ./out-report.ps1 "c:\\users\\u00\\bin\\aliases.jpeg" -filetype image -imagetype JPEG -height 22 -width 14 param($fileName,$fileType,$imageType,$height=11,$width=8.5) $libraryDir = Convert-Path (Resolve-Path "$ProfileDir\\Libraries") [void][reflection.assembly]::LoadWithPartialName("Microsoft.ReportViewer.WinForms") [void][Reflection.Assembly]::LoadFrom("$libraryDir\\ReportExporters.Common.dll") [void][Reflection.Assembly]::LoadFrom("$libraryDir\\ReportExporters.WinForms.dll") $fileTypes = 'XLS','PDF','IMAGE' if (!($fileTypes -contains $fileType)) { throw 'Valid file types are XLS, PDF, IMAGE' } $imageTypes = 'BMP','EMF','GIF','JPEG','PNG','TIFF' if ( $imageType -and !($imageTypes -contains $imageType)) { throw 'Valid image types are BMP,EMF,GIF,JPEG,PNG or TIFF' } ####################### function New-ImageDeviceInfo { param($imageType,$height,$width) $deviceInfo = new-object ("ReportExporters.Common.Exporting.ImageDeviceInfoSettings") $imageType $deviceInfo.PageHeight = new-object System.Web.UI.WebControls.Unit($height,[System.Web.UI.WebControls.UnitType]::Inch) $deviceInfo.PageWidth = new-object System.Web.UI.WebControls.Unit($width,[System.Web.UI.WebControls.UnitType]::Inch) $deviceInfo.StartPage = 0 return $deviceInfo } #New-ImageDeviceInfo #DataTable section from http://mow001.blogspot.com/2006/05/powershell-out-datagrid-update-and.html $dt = new-Object Data.datatable $First = $true foreach ($item in $input){ $DR = $DT.NewRow() $Item.PsObject.get_properties() | foreach { If ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $_.Name.ToString() $DT.Columns.Add($Col) } if ($_.value -eq $null) { $DR.Item($_.Name) = "[empty]" } ElseIf ($_.IsArray) { $DR.Item($_.Name) =[string]::Join($_.value ,";") } Else { $DR.Item($_.Name) = $_.value } } $DT.Rows.Add($DR) $First = $false } #End DataTable section $ds = new-object System.Data.dataSet $ds.merge($dt) $dsaProvider = new-object ReportExporters.Common.Adapters.DataSetAdapterProvider $ds $dsa = $dsaProvider.GetAdapters() $reportExporter = new-object ReportExporters.WinForms.WinFormsReportExporter $dsa switch ($fileType) { 'XLS' { $content =$reportExporter.ExportToXls() } 'PDF' { $content = $reportExporter.ExportToPdf() } 'IMAGE' { $deviceInfo = New-ImageDeviceInfo $imageType $height $width; $content = $reportExporter.ExportToImage($deviceInfo) } } [System.IO.File]::WriteAllBytes($fileName,$content.ToArray())
PowerShellCorpus/PoshCode/AD Recycle Bin - Restore.ps1
AD Recycle Bin - Restore.ps1
' Script: Create_Restore.vbs ' Purpose: This script will graphically create a Powershell script based on user input, the powershell script can be run to restore deleted AD Objects ' Author: Paperclips ' Email: magiconion_M@hotmail.com ' Date: Feb 2011 ' Comments: Creating a ps1 script to restore deleted AD objects ' Notes: ' - The recycling feature must be enabled on teh DC that this is run on - At present only available in 2008 R2 Dim objFSO, objFolder, objFile, objWMI, objItem, GUID, x, ShellMessage ' ---------------------------------------------------Set the folder and file name------------------------------------------------------------------- strComputer = "." strFileName1 = "Commit_Restore.ps1" strFileName2 = "Query_Del_Obj.ps1" strFolder1 = ".\\" strPath1 = strFolder1 & strFileName1 strPath2 = strFolder1 & strFileName2 ' ----------------------------------------------------Create the File System Object----------------------------------------------------------------- Set objFSO = CreateObject("Scripting.FileSystemObject") '----------------------------------------------------Check that the strFolder2 folder exists-------------------------------------------------------- If objFSO.FolderExists(strFolder1) Then Set objFolder = objFSO.GetFolder(strFolder1) Else Set objFolder = objFSO.CreateFolder(strFolder1) End If If objFSO.FileExists(strFolder1 & strFileName2) Then Set objFolder = objFSO.GetFolder(strFolder1) Else Set objFile = objFSO.CreateTextFile(strFolder1 & strFileName2) End If '----------------------------------------------------Generate the Query.ps1 Script and run Query Script and Open report-------------------------------- set objFile = nothing set objFolder = nothing Set strFileOpen2 = objFSO.CreateTextFile(strPath2, True) '---------------------generate Script--------------------------------- strFileOpen2.WriteLine("import-module activedirectory") strFileOpen2.WriteLine("Get-AdObject -filter 'isdeleted -eq $True -and name -ne ""Deleted Objects""' -includeDeletedObjects -property * |Format-List samAccountName,DistinguishedName,LastKnownParent,ObjectGUID,ObjectClass > Deleted_Obj.txt") strFileOpen2.Close '---------------------Run Script that was generated------------------- Set objShell = CreateObject("Wscript.Shell") objShell.Run("powershell.exe -WindowStyle minimized -noprofile .\\Query_Del_Obj.ps1") WScript.Sleep(3000) '------------Open report that was generated by running script--------- ShellMessage = MsgBox("Please wait while the report is genereated" & VbNewLine & "The report will open automatically in a text file when the process completes",0,"Please wait") WScript.Sleep(7000) objShell.Run("notepad.exe .\\Deleted_Obj.txt") '-----------------------------------------------------Check that the strFolder1 folder exists-------------------------------------------------------- If objFSO.FolderExists(strFolder1) Then Set objFolder = objFSO.GetFolder(strFolder1) Else Set objFolder = objFSO.CreateFolder(strFolder1) End If If objFSO.FileExists(strFolder1 & strFileName1) Then Set objFolder = objFSO.GetFolder(strFolder1) Else Set objFile = objFSO.CreateTextFile(strFolder1 & strFileName1) End If ' -----Cleanup----- set objFile = nothing set objFolder = nothing ' -----------------------------------------------------Write the information to the file------------------------------------------------------------ Set strFileOpen1 = objFSO.CreateTextFile(strPath1, True) ' -----------------------------------------------------Create script based ojn this Criteria----------------------------------------------------------- x = MsgBox("Do you want to create the powershell script for restoring Deleted AD Objects?" & VbNewLine & "Please note that you will need the GUID" & VbnewLine & "Also note that any objects deleted prior to 180 days ago, will not be recoverable!" & VbnewLine & "" & VbnewLine & "IMPORTANT: Always restore Parent OU's first (This is because if any child objects exist under an OU, The OU must exist)",4,"Confirmation") If x = vbyes Then strFileOpen1.WriteLine("import-module activedirectory") Do While x = vbyes Call Criteria x = MsgBox("Would you like to add another GUID",4,"Confirmation") Loop End if strFileOpen1.Close '---------------------Run Script that was generated------------------- Set objShell = CreateObject("Wscript.Shell") y = MsgBox("Do you want to commit the script for restoring Deleted AD Objects? " & VbNewLine & "The GUID's entered will be restored",4,"Confirmation") If y = vbyes Then objShell.Run("powershell.exe -WindowStyle minimized -noprofile .\\Commit_Restore.ps1") WScript.Sleep(3000) ShellMessage = MsgBox("The objects have now been restored.",0,"Finished") End if On Error goTo 0 Function Criteria() GUID = InputBox("Please Enter the GUID you would like to restore", "Input Criteria") strFileOpen1.WriteLine("restore-ADObject -identity " &GUID) End Function
PowerShellCorpus/PoshCode/4aea4469-64f1-4f01-9c7f-054ecd61a063.ps1
4aea4469-64f1-4f01-9c7f-054ecd61a063.ps1
function Get-VCTime() { return (Get-View "ServiceInstance-ServiceInstance").CurrentTime() } $lastCheckTime = Get-VCTime while ($true) { $modifiedVMs = @() $freshEventsStartTime = $lastCheckTime $lastCheckTime = Get-VCTime # Get all the VM network edit events foreach ($event in Get-VIEvent -Start $freshEventsStartTime -Types Info) { if ($event.GetType().FullName -eq "VimApi.VmReconfiguredEvent" -and $event.configSpec -ne $null) { foreach ($change in $event.configSpec.deviceChange) { if ($change.operation -eq "edit" -and $change.device -ne $null -and $change.device.GetType().FullName -eq "VimApi.VirtualPCNet32") { # VM's networking was reconfigured. $vmId = $event.vm.vm.Type + '-' + $event.vm.vm.Value $modifiedVMs += Get-VM -Id $vmId } } } } # Did one of these edits violate isolation? foreach ($vm in $modifiedVMs | select -Unique) { $intranetNics = $vm.NetworkAdapters | where { $_.NetworkName -eq 'Intranet' } $dmzNics = $vm.NetworkAdapters | where { $_.NetworkName -eq 'DMZ' } if ($intranetNics -ne $null -and $dmzNics -ne $null) { # Send an email notification $message = "VM '" + $vm.Name + "' violates network isolation rules!" Write-Host $message -ForegroundColor Yellow # Use .Net’s SmtpClient to send mail. Just tell it which SMTP server to use (New-Object 'System.Net.Mail.SmtpClient' 'smtp.example1234.com').Send( 'NetworkMonitor@example1234.com', # Sender 'john.doe@example1234.com', # Recipient 'Network isolation violation', # Subject $message) } } Start-Sleep 60 } # while ($true)
PowerShellCorpus/PoshCode/chkhash_17.ps1
chkhash_17.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false "ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, " "in order to detect corrupt or hacked files." "" ".\\chkhash.ps1 -h for usage." "" for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]" " [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml" " or create it and store hashes there if not present]" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" " [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude " " c:\\users\\eve\\hashes directory and subdirs]" " PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u" " [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to" " existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]" " PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml" " [Load hashes.xml and check hashes of all files contained within.]" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { while (($i+1) -lt $args2.count) { $i++ if ($args2[$i] -like "-*") {break} $exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories. } continue } $args3+=@($args2[$i]) # Add files/dirs } if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es)." $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/c36fba47-49ce-4fb7-8194-54b0294b4a9b.ps1
c36fba47-49ce-4fb7-8194-54b0294b4a9b.ps1
function Write-Host { <# .SYNOPSIS Replacement of Write-Host function to work around an issue where use of Write-Host can cause an eventual problem with launching EXEs from within the same Powershell session. .DESCRIPTION This Write-Host replacement can act as a temporary workaround to an issue with some PowerShell versions currently released. The high-level description of the problem is that excessive use of Write-Host eventually leads to failures to execute EXEs from the same PowerShell session. For platforms where the problem exists, the following has been seen to reproduce the issue: for( $i = 0; $i -lt 1000; $i += 1 ) { Write-Host line }; whoami.exe; "0x{0:X}" -f $LASTEXITCODE On repro, the $LASTEXITCODE will be 0xC0000142. This issue is described by the following Connect article: https://connect.microsoft.com/PowerShell/feedback/details/496326/stability-problem-any-application-run-fails-with-lastexitcode-1073741502 Some folks workaround the issue by simply using pipeline output to display status messages. Use the pipeline in this manner may be ideal for situations where it is not used for other purposes. If you have scripts that use the pipeline for other purposes, and rely on Write-Host for non-pipeline status output, where your scripts hit this issue, perhaps this workaround may be of use. .PARAMETER Object Object to be outputed to stdout. .PARAMETER NoNewLine Specify this flag if you don't what the output to end with NewLine character .PARAMETER ForegroundColor Specifies the text color. There is no default. Use Get-Colors command to output all available colors in color. Possible color names taken from '[ConsoleColor] | gm -Static' are: Blue | DarkBlue Cyan | DarkCyan Gray | DarkGray Green | DarkGreen Magenta | DarkMagenta Red | DarkRed Yellow | DarkYellow White | Black .PARAMETER BackgroundColor Specifies the background color. There is no default. Use Get-Colors command to output all available colors in color. Possible color names taken from '[ConsoleColor] | gm -Static' are: Blue | DarkBlue Cyan | DarkCyan Gray | DarkGray Green | DarkGreen Magenta | DarkMagenta Red | DarkRed Yellow | DarkYellow White | Black .EXAMPLE Write-Console "=)", "test" -ForegroundColor Green -NoNewLine Prints all items in passed string array to stdout with green color used in console. .LINK Write-Colorized Write-Host Get-Colors #> param ( [Parameter(Mandatory = $true, Position = 0, ValueFromRemainingArguments = $true, ValueFromPipeline = $true)] [object] $Object, [object] $Separator = " ", [ConsoleColor] $ForegroundColor, [ConsoleColor] $BackgroundColor, [switch] $NoNewLine ) begin { function printObject($o) { function WriteObject([string]$s) { if ($s.Length -gt 0) { if ($consoleHost) { [Console]::Write($s); } else { $host.UI.Write($ForegroundColor, $BackgroundColor, $s) } } } # If null, exit. if ($o -eq $null) { return; } # If type is directly a string, write it directly. if ($o -is [string]) { WriteObject $o } else { # Object is not a string. See if it is enumerable. if ($o -is [System.Collections.IEnumerable]) { # Access the enumerator and print each item with any defined separation. $objectEnumerator = $o.GetEnumerator(); $printSeparator = $false; foreach ($element in $objectEnumerator) { # If separator defined, print it if this is not first item. if ($Separator -ne $null -and $printSeparator) { WriteObject $Separator } # Recursive. printObject $element # Print separator after first item. $printSeparator = $true; } } else { # Object was not a string, and it did not have a # GetEnumerator() method, so simply use the object's # ToString() method to access the printable content. WriteObject $o.ToString() } } } $consoleHost = $host.Name -eq "ConsoleHost" if (!$consoleHost) { if (!$ForegroundColor) { $ForegroundColor = $host.UI.RawUI.ForegroundColor } if (!$BackgroundColor) { $BackgroundColor = $host.ui.RawUI.BackgroundColor } } } process { if ($consoleHost) { if( $ForegroundColor ) { $previousForegroundColor = [Console]::ForegroundColor [Console]::ForegroundColor = $ForegroundColor } if( $BackgroundColor ) { $previousBackgroundColor = [Console]::BackgroundColor [Console]::BackgroundColor = $BackgroundColor } } try { printObject $Object $consoleHost if( $NoNewLine -eq $false) { [Console]::WriteLine('') # Parameterless WriteLine seems to not print a newline from ISE whereas empty string works on both cmd line/ISE. } } finally { if ($consoleHost) { if( $ForegroundColor ) { [Console]::ForegroundColor = $previousForegroundColor } if( $BackgroundColor ) { [Console]::BackgroundColor = $previousBackgroundColor } } } } } # Simple test... function Test-WriteConsole { Write-Host 'new console write'; Write-Host @(1,2,3,4) -Separator '-sep-' Write-Host @(1,2,3,4) -Separator '-sep-' -ForegroundColor Yellow Write-Host @(1,2,3,4) -Separator '-sep-' -ForegroundColor Black -BackgroundColor White Write-Host ([int32]123) -Separator '-sep-' -ForegroundColor Cyan -BackgroundColor DarkGreen Write-Host '123' -Separator '-sep-' -ForegroundColor Green -BackgroundColor Black Write-Host @([int32]123,[int32]123,[int32]123,[int32]123,[int32]123) -Separator '-sep-' -ForegroundColor Cyan -BackgroundColor DarkGreen Write-Host 'This is one write. ' -NoNewLine; Write-Host 'This is another write on the same line. ' -NoNewLine -ForegroundColor Black -BackgroundColor White Write-Host @('abc', [uint32]123, 'def', ' array on same line. ') -Separator ',' -NoNewLine -ForegroundColor Cyan -BackgroundColor DarkMagenta Write-Host 'This is the last sentence on this line.' Write-Host 'This should be on a new line.'; 1..5 | Write-Host Write-Host 1 2 3 4 5 } Test-WriteConsole
PowerShellCorpus/PoshCode/Get-Selection.ps1
Get-Selection.ps1
function Write-Choice { param($prompt, $choice) write-host -n "[" write-host -n -f yellow $prompt write-host "]", $choice Write-Output $prompt } function Get-Selection { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0,HelpMessage="Choices")] [Object] $choice, [Parameter(HelpMessage="Intro message")] [string] $introMessage="Choose from the following options:", [Parameter(HelpMessage="Prompt message")] [string] $prompt="Select an option", [Parameter(HelpMessage="Window size")] [Int] $windowSize=10 ) $currentWindow = 0 $maxWindow = [Math]::Floor($choice.length / $windowSize) while ($true) { Clear-Host $start = $currentWindow*$windowSize $thisWindowSize = [Math]::Min($windowSize, $choice.length - $start) if ($introMessage) { write-host -fore yellow $introMessage } $choices = @() for ($i = 1; $i -lt $thisWindowSize + 1; $i++) { $choices += Write-Choice $i $choice[$start + $i - 1] } if ($currentWindow -gt 0) { $choices += Write-Choice "P" "Previous Page Of Choices" } if ($currentWindow -lt $maxWindow) { $choices += Write-Choice "N" "Next Page Of Choices" } while ($true) { $input = read-host $prompt if ($choices -notcontains $input) { continue } if ($input -eq "N") { $currentWindow++ break } elseif ($input -eq "P") { $currentWindow-- break } else { Write-Output $choice[$start + [int]$input - 1] return } } } } # Example 1 # $choices = 1..25 # Get-Selection $choices # Example 2 # $choices = Get-Childitem c:\\windows\\system32 # Get-Selection $choices -windowsize 20 -prompt "Choose a file"
PowerShellCorpus/PoshCode/CDRom Open__Close.ps1
CDRom Open__Close.ps1
using System; using System.Reflection; using System.Globalization; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.0.0.0")] namespace CDRomOpenClose { internal static class WinAPI { [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwSharedMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped); } internal sealed class Program { const uint GENERIC_READ = 0x80000000; const uint IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808; const uint IOCTL_STORAGE_LOAD_MEDIA = 0x002D480C; const uint OPEN_EXISTING = 3; const int INVALID_HANDLE = -1; static IntPtr hndl; static uint retBytes; static void EjectClose(string drvLetter, bool curStatus) { try { hndl = WinAPI.CreateFile(drvLetter, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if ((int)hndl != INVALID_HANDLE) { if (curStatus) WinAPI.DeviceIoControl(hndl, IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, out retBytes, IntPtr.Zero); else WinAPI.DeviceIoControl(hndl, IOCTL_STORAGE_LOAD_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, out retBytes, IntPtr.Zero); } } finally { WinAPI.CloseHandle(hndl); hndl = IntPtr.Zero; } } static void Main(string[] args) { if (args.Length == 1) { string arg = args[0].ToLower(CultureInfo.CurrentCulture).TrimStart('-', '/'); switch (arg) { case "c": EjectClose(@"\\\\.\\E:", false); break; case "e": EjectClose(@"\\\\.\\E:", true); break; default: Console.WriteLine("Unknown {0} parameter.", arg); break; } } else Console.WriteLine("Arguments are out of length."); } } }
PowerShellCorpus/PoshCode/Add-SqlTable_1.ps1
Add-SqlTable_1.ps1
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"} ####################### function Get-SqlType { param([string]$TypeName) switch ($TypeName) { 'Boolean' {[Data.SqlDbType]::Bit} 'Byte[]' {[Data.SqlDbType]::VarBinary} 'Byte' {[Data.SQLDbType]::VarBinary} 'Datetime' {[Data.SQLDbType]::DateTime} 'Decimal' {[Data.SqlDbType]::Decimal} 'Double' {[Data.SqlDbType]::Float} 'Guid' {[Data.SqlDbType]::UniqueIdentifier} 'Int16' {[Data.SQLDbType]::SmallInt} 'Int32' {[Data.SQLDbType]::Int} 'Int64' {[Data.SqlDbType]::BigInt} default {[Data.SqlDbType]::VarChar} } } #Get-SqlType ####################### <# .SYNOPSIS Creates a SQL Server table from a DataTable .DESCRIPTION Creates a SQL Server table from a DataTable using SMO. .EXAMPLE $dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table .EXAMPLE $dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table. .NOTES Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52 Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Updated documentation #> function Add-SqlTable { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [String]$TableName, [Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable, [Parameter(Position=4, Mandatory=$false)] [string]$Username, [Parameter(Position=5, Mandatory=$false)] [string]$Password, [ValidateRange(1,8000)] [Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000 ) if($Username) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance } $con.Connect() $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con $db = $server.Databases[$Database] $table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName foreach ($column in $DataTable.Columns) { $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)" if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength } else { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType } $col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType $col.Nullable = $column.AllowDBNull $table.Columns.Add($col) } $table.Create() } #Add-SqlTable
PowerShellCorpus/PoshCode/Brushes.ps1
Brushes.ps1
$frmMain_OnLoad= { $m_BrushSize = New-Object Drawing.Rectangle(0, 0, $picDemo.Width, $picDemo.Height) $wm = [Drawing.Drawing2D.WrapMode] $cboWraM.Items.AddRange(@($wm::Clamp, $wm::Tile, $wm::TileFlipX, $wm::TileFlipY, $wm::TileFlipXY)) $cboWraM.SelectedIndex = 0 [int]$maxHatchStyle = 53 for ($i = [Convert]::ToInt32([Drawing.Drawing2D.HatchStyle]::Min); $i -lt $maxHatchStyle; $i++) { $cboHatS.Items.Add([Drawing.Drawing2D.HatchStyle] $i) } $cboHatS.SelectedIndex = 0 $lgm = [Drawing.Drawing2D.LinearGradientMode] $cboGraM.Items.AddRange(@($lgm::BackwardDiagonal, $lgm::ForwardDiagonal, ` $lgm::Horizontal, $lgm::Vertical)) $cboGraM.SelectedIndex = 0 } $btnCol1_OnClick= { $cdlg = New-Object Windows.Forms.ColorDialog if ($cdlg.ShowDialog() -eq [Windows.Forms.Dialogresult]::OK) { $col1 = $cdlg.Color $txtCol1.Text = $cdlg.Color.ToString() $txtCol1.BackColor = $cdlg.Color } } $btnCol2_OnClick= { $cdlg = New-Object Windows.Forms.ColorDialog if ($cdlg.ShowDialog() -eq [Windows.Forms.Dialogresult]::OK) { $col2 = $cdlg.Color $txtCol2.Text = $cdlg.Color.ToString() $txtCol2.BackColor = $cdlg.Color } } $cboBruS_OnSelectedIndexChanged= { switch ($cboBruS.Text) { "Large" { $m_BrushSize = New-Object Drawing.Rectangle(0, 0, $picDemo.Width, $picDemo.Height) break } "Medium" { $m_BrushSize = New-Object Drawing.Rectangle(0, 0, [Convert]::ToInt32($picDemo.Width / 2), ` [Convert]::ToInt32($picDemo.Height / 2)) break } "Small" { $m_BrushSize = New-Object Drawing.Rectangle(0, 0, [Convert]::ToInt32($picDemo.Width / 4), ` [Convert]::ToInt32($picDemo.Height / 4)) break } } RedrawPicture } function RedrawPicture { $picDemo.CreateGraphics().Clear([Drawing.Color]::White) $picDemo.Refresh() switch ($cboBruT.Text) { "Solid" { $txtCol2.Enabled = $false $btnCol2.Enabled = $false $cboBruS.Enabled = $false $cboWraM.Enabled = $false $cboHatS.Enabled = $false $nudRota.Enabled = $false $nudGraB.Enabled = $false $cboGraM.Enabled = $false $brush = New-Object Drawing.SolidBrush $col1 break } "Hatch" { $txtCol1.Enabled = $true $btnCol1.Enabled = $true $txtCol2.Enabled = $true $btnCol2.Enabled = $true $cboBruS.Enabled = $false $cboWraM.Enabled = $false $cboHatS.Enabled = $true $nudRota.Enabled = $false $nudGraB.Enabled = $false $cboGraM.Enabled = $false $brush = New-Object ` Drawing.Drawing2D.HatchBrush([Drawing.Drawing2D.HatchStyle]$cboHatS.SelectedItem, $col1, $col2) break } "Texture" { $txtCol1.Enabled = $false $btnCol1.Enabled = $false $txtCol2.Enabled = $false $btnCol2.Enabled = $false $cboBruS.Enabled = $true $cboWraM.Enabled = $true $cboHatS.Enabled = $false $nudRota.Enabled = $true $nudGraB.Enabled = $false $cboGraM.Enabled = $false $file = "$env:allusersprofile\\&#1044;&#1086;&#1082;&#1091;&#1084;&#1077;&#1085;&#1090;&#1099;\\&#1052;&#1086;&#1080; &#1088;&#1080;&#1089;&#1091;&#1085;&#1082;&#1080;\\&#1054;&#1073;&#1088;&#1072;&#1079;&#1094;&#1099; &#1088;&#1080;&#1089;&#1091;&#1085;&#1082;&#1086;&#1074;\\&#1047;&#1072;&#1082;&#1072;&#1090;.jpg" $pic = New-Object Drawing.Bitmap($file) $brush = New-Object Drawing.TextureBrush($pic, $m_BrushSize) $brush.WrapMode = [Drawing.Drawing2D.WrapMode]$cboWraM.SelectedItem $brush.RotateTransform([Convert]::ToSingle($nudRota.Value)) break } "LinearGradient" { $txtCol1.Enabled = $true $btnCol1.Enabled = $true $txtCol2.Enabled = $true $btnCol2.Enabled = $true $cboBruS.Enabled = $true $cboWraM.Enabled = $false $cboHatS.Enabled = $false $nudGraB.Enabled = $true $cboGraM.Enabled = $true $brush = New-Object Drawing.Drawing2D.LinearGradientBrush($m_BrushSize, $col1, $col2, ` [Drawing.Drawing2D.LinearGradientMode]$cboGraM.SelectedItem) $brush.RotateTransform([Convert]::ToSingle($nudRota.Value)) $brush.SetBlendTriangularShape([Convert]::ToSingle($nudGraB.Value)) break } } $g = $picDemo.CreateGraphics() switch ($cboDraw.Text) { "Fill" { $g.FillRectangle($brush, 0, 0, $picDemo.Width, $picDemo.Height) break } "Ellipses" { $g.FillEllipse($brush, $picDemo.Width / 10, $picDemo.Height / 10, ` $picDemo.Width / 2, $picDemo.Height / 2) $g.FillEllipse($brush, $picDemo.Width / 3, $picDemo.Height / 3, ` $picDemo.Width / 2, $picDemo.Height / 2) break } "Lines" { $pen = New-Object Drawing.Pen($brush, 40) $g.DrawLine($pen, 0, 0, $picDemo.Width, $picDemo.Height) $g.DrawLine($pen, 0, 0, 0, $picDemo.Height) $g.DrawLine($pen, 0, 0, $picDemo.Height, 0) $g.DrawLine($pen, $picDemo.Width, 0, $picDemo.Width, $picDemo.Height) $g.DrawLine($pen, 0, $picDemo.Height, $picDemo.Width, $picDemo.Height) $g.DrawLine($pen, $picDemo.Width, 0, 0, $picDemo.Height) break } } } function ShowMainWindow { [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Drawing") [Windows.Forms.Application]::EnableVisualStyles() $col1 = [Drawing.Color]::Blue $col2 = [Drawing.Color]::White $frmMain = New-Object Windows.Forms.Form $mnuMain = New-Object Windows.Forms.MainMenu $mnuFile = New-Object Windows.Forms.MenuItem $mnuExit = New-Object Windows.Forms.MenuItem $mnuHelp = New-Object Windows.Forms.MenuItem $mnuInfo = New-Object Windows.Forms.MenuItem $lblBruT = New-Object Windows.Forms.Label $lblDraw = New-Object Windows.Forms.Label $lblCol1 = New-Object Windows.Forms.Label $lblCol2 = New-Object Windows.Forms.Label $lblBruS = New-Object Windows.Forms.Label $lblWraM = New-Object Windows.Forms.Label $lblHatS = New-Object Windows.Forms.Label $lblRota = New-Object Windows.Forms.Label $lblGraB = New-Object Windows.Forms.Label $lblGraM = New-Object Windows.Forms.Label $cboBruT = New-Object Windows.Forms.ComboBox $cboDraw = New-Object Windows.Forms.ComboBox $txtCol1 = New-Object Windows.Forms.TextBox $txtCol2 = New-Object Windows.Forms.TextBox $btnCol1 = New-Object Windows.Forms.Button $btnCol2 = New-Object Windows.Forms.Button $cboBruS = New-Object Windows.Forms.ComboBox $cboWraM = New-Object Windows.Forms.ComboBox $cboHatS = New-Object Windows.Forms.ComboBox $nudRota = New-Object Windows.Forms.NumericUpDown $nudGraB = New-Object Windows.Forms.NumericUpDown $cboGraM = New-Object Windows.Forms.ComboBox $picDemo = New-Object Windows.Forms.PictureBox #mnuMain $mnuMain.MenuItems.AddRange(@($mnuFile, $mnuHelp)) #mnuFile $mnuFile.MenuItems.AddRange(@($mnuExit)) $mnuFile.Text = "&File" #mnuExit $mnuExit.Shortcut = "CtrlX" $mnuExit.Text = "E&xit" $mnuExit.Add_Click( { $frmMain.Close() } ) #mnuHelp $mnuHelp.MenuItems.AddRange(@($mnuInfo)) $mnuHelp.Text = "&Help" #mnuInfo $mnuInfo.Text = "About..." $mnuInfo.Add_Click( { ShowAboutWindow } ) #lblBruT $lblBruT.Location = New-Object Drawing.Point(8, 16) $lblBruT.Size = New-Object Drawing.Size(96, 23) $lblBruT.Text = "Brush Type:" #lblDraw $lblDraw.Location = New-Object Drawing.Point(8, 40) $lblDraw.Size = New-Object Drawing.Size(96, 23) $lblDraw.Text = "Drawing:" #lblCol1 $lblCol1.Location = New-Object Drawing.Point(8, 80) $lblCol1.Size = New-Object Drawing.Size(96, 23) $lblCol1.Text = "Color 1:" #lblCol2 $lblCol2.Location = New-Object Drawing.Point(8, 104) $lblCol2.Size = New-Object Drawing.Size(96, 23) $lblCol2.Text = "Color 2:" #lblBruS $lblBruS.Location = New-Object Drawing.Point(8, 152) $lblBruS.Size = New-Object Drawing.Size(96, 23) $lblBruS.Text = "Brush Size:" #lblWraM $lblWraM.Location = New-Object Drawing.Point(8, 184) $lblWraM.Size = New-Object Drawing.Size(96, 23) $lblWraM.Text = "Wrap Mode:" #lblHatS $lblHatS.Location = New-Object Drawing.Point(8, 216) $lblHatS.Size = New-Object Drawing.Size(96, 23) $lblHatS.Text = "Hatch Style:" #lblRota $lblRota.Location = New-Object Drawing.Point(8, 248) $lblRota.Size = New-Object Drawing.Size(96, 23) $lblRota.Text = "Rotation:" #lblGraB $lblGraB.Location = New-Object Drawing.Point(8, 280) $lblGraB.Size = New-Object Drawing.Size(104, 23) $lblGraB.Text = "Gradient Blend:" #lblGraM $lblGraM.Location = New-Object Drawing.Point(8, 312) $lblGraM.Size = New-Object Drawing.Size(104, 23) $lblGraM.Text = "Gradient Mode:" #cboBruT $cboBruT.Items.AddRange(@("Solid", "Hatch", "Texture", "LinearGradient")) $cboBruT.Location = New-Object Drawing.Point(112, 13) $cboBruT.SelectedItem = "Solid" $cboBruT.Size = New-Object Drawing.Size(176, 24) $cboBruT.Add_SelectedIndexChanged( { RedrawPicture } ) #cboDraw $cboDraw.Items.AddRange(@("Fill", "Ellipses", "Lines")) $cboDraw.Location = New-Object Drawing.Point(112, 40) $cboDraw.SelectedItem = "Fill" $cboDraw.Size = New-Object Drawing.Size(176, 24) $cboDraw.Add_SelectedIndexChanged( { RedrawPicture } ) #txtCol1 $txtCol1.BackColor = "Blue" $txtCol1.Location = New-Object Drawing.Point(112, 77) $txtCol1.Size = New-Object Drawing.Size(144, 23) $txtCol1.Text = "Color [Blue]" $txtCol1.Add_TextChanged( { RedrawPicture } ) #txtCol2 $txtCol2.Location = New-Object Drawing.Point(112, 102) $txtCol2.Size = New-Object Drawing.Size(144, 23) $txtCol2.Text = "Color [White]" $txtCol2.Add_TextChanged( { RedrawPicture } ) #btnCol1 $btnCol1.Location = New-Object Drawing.Point(256, 76) $btnCol1.Size = New-Object Drawing.Size(32, 25) $btnCol1.Text = "..." $btnCol1.Add_Click($btnCol1_OnClick) #btnCol2 $btnCol2.Location = New-Object Drawing.Point(256, 101) $btnCol2.Size = New-Object Drawing.Size(32, 25) $btnCol2.Text = "..." $btnCol2.Add_Click($btnCol2_OnClick) #cboBruS $cboBruS.Items.AddRange(@("Large", "Medium", "Small")) $cboBruS.Location = New-Object Drawing.Point(112, 149) $cboBruS.SelectedItem = "Large" $cboBruS.Size = New-Object Drawing.Size(176, 24) $cboBruS.Add_SelectedIndexChanged($cboBruS_OnSelectedIndexChanged) #cboWraM $cboWraM.Location = New-Object Drawing.Point(112, 181) $cboWraM.Size = New-Object Drawing.Size(176, 24) $cboWraM.Add_SelectedIndexChanged( { RedrawPicture } ) #cboHatS $cboHatS.Location = New-Object Drawing.Point(112, 213) $cboHatS.Size = New-Object Drawing.Size(176, 24) $cboHatS.Add_SelectedIndexChanged( { RedrawPicture } ) #nudRota [decimal]$nudRota.Increment = [int[]](5, 0, 0, 0) $nudRota.Location = New-Object Drawing.Point(112, 245) [decimal]$nudRota.Maximum = [int[]](180, 0, 0, 0) $nudRota.Size = New-Object Drawing.Size(176, 23) $nudRota.Add_ValueChanged( { RedrawPicture } ) #nudGraB $nudGraB.DecimalPlaces = 2; [decimal]$nudGraB.Increment = [int[]](1, 0, 0, 65536) $nudGraB.Location = New-Object Drawing.Point(112, 277) [decimal]$nudGraB.Maximum = [int[]](1, 0, 0, 0) $nudGraB.Size = New-Object Drawing.Size(176, 23) [decimal]$nudGraB.Value = [int[]](1, 0, 0, 0) $nudGraB.Add_ValueChanged( { RedrawPicture } ) #cboGraM $cboGraM.Location = New-Object Drawing.Point(112, 309) $cboGraM.Size = New-Object Drawing.Size(176, 24) $cboGraM.Add_SelectedIndexChanged( { RedrawPicture } ) #picDemo $picDemo.BorderStyle = "FixedSingle" $picDemo.Location = New-Object Drawing.Point(304, 16) $picDemo.Size = New-Object Drawing.Size(312, 320) #frmMain $frmMain.ClientSize = New-Object Drawing.Size(626, 371) $frmMain.Controls.AddRange(@($lblBruT, $lblDraw, $lblCol1, $lblCol2, $lblBruS, $lblWraM, ` $lblHatS, $lblRota, $lblGraB, $lblGraM, $cboBruT, $cboDraw, ` $txtCol1, $txtCol2, $btnCol1, $btnCol2, $cboBruS, $cboWraM, ` $cboHatS, $nudRota, $nudGraB, $cboGraM, $picDemo)) $frmMain.Font = New-Object Drawing.Font("Microsoft Sans Serif", 10) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.MaximizeBox = $false $frmMain.Menu = $mnuMain $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Brushes" $frmMain.Add_Load($frmMain_OnLoad) [void]$frmMain.ShowDialog() } function ShowAboutWindow { $frmMain = New-Object Windows.Forms.Form $lblThis = New-Object Windows.Forms.Label $btnExit = New-Object Windows.Forms.Button #lblThis $lblThis.Location = New-Object Drawing.Point(5, 29) $lblThis.Size = New-Object Drawing.Size(330, 50) $lblThis.Text = "(C) 2012 Grigori Zakharov `n This is just an example that you can make better." $lblThis.TextAlign = "MiddleCenter" #btnExit $btnExit.Location = New-Object Drawing.Point(132, 97) $btnExit.Text = "Close" $btnExit.Add_Click( { $frmMain.Close() } ) #frmMain $frmMain.ClientSize = New-Object Drawing.Size(350, 137) $frmMain.ControlBox = $false $frmMain.Controls.AddRange(@($lblThis, $btnExit)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.ShowInTaskbar = $false $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "About..." [void]$frmMain.ShowDialog() } ShowMainWindow
PowerShellCorpus/PoshCode/Get-GrowthRate_2.ps1
Get-GrowthRate_2.ps1
function Get-GrowthRate { param( $Start, $End, $Period ) @@ $rate = [math]::Abs( [math]::Pow( ( $End / $Start ),( 1 / ($Period - 1 ) ) - 1 ) "{0:P}" -f $rate }
PowerShellCorpus/PoshCode/Enter-Module.ps1
Enter-Module.ps1
##############################################################################\n##\n## Enter-Module\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nLets you examine internal module state and functions by executing user\ninput in the scope of the supplied module.\n\n.EXAMPLE\n\nPS >Import-Module PersistentState\nPS >Get-Module PersistentState\n\nModuleType Name ExportedCommands\n---------- ---- ----------------\nScript PersistentState {Set-Memory, Get-Memory}\n\n\nPS >"Hello World" | Set-Memory\nPS >$m = Get-Module PersistentState\nPS >Enter-Module $m\nPersistentState: dir variable:\\mem*\n\nName Value\n---- -----\nmemory {Hello World}\n\nPersistentState: exit\nPS >\n\n#>\n\nparam(\n ## The module to examine\n [System.Management.Automation.PSModuleInfo] $Module\n)\n\nSet-StrictMode -Version Latest\n\n$userInput = Read-Host $($module.Name)\nwhile($userInput -ne "exit")\n{\n $scriptblock = [ScriptBlock]::Create($userInput)\n & $module $scriptblock\n\n $userInput = Read-Host $($module.Name)\n}
PowerShellCorpus/PoshCode/Findup_31.ps1
Findup_31.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"/x", new List<string>()},{"/i",new List<string>()},{"/xf",new List<string>()},{"/if",new List<string>()}, {"/xd",new List<string>()},{"/id",new List<string>()},{"/paths",new List<string>()} }; public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>> { {"/xr", new List<Regex>()},{"/ir",new List<Regex>()},{"/xfr",new List<Regex>()},{"/ifr",new List<Regex>()}, {"/xdr",new List<Regex>()},{"/idr",new List<Regex>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "/recurse", false }, { "/noerr", false }, {"/delete",false}, {"/xj", false}}; public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes. public static long errors = 0; public static string delconfirm; public static void Main(string[] args) { DateTime startTime = DateTime.Now; Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files."); Console.WriteLine(" "); string optionskey = "/paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem = args[i].ToLower(); if ((System.String.Compare(argitem, "/help", true) == 0) || (System.String.Compare(argitem, "/h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [/recurse] [/noerr] [/x /i /xd /id /xf /if + [r]] <files/directories/regex> [/delete]"); Console.WriteLine(" "); Console.WriteLine("Options: /help - displays this help message."); Console.WriteLine(" /recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" /noerr - discards error messages."); Console.WriteLine(" /delete - delete each duplicate file with confirmation."); Console.WriteLine(" /x - eXcludes if full file path starts with (or RegEx matches if /xr) one of the items following this switch until another switch is used."); Console.WriteLine(" /i - include if full file path starts with (or Regex matches if /ir) one of the items following this switch until another switch is used."); Console.WriteLine(" /xd - eXcludes all directories - minus drive/files - (using RegEx if /xdr) including subdirs following this switch until another switch is used."); Console.WriteLine(" /id - Include only directories - minus drive/files - (using RegEx if /idr) including subdirs following this switch until another switch is used."); Console.WriteLine(" /xf - eXcludes all files - minus drive/directories - (using RegEx if /xfr) following this switch until another switch is used."); Console.WriteLine(" /if - Include only files - minus drive/directories - (using RegEx if /ifr) following this switch until another switch is used."); Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr."); Console.WriteLine(" /paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" /xj - Exclude File and Directory Junctions."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" - deletes duplicates after consent is given."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data /recurse /x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc /xfr \\"(jim)\\""); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc /xr \\"[bf]\\" /ir \\"(smith)\\""); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the path name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionskey = "/paths"; continue; } if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem)) { optionskey = argitem; continue; } if (optionspaths.ContainsKey(optionskey)) optionspaths[optionskey].Add(args[i]); else { try { Regex rgx = new Regex(args[i], RegexOptions.Compiled); optionsregex[optionskey].Add(rgx); } catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);} } } if (optionspaths["/paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe /help. Assuming current directory."); optionspaths["/paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["/paths"], "*.*", files, optionsbools["/recurse"], optionsbools["/xj"]); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe /help"); Console.WriteLine("\\n"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.WriteLine("Building dictionary of file sizes, SHA512 hashes and full paths..."); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) continue; var breakout = false; var HashFile = new Dictionary<string, List<FileInfo>>(); long filesize = files[i].Length; while (true) { try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } string SHA512string = Hash2String(_SHA512.Hash); if (!HashFile.ContainsKey(SHA512string)) HashFile[SHA512string] = new List<FileInfo>() { }; HashFile[SHA512string].Add(files[i]); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) { break; } i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } foreach (var HG in HashFile) { if (HG.Value.Count > 1) // display filenames if number of files in SHA512 Hash Group > 1 { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count); foreach (var finfo in HG.Value) { Console.WriteLine(finfo.FullName); numOfDupes++; dupeBytes += filesize; if (optionsbools["/delete"]) if (DeleteDupe(finfo)) { bytesrecovered += filesize; deletedfiles++; } } } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS. Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); Console.WriteLine("Errors : {0:N0}", errors); Console.WriteLine("Execution time : " + (DateTime.Now - startTime)); } private static void WriteErr(string Str) { errors++; if (!optionsbools["/noerr"]) Console.WriteLine(Str); } private static string Hash2String(Byte[] hasharray) { string SHA512string = ""; foreach (var c in hasharray) { SHA512string += String.Format("{0:x2}", c); } return SHA512string; } private static Boolean DeleteDupe(FileInfo Filenfo) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { Filenfo.Delete(); Console.WriteLine("File Successfully deleted."); return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckNames(string fullname) { var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt") var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp") if (CheckNamesWorker(fullname, "/x", "/xr", true)) return false; if (CheckNamesWorker(filePart, "/xf", "/xfr", true)) return false; if (CheckNamesWorker(dirPart, "/xd", "/xdr", true)) return false; if (CheckNamesWorker(fullname, "/i", "/ir", false)) return false; if (CheckNamesWorker(filePart, "/if", "/ifr", false)) return false; if (CheckNamesWorker(dirPart, "/id", "/idr", false)) return false; return true; } private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType) { foreach (var filepath in optionspaths[pathskey]) { if (filestr.ToLower().StartsWith(filepath.ToLower()) == CheckType) return true; } foreach (var rgx in optionsregex[rgxkey]) { if (rgx.IsMatch(filestr) == CheckType) return true; } return false; } private static void getFiles(List<string> pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); } } private static void getFiles(string[] pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); } } private static void getFiles(string pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) if (CheckNames(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !xj) if (CheckNames(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, returnList, recursiveFlag, xj); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, returnList, recursiveFlag, xj); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Get-WebFile _2.7.ps1
Get-WebFile _2.7.ps1
## Function Get-WebFile (aka wget for PowerShell) ## Author: Joel Bennett and ## Peter Kriegel http://www.admin-source.de ## Original : http://poshcode.org/417 ## ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7 - Add Proxy support, check if a proxy is required and get credentials for it ## -ProxyAdress to Set the Adress of a Proxy Server ## -ProxyPort to Set the Port of a Proxy Server ## -ProxyUserName to Set the Username for the Proxy Server ## -ProxyUserPassword to Set the Password for the Proxy Server ## -ProxyUserDomain to Set the Domain which is used with the user for the Proxy Server ## -$userAgent cookie container to prevent the error with too many automatic redirections using a httpWebRequest in .NET ## Author: Peter Kriegel ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## Function Get-WebFile { [CmdletBinding(SupportsShouldProcess=$False)] param( [Parameter(Mandatory=$true)] [String]$url, [Parameter(Mandatory=$false)] [String]$fileName, [String]$ProxyAdress = $Null, [Int]$ProxyPort = 0, [String]$ProxyUserName = '', [String]$ProxyUserPassword = '', [String]$ProxyUserDomain = '', [String]$userAgent = 'JoelBennett417Get-WebFile', [switch]$Passthru, [switch]$quiet ) $req = [System.Net.HttpWebRequest]::Create($url); $webclient = new-object System.Net.WebClient If($ProxyAdress.length -eq 0){ # no Proxy is given by the User # check if a proxy is required If (!$webclient.Proxy.IsBypassed($url)) { $creds = [net.CredentialCache]::DefaultCredentials if ($creds -eq $null) { Write-Debug "Default credentials were null. Attempting backup method" $cred = get-credential $creds = $cred.GetNetworkCredential() } $proxyaddress = $webclient.Proxy.GetProxy($url).Authority Write-Verbose "Using this proxyserver: $proxyaddress" $proxy = New-Object System.Net.WebProxy($proxyaddress) $proxy.credentials = $creds $req.proxy = $proxy } } Else { # Proxy was given by the User If($ProxyPort -gt 0){ $proxy = New-Object System.Net.WebProxy($ProxyAdress,$ProxyPort) } Else { $proxy = New-Object System.Net.WebProxy($ProxyAdress) } If($ProxyUserName.length -gt 0){ # if username is given we create the credentials $creds = New-Object System.Net.NetworkCredential($ProxyUserName,$ProxyUserPassword,$ProxyUserDomain) } Else { # if no username is given try to get the default credentials $creds = [net.CredentialCache]::DefaultCredentials } if ($creds -eq $null) { # no credentials given or found so we as for it Write-Debug "Default credentials were null. Attempting backup method" $cred = get-credential $creds = $cred.GetNetworkCredential() } $proxy.credentials = $creds $req.proxy = $proxy } #http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw $req.CookieContainer = New-Object System.Net.CookieContainer if ($userAgent -ne $null) { Write-Debug "Setting the UserAgent to `'$userAgent`'" $req.UserAgent = $userAgent } $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path $env:TEMP $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding($res.CharacterSet ) # 'utf-8' [string]$output = "" } if($res.StatusCode -eq 200) { [int]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/New-CodeSigningCert_1.ps1
New-CodeSigningCert_1.ps1
## New-CodeSigningCert.ps1 ######################################################################################################################## ## Does the setup needed to self-sign PowerShell scripts ... ## Generates a "test" self-signed root Certificate Authority ## And then generates a code-signing certificate (and signs it with the CA certificate) ## OPTIONALLY (specify -import or -importall) imports the certificates to the store(s) ######################################################################################################################## ## NOTE: Uses OpenSSL (because it's xcopy redistributable -- wake up Microsoft) ## In order for this to work you should KEEP the script in the folder with OpenSsl.exe ## Also, it is VERY important that you properly provide passwords and the locale data... ## You can obviously reorder the parameters however you like, and hard-code some of the values in the parameters, but ## you need to make sure that if you use this to generate multiple certificates, that you preserve all of the certs ## and keep track of all your passwords so you don't lock yourself out of any of them. ######################################################################################################################## ## Usage: ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" Jaykul@HuddledMasses.org HuddledMasses.org Mystery Rochester "New York" US -importall -OpenSSLLocation C:\\Users\\Joel\\Documents\\WindowsPowershell\\PoshCerts\\bin -CAPassword MyCleverRootPassword -CodeSignPassword EvenMoreCleverPasswords ## ## If I hard-coded the company/dept/etc ... I could use this to generate certs for all my devs: ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" FakeEmail@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword MarksPassword ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" FakeEmail2@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword JessesPassword ## ## For the signed scripts to work, I just have to -import on the devices where the scripts need to run: ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" -import ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" -import ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -import ## ## On the developers' workstations, I need to use Get-PfxCertificate to sign, or else run -importall ## That will load the codesigning cert in their "my" store, and will only require the password for the initial import ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -importall -CodeSignPassword MyCodeSignPassword ######################################################################################################################## ## History ## 1.0 - Initial public release ## 1.1 - Bug fix release to make it easier to use... ## 1.2 - Bug fix to get the ORG and COMMON NAME set correctly -- Major whoops! ## Param( $CertStorageLocation = (join-path (split-path $Profile) "Certs"), $UserName = (Read-Host "User name") , $email , $company , $department , $city , $state , $country , $RootCAName = "Self-Signed-Root-CA" , $CodeSignName = "$UserName Code-Signing" , $alias = "PoshCert", [string]$keyBits = 4096, [string]$days = 365, [string]$daysCA = (365 * 5), [switch]$forceNew = $false, [switch]$importall = $false, [switch]$import = ($false -or $importall), ## we ask you to specify the CA password and your codesign password ## You can leave these null when importing on end-user desktops $CAPassword = $null, $CodeSignPassword = $null, ## You really shouldn't pass these unless you know what you're doing $OpenSSLLocation = $null, $RootCAPassword = $Null, $CodeSignCertPassword = $null ) function Get-UserEmail { if(!$script:email) { $script:email = (Read-Host "Email address") } return $script:email } function Get-RootCAPassword { if(!$script:RootCAPassword) { if(!$script:CAPassword) { $script:CAPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Root CA Password")).GetNetworkCredential().Password) } ## Then down here we calculate large passwords to actually use: ## This works as long as you keep the same company name and root ca name $script:RootCAPassword = [Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CaPassword)), ([Text.Encoding]::UTF8.GetBytes("$company$RootCAName")), "SHA1", 5).GetBytes(64) ) } return $script:RootCAPassword } function Get-CodeSignPassword { if(!$script:CodeSignCertPassword) { if(!$script:CodeSignPassword) { $script:CodeSignPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Code Signing Password")).GetNetworkCredential().Password) } ## This works as long as you keep the same PFX password and email address $script:CodeSignCertPassword = ([Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CodeSignPassword)), ([Text.Encoding]::UTF8.GetBytes((Get-UserEmail))), "SHA1", 5).GetBytes(64) )) } return $script:CodeSignCertPassword } function Get-SslConfig { Param ( $keyBits, $Country = (Read-Host "Country (2-Letter code)"), $State = (Read-Host "State (Full Name, no intials)"), $city = (Read-Host "City"), $company = (Read-Host "Company Name (or Web URL)"), $orgUnit = (Read-Host "Department (team, group, family)"), $CommonName, $email = (Read-Host "Email Address") ) @" # OpenSSL example configuration file for BATCH certificate generation # This definition stops the following lines choking if HOME isn't defined. HOME = . RANDFILE = $($ENV::HOME)/.rnd # To use this configuration with the "-extfile" option of the "openssl x509" utility # name here the section containing the X.509v3 extensions to use: #extensions = code_sign #################################################################### [ req ] default_bits = {0} default_keyfile = privkey.pem distinguished_name = req_distinguished_name #attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert # req_extensions = v3_ca # Other extensions to add to a certificate request? ## Passwords for private keys could be specified here, instead of on the commandline # input_password = secret # output_password = secret ## Set the permitted string types... ## Some software crashes on BMPStrings or UTF8Strings, so we'll stick with string_mask = nombstr [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = {1} countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = {2} localityName = Locality Name (eg, city) localityName_default = {3} 0.organizationName = Organization Name (eg, company) 0.organizationName_default = {4} # we can do this but it is not usually needed #1.organizationName = Second Organization Name (eg, company) #1.organizationName_default = World Wide Web Pty Ltd organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = {5} commonName = Common Name (eg, YOUR name) commonName_default = {6} commonName_max = 64 emailAddress = Email Address emailAddress_default = {7} emailAddress_max = 64 # SET-ex3 = SET extension number 3 # [ req_attributes ] # challengePassword = A challenge password # challengePassword_min = 4 # challengePassword_max = 20 # unstructuredName = An optional company name [ v3_ca ] ## Extensions for a typical CA ## PKIX recommendations: subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always ## PKIX suggests we should include email address in subject alt name # subjectAltName=email:copy ## But really they want it *only* there or the certs are "deprecated" # subjectAltName=email:move ## And the issuer details # issuerAltName=issuer:copy ## This is what PKIX recommends basicConstraints = critical,CA:true ## some broken software chokes on critical extensions, so you could do this instead. #basicConstraints = CA:true ## For a normal CA certificate you would want to specify this. ## But it will cause problems for our self-signed certificate. # keyUsage = cRLSign, keyCertSign ## You might want the netscape-compatible stuff too # nsCertType = sslCA, emailCA [ code_sign ] # These extensions are added when we get a code_signing cert ## PKIX recommendations: subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer ## PKIX suggests we should include email address in subject alt name # subjectAltName=email:copy ## But really they want it *only* there or the certs are "deprecated" # subjectAltName=email:move ## And the issuer details # issuerAltName=issuer:copy # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # If nsCertType is omitted, the certificate can be used for anything *except* object signing. # We just want to allow everything including object signing: nsCertType = server, client, email, objsign # This is the vital bit for code-signing extendedKeyUsage = critical, serverAuth,clientAuth,codeSigning # This is typical in keyUsage for a client certificate. keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" [ crl_ext ] # CRL extensions. # Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. # issuerAltName=issuer:copy authorityKeyIdentifier=keyid:always,issuer:always "@ -f $keyBits,$Country,$State,$city,$company,$orgUnit,$CommonName,$email } if(!$OpenSSLLocation) { ## You should be running the script from the OpenSsl folder $OpenSSLLocation = Split-Path $MyInvocation.MyCommand.Path Write-Debug "OpenSSL: $OpenSSLLocation" } if( Test-Path $OpenSslLocation ) { ## The OpenSslLoction needs to actually have OpenSsl in it ... $files = ls (Join-Path $OpenSSLLocation "*.[de][lx][el]") -include libeay32.dll,ssleay32.dll,OpenSSL.exe # libssl32.dll, if($files.count -lt 3) { THROW "You need to configure a location where OpenSSL can be run from" } } else { THROW "You need to configure a location where OpenSSL can be run from" } ## Don't touch these [string]$SslCnfPath = (join-path (Convert-Path $CertStorageLocation) PoshOpenSSL.config) New-Alias OpenSsl (join-path $OpenSSLLocation OpenSSL.exe) if( !(Test-Path $CertStorageLocation) ) { New-Item -type directory -path $CertStorageLocation | Push-Location $forceNew = $true } else { Push-Location $CertStorageLocation } Write-Debug "SslCnfPath: $SslCnfPath" Write-Debug "OpenSsl: $((get-alias OpenSsl).Definition)" ## Process the CSR and generate a pfx file if($forceNew -or (@(Test-Path "$CodeSignName.crt","$CodeSignName.pfx") -contains $false)) { ## Generate the private code-signing key and a certificate signing request (csr) if($forceNew -or (@(Test-Path "$CodeSignName.key","$CodeSignName.csr") -contains $false)) { ## Generate the private root CA key and convert it into a self-signed certificate (crt) if($forceNew -or (@(Test-Path "$RootCAName.key","$RootCAName.crt") -contains $false)) { ## Change configuration before -batch processing root key $CommonName = "$company Certificate Authority" $orgUnit = "$department Certificate Authority" $email = Get-UserEmail Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file OpenSsl genrsa -out "$RootCAName.key" -des3 -passout pass:$(Get-RootCAPassword) $keyBits OpenSsl req -new -x509 -days $daysCA -key "$RootCAName.key" -out "$RootCAName.crt" -passin pass:$(Get-RootCAPassword) -config $SslCnfPath -batch } ## Change configuration before -batch processing code-signing key $CommonName = "$UserName" $orgUnit = "$department" $email = Get-UserEmail Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file OpenSsl genrsa -out "$CodeSignName.key" -des3 -passout pass:$(Get-CodeSignPassword) $keyBits OpenSsl req -new -key "$CodeSignName.key" -out "$CodeSignName.csr" -passin pass:$(Get-CodeSignPassword) -config $SslCnfPath -batch } ## Use the root CA key to process the CSR and sign the code-signing key in one step... OpenSsl x509 -req -days $days -in "$CodeSignName.csr" -CA "$RootCAName.crt" -CAcreateserial -CAkey "$RootCAName.key" -out "$CodeSignName.crt" -setalias $alias -extfile $SslCnfPath -extensions code_sign -passin pass:$(Get-RootCAPassword) ## Combine the signed certificate and the private key into a single file and specify a new password for it ... OpenSsl pkcs12 -export -out "$CodeSignName.pfx" -inkey "$CodeSignName.key" -in "$CodeSignName.crt" -passin pass:$(Get-CodeSignPassword) -passout pass:$script:CodeSignPassword } Pop-Location if($import) { ## Now we need to import the certificates to the computer so we can use them... ## Sadly, the PowerShell Certificate Provider is read-only, so we need to do this by hand trap { if($_.Exception.GetBaseException() -is [UnauthorizedAccessException]) { write-error "Cannot import certificates as 'Root CA' or 'Trusted Publisher' except in an elevated console." continue } } ## In order to be able to use scripts signed by these certs ## The root cert that signed the code-signing certs must be loaded into the "Root" store $lm = new-object System.Security.Cryptography.X509certificates.X509Store "root", "LocalMachine" $lm.Open("ReadWrite") $lm.Add( (Get-PfxCertificate "$CertStorageLocation\\$RootCAName.crt") ) if($?) { Write-Host "Successfully imported root certificate to trusted root store" -fore green } $lm.Close() ## In order to avoid the "untrusted publisher" prompt ## The public code-signing cert must be loaded into the "TrustedPublishers" store $tp = new-object System.Security.Cryptography.X509certificates.X509Store "TrustedPublisher", "LocalMachine" $tp.Open("ReadWrite") $tp.Add( (Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.crt") ) if($?) { Write-Host "Successfully imported code-signing certificate to trusted publishers store" -fore green } $tp.Close() if($importall) { ## It's a good practice to go ahead and put our private certificates in "OUR" store too ### Otherwise we have to load it each time from the pfx file using Get-PfxCertificate ##### $cert = Get-PfxCertificate "$CodeSignName.pfx" ##### Set-AuthenticodeSignature -Cert $cert -File Test-Script.ps1 $my = new-object System.Security.Cryptography.X509certificates.X509Store "My", "CurrentUser" $my.Open( "ReadWrite" ) Get-CodeSignPassword $my.Add((Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.pfx")) #$script:CodeSignPassword, $DefaultStorage) if($?) { Write-Host "Successfully imported code-signing certificate to 'my' store" -fore yellow } $my.Close() } } # SIG # Begin signature block # MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUunVl0UTZlvAjOS219sL9EUT4 # EE6gggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL # Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw # Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ # KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx # OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l # dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk # bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs # IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y # ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM # +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ # qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ # /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX # IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05 # 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7 # tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8 # xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx # gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs # VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG # fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1 # JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH # Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG # A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF # BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB # DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF # AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2 # bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q # V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha # vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg # oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1 # jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7 # iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp # Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz # y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp # JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0 # u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB # ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH # EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo # MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE # AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0 # eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo # OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ # KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB # gjcCARUwIwYJKoZIhvcNAQkEMRYEFGPa+3yKeAOuG8MGktIPE98U9IQyMA0GCSqG # SIb3DQEBAQUABIICACukiWmmkw/T3q/IukaKIIO4/jJLng9v52P60RViKwJn7TOZ # C6Qcov2zO8/LBm8oIlY+kQil8MXqA3+5D7TGtFfYpyzoUh+Nwks1C9KAMWeRBKAL # b3H6CVX0H5nRh9PLa2a4WxbYHM6IxCOa/Z8clH4veAZbs5Zq5mtjLV14u8PszAYM # 4P/H0sXHMZYb9nj0vKjsZdxOlM0g6JHqUszE40tND/5dFuzdr3Tyu/aC6/j/ZFGZ # jdyaM88kE88qAU9Bs2M18LsSUJx6GsdlXwDD4eCBRH59+QtAnQZB4HUL5KkF53DG # J0WtRuI+wWmeMU9nNtDMQgSGJev0LVEJ2Ui+UsVA+RvWH04VCBrzlXi2TLzS9bCQ # 5Fo/t/czCbC4m/WrXQyYNDoHtI/fXE2ctSPq2QQaDF9Bu65MuMGzWa3iFSFmq0uA # nYivtHSlgyqhPBBmu8fspePkye7PzYoH2Gpykp17R5fBx+rQriKjTkZcGNdAGdQY # j7SEC93e0KjtZRQA+ABxmVacmNrO6NGbMN2Zd8Pheham1T38V3aWjKvq2d94iUfh # dgqvWhSu6zw0yE/NaJPTKnixN0j+up/Y7jSO9Cytvl4TNWJkFjDp+u0exl4s6eQ5 # cspbWHwWyYWyg7e0YaclbL7mPygvjxQDWOWgMN9cddvHCq8fiq6VPNTJqeLB # SIG # End signature block
PowerShellCorpus/PoshCode/RSS Enclosure Downloader_1.ps1
RSS Enclosure Downloader_1.ps1
# author: Alexander Grofl # http://www.therightstuff.de/2008/07/25/RSS+Enclosure+Downloader+In+PowerShell.aspx $feed=[xml](New-Object System.Net.WebClient).DownloadString("http://the/rss/feed/url") foreach($i in $feed.rss.channel.item) { $url = New-Object System.Uri($i.enclosure.url) $url.ToString() $url.Segments[-1] (New-Object System.Net.WebClient).DownloadFile($url, $url.Segments[-1]) }
PowerShellCorpus/PoshCode/ESXiMgmt module sample 5.ps1
ESXiMgmt module sample 5.ps1
####################################################################################################################### # File: ESXiMgmt_register_all_virtual_machines_sample.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param([string]$Server, [string]$User, [string]$Password, [string]$DatastoreName, [string]$Drive ) # USAGE: .\\ESXiMgmt_register_all_virtual_machines_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 cls Set-StrictMode -Version Latest Import-Module ESXiMgmt -Force; Connect-ESXi -Server $Server -Port 443 ` -Protocol HTTPS -User $User -Password $Password ` -DatastoreName $DatastoreName -Drive $Drive; dir "$($Drive):" | %{ ` # supposedly, all the *.vmx files have # the same names as their folders # like VMName\\VMName.vmx if (Test-Path "$($_.FullName)\\$($_.Name).vmx") { Register-ESXiVM -Server $Server ` -User $User -Password $Password ` -Path "/vmfs/volumes/$($DatastoreName)/$($_.Name)/$($_.Name).vmx" ` -OperationTImeout 5; } }
PowerShellCorpus/PoshCode/Get-ExcludedCsprojJavasc_1.ps1
Get-ExcludedCsprojJavasc_1.ps1
param( $projectDirectoryName = "MyProject" ) $thisDir = Split-Path $MyInvocation.MyCommand.Path $projectDir = "$thisDir/../$projectDirectoryName" $csproj = [xml](cat $projectDir/*.csproj) $csprojScripts = $csproj.Project.ItemGroup.Content.Include | ? {$_ -match '\\.js$'} "$($csprojScripts.length) scripts included in csproj file" $scripts = ls $projectDir -rec -inc *.js $scripts = $scripts.FullName | % {($_ -match "$projectDirectoryName\\\\(.*)" | out-null); $matches[1]} "$($scripts.length) scripts contained in scripts directory" $diff = $scripts |? {-not ($csprojScripts -contains $_)} "Scripts in directory but not in csproj:" $diff return $diff.length
PowerShellCorpus/PoshCode/TabExpansion_14.ps1
TabExpansion_14.ps1
## Tab-Completion ################# ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion (this also support default help function and man alias) ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion (this also support default help function and man alias) ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Errora s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" } ## $data = Get-Process ## $data[2,4,5] | % { $_.<tab> ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion by -Property parameter ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ## #Parameter expansion for function, filter and script ## man -f<tab> ## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1 ## .\\foobar.ps1 -<tab> -b<tab> ## #Enum expansion for function, filter and scripts ## # this can do continuous enum expansion with comma and no spaces ## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab> ## #Enum expansion for assignment expression ## #needs space(s) after '=' and comma ## #strongly-typed with -as operator and space(s) ## $ErrorActionPreference =<space><tab> ## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3 ## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab> ## #Path expansion with variable and '\\' or '/' ## $PWD\\../../<tab>\\<tab> ## "$env:SystemDrive/pro<tab>/<tab> ## #Operator expansion which starts with '-' ## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2' ## 1..9 -co<tab> 5 ## #Keyword expansion ## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } } ## #Variable name expansion (only global scope) ## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab> ## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab> ## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab> ## Tee-Object -Variable <tab> ## gv pro<tab>,<tab> ## Remove-Variable -Name out<tab>,<tab>,ps<tab> ## ... | ... | tee -v <tab> ## #Alias name expansion ## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab> ## Export-Alias -Name <tab> ## Get-Alias i<tab>,e<tab>,a<tab> ## epal -n for<tab> ## #Property name expansion with -groupBy parameter ## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab> ## ps | ft -g <tab> ## gcm | Format-Wide -GroupBy Par<tab> ## #Type accelerators expansion with no characters ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ## #Switch syntax option expansion ## switch -w<tab> -f<tab> ## #Better powershell.exe option expansion with '-' ## powershell -no<tab> -<tab> -en<tab> ## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* ) ## [par<tab> ## [cmd<tab> ## #Member expansion for CmdletBinding and Parameter attributes ## [Parameter(man<tab>,<tab>1,val<tab>$true)] ## [CmdletBinding( <tab>"foo", su<tab>$true)] ## #Several current date/time formats with Ctrl+D ## <Ctrl+D><tab><tab><tab><tab><tab>... ## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,') ## <command>;<tab> # push command ## <Ctrl+D><tab> # pop ## #Paste clipboard with Ctrl+V ## <Ctrl+V><tab> ## # Cut current line with Ctrl+X ## <command><Ctrl+X><tab> ## # Cut words with a character after Ctrl+X until the character ## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-' ## 2: PS > dir - ## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now ## # Cut last word in current line with Ctrl+Z ## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line ## 2: PS > Get-ChildItem ## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now ## #[ScriptBlock] member expansion for [ScriptBlock] literal ## { 1+1 }.inv<tab> ## #A part of history commands expansion with Ctrl+L (using split(";"),split("|"),split(";|") ) ## ls -Force -Recurse -Filter *.txt | ? { $_.LastWriteTime -lt [DateTime]::Today } ; echo PowerShell ## ls<Ctrl+L><tab><tab> ## ?<Ctrl+L><tab><tab> ## ec<Ctrl+L><tab> ## # Using Ctrl+K, characters insertion (bihind space or semi-coron or pipe operator) feature : it encloses tokens with parnthesis by default ## 1 - 1 - 1 - 1<Ctrl+K><tab> ## 1 - 1 - 1 - (1)<tab> ## 1 - 1 - 1 (- 1)<tab> ## 1 - 1 - (1 - 1)<tab><tab><tab>... ## with double Ctrl+K, it encloses tokens with $( ) ## for ( $i=0;$j=1<Ctrl+K><Ctrl+K><tab><tab> ## for ( $($i=0;$j=1) ## if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens ## 1+1 | {$_*2}<Ctrl+K>%<tab> ## 1+1 | %{$_*2} ## 1+1 +1+1<Ctrl+K>;<tab> ## 1+1 ;+1+1 ## if the character is ( or { or {, tokens are enclosed ( ) or { } or {} ## int<Ctrl+K>[<tab> ## [int] ## with double Ctrl+K, and if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens with '$' ## C:\\WINDOWS\\system32\\notepad.exe<Ctrl+K><Ctrl+K>{<tab> ## ${C:\\WINDOWS\\system32\\notepad.exe} ## % and ? are given special treatment with double Ctrl+K, these enclose tokens with % { } or ? { } behind '|' ## ls | $_.LastWriteTime -gt "2009/5"<Ctrl+K><Ctrl+K>?<tab> ## ls | ? {$_.LastWriteTime -gt "2009/5"} ## ls | $_.FullName<Ctrl+K><Ctrl+K>%<tab> ## ls | % {$_.FullName} ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0 } else { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") $_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID.Add($_i.GetValue("")) } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose } ### Generate TypeNames list... if ( Test-Path $PSHOME\\TypeNames.txt ) { $_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0 } else { $_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames.Add($_type.FullName) } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose } if ( Test-Path $PSHOME\\TypeNames_System.txt ) { $_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0 } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0 } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref", "Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml" $global:_cmdline = New-Object Collections.ArrayList iex (@' function prompt { h -Count 1 -OutVariable line | % { $_.CommandLine.Split("|"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";|") } | Get-Unique | ? { $_ -ne $line.CommandLine -and $_ -notmatch '^\\s*$' } | % { $_.Trim(" ") } | ? { $global:_cmdline -notcontains $_ } | % { Set-CommandLine $_ | Out-Null } if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru | Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru | Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru | Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru | Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru | Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru | Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru | Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru | Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru | Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru | Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru | Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru | Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru | Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru | Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru | Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru | Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru | Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru | Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru | Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru | Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru | Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru | Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru | Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru | Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru | Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru | Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru | Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru | Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru | Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru | Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru | Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru | Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru | Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru | Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru | Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru | Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru | Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru | Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru | Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru | Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru | Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru | Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru | Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru | Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru | Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru | Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru | Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru | Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru | Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru | Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru | Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru | Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru | Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru | Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru | Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru | Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru | Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru | Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru | Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru | Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru | Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru | Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru | Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru | Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru | Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru | Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru | Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru | Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru | Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru | Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru | Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru | Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru | Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru | Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru | Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru | Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru | Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru | Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru | Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru | Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru | Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru | Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru | Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru | Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru | Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru | Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru | Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru | Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru | Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru | Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru | Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru | Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = Get-EventLog Windows` PowerShell -Newest 1 } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function Set-CommandLine ( [string]$script ) { $global:_cmdline.Add($script) } function Get-CommandLine ( [string]$name ) { $name = $name -replace '\\?','`?' $global:_cmdline -like "$name*" } function TabExpansion { # This is the default function to use for tab expansion. It handles simple # member expansion on variables, variable name expansion and parameter completion # on commands. It doesn't understand strings so strings containing ; | ( or { may # cause expansion to fail. param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $members = ( [Object[]](Get-Member -InputObject $_val.PSextended $_pat) + [Object[]](Get-Member -InputObject $_val.PSadapted $_pat) + [Object[]](Get-Member -InputObject $_val.PSbase $_pat) ) if ( $_val -is [Hashtable] ) { [Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } $members += [Object[]]$_keys | ? { $_.Name -like $_pat } } foreach ($_m in $members | sort membertype,name -Unique) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } else { foreach ($_m in Get-Member -Static -InputObject $_val $_pat | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } } switch ([int]$line[-1]) { # Ctrl+D several date/time formats 4 { "[DateTime]::Now" [DateTime]::Now [DateTime]::Now.ToString("yyyyMMdd") [DateTime]::Now.ToString("MMddyyyy") [DateTime]::Now.ToString("yyyyMMddHHmmss") [DateTime]::Now.ToString("MMddyyyyHHmmss") 'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) } break TabExpansion; } # Ctrl+K put parentheses behind space or semi-coron or pipe operator 11 { if ( $line -ne $( "=" + [Char]11 ) ) { if ( $line[-2] -eq 11 ) { $left = '$' + "(" $line = $line.Substring(0,$line.length-2) } else { $left = "(" $line = $line.Substring(0,$line.length-1) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny(" ;|") $global:_ctrlk += $line.Insert($i+1, $left) + ")" $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") } else { $global:_ctrlk } break TabExpansion; } # Ctrl+L a part of history commands expansion 12 { Get-CommandLine $lastWord.SubString(0, $lastword.Length-1) break TabExpansion; } # Ctrl+P hand-operated pop from command buffer stack 16 { $_base = $lastword.SubString(0, $lastword.Length-1) $_buf = $global:_cmdstack.Pop() if ( $_buf.Contains("'") ) { $line = ($line.SubString(0, $line.Length-1) + $_buf) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") } else { $_base + $_buf } break TabExpansion; } # Ctrl+R $Host.UI.RawUI. 18 { '$Host.UI.RawUI.' '$Host.UI.RawUI' break TabExpansion; } # Ctrl+V paste clipboard 22 { $_base = $lastword.SubString(0, $lastword.Length-1) $global:_clip = New-Object System.Windows.Forms.TextBox $global:_clip.Multiline = $true $global:_clip.Paste() $line = ($line.SubString(0, $line.Length-1) + $global:_clip.Text) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") break TabExpansion; } # Ctrl+X cut current line 24 { $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $line.SubString(0, $line.Length-1) $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") break TabExpansion; } # Ctrl+Z cut last word in current line 26 { $line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break TabExpansion; } } switch ( [int]$line[-2] ) { # Ctrl+K put character behind space or semi-coron or pipe operator 11 { switch ( $line[-1] ) { '{' { $right = '}' } '(' { $right = ')' } '[' { $right = ']' } } $left = $line[-1] $delimiter = " ;|" if ( $line[-3] -eq 11 ) { if ( $line[-1] -eq '%' -or $line[-1] -eq '?' ) { $left = ' ' + $left + ' {'; $right = '}' $delimiter = '|' } else { $left = '$' + $left } $line = $line.Substring(0,$line.length-3) } else { $line = $line.Substring(0,$line.length-2) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny($delimiter) $global:_ctrlk += $line.Insert($i+1, $left) + $right $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") break TabExpansion; } # Ctrl+X cut words with a character after Ctrl+X until the character 24 { $line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break TabExpansion; } } switch -regex ($lastWord) { # Handle property and method expansion at '$_' '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] $_pat = $matches[4] + '*' if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. { 1+1 }.inv<tab> '(^.*})\\.(\\w*)$' { $_base = $matches[1] $_pat = $matches[2] + '*' foreach ( $_m in {} | Get-Member $_pat | sort membertype,name ) { if ($_m.MemberType -eq "Method") { $_base + '.' + $_m.name + '(' } else { $_base + '.' + $_m.name } } break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle item name expansion in variable notation... '(^.*\\${)(((\\w+):([\\\\/]?))[^\\\\/]+([\\\\/][^\\\\/]*)*)$' { $_prefix = $matches[1] $_driveName = $matches[3] $_itemName = $matches[2] + "*" Get-ChildItem $_itemName | % { if ( $matches[5] -and $_.PSProvider.Name -eq "FileSystem" ) { $output = $_prefix + $_.FullName } elseif ( $_.PSProvider.Name -eq "FileSystem" -and $matches[6] ) { $cd = (Get-Location -PSDrive $matches[4]).Path $output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1) } elseif ( $_.PSProvider.Name -eq "FileSystem" ) { $cd = (Get-Location -PSDrive $matches[4]).Path $output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1) } else { $output = $_prefix + $_driveName + $_.Name } if ( $_.PSIsContainer ) { $output } else { $output + "}" } } break; } # Handle PSDrive name expansion in variable notation... '(^.*\\${)(\\w+)$' { $_prefix = $matches[1] $_driveName = $matches[2] + "*" Get-PSDrive $_driveName | % { $_prefix + $_ + ':' } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break;
PowerShellCorpus/PoshCode/Modified WOL impl..ps1
Modified WOL impl..ps1
function SendUdpWol { #Packet construction reference: #- http://wiki.wireshark.org/WakeOnLAN #- http://en.wikipedia.org/wiki/Wake-on-LAN # #This code is a modified version of: # - http://thepowershellguy.com/blogs/posh/archive/2007/04/01/powershell-wake-on-lan-script.aspx param ( [parameter(Mandatory=$true)] [ValidatePattern("[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}")] [String] $MacAddress, [parameter(Mandatory=$false)] [int[]] $Ports=@(0,7,9) ) [int]$MAGICPACKETLENGTH=102 #'Constant' defining total magic packet length. [Byte[]]$magicPacket=[Byte[]](,0xFF * $MAGICPACKETLENGTH) #Initialize packet all 0xFF for packet length. [Byte[]]$byteMac=$MacAddress.Split(":") |% { #Convert the string MacAddress to a byte array (6 bytes). [Byte]("0x" + $_) } #Starting from byte 6 till 101, fill the packet with the MAC address (= 16 times). 6..($magicPacket.Length - 1) |% { $magicPacket[$_]=$byteMac[($_%6)] } #Setup the UDP client socket. [System.Net.Sockets.UdpClient] $UdpClient = new-Object System.Net.Sockets.UdpClient foreach ($port in $Ports) { $UdpClient.Connect(([System.Net.IPAddress]::Broadcast),$port) #Send packet on each defined port. Write-Verbose $("Sending magic packet to {0} port {1}" -f $MacAddress,$port) [Void]$UdpClient.Send($magicPacket,$magicPacket.Length) #Don't return the packet length => [void] } $UdpClient.Close() }
PowerShellCorpus/PoshCode/WindowsInstallPoint.ps1
WindowsInstallPoint.ps1
function Initialize-WindowsInstallPoint { <# .SYNOPSIS Initializes a drive to become a Windows OS install point. .DESCRIPTION The Initialize-WindowsInstallPoint function uses the "diskpart" utility to wipe, partition, and format a local or removable drive. The "bootsect" tool processes the bootmgr allowing the drive to become a bootable device from which Windows can be installed. Once the drive is initialized, copy the entire contents of the Windows install media to the drive. Windows Vista, 7, Server 2008, and Server 2008 R2 are supported. .PARAMETER Drive Specifies the drive to initialize as a Windows install point. <DriveLetter:> .PARAMETER BootsectPath The full file path to the "bootsect.exe" tool. For Windows versions 6.x, it's located on the installation media in the "boot" folder. .PARAMETER DiskpartPath The full file path to the "diskpart.exe" tool. Default parameter value: $env:SystemRoot\\System32\\diskpart.exe .EXAMPLE Initialize-WindowsInstallPoint X: D:\\boot\\bootsect.exe Initializes drive X: using the bootsect.exe tool located in the boot folder of drive D: .INPUTS System.String .OUTPUTS None .NOTES Name: Initialize-WindowsInstallPoint Author: Rich Kusak (rkusak@cbcag.edu) Created: 2009-10-24 Last Edit: 2011-04-07 18:48 Version: 1.7.0.0 #Requires Version 2.0 .LINK bootsect.exe .LINK diskpart.exe #> [CmdletBinding(ConfirmImpact='High', SupportsShouldProcess=$true)] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, HelpMessage='The drive qualifier of the device to become a Windows install point.' )] [ValidateScript({ switch ($_) { $env:SystemDrive {throw 'This operation cannot be performed on the system drive.'} {$_ -match '^[a-z]:$'} {$true} default {throw "The argument '$_' is not a valid drive designation. Supply an argument that matches '<DriveLetter>:' and try the command again."} } })] [string]$Drive, [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage='The full path to the bootsect.exe tool.' )] [Alias('FullName')] [ValidateScript({ if (Test-Path $_ -Include '*bootsect.exe') {$true} else { throw "The argument '$_' is not a real path to the bootsect.exe tool." } })] [string]$BootsectPath, [Parameter(ValueFromPipelineByPropertyName=$true, HelpMessage='The full path to the diskpart.exe tool.' )] [ValidateScript({ if (Test-Path $_ -Include '*diskpart.exe') {$true} else { throw "The arguments '$_' is not a real path to the diskpart.exe tool." } })] [string]$DiskpartPath = "$env:SystemRoot\\System32\\diskpart.exe" ) begin { function Test-Elevation { $admin = [System.Security.Principal.WindowsBuiltInRole]::Administrator $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object System.Security.Principal.WindowsPrincipal($identity) $principal.IsInRole($admin) } # Test that PowerShell is running as an administrator if (-not (Test-Elevation)) { throw 'Administrator privileges are required. PowerShell is not running as an administrator.' } $dpExitCodes = @{ 0 = 'No error occurred. The entire script ran without failure.' 1 = 'A fatal exception occurred. There may be a serious problem.' 2 = 'The arguments specified on a Diskpart command line were incorrect.' 3 = 'Diskpart was unable to open the specified script or output file.' 4 = 'One of the services Diskpart uses returned a failure.' 5 = 'A command syntax error occurred. The script failed because an object was improperly selected or was invalid for use with that command.' } # Temporary files for the diskpart script and redirect standard output $dpScript = [System.IO.Path]::GetTempFileName() $rso = [System.IO.Path]::GetTempFileName() # Set the initial instance of the variable used to control the flow of $psCmdlet $psc = $null } # end begin process { # Capitalize drive letter for display $Drive = $Drive.ToUpper() # Detrimine if the drive meets the requirements to become a Windows install point Write-Debug 'Getting WMI object Win32_LogicalDisk' $logicalDisk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID = '$Drive' " if ($logicalDisk.DriveType -notmatch '^(2|3)$') { return Write-Error "Drive '$Drive' is not a local or removable drive." -TargetObject $Drive } elseif ($logicalDisk.Size -lt 3.5GB) { # Different Windows editions vary in size but a drive 3.5GB or greater should accomidate all editions Write-Warning "Drive '$Drive' may not be large enough for Windows installation files." } if ($psc -eq $null) {$psc = $psCmdlet} if ($psc.ShouldProcess($Drive, "Initialize Windows install point. Any existing data will be DESTROYED")) { Write-Progress -Activity 'Initialize Windows Install Point' -Status "Drive $Drive" -CurrentOperation 'Preparing disk volume' -PercentComplete 0 # Diskpart script content @" Select Volume $($Drive[0]) Clean Create Partition Primary Select Partition 1 Active Format Quick FS=NTFS Label=WindowsInstallPoint Assign Letter $Drive Exit "@ | Out-File $dpScript -Encoding ASCII -Force Write-Debug 'Starting process diskpart.exe' # Using Start-Process allows the exit code to be processed from either the console or ISE. $diskpart = Start-Process $DiskpartPath "/s $dpScript" -NoNewWindow -Wait -PassThru -RedirectStandardOutput $rso 1..45 | ForEach { Write-Progress -Activity 'Initialize Windows Install Point' -Status "Drive $Drive" -CurrentOperation 'Preparing disk volume' -PercentComplete $_ Sleep -Milliseconds 20 } # Removes empty lines from the original diskpart.exe output and sends it to the verbose stream Get-Content $rso | Select-String '.' | ForEach {Write-Verbose $_} # Diskpart error handling if ($diskpart.ExitCode -eq 0) { Write-Verbose "Drive '$Drive' has been successfully processed by the diskpart.exe tool." } elseif ($diskpart.ExitCode -gt 0) { return Write-Error $dpExitCodes.($diskpart.ExitCode) } else { return Write-Error 'An unknown error occured.' } Write-Debug 'Starting process bootsect.exe' # Using Start-Process allows the exit code to be processed from either the console or ISE. $bootsect = Start-Process $BootsectPath "/NT60 $Drive" -NoNewWindow -Wait -PassThru -RedirectStandardOutput $rso 46..90 | ForEach { Write-Progress -Activity 'Initialize Windows Install Point' -Status "Drive $Drive" -CurrentOperation 'Setting boot code' -PercentComplete $_ Sleep -Milliseconds 20 } # Removes empty lines from the original bootsect.exe output and sends it to the verbose stream Get-Content $rso | Select-String '.' | ForEach {Write-Verbose $_} # Bootsect error handling if ($bootsect.ExitCode -eq 0) { Write-Verbose "Drive '$Drive' has been successfully processed by the bootsect.exe tool." Write-Progress -Activity 'Initialize Windows Install Point' -Status "Drive $Drive" -CurrentOperation 'Complete' -PercentComplete 100 Sleep -Seconds 1 } else { return Write-Error "$bootsect" } } # end ShouldProcess Write-Verbose "Drive '$Drive' has been successfully initialized as a Windows install point." } # end process end { # Cleanup temporary files Remove-Item $dpScript, $rso -Force -WhatIf:$false } } # end function Initialize-WindowsInstallPoint
PowerShellCorpus/PoshCode/Compare Reg Keys.ps1
Compare Reg Keys.ps1
<# .SYNOPSIS Compares Registry Key Properties and subkeys across multiple computers .DESCRIPTION The function Get-AllRegKey will recurse down from a given key, returning an array having the key's properties, subkeys, and their properties and subkeys. Provide Get-AllRegKey a list of computernames, and it will remote to those computers and return the properties, etc. of the same key on the remote computer Provide function Compare-AllRegKey with the name of the reference computer, a list of two or more computer names, and it will call Get-AllRegKey to retrieve the key information from all the listed computers, then use Compare-Object to return just the differences. If you want more control over the Compare-Object step, you should modify the function (suggestions welcome for an efficient/concise way to add Compare-Object parameters to the Compare-AllRegKey function) .PARAMETER ComputerNames In the Get-AllRegKey function this is a single computer name or an array of computer names In the Compare-AllRegKey function, this must be an array of at least two computer names .PARAMETER RegKey a single registry key/hive from which recursion starts, using the Registry Provider syntax The value defaults to the current-scoped variable $DefaultRegistryKey .PARAMETER -ReferenceObject Applies only to the Compare-AllRegKey function, this parameter identifies the computer against which the other computers are compared. This string must be one of the computer names found in the ComputerNames parameter. .EXAMPLE C:\\PS> Get-AllRegKey .EXAMPLE C:\\PS> Get-AllRegKey -RegistryKey 'HKLM:\\SOFTWARE\\Microsoft\\PowerShell' .EXAMPLE C:\\PS> Get-AllRegKey -ComputerNames @('localhost','RemoteCN') .EXAMPLE C:\\PS> Get-AllRegKey -ComputerNames @('localhost','Computer1','Computer2') .EXAMPLE C:\\PS> Get-AllRegKey localhost 'HKLM:\\SOFTWARE\\Microsoft\\PowerShell' .EXAMPLE C:\\PS> Compare-AllRegKey -ComputerNames @('localhost','RemoteCN') .EXAMPLE C:\\PS> Compare-AllRegKey -ComputerNames @('CN1','CN2') -ReferenceObject CN2 #> ################################################################################ # Default values for the Registry Key and the list of computernames $DefaultRegistryKey='HKLM:\\SOFTWARE\\Microsoft\\PowerShell' $computerNames= @('localhost','ncat099') ################################################################################ # The scriptblock that does the actual work of creating an object representing a # registry key and all it's properties and subkeys and their properties. No Defaults # This is recursive and remoteable $_getRegKeySB = {Param($RegistryHive) # Create a local named function function _getRegKey { Param($RegistryHive) # $data is an array, local to each loop of the recursion # initialize it with the name of the hive/key $data=@($RegistryHive) # Get the hive/keys properties, excluding the ones added by PS $props = Get-ItemProperty -Path $RegistryHive | Select * -Exclude PS*Path,PSChildName,PSDrive,PSProvider # if $props is empty, piping it to get-member produces an error message # so test it for non-null first if ($props) { $props = $props | get-member -memberType NoteProperty # prepend each property with the full name of the key, and add it to $data foreach ($p in $props) {$data+=("$RegistryHive`:"+$p.Definition)} } # recursivly call the same algorithm for any subkeys of the hive/key foreach ($sk in (get-item $RegistryHive).GetSubKeyNames()) { # if there are any subkeys, append their data to the current data. # Use the full name of the key $data += (&_getRegKey (($RegistryHive)+'\\'+ $sk)) } # the local named function's output is the array representation of the hive/key $data } # Call the local named function &_getRegKey $RegistryHive } ################################################################################ # Across all computers, get the key and subkeys from the registry # returns a hash of array objects, keyed by computer name function Get-AllRegKey { Param ( # Single computer name or an array of computer names. # Defaults to the "current scoped variable by the same name" $computerNames = $computerNames # A valid key ,$RegistryKey = $DefaultRegistryKey ) # create the empty hash $AllRegKey = @{} # iterate over each computer name foreach ($cn in $computerNames) { switch ($cn) { # If the computer name is localhost, or the same name as hostname # use the Call operator to call the scriptblock, and assign the array returned # to the hash using the current computername as the key {$_ -match "localhost|" + (hostname)} { $AllRegKey.$cn = &$_getRegKeySB $RegistryKey break } # for all other computer names, execute the command remotely using invoke-command default { # pass the scriptblock to the remote computers # assign the array returned to the hash using the current computername as the key $AllRegKey.$cn = (invoke-command -Scriptblock $_getRegKeySB ` -ArgumentList $RegistryKey -computername "$cn") } } } #return the hash of arrays $AllRegKey } ################################################################################ # Across all computers, get the key and subkeys from the registry # returns a hash of array objects, keyed by computer name function Compare-AllRegKey { Param ( # Must be an array, with 2 or more members; # defaults to the "current scoped variable by the same name" $computerNames = $computerNames # A valid key ,$RegistryKey = $DefaultRegistryKey # The name of the computer to use as the reference ,$ReferenceObject ) Begin { # If the argument for $ReferenceObject is null, then default # to the first element of $computerNames if (!$ReferenceObject) {$ReferenceObject =$computerNames[0]} else { # Validate that the $referenceObject is an element of $computerNames if (!($computerNames -contains $ReferenceObject)) { throw ("{0} is not a member of the list {1}" -f $ReferenceObject, ` ($computerNames -join ','))} } # Get the Registry Key data for all computers $AllRegKey = Get-AllRegKey $computerNames $RegistryKey } Process { # Iterate over the computernames, excluding the $ReferenceObject $diff = @{}; foreach ($cn in $computerNames | Where {$cn -ne $ReferenceObject}) { # compare $ReferenceObject to the remaining objects, accumulate into $diff $diff.$cn = Compare-Object -ReferenceObject $AllRegKey.$ReferenceObject ` $AllRegKey.$cn | Where-Object { ` ($_.SideIndicator -eq '=>') -or ($_.SideIndicator -eq '<=') } } # Return the difference hash $diff } } # The following lines will compare the default registry key # across the default array of computernames Compare-AllRegKey
PowerShellCorpus/PoshCode/Remove-Games.ps1
Remove-Games.ps1
#/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\ # # Script Name: Remove-Games.ps1 # Title: Remove Games # Version: 1.0 # Author: John W. Cannon <johnwcannon at_gmail_dot_com> # Date: September 20, 2011 # # Description: This tool removes the built-in games # from Windows XP (tested on SP3) # #/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\ #Obtain processes and kill any running games $a = Get-Process #Get a list of running processes #Kill Freecell If ($a | Where-Object {$_.ProcessName -eq "freecell"}){ Stop-Process -name freecell -Force } #Kill Zone.com client If ($a | Where-Object {$_.ProcessName -eq "zClientm"}){ Stop-Process -name zClientm -Force } #Kill Hearts If ($a | Where-Object {$_.ProcessName -eq "mshearts"}){ Stop-Process -name mshearts -Force } #Kill Internet Backgammon If ($a | Where-Object {$_.ProcessName -eq "bckgzm"}){ Stop-Process -name bckgzm -Force } #Kill Internet Checkers If ($a | Where-Object {$_.ProcessName -eq "chkrzm"}){ Stop-Process -name chkrzm -Force } #Kill Internet Hearts If ($a | Where-Object {$_.ProcessName -eq "hrtzzm"}){ Stop-Process -name hrtzzm -Force } #Kill Internet Reversi If ($a | Where-Object {$_.ProcessName -eq "rvsezm"}){ Stop-Process -name rvsezm -Force } #Kill Internet Spades If ($a | Where-Object {$_.ProcessName -eq "shvlzm"}){ Stop-Process -name shvlzm -Force } #Kill Minesweeper If ($a | Where-Object {$_.ProcessName -eq "winmine"}){ Stop-Process -name winmine -Force } #Kill Pinball If ($a | Where-Object {$_.ProcessName -eq "pinball"}){ Stop-Process -name pinball -Force } #Kill Solitaire If ($a | Where-Object {$_.ProcessName -eq "sol"}){ Stop-Process -name sol -Force } #Kill Spider Solitaire If ($a | Where-Object {$_.ProcessName -eq "spider"}){ Stop-Process -name spider -Force } #Create the file needed for the sysocmgr.exe program $file = New-Item -ItemType file "c:\\Windows\\inf\\ocm.txt" -Force Add-Content $file "[Components]" Add-Content $file "freecell=off" Add-Content $file "hearts=off" Add-Content $file "minesweeper=off" Add-Content $file "msnexplr=off" Add-Content $file "pinball=off" Add-Content $file "solitaire=off" Add-Content $file "spider=off" Add-Content $file "zonegames=off" #Run the sysocmgr.exe utility with the file we just created #More information on sysocmgr.exe here: http://support.microsoft.com/kb/222444 Invoke-Expression "sysocmgr.exe /i:c:\\windows\\inf\\sysoc.inf /u:c:\\windows\\inf\\ocm.txt /q" #Remove the Games folder from the All Users profile because it isn't deleted by sysocmgr Remove-Item 'c:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Games' -Force -WarningAction SilentlyContinue -Recurse
PowerShellCorpus/PoshCode/Download Free Reflector.ps1
Download Free Reflector.ps1
#Thanks http://27.am/posts/how-to-download-net-reflector-6-for-free add-type @' using System; using System.Diagnostics; using System.IO; using System.Net; using System.Reflection; namespace LookingGlass { 젨젨public class RedGateDownloader 젨젨젨젨public static void Download() 젨젨젨젨{ 젨젨젨젨젨젨QueryDownloadUrl("http://reflector.red-gate.com/Reflector.version"); 젨젨젨젨} 젨젨젨젨static void QueryDownloadUrl(string versionUrl) 젨젨젨젨{ 젨젨젨젨젨젨Console.WriteLine("Phase 1: Getting download URL..."); 젨젨젨젨젨젨HttpWebRequest request = GetHttpWebRequest(versionUrl); 젨젨젨젨젨젨string downloadUrl = null; 젨젨젨젨젨젨string data; 젨젨젨젨젨젨using (WebResponse response = request.GetResponse()) 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨data = ReadResponse(response); 젨젨젨젨젨젨젨젨foreach (string line in data.Split('\\n')) 젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨if (line.StartsWith("http", StringComparison.OrdinalIgnoreCase)) 젨젨젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨젨젨// If this version number stops working, search for other known .NET Reflector version numbers; Red Gates own forums mention a few 젨젨젨젨젨젨젨젨젨젨젨젨downloadUrl = line.Trim('\\r').Replace("{Client}", "Reflector").Replace("{Version}", "6.1.0.11"); 젨젨젨젨젨젨젨젨젨젨젨젨break; 젨젨젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨} 젨젨젨젨젨젨if (downloadUrl == null) 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨Console.WriteLine("Failed to find download URL. Returned data was:"); 젨젨젨젨젨젨젨젨Console.WriteLine(data); 젨젨젨젨젨젨젨젨Console.ReadLine(); 젨젨젨젨젨젨} 젨젨젨젨젨젨else 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨Console.WriteLine("Launching download process... for "+downloadUrl); 젨젨젨젨젨젨젨젨Process.Start(Process.GetCurrentProcess().MainModule.FileName, downloadUrl); 젨젨젨젨젨젨젨젨Console.WriteLine("Phase 1 complete."); Console.ReadLine(); Download(downloadUrl); 젨젨젨젨젨젨} 젨젨젨젨} 젨젨젨젨static void Download(string downloadUrl) 젨젨젨젨{ 젨젨젨젨젨젨Console.WriteLine("Phase 2: Downloading..."); 젨젨젨젨젨젨HttpWebRequest request = GetHttpWebRequest(downloadUrl); 젨젨젨젨젨젨string path; 젨젨젨젨젨젨using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨path = GetDownloadFilename(response); 젨젨젨젨젨젨젨젨if (response.StatusCode == HttpStatusCode.OK && !string.IsNullOrEmpty(path)) 젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Saving to {0}...", path); 젨젨젨젨젨젨젨젨젨젨SaveResponse(response, path); 젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Done!"); 젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨젨젨else 젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨Console.WriteLine("Download failed; server returned status code {0}. Returned data was:", response.StatusCode); 젨젨젨젨젨젨젨젨젨젨Console.WriteLine(ReadResponse(response)); 젨젨젨젨젨젨젨젨젨젨Console.ReadLine(); 젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨} 젨젨젨젨} 젨젨젨젨static HttpWebRequest GetHttpWebRequest(string url) 젨젨젨젨{ 젨젨젨젨젨젨HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 젨젨젨젨젨젨request.Headers.Add("Cache-Control: no-cache, no-store, max-age=0"); 젨젨젨젨젨젨// Emulate the manner in which the headers are handled 젨젨젨젨젨젨FieldInfo usesProxySemantics = typeof(ServicePoint).GetField("m_ProxyServicePoint", BindingFlags.NonPublic | BindingFlags.Instance); 젨젨젨젨젨젨usesProxySemantics.SetValue(request.ServicePoint, true); 젨젨젨젨젨젨return request; 젨젨젨젨} 젨젨젨젨static string GetDownloadFilename(HttpWebResponse response) 젨젨젨젨{ 젨젨젨젨젨젨string contentDisposition = response.Headers["content-disposition"]; 젨젨젨젨젨젨if (string.IsNullOrEmpty(contentDisposition)) 젨젨젨젨젨젨젨젨return null; 젨젨젨젨젨젨string filenameField = "filename="; 젨젨젨젨젨젨int index = contentDisposition.IndexOf(filenameField, StringComparison.CurrentCultureIgnoreCase); 젨젨젨젨젨젨if (index < 0) 젨젨젨젨젨젨젨젨return null; 젨젨젨젨젨젨return contentDisposition.Substring(index + filenameField.Length).Trim('"'); 젨젨젨젨} 젨젨젨젨static string ReadResponse(WebResponse response) 젨젨젨젨{ 젨젨젨젨젨젨using (Stream netStream = response.GetResponseStream()) 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨using (StreamReader reader = new StreamReader(netStream)) 젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨return reader.ReadToEnd(); 젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨} 젨젨젨젨} 젨젨젨젨static void SaveResponse(WebResponse response, string path) 젨젨젨젨{ 젨젨젨젨젨젨byte[] buffer = new byte[4 * 1024]; 젨젨젨젨젨젨int bytesRead; 젨젨젨젨젨젨using (Stream netStream = response.GetResponseStream()) 젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨if (File.Exists(path)) 젨젨젨젨젨젨젨젨젨젨File.Delete(path); 젨젨젨젨젨젨젨젨using (FileStream fileStream = File.Create(path)) 젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨while ((bytesRead = netStream.Read(buffer, 0, buffer.Length)) > 0) 젨젨젨젨젨젨젨젨젨젨{ 젨젨젨젨젨젨젨젨젨젨젨젨Console.Write("."); 젨젨젨젨젨젨젨젨젨젨젨젨fileStream.Write(buffer, 0, bytesRead); 젨젨젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨젨젨} 젨젨젨젨젨젨} 젨젨젨젨젨젨Console.WriteLine(); 젨젨젨젨} 젨젨} } '@ [LookingGlass.RedGateDownloader]::Download()
PowerShellCorpus/PoshCode/Dell Order Status.ps1
Dell Order Status.ps1
# Version: 0.1 # Author: Stefan Stranger # Description: Retrieve Dell Order Status # Start Page Order Status USA: https://support.dell.com/support/order/status.aspx?c=us&cs=19&l=en&s=dhs&~ck=pn # Start Page Order Status EMEA(nl): http://support.euro.dell.com/support/index.aspx?c=nl&l=nl&s=gen&~ck=bt # Example Dell Order Status URL: http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=[IR Number]&ea=[emailaddress]' #param ([string]$url = $(read-host "Please enter Dell Order Status URL")) $wc = New-Object System.Net.WebClient $url = 'http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=NL0131-8510-29070&ea=stefan.stranger@getronics.com' $RawResult = $wc.DownloadString($url) # $RawResult = gc orderstatus.txt # Search for the Estimated Delivery Date in the url that starts with the word "lever" (Levering is the Dutch word for Delivery" and # and ends with </B></TD></TR> # You should probable need to change the string "Lever" in "Deliv" or something $r = New-Object regex('Lever.*?(\\d+-\\d+-\\d{4})</B></TD></TR>','SingleLine' ) # String block with the Estimated Delivery Date $m = $r.Matches($RawResult) # Extract Delivery Date from string block $date = ($m |% {$_.groups[1].value }) # Search for Current Order Status ("In preproduction" is Dutch for "In preproduction" $r = New-Object regex('target="popup:640x480">(.*?)</a>' ) $m = $r.Matches($RawResult) $status = ($m |% {$_.groups[1].value }) $Orderstatus = 1 | select @{name='Status';expression={$status[0]}},@{name='Estimated Delivery Date';expression={$date}} $Orderstatus | ft -a #[string]$output = $orderstatus $startdate = "16-09-2007" $startdate $currentdate = (get-date).ToString('MM-dd-yyyy') $currentdate $date
PowerShellCorpus/PoshCode/Deleted-ObjectsAD_1.ps1
Deleted-ObjectsAD_1.ps1
param( $Domen, $ObjectsDeleted ) function Ping ($Name){ $ping = new-object System.Net.NetworkInformation.Ping if ($ping.send($Name).Status -eq "Success") {$True} else {$False} trap {Write-Verbose "Error Ping"; $False; continue} } [string[]]$ObjectPath [string[]]$Disks [string[]]$Info [string[]]$Computers $Computers = Get-QADComputer -Service $Domen -OSName '*XP*','*Vista*','*7*' -SizeLimit 0 -ErrorAction SilentlyContinue | Select-Object name -ExpandProperty name foreach ($Computer in $Computers){ $Alive = Ping $Computer if ($Alive -eq "True"){ Write-Host "Seach $Computer" -BackgroundColor Blue trap {Write-Host "Error WmiObject $Computer";Continue} $Disks += Get-WmiObject win32_logicaldisk -ComputerName $Computer -ErrorAction SilentlyContinue | Where-Object {$_.Size -ne $null} if ($Disks){ foreach ($Disk in $Disks){ if ($Disk.Name -like "*:*") { $Disk = $Disk.Name.Replace(":","$") } trap {Write-Host "Error ChildItem $Computer";Continue} $ObjectPath += Get-ChildItem "\\\\$Computer\\$Disk\\*" -Recurse -ErrorAction SilentlyContinue if ($ObjectPath){ foreach ($Object in $ObjectsDeleted){ $ObjectPath | Where-Object {$_.Name -like $Object} | % { $Path = $_.FullName; Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue; $Info += "" | Select-Object @{e={$Path};n='Path'},` @{e={"Delete"};n='Action'} } } } } } } } $Info | Format-Table -AutoSize -ErrorAction SilentlyContinue
PowerShellCorpus/PoshCode/disabled AD accounts_1.ps1
disabled AD accounts_1.ps1
#Get Domain List $objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = @($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name} #get users list $users = Get-Content U:\\EMCU15FI3_USER.txt $total = $users.count "SAMaccountname;DisplayName;HomeDir;Domain" | Out-File -FilePath test.txt foreach($Domain in $Domains){ $i=0 foreach($user in $users) { # serializevalue parameter is used to inly get the properties needed so variable doesn't use too much RAM. $b = Get-QADUser -SamAccountName $user -SizeLimit 0 -Disabled -DontUseDefaultIncludedProperties -IncludedProperties NTAccountName, DisplayName, HomeDirectory, userprincipalname -SerializeValues $storing = $b.sAMAccountName + ";" + $b.displayName + ";" + $b.homeDirectory + ";" +$domain if ($storing.StartsWith(";")) { } else{ $storing | Out-File -FilePath test.txt -append } $storing=$null $b=$null #free up the garbage collect (empties unused variables) [System.GC]::Collect() $i++; Write-Progress -Activity "Searching disabled accounts in $domain" -Status "Progress:" -PercentComplete $($i*100/$total) } }
PowerShellCorpus/PoshCode/New-Type.ps1
New-Type.ps1
## New-Type (like Add-Type, but for PowerShell 1.0) ## Takes C# source code, and compiles it (in memory) for use in scripts ... #################################################################################################### ## USAGE EXAMPLE: ## New-Type @" ## using System; ## public struct User { ## public string Name; ## public int Age; ## public User(string name, int age) { ## Name = name; Age = age; ## } ## } ## "@ ## ## $user = New-Object User "Bobby",28 ## $user.Name #################################################################################################### ## NOTE: Save as New-Type.ps1 in your path, or uncomment the function line below (and the last line) #################################################################################################### #function New-Type { param([string]$TypeDefinition,[string[]]$ReferencedAssemblies) ## Obtains an ICodeCompiler from a CodeDomProvider class. $provider = New-Object Microsoft.CSharp.CSharpCodeProvider ## Get the location for System.Management.Automation DLL $dllName = [PsObject].Assembly.Location ## Configure the compiler parameters $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters $assemblies = @("System.dll", $dllName) $compilerParameters.ReferencedAssemblies.AddRange($assemblies) if($ReferencedAssemblies) { $compilerParameters.ReferencedAssemblies.AddRange($ReferencedAssemblies) } $compilerParameters.IncludeDebugInformation = $true $compilerParameters.GenerateInMemory = $true $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $TypeDefinition) if($compilerResults.Errors.Count -gt 0) { $compilerResults.Errors | % { Write-Error ("{0}:`t{1}" -f $_.Line,$_.ErrorText) } } #}
PowerShellCorpus/PoshCode/Remove-Trash.ps1
Remove-Trash.ps1
#requires -version 2.0 add-type @" using System; using System.Runtime.InteropServices; using Microsoft.Win32; namespace recyclebin { public class Empty { [DllImport("shell32.dll")] static extern int SHEmptyRecycleBin(IntPtr hWnd, string pszRootPath, uint dwFlags); public static void EmptyTrash(string RootDrive, uint Flags) { SHEmptyRecycleBin(IntPtr.Zero, RootDrive, Flags); } } } "@ cmdlet Remove-Trash -snapin CMSchill.RemoveTrash { param( [Parameter(Position=0, Mandatory=$false)][string]$Drive = "", [switch]$NoConfirmation, [switch]$NoProgressGui, [switch]$NoSound ) [int]$Flags = 0 if ( $NoConfirmation ) { $Flags = $Flags -bor 1 } if ( $NoProgressGui ) { $Flags = $Flags -bor 2 } if ( $NoSound ) { $Flags = $Flags -bor 4 } [recyclebin.Empty]::EmptyTrash($RootPath, $Flags) }
PowerShellCorpus/PoshCode/WPF v3 DEMO.ps1
WPF v3 DEMO.ps1
# Plik: 4_Demo_v3_Reflection.ps1 #requires -version 3 $Akceleratory = [PSObject]. Assembly. GetType("System.Management.Automation.TypeAccelerators") Add-Type -AssemblyName PresentationCore, PresentationFramework -PassThru | Where-Object IsPublic | ForEach-Object { $Class = $_ try { $Akceleratory::Add($Class.Name,$Class) } catch { "Failed to add $($Class.Name) accelerator pointing to $($Class.FullName)" } } [Window]@{ OpacityMask = [DrawingBrush]@{ Drawing = [DrawingGroup]@{ Children = & { $Kolekcja = New-Object DrawingCollection $Kolekcja.Add([GeometryDrawing]@{ Brush = 'Black' Geometry = [EllipseGeometry]@{ radiusX = 0.48 radiusY = 0.48 Center = '0.5,0.5' } }) $Kolekcja.Add([GeometryDrawing]@{ Brush = 'Transparent' Geometry = [RectangleGeometry]@{ Rect = '0,0,1,1' } }) , $Kolekcja } } } Background = [LinearGradientBrush]@{ Opacity = 0.5 StartPoint = '0,0.5' Endpoint = '1,0.5' GradientStops = & { $Stopki = New-Object GradientStopCollection $Colors = 'Blue', 'Green' foreach ($i in 0..1) { $Stopki.Add( [GradientStop]@{ Color = $Colors[$i] Offset = $i } ) } , $Stopki } } Width = 800 Height = 400 WindowStyle = 'None' AllowsTransparency = $true Effect = [DropShadowEffect]@{ BlurRadius = 10 } TopMost = $true Content = & { $Stos = [StackPanel]@{ VerticalAlignment = 'Center' HorizontalAlignment = 'Center' } $Stos.AddChild( [Label]@{ Content = 'PowerShell Rocks!' FontSize = 80 FontFamily = 'Consolas' Foreground = 'White' Effect = [DropShadowEffect]@{ BlurRadius = 5 } } ) , $Stos } } | ForEach-Object { $_.Add_MouseLeftButtonDown({ $this.DragMove() }) $_.Add_MouseRightButtonDown({ $this.Close() }) $_.ShowDialog() | Out-Null }
PowerShellCorpus/PoshCode/Form manipulation.ps1
Form manipulation.ps1
$code = @' using System; using System.Runtime.InteropServices; namespace LibWrap { public class Animator { [DllImport("user32.dll")] public static extern bool AnimateWindow(IntPtr hWnd, uint dwTime, uint dwFlags); } } '@ function BuildAssembly { $cscp = New-Object Microsoft.CSharp.CSharpCodeProvider $cpar = New-Object CodeDom.Compiler.CompilerParameters $cpar.GenerateInMemory = $true $exec = $cscp.CompileAssemblyFromSource($cpar, $code) } $frmMain_OnClick= { BuildAssembly [void][LibWrap.Animator]::AnimateWindow($frmMain.Handle, 1000, 0x90000) $end = [DateTime]::Now.AddSeconds(3) while ($end -gt [DateTime]::Now) { Start-Sleep -m 1000 } [void][LibWrap.Animator]::AnimateWindow($frmMain.Handle, 1000, 0x80000) } $frmMain_OnLoad= { $g = New-Object Drawing.Drawing2D.GraphicsPath $g.AddEllipse($frmMain.ClientRectangle) $frmMain.Region = New-Object Drawing.Region($g) } function ShowMainWindow { [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Drawing") [Windows.Forms.Application]::EnableVisualStyles() $frmMain = New-Object Windows.Forms.Form #frmMain $frmMain.ClientSize = New-Object Drawing.Size(300, 300) $frmMain.MaximizeBox = $false $frmMain.StartPosition = "CenterScreen" $frmMain.Add_Click($frmMain_OnClick) $frmMain.Add_KeyDown( { if ($_.KeyCode -eq "Escape") { $frmMain.Close() } } ) $frmMain.Add_Load($frmMain_OnLoad) [void]$frmMain.ShowDialog() } ShowMainWindow
PowerShellCorpus/PoshCode/get-SQLInstanceInfo.ps1
get-SQLInstanceInfo.ps1
function get-SQLInstanceInfo { <# .SYNOPSIS get-SQLInstanceInfo .DESCRIPTION Retrieves the following information for each SQL Instance on the server or cluster node, and returns as an array of PSCustomObjects DisplayName Name Clustered InstanceID FileVersion Version VirtualName Instance Port ServiceState ServiceAccount Edition AuditLevel LoginMode PhysicalMemory Processors Product ProductLevel MajorVersion MinorVersion Build Release .NOTES Dependencies : None ChangeLog : Date Initials Short Description 10/04/2011 RLV New .LINK http://technet.microsoft.com/en-us/magazine/ff458353.aspx #> [CmdletBinding()] param ( [Parameter(Mandatory=$false)][string]$ServerName = $(hostname) ) trap { #show-InnerException -ex $_ $_ break } #write-log "$($MyInvocation.InvocationName) - Begin function" foreach($Key in $PSBoundParameters.Keys){ write-log "$($MyInvocation.InvocationName) PARAM: -$Key - $($PSBoundParameters[$Key])" } [system.reflection.assembly]::LoadWithPartialName('Microsoft.SQLServer.SQLWMIManagement') | out-null $InstanceInfos = @() $Instances = (new-object 'microsoft.sqlserver.management.smo.Wmi.ManagedComputer' "$ServerName").Services | where-object{$_.type -eq 'SqlServer'} foreach($Instance in $Instances ) { [psobject]$InstanceInfo = "" | Select-Object DisplayName, Name, Clustered, ` InstanceID, FileVersion, Version, ` VirtualName, Instance, Port, ServiceState, ` ServiceAccount, Edition, AuditLevel, LoginMode, ` PhysicalMemory, Processors, Product, ProductLevel, ` MajorVersion, MinorVersion, Build, Release write-verbose "Processing SQL Instance: $($Instance.Name)" $InstanceInfo.DisplayName = $Instance.DisplayName $InstanceInfo.Name = $Instance.Name $InstanceInfo.Clustered = $Instance.AdvancedProperties['CLUSTERED'].Value $InstanceInfo.InstanceID = $Instance.AdvancedProperties['INSTANCEID'].Value $InstanceInfo.FileVersion = $Instance.AdvancedProperties['FILEVERSION'].Value $InstanceInfo.Version = $Instance.AdvancedProperties['VERSION'].Value if($Instance.AdvancedProperties['VSNAME'].Value -eq ''){ $InstanceInfo.VirtualName = 'N/A' } else { $InstanceInfo.VirtualName = $Instance.AdvancedProperties['VSNAME'].Value } if($Instance.Name.Split('$')[1] -eq $Null){ [string]$InstanceName = 'MSSQLSERVER' } else { [string]$InstanceName = $Instance.Name.Split('$')[1] } $InstanceInfo.Instance = $InstanceName $InstanceInfo.Port = $Instance.Parent.ServerInstances[$InstanceName].ServerProtocols['Tcp'].IPAddresses['IPALL'].IPAddressProperties['TcpPort'].Value $InstanceInfo.ServiceAccount = $Instance.ServiceAccount $InstanceInfo.ServiceState = $Instance.ServiceState if($InstanceInfo.Clustered){ $SQLInstanceName = "$($InstanceInfo.VirtualName),$($InstanceInfo.Port)" } else { $SQLInstanceName = "$ServerName,$($InstanceInfo.Port)" } write-verbose "SQL InstanceName: $SQLInstanceName" [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") |out-null $SQL = new-object "Microsoft.SQLServer.Management.SMO.Server" $SQLInstanceName $InstanceInfo.Edition = $SQL.Edition $InstanceInfo.AuditLevel = $SQL.AuditLevel $InstanceInfo.LoginMode = $SQL.LoginMode $InstanceInfo.PhysicalMemory = $SQL.PhysicalMemory $InstanceInfo.Processors = $SQL.Processors $InstanceInfo.Product = $SQL.Product $InstanceInfo.ProductLevel = $SQL.ProductLevel $InstanceInfo.MajorVersion = $SQL.Version.Major $InstanceInfo.MinorVersion = $SQL.Version.Minor $InstanceInfo.Build = $SQL.Version.Build if($SQL.Version.Major -eq 10) { switch($SQL.Version.Minor) { 0 { $InstanceInfo.Release = 'Gold' } 50 { $InstanceInfo.Release = 'R2' } else { throw "Could not convert minor version into release. Version number $($SQL.Versioin.Minor)" } } } else { $InstanceInfo.Release = 'Gold' } $InstanceInfos += $InstanceInfo } write-verbose "Showing results" $InstanceInfos }
PowerShellCorpus/PoshCode/Replicate-ADDS.ps1
Replicate-ADDS.ps1
# Transcribe output to log $null = Start-Transcript "$pwd\\$([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition)).log" # Check the QAD snapins are installed if ( (Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction silentlycontinue) -eq $null ) { # The QAD snapin is not active. Check it's installed if ( (Get-PSSnapin -Name Quest.ActiveRoles.ADManagement -Registered -ErrorAction SilentlyContinue) -eq $null) { Write-Error "You must install Quest ActiveRoles AD Tools to use this script!" } else { Write-Host "Importing QAD Tools" Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction Stop } } Write-Host "Beginning ADDS Replication" Write-Host "==========================" Get-QADComputer -ComputerRole 'DomainController' | % { Write-Host "Replicating $($_.Name)" $null = repadmin /kcc $_.Name $null = repadmin /syncall /A /e $_.Name } Write-Host "==========================" Write-Host "Completed ADDS Replication" Stop-Transcript
PowerShellCorpus/PoshCode/Findup_28.ps1
Findup_28.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"/x", new List<string>()},{"/i",new List<string>()},{"/xf",new List<string>()},{"/if",new List<string>()}, {"/xd",new List<string>()},{"/id",new List<string>()},{"/paths",new List<string>()} }; public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>> { {"/xr", new List<Regex>()},{"/ir",new List<Regex>()},{"/xfr",new List<Regex>()},{"/ifr",new List<Regex>()}, {"/xdr",new List<Regex>()},{"/idr",new List<Regex>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "/recurse", false }, { "/noerr", false }, {"/delete",false}, {"/xj", false}}; public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes. public static long errors = 0; public static string delconfirm; public static void Main(string[] args) { DateTime startTime = DateTime.Now; Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files."); Console.WriteLine(" "); string optionskey = "/paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem = args[i].ToLower(); if ((System.String.Compare(argitem, "/help", true) == 0) || (System.String.Compare(argitem, "/h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [/recurse] [/noerr] [/x /i /xd /id /xf /if + [r]] <files/directories/regex> [/delete]"); Console.WriteLine(" "); Console.WriteLine("Options: /help - displays this help message."); Console.WriteLine(" /recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" /noerr - discards error messages."); Console.WriteLine(" /delete - delete each duplicate file with confirmation."); Console.WriteLine(" /x - eXcludes if full file path starts with (or RegEx matches if /xr) one of the items following this switch until another switch is used."); Console.WriteLine(" /i - include if full file path starts with (or Regex matches if /ir) one of the items following this switch until another switch is used."); Console.WriteLine(" /xd - eXcludes all directories - minus drive/files - (using RegEx if /xdr) including subdirs following this switch until another switch is used."); Console.WriteLine(" /id - Include only directories - minus drive/files - (using RegEx if /idr) including subdirs following this switch until another switch is used."); Console.WriteLine(" /xf - eXcludes all files - minus drive/directories - (using RegEx if /xfr) following this switch until another switch is used."); Console.WriteLine(" /if - Include only files - minus drive/directories - (using RegEx if /ifr) following this switch until another switch is used."); Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr."); Console.WriteLine(" /paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" /xj - Exclude File and Directory Junctions."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" - deletes duplicates after consent is given."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data /recurse /x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc /xfr \\"(jim)\\""); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc /xr \\"[bf]\\" /ir \\"(smith)\\""); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the path name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionskey = "/paths"; continue; } if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem)) { optionskey = argitem; continue; } if (optionspaths.ContainsKey(optionskey)) optionspaths[optionskey].Add(args[i]); else { try { Regex rgx = new Regex(args[i], RegexOptions.Compiled); optionsregex[optionskey].Add(rgx); } catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);} } } if (optionspaths["/paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory."); optionspaths["/paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["/paths"], "*.*", optionsbools["/recurse"], files); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help"); Console.WriteLine("\\n"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>(); long filesize = 0; for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) continue; var breakout = false; while (true) { filesize = (files[i].Length); try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } string SHA512string = Hash2String(_SHA512.Hash); if (!SizeHashFile.ContainsKey(filesize)) SizeHashFile.Add(filesize, new Dictionary<string,List<FileInfo>>()); if (!SizeHashFile[filesize].ContainsKey(SHA512string)) { SizeHashFile[filesize][SHA512string] = new List<FileInfo>() {}; } SizeHashFile[filesize][SHA512string].Add(files[i]); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } if (SizeHashFile.ContainsKey(filesize)) { foreach (var HG in SizeHashFile[filesize]) { if (HG.Value.Count > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count); foreach (var finfo in HG.Value) { Console.WriteLine(finfo.FullName); numOfDupes++; dupeBytes += finfo.Length; if (optionsbools["/delete"]) if (DeleteDupe(finfo)) { bytesrecovered += finfo.Length; deletedfiles++; } } } } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS. Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); Console.WriteLine("Errors : {0:N0}", errors); Console.WriteLine("Execution time : " + (DateTime.Now - startTime)); } private static void WriteErr(string Str) { errors++; if (!optionsbools["/noerr"]) Console.WriteLine(Str); } private static string Hash2String(Byte[] hasharray) { string SHA512string = ""; foreach (var c in hasharray) { SHA512string += String.Format("{0:x2}", c); } return SHA512string; } private static Boolean DeleteDupe(FileInfo Filenfo) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { Filenfo.Delete(); Console.WriteLine("File Successfully deleted."); return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckNames(string fullname) { var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt") var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp") if (CheckNamesWorker(fullname, "/x", "/xr", true)) return false; if (CheckNamesWorker(filePart, "/xf", "/xfr", true)) return false; if (CheckNamesWorker(dirPart, "/xd", "/xdr", true)) return false; if (CheckNamesWorker(fullname, "/i", "/ir", false)) return false; if (CheckNamesWorker(filePart, "/if", "/ifr", false)) return false; if (CheckNamesWorker(dirPart, "/id", "/idr", false)) return false; return true; } private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType) { foreach (var filepath in optionspaths[pathskey]) { if (filestr.ToLower().StartsWith(filepath.ToLower()) == CheckType) return true; } foreach (var rgx in optionsregex[rgxkey]) { if (rgx.IsMatch(filestr) == CheckType) return true; } return false; } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"]) if (CheckNames(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"]) foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"]) if (CheckNames(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Convert-BounceToX_4.ps1
Convert-BounceToX_4.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/ShowUI Clock 4.ps1
ShowUI Clock 4.ps1
New-UIWidget -AsJob -Content { $shadow = DropShadowEffect -Color Black -Shadow 0 -Blur 8 Grid { Ellipse -Fill Transparent -Stroke Black -StrokeThickness 4 -Width 300 -Height 300 Ellipse -Fill Transparent -Stroke Black -StrokeThickness 6 -Width 290 -Height 290 -StrokeDashArray 1,11.406 Ellipse -Fill Transparent -Stroke Black -StrokeThickness 10 -Width 280 -Height 280 -StrokeDashArray 64.25 Ellipse -Fill Transparent -Stroke Black -StrokeThickness 5 -Width 255 -Height 255 -StrokeDashArray 60,59 Ellipse -Name Hour -Fill Transparent -Stroke White -StrokeThickness 100 -Width 255 -Height 255 -StrokeDashArray 0.04,300 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } -Effect $shadow Ellipse -Name Minute -Fill Transparent -Stroke '#FFC0B7B7' -StrokeThickness 100 -Width 275 -Height 275 -StrokeDashArray 0.05,300 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } -Effect $shadow Ellipse -Name Second -Fill Transparent -Stroke '#FF31C2FF' -StrokeThickness 100 -Width 215 -Height 215 -StrokeDashArray 0.02,300 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } -Effect $shadow } } -Refresh "00:00:00.2" -Update { $now = Get-Date $deg = (1/60) * 360 $Hour.RenderTransform.Angle = $now.Hour * 5 * $deg -90 $Minute.RenderTransform.Angle = $now.Minute * $deg -90 $Second.RenderTransform.Angle = $now.Second * $deg -90 }
PowerShellCorpus/PoshCode/Get-StatType proxy.ps1
Get-StatType proxy.ps1
# get-mystattype.ps1 : Proxy cmdlet for the Get-StatType cmdlet. # The scripts add the parameter -ShowInstances to the cmdlet # Parameters: # ShowInstances : switch to define if all the instances for each metric will be shown # Author: LucD # History: # v1.0 27/08/09 first version # [CmdletBinding()] param( [Parameter(Position=0)] [ValidateNotNullOrEmpty()] [System.String[]] ${Name}, [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [VMware.VimAutomation.Types.InventoryItem[]] ${Entity}, [System.DateTime] ${Start}, [System.DateTime] ${Finish}, [ValidateNotNullOrEmpty()] [VMware.VimAutomation.Types.StatInterval[]] ${Interval}, [ValidateNotNullOrEmpty()] [VMware.VimAutomation.Types.VIServer[]] ${Server}, [switch] ${ShowInstances}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-StatType', [System.Management.Automation.CommandTypes]::Cmdlet) if ($ShowInstances) { $perfMgr = Get-View (Get-View ServiceInstance).content.perfManager $PCLookup = @{} $perfMgr.PerfCounter | %{$PCLookup[$_.GroupInfo.Key + "." + $_.NameInfo.Key + "." + $_.RollupType]=$_.Key} $InstLookup = @{} $perfMgr.QueryAvailablePerfMetric(($entity | Get-View).MoRef,$null,$null,$null) | %{ if($_.Instance -eq ""){ $InstLookup[$_.CounterId] += @('""') } else{ $InstLookup[$_.CounterId] += @($_.Instance) } } [Void]$PSBoundParameters.Remove("ShowInstances") $scriptCmd = {& $wrappedCmd @PSBoundParameters | %{ if($InstLookup.ContainsKey($PCLookup[$_])){ $t = New-Object PSObject $t | Add-Member -MemberType NoteProperty -Name Metric -Value $_ $t | Add-Member -MemberType NoteProperty -Name Instances -Value ($InstLookup[$PCLookup[$_]]) # Output the new object $t # Get rid of metric so identical return values from original Get-StatType wont produce output $InstLookup.Remove($PCLookup[$_]) } }} } else{ $scriptCmd = {& $wrappedCmd @PSBoundParameters } } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { Throw } } end { try { $steppablePipeline.End() } catch { throw } }
PowerShellCorpus/PoshCode/Lot buttons at one time.ps1
Lot buttons at one time.ps1
$frmMain_Load= { for ($i = 0; $i -lt 2; $i++) { for ($j = 0; $j -lt 5; $j++) { $num[$i, $j] = $i * 5 + $j + 1 $btn[$i, $j] = New-Object Windows.Forms.Button # #btnX # $btn[$i, $j].Font = New-Object Drawing.Font("Tahoma", 14, [Drawing.FontStyle]::Bold) $btn[$i, $j].Left = $j * 50 + 10 $btn[$i, $j].Parent = $frmMain $btn[$i, $j].Size = New-Object Drawing.Size(50, 50) $btn[$i, $j].Text = $(if ($num[$i, $j] -eq 10) {'0'} else {$num[$i, $j]}) $btn[$i, $j].Top = $i * 50 + 5 }#for }#for } function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() $btn = New-Object "Windows.Forms.Button[,]" 2, 5 $num = New-Object "int32[,]" 2, 5 $frmMain = New-Object Windows.Forms.Form # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(270, 110) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.MaximizeBox = $false $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Form1" $frmMain.Add_Load($frmMain_Load) [void]$frmMain.ShowDialog() } frmMain_Show
PowerShellCorpus/PoshCode/Deploy VM with Static IP_1.ps1
Deploy VM with Static IP_1.ps1
# 1. Create a simple customizations spec: $custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows ` -OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” ` –DomainAdminUsername “user” –DomainAdminPassword “password” # 2. Modify the default network customization settings: $custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping ` -IpMode UseStaticIP -IpAddress 192.168.121.228 -SubnetMask 255.255.248.0 ` -Dns 192.168.108.1 -DefaultGateway 192.168.108.1 # 3. Deploy a VM from a template using the newly created customization: New-VM -Name “MyNewVM” -Template $template -VMHost $vmHost ` -OSCustomizationSpec $custSpec
PowerShellCorpus/PoshCode/MacroScopeParser.ps1
MacroScopeParser.ps1
#requires -version 2 #Chad Miller #http://www.sev17.com/ #Uses MacroScope/Antlr to parse SQL query for tables and table aliases #Download MacroScope from http://macroscope.sourceforge.net/ and compile from source #Or grab compiled assemblies from http://cid-ea42395138308430.skydrive.live.com/embedicon.aspx/Public/Blog/macroscopeParser.zip param ($commandText) #Assumes MacroScope and Antlr3 assemblies are in same directory add-type -Path $(Resolve-Path .\\Antlr3.Runtime.dll | Select-Object -ExpandProperty Path) add-type -Path $(Resolve-Path .\\MacroScope.dll | Select-Object -ExpandProperty Path) ####################### function Get-Table { param($table) $table if ($table.HasNext) { Get-Table $table.Next } } $sqlparser =[MacroScope.Factory]::CreateParser($commandText) $expression = $sqlparser.queryExpression() Get-Table $expression.From.Item | Select @{n='Name';e={$_.Source.Identifier}}, @{n='Alias';e={$_.Alias}}
PowerShellCorpus/PoshCode/repr_1.ps1
repr_1.ps1
function repr { [CmdletBinding()] [OutputType([string])] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] $InputObject) process { if($null -eq $InputObject) { $PSCmdlet.WriteObject('$null') } elseif($InputObject -is [bool]) { $PSCmdlet.WriteObject('$' + $InputObject.ToString().ToLowerInvariant()) } elseif($InputObject -is [scriptblock]) { $PSCmdlet.WriteObject("{$InputObject}") } elseif($InputObject -is [string]) { $PSCmdlet.WriteObject("'$InputObject'") } else { $PSCmdlet.WriteObject($InputObject.ToString()) } } }
PowerShellCorpus/PoshCode/Get-Scope_4.ps1
Get-Scope_4.ps1
#function Get-Scope { #.Synopsis # Determine the scope of execution (are you in a module? how many scope layers deep are you?) #.Parameter Invocation # In order to correctly determine the scope, this function requires that you pass in the $MyInvocation variable when you call it. #.Parameter ToHost # If you just want to *see* the value in the console to debug something, you can pass this switch (and optionally, set the foreground/background colors) #.Parameter Foreground # The Foreground color of host output #.Parameter Background # The Background color of host output #.Example # $scope = Get-Scope $MyInvocation # # Description # ----------- # Call Get-Scope and store the output so you can test if you're in module scope, etc. #.Example # Get-Scope $MyInvocation -ToHost Magenta DarkBlue # # Description # ----------- # Call Get-Scope and write the output to host, specifying the foreground and background colors [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$false)] [System.Management.Automation.InvocationInfo]$Invocation = $((Get-Variable -scope 1 'MyInvocation').Value) , [Parameter(ParameterSetName="Debugging")] [Switch]$ToHost , [Parameter(Position=1,ParameterSetName="Debugging")] [ConsoleColor]$Foreground = "Cyan" , [Parameter(Position=2,ParameterSetName="Debugging")] [ConsoleColor]$Background = "Black" ) end { function Get-ScopeDepth { trap { continue } $depth = 0 do { Set-Variable scope_test -Value $depth -Scope ($depth++) } while($?) return $depth - 1 } $depth = . Get-ScopeDepth $callstack = Get-PSCallStack $IsInteractive = $true foreach ($entry in $callStack[1..($callStack.Count - 1)]) { write-host $($entry | fl | out-string) -fore Cyan if((@('&','.','<ScriptBlock>') -contains $entry.Command)) { # @('&','.') -contains $entry.Position.Text[0] continue } if (($entry.Command -eq 'prompt') -or ($entry.Location -eq 'prompt')) { write-host "Found the prompt, we're done here" break } $IsInteractive = $false break } $IsGlobal = 0 -eq (Get-Variable scope_test -Scope global).Value Remove-Variable scope_test Remove-Variable scope_test -Scope global -EA 0 $PSScope = New-Object PSObject -Property @{ Module = $Invocation.MyCommand.Module IsModuleScope = [bool]$Invocation.MyCommand.Module IsGlobalScope = $IsGlobal IsInteractive = $IsInteractive ScopeDepth = $depth PipelinePosition = $Invocation.PipelinePosition PipelineLength = $Invocation.PipelineLength StackDepth = $callstack.Count - 1 Invocation = $Invocation CallStack = $callstack } if($ToHost) { &{ $PSScope, $PSScope.Invocation | Out-String } | Write-Host -Foreground $Foreground -Background $Background } else { $PSScope } } #}
PowerShellCorpus/PoshCode/Start-AppVTestMode.ps1
Start-AppVTestMode.ps1
#This script is designed to set a test server to use a specific directory for App-V Apps, to enable testing #Without having to publish to an external repository. #REQUIREMENTS: Windows 2008 ##FUNCTIONS # DESCRIPTION: Displays the attention message box & checks to see if the user clicks the ok button. function Show-MessageBox ($title, $msg) { [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null [Windows.Forms.MessageBox]::Show($msg, $title, [Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Warning, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly) | Out-Null } function Show-InformationBox ([string]$Title,[string]$Message) { [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null [Windows.Forms.MessageBox]::Show($Message, $Title, [Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information, [System.Windows.Forms.MessageBoxDefaultButton]::Button1, [System.Windows.Forms.MessageBoxOptions]::DefaultDesktopOnly) | Out-Null } ##VARIABLES #App-V Test Repository $Repository = "\\\\server\\share\\AppVRepository\\2-TestPackages" #App-V Client Registry Path $AppVRegRoot = "HKLM:\\SOFTWARE\\Microsoft\\SoftGrid\\4.5\\Client" # Different App-V Client Registry for x64 systems if ((Get-WMIObject win32_operatingsystem).OSArchitecture -match "64-bit") { $AppVRegRoot = "HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\SoftGrid\\4.5\\Client" } ##SCRIPT #Start Transaction $transEnterAppVTestMode = start-transaction #Enter AppV Registry Path set-location $AppVRegRoot #Get Original App-V Settings $ASROriginalSetting = (get-itemproperty Configuration).ApplicationSourceRoot $AIFSOriginalSetting = (get-itemproperty Configuration).AllowIndependentFileStreaming #Set AppV Variables set-itemproperty Configuration -name "ApplicationSourceRoot" -value $repository set-itemproperty Configuration -name "IconSourceRoot" -value $repository #Delete all App-V Applications sftmime DELETE obj:app /global #Get App Manifest Files from Repository and import them set-location C: pwd set-location $repository pwd $i=1 get-childitem $repository | where {$_.Name -match "manifest.xml"} | foreach { echo $_.Name sftmime ADD PACKAGE:TestApp$i /manifest $_.Name /global $i++ } #Display Dialog box that the test mode is active Show-InformationBox "App-V Testing Mode is active" "Apps will be sourced from $Repository. NOTE: File Associations (launching programs by double-clicking their files like .docx) will not be testable due to SCCM vAppLauncher bug Click OK to return to normal mode" #Set AppV Variable back to original setting and close script. set-location $AppVRegRoot pwd set-itemproperty Configuration -name "ApplicationSourceRoot" -value "" set-itemproperty Configuration -name "IconSourceRoot" -value "" #Delete all App-V Applications sftmime DELETE obj:app /global
PowerShellCorpus/PoshCode/LibraryChart_2.ps1
LibraryChart_2.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Defines functions for wokring with Microsoft Chart Control for .NET 3.5 Framework ### Pipe output of Powershell command to Out-Chart function and specify chart type ### Chart will display in form or save to image file ### Real-time charts are supported by passing in a script block ### My thanks to Richard MacDonald for his wonderful post on Charting with PowerShell ### http://blogs.technet.com/richard_macdonald/archive/2009/04/28/3231887.aspx ### Note: Requires NET Framework 3.5 and Microsoft Chart Controls for Microsoft .NET Framework 3.5 ### *** Updated 9/20/09 with Ben's fixes http://xcud.com/post/192277838/mschart-in-psh *** ### </Description> ### <Usage> ### . ./LibraryChart.ps1 ### -------------------------- EXAMPLE 1 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' ### ### This command will produce a default column chart ### ### -------------------------- EXAMPLE 2 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -filename 'c:\\users\\u00\\documents\\process.png' ### This command will output the chart to a file ### ### -------------------------- EXAMPLE 3 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -chartType 'Pie' ### ### This command will produce a pie chart ### ### -------------------------- EXAMPLE 4 -------------------------- ### out-chart -xField 'name' -yField 'WS' -scriptBlock {Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 1} -chartType 'line' ### ### This command will produce a real-time line chart ### ### </Usage> ### </Script> # -------------------------------------------------------------------------- [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") ####################### function New-Chart { param ([int]$width,[int]$height,[int]$left,[int]$top,[string]$chartTitle) # create chart object $global:Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart $global:Chart.Width = $width $global:Chart.Height = $height $global:Chart.Left = $left $global:Chart.Top = $top # create a chartarea to draw on and add to chart $chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea $global:chart.ChartAreas.Add($chartArea) [void]$global:Chart.Titles.Add([string]$chartTitle) # change chart area colour $global:Chart.BackColor = [System.Drawing.Color]::Transparent } #New-Chart ####################### function New-BarColumnChart { param ([hashtable]$ht, $chartType='Column', $chartTitle,$xTitle,$yTitle, [int]$width,[int]$height,[int]$left,[int]$top,[bool]$asc) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle $chart.ChartAreas[0].AxisX.Title = $xTitle $chart.ChartAreas[0].AxisY.Title = $yTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::$chartType if ($asc) { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Ascending, "Y") } else { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") } $global:Chart.Series["Data"]["DrawingStyle"] = "Cylinder" $global:chart.Series["Data"].IsValueShownAsLabel = $true $global:chart.Series["Data"]["LabelStyle"] = "Top" } #New-BarColumnChart ####################### function New-LineChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") # $global:Chart.Series["Data"].Points.AddXY($(get-date), $($ht.Values)) $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys,$ht.Values) #$global:Chart.Series["Data"].XValueType = [System.Windows.Forms.DataVisualization.Charting.ChartValueType]::Time #$global:Chart.chartAreas[0].AxisX.LabelStyle.Format = "hh:mm:ss" #$global:Chart.chartAreas[0].AxisX.LabelStyle.Interval = 1 #$global:Chart.chartAreas[0].AxisX.LabelStyle.IntervalType = [System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType]::Seconds $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line #$global:chart.Series["Data"].IsValueShownAsLabel = $false } #New-LineChart ####################### function New-PieChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie $global:Chart.Series["Data"]["PieLabelStyle"] = "Outside" $global:Chart.Series["Data"]["PieLineColor"] = "Black" #$global:chart.Series["Data"].IsValueShownAsLabel = $true #$global:chart.series["Data"].Label = "#PERCENT{P1}" #$legend = New-object System.Windows.Forms.DataVisualization.Charting.Legend #$global:Chart.Legends.Add($legend) #$Legend.Name = "Default" } #New-PieChart ####################### function Remove-Points { param($name='Data',[int]$maxPoints=200) while ( $global:chart.Series["$name"].Points.Count > $maxPoints ) { $global:chart.Series["$name"].Points.RemoveAT(0) } } #Add-Series ####################### function Out-Form { param($interval,$scriptBlock,$xField,$yField) # display the chart on a form $global:Chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = 'PowerCharts' $Form.Width = 600 $Form.Height = 600 $Form.controls.add($global:Chart) if ($scriptBlock -is [ScriptBlock]) { if (!($xField -or $yField)) { throw 'xField and yField required with scriptBlock parameter.' } $timer = New-Object System.Windows.Forms.Timer $timer.Interval = $interval $timer.add_Tick({ $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField if ($global:Chart.Series["Data"].ChartTypeName -eq 'Line') { Remove-Points $ht | foreach { $global:Chart.Series["Data"].Points.AddXY($($_.Keys), $($_.Values)) } } else { $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) } $global:chart.ResetAutoValues() $global:chart.Invalidate() }) $timer.Enabled = $true $timer.Start() } $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog() } #Out-Form ####################### function Out-ImageFile { param($fileName,$fileformat) $global:Chart.SaveImage($fileName,$fileformat) } ####################### ### ConvertTo-Hashtable function based on code by Jeffery Snover ### http://blogs.msdn.com/powershell/archive/2008/11/23/poshboard-and-convertto-hashtable.aspx ####################### function ConvertTo-Hashtable { param([string]$key, $value) Begin { $hash = @{} } Process { $thisKey = $_.$Key $hash.$thisKey = $_.$Value } End { Write-Output $hash } } #ConvertTo-Hashtable ####################### function Out-Chart { param( $xField=$(throw 'Out-Chart:xField is required'), $yField=$(throw 'Out-Chart:yField is required'), $chartType='Column',$chartTitle, [int]$width=500, [int]$height=400, [int]$left=40, [int]$top=30, $filename, $fileformat='png', [int]$interval=1000, $scriptBlock, [switch]$asc ) Begin { $ht = @{} } Process { if ($_) { $thisKey = $_.$xField $ht.$thisKey = $_.$yField } } End { if ($scriptBlock) { $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField } switch ($chartType) { 'Bar' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Column' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Pie' {New-PieChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } 'Line' {New-LineChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } } if ($filename) { Out-ImageFile $filename $fileformat } elseif ($scriptBlock ) { Out-Form $interval $scriptBlock $xField $yField } else { Out-Form } } } #Out-Chart
PowerShellCorpus/PoshCode/Enable-RemoteCredSSP.ps1
Enable-RemoteCredSSP.ps1
##############################################################################\n##\n## Enable-RemoteCredSSP\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nEnables CredSSP support on a remote computer. Requires that the machine\nhave PowerShell Remoting enabled, and that its operating system is Windows\nVista or later.\n\n.EXAMPLE\n\nEnable-RemoteCredSSP <Computer>\n\n#>\n\nparam(\n ## The computer on which to enable CredSSP\n $Computername,\n\n ## The credential to use when connecting\n $Credential = (Get-Credential)\n)\n\nSet-StrictMode -Version Latest\n\n## Call Get-Credential again, so that the user can type something like\n## Enable-RemoteCredSSP -Computer Computer -Cred DOMAIN\\user\n$credential = Get-Credential $credential\n$username = $credential.Username\n$password = $credential.GetNetworkCredential().Password\n\n## Define the script we will use to create the scheduled task\n$powerShellCommand =\n "powershell -noprofile -command Enable-WsManCredSSP -Role Server -Force"\n$script = @"\nschtasks /CREATE /TN 'Enable CredSSP' /SC WEEKLY /RL HIGHEST ``\n /RU $username /RP $password ``\n /TR "$powerShellCommand" /F\n\nschtasks /RUN /TN 'Enable CredSSP'\n"@\n\n## Create the task on the remote system to configure CredSSP\n$command = [ScriptBlock]::Create($script)\nInvoke-Command $computername $command -Cred $credential\n\n## Wait for the remoting changes to come into effect\nfor($count = 1; $count -le 10; $count++)\n{\n $output =\n Invoke-Command $computername { 1 } -Auth CredSSP -Cred $credential\n if($output -eq 1) { break; }\n\n "Attempt $count : Not ready yet."\n Sleep 5\n}\n\n## Clean up\n$command = [ScriptBlock]::Create($script)\nInvoke-Command $computername {\n schtasks /DELETE /TN 'Enable CredSSP' /F } -Cred $credential\n\n## Verify the output\nInvoke-Command $computername {\n Get-WmiObject Win32_ComputerSystem } -Auth CredSSP -Cred $credential
PowerShellCorpus/PoshCode/BufferBox 3.5.ps1
BufferBox 3.5.ps1
#################################################################################################### ## This script is just a demonstration of some of the things you can do with the buffer ## in the default PowerShell host... it serves as a reminder of how much work remains on ## PoshConsole, and as an inspiration to anyone who is thinking about trying to create ## "interactive" PowerShell applications. ## ## Try Test-DisplayBox and then Test-BufferBox (note it has tab completion and everything). #################################################################################################### $global:BoxChars = new-object PSObject -Property @{ 'HorizontalDouble' = ([char]9552).ToString() 'VerticalDouble' = ([char]9553).ToString() 'TopLeftDouble' = ([char]9556).ToString() 'TopRightDouble' = ([char]9559).ToString() 'BottomLeftDouble' = ([char]9562).ToString() 'BottomRightDouble' = ([char]9565).ToString() 'HorizontalDoubleSingleDown' = ([char]9572).ToString() 'HorizontalDoubleSingleUp' = ([char]9575).ToString() 'Horizontal' = ([char]9472).ToString() 'Vertical' = ([char]9474).ToString() 'TopLeft' = ([char]9484).ToString() 'TopRight' = ([char]9488).ToString() 'BottomLeft' = ([char]9492).ToString() 'BottomRight' = ([char]9496).ToString() 'Cross' = ([char]9532).ToString() 'VerticalDoubleRightSingle' = ([char]9567).ToString() 'VerticalDoubleLeftSingle' = ([char]9570).ToString() } $global:RectType = "system.management.automation.host.rectangle" function Show-ConsoleMenu { param( [Parameter(ValueFromPipeline=$true)] [Array]$choices, [string]$Caption, [int]$indentLeft=8, [Switch]$Passthru , [Switch]$UseBufferBox ) begin { $allchoices = New-Object System.Collections.ArrayList } process { if($choices) { $allchoices.AddRange($choices) } } end { # Make a hashtable with keys $hashChoices = @{} for($i=0; $i -lt $allchoices.Count; $i++) { $hashChoices."$i" = $allchoices[$i] } # output the menu to the screen $menu = $hashChoices | Format-Table -HideTableHeader @{E="Key";A="Right";W=$indentLeft}, @{E="Value";A="Left"} | Out-String $menu = "`n" + (" " * ($indentLeft/2)) + $Caption + "`n" + $menu.TrimEnd() + "`n" if($UseBufferBox) { $menu -split "`n" | Out-Buffer } else { $menu } # get a choice from the user do { [string]$Key = $Host.UI.RawUI.ReadKey("IncludeKeyDown,NoEcho").Character } while(!$hashChoices.ContainsKey($Key) -and !(13,27 -contains [int][char]$Key)) if($Passthru) { $hashChoices.$Key } else { $Key -as [int] } }} function Reset-Buffer { param( $Position = $Host.UI.RawUI.WindowPosition, [int]$Height = $Host.UI.RawUI.WindowSize.Height, [int]$Width = $Host.UI.RawUI.WindowSize.Width, # Note: all edges are padded by 1 for the box edges, but we also pad each side by this ammount: [int]$Padding = 1, $ForegroundColor = $Host.UI.RawUI.ForegroundColor, $BackgroundColor = $Host.UI.RawUI.BackgroundColor, $BorderColor = "Yellow", [switch]$NoBorder, [switch]$ShowInput, [string]$Title = "" ) $global:BufferHeight = $Height $global:BufferWidth = $Width $global:BufferPadding = $Padding $global:BufferForegroundColor = $ForegroundColor $global:BufferBackgroundColor = $BackgroundColor $global:BufferBorderColor = $BorderColor if($NoBorder) { $global:BufferBoxSides = 0 } else { $global:BufferBoxSides = 2 } if($ShowInput) { $global:BufferHeight -= 2 } $Host.UI.RawUI.SetBufferContents($Position,(New-BufferBox $BufferHeight $BufferWidth -Title:$Title -NoBorder:$NoBorder -ShowInput:$ShowInput -Background $BufferBackgroundColor -Border $BufferBorderColor)) $global:BufferPosition = $Position $global:BufferPosition.X += $global:BufferPadding + ($global:BufferBoxSides/2) # this gets set to the BOTTOM line, because I assume text will flow in from the bottom. $global:BufferPosition.Y += $global:BufferHeight - 2 # and this goes below that ... $global:BufferPromptPosition = $BufferPosition $global:BufferPromptPosition.Y += 2 $global:BufferPromptPosition.X += 2 - $global:BufferPadding # Prompt = "> " } function New-BufferBox { param( [int]$Height = $global:BufferHeight, [int]$Width = $global:BufferWidth, $Title = "", [switch]$NoBorder, [switch]$ShowInput, $BackgroundColor = $global:BufferBackgroundColor, $BorderColor = $global:BufferBorderColor ) $Width = $Width - $global:BufferBoxSides $LineTop =( $global:BoxChars.HorizontalDouble * 2) + $Title ` + $($global:BoxChars.HorizontalDouble * ($Width - ($Title.Length+2))) $LineField = ' ' * $Width $LineBottom = $global:BoxChars.HorizontalDouble * $Width $LineSeparator = $global:BoxChars.Horizontal * $Width $LinePrompt = '> ' + ' ' * ($Width-2) # Prompt = "> " if(!$NoBorder) { $LineField = $global:BoxChars.VerticalDouble + $LineField + $global:BoxChars.VerticalDouble $LinePrompt = $global:BoxChars.VerticalDouble + $LinePrompt + $global:BoxChars.VerticalDouble $LineBottom = $global:BoxChars.BottomLeftDouble + $LineBottom + $global:BoxChars.BottomRightDouble $LineTop = $global:BoxChars.TopLeftDouble + $LineTop + $global:BoxChars.TopRightDouble $LineSeparator = $global:BoxChars.VerticalDoubleRightSingle + $LineSeparator + $global:BoxChars.VerticalDoubleLeftSingle } if($ShowInput) { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineSeparator;$LinePrompt;$LineBottom} } else { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineBottom} } $boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,$BorderColor,$BackgroundColor) return ,$boxBuffer } function Move-Buffer { param( $Position = $global:BufferPosition, [int]$Left = $($global:BufferBoxSides/2), [int]$Top = (2 - $global:BufferHeight), [int]$Width = $global:BufferWidth - $global:BufferBoxSides, [int]$Height = $global:BufferHeight, [int]$Offset = -1 ) $Position.X += $Left $Position.Y += $Top $Rect = New-Object $RectType $Position.X, $Position.Y, ($Position.X + $width), ($Position.Y + $height -1) $Position.Y += $OffSet $Host.UI.RawUI.ScrollBufferContents($Rect, $Position, $Rect, (new-object System.Management.Automation.Host.BufferCell(' ',$global:BufferForegroundColor,$global:BufferBackgroundColor,'complete'))) } function Out-Buffer { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Message, [Parameter(ValueFromPipelineByPropertyName=$true)] $ForegroundColor = $global:BufferForegroundColor, [Parameter(ValueFromPipelineByPropertyName=$true)] $BackgroundColor = $global:BufferBackgroundColor, [switch]$NoScroll, [Parameter(ValueFromPipelineByPropertyName=$true)] $Position = $global:BufferPosition, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Left = 0, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Top = $(3 - $global:BufferHeight), # Box Edge + New Lines [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Width = ($global:BufferWidth - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Height = ($global:BufferHeight - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Offset = $( 0 - ($Message.Split("`n").Count)) ) process { $lineCount = $Message.Split("`n").Count $Width = $Width - ($global:BufferPadding * 2) if(!$NoScroll){ Move-Buffer $Position $Left $Top $Width $Height $Offset } $MessageBuffer = New-Object "System.Management.Automation.Host.BufferCell[,]" $lineCount, $width $index = 0 foreach( $line in $Message.Split("`n") ) { $Buffer = $Host.UI.RawUI.NewBufferCellArray( @($line.Trim("`r").PadRight($Width)), $ForegroundColor, $BackgroundColor ) for($i = 0; $i -lt $width; $i++) { $MessageBuffer[$index,$i] = $Buffer[0,$i] } $index++ } $Y = $global:BufferPosition.Y $global:BufferPosition.Y -= $lineCount - 1 $Host.UI.RawUI.SetBufferContents($global:BufferPosition,$MessageBuffer) $global:BufferPosition.Y = $Y } } function Set-BufferInputLine { param([String]$Line = "") $PromptText = $line.PadRight(($global:BufferWidth - $line.Length - 3)) # Prompt = "> " $CursorPosition = $BufferPromptPosition $CursorPosition.X += $line.Length $Prompt = $Host.UI.RawUI.NewBufferCellArray( @($PromptText),$global:BufferForegroundColor, $global:BufferBackgroundColor) $Host.UI.RawUI.SetBufferContents( $BufferPromptPosition, $prompt ) $Host.UI.RawUI.CursorPosition = $CursorPosition } function Test-DisplayBox { $Position = $Host.UI.RawUI.WindowPosition $Position.X += 10 $Position.Y += 3 Reset-Buffer $Position 20 66 3 -ForegroundColor 'Gray' -BackgroundColor 'Black' -BorderColor 'Green' Out-Buffer 'Greetings!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer '- - - Thank you for running this simple demo script! - - -' 'Green' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'We are demonstrating how the scroll buffer works: you can add more than one line at a time, but you don''t really need to, since they add almost as fast one at a time.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'That is, as long as you don''t have any delay, you can just' 'white' 'black' Out-Buffer 'write out as many lines as you like, one-at-a-time, like' 'white' 'black' Out-Buffer 'this, and there is really no downside to doing that.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'Right? '.PadRight(58,"-") 'Red' 'black' Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'It''s clearly not as slick to just pop in multiple lines' 'white' 'black' sleep -m 1200 Out-Buffer 'with absolutely no scroll delay, and it makes it a little ' 'white' 'black' sleep -m 1200 Out-Buffer 'hard to tell what you have read already, but that''s ok.' 'white' 'black' sleep -m 1200 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'If you delay between paragraphs.' 'Red' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'But: don''t scroll off-screen faster than I can read!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' } ## Test-BufferBox 3.1 - Now with Tab completion #################################################################################################### ## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the ## chat room you have joined is going on in the background. ## ## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line ## you have to enclose it inside $() braces. #################################################################################################### function Test-BufferBox { param( $title = "PowerShell Interactive Buffer Demo" ) Reset-Buffer -ShowInput -Title $Title ################################################################################################### ##### We only need this for the purposes of the demo... ##### In a real script you would, presumably, be getting stuff from somewhere else to display $noise = $MyInvocation.MyCommand.Definition -split "`n" $index = 0; $random = New-Object "Random" [regex]$chunker = @' [^ \\"']+|([\\"'])[^\\\\1]*?\\\\1[^ \\"']*|([\\"'])[^\\\\1]*$| $ '@ ##### Printing a "How to Exit" message Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " This is just a demo. " -Fore Black -Back Cyan Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan ##### Setting the prompt Set-BufferInputLine ##### And initializing our two variables ... $line="" $exit = $false switch(Show-ConsoleMenu "Continue the demo","Stop the demo","Exit PowerShell" "What would you like to do now?" -UseBuffer) { 0 { <# do nothing, will continue #> } 1 { $exit = $true <#this script exits cleanly below#> } 2 { exit <# stop abruptly #> } } while(!$exit){ while(!$exit -and $Host.UI.RawUI.KeyAvailable) { $char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho"); # we don't want the key up events, but we do want to get rid of them if($char.KeyDown) { switch([int]$char.Character) { 13 { # Enter if($line.Trim() -eq "exit") { $exit = $true; break; } ################################################################################################### ################################################################################################### ############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ############# ############# This executes the user input! ############# ############# Don't use this on, say, content you got from a web page or chat room ############# iex "Out-Buffer `"$line`" -Fore Red"; ############# ################################################################################################### ################################################################################################### $line = ""; Set-BufferInputLine break; } 27 { # Esc $exit = $true; break; } 9 { # Tab if($line.Length -gt 0) { [Array]$words = $chunker.Matches($line) if($words.Count -ge 1) { Out-Buffer ($Words | Out-String) -Fore Black -Back White $lastWord = $words[$($words.Count-1)].Value $trim = $lastWord.TrimEnd("`r","`n") ## This may return more than one ... in which case subsequent tabs should iterate through them ## But for demo purposes, this is more than enough work... $replacement = TabExpansion -Line $line -LastWord ($lastWord.Trim() -replace '"') Out-Buffer ($replacement | Out-String) -Fore Black -Back White $line = $line.SubString(0, $line.Length - $lastWord.Length) + @($replacement)[0] Set-BufferInputLine $line } } break; } 8 { # Backspace if($line.Length -gt 0) { $line = $line.SubString(0,$($line.Length-1)) } # $pos = $Host.UI.RawUI.CursorPosition Set-BufferInputLine $line break; } 0 { # Not actually a key # Out-Buffer $($Char | Out-String) break; } default { $line += $char.Character Set-BufferInputLine $line } } } } # Simulate doing useful things 25% of the time if($random.NextDouble() -gt 0.75) { $noise[($index)..($index++)] | Out-Buffer if($index -ge $noise.Length){$index = 0} } sleep -milli 100 } $CursorPosition = $BufferPromptPosition $CursorPosition.Y += 2 $CursorPosition.X = 0 $Host.UI.RawUI.CursorPosition = $CursorPosition }
PowerShellCorpus/PoshCode/Dell Order Status_1.ps1
Dell Order Status_1.ps1
# Version: 0.1 # Author: Stefan Stranger # Description: Retrieve Dell Order Status # Start Page Order Status USA: https://support.dell.com/support/order/status.aspx?c=us&cs=19&l=en&s=dhs&~ck=pn # Start Page Order Status EMEA(nl): http://support.euro.dell.com/support/index.aspx?c=nl&l=nl&s=gen&~ck=bt # Example Dell Order Status URL: http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=[IR Number]&ea=[emailaddress]' #param ([string]$url = $(read-host "Please enter Dell Order Status URL")) $wc = New-Object System.Net.WebClient $url = 'http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=NL0131-8510-29070&ea=stefan.stranger@getronics.com' $RawResult = $wc.DownloadString($url) # $RawResult = gc orderstatus.txt # Search for the Estimated Delivery Date in the url that starts with the word "lever" (Levering is the Dutch word for Delivery" and # and ends with </B></TD></TR> # You should probable need to change the string "Lever" in "Deliv" or something $r = New-Object regex('Lever.*?(\\d+-\\d+-\\d{4})</B></TD></TR>','SingleLine' ) # String block with the Estimated Delivery Date $m = $r.Matches($RawResult) # Extract Delivery Date from string block $date = ($m |% {$_.groups[1].value }) # Search for Current Order Status ("In preproduction" is Dutch for "In preproduction" $r = New-Object regex('target="popup:640x480">(.*?)</a>' ) $m = $r.Matches($RawResult) $status = ($m |% {$_.groups[1].value }) $Orderstatus = 1 | select @{name='Status';expression={$status[0]}},@{name='Estimated Delivery Date';expression={$date}} $Orderstatus | ft -a #[string]$output = $orderstatus $startdate = "16-09-2007" $startdate $currentdate = (get-date).ToString('MM-dd-yyyy') $currentdate $date
PowerShellCorpus/PoshCode/ESXiMgmt module sample 4.ps1
ESXiMgmt module sample 4.ps1
####################################################################################################################### # File: ESXiMgmt_search_for_guest_hostname_sample.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param([string]$Server, [string]$User, [string]$Password, [string]$DatastoreName, [string]$Drive ) # USAGE: .\\ESXiMgmt_search_for_guest_hostname_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 cls Set-StrictMode -Version Latest Import-Module ESXiMgmt -Force; Connect-ESXi -Server $Server -Port 443 ` -Protocol HTTPS -User $User -Password $Password ` -DatastoreName $DatastoreName -Drive $Drive; $vmname = Get-ESXiVMName -VMHostname 'B45E19A64B5E418' Write-Host "Guest host $($vmname) corresponds to $($vmname)"; $hostnames = @( '1-0028687D9BSP3', '1-07B328CA254D4', '1-081D88F5DF2D4', '1-10BF79C694094', '1-15DB4C70F57B4', '1-1B154BAE5CD84', '1-1D33859002954', '1-3502988189C24', '1-3A324DA9EBE54', '1-9160383452304', '1-96B95B980BDE4', '1-B3F725FTYE56', '1-E49B84B0A4AA4', '1-FECEC772CBB74' ); $vmnamesFromHostnames = Get-ESXiVMName -VMHostname $hostnames; for ($private:i = 0; $private:i -lt $vmnamesFromHostnames.Length; $private:i++) { Write-Host "Guest host $($hostnames[$private:i]) corresponds to $($vmnamesFromHostnames[$private:i])"; }
PowerShellCorpus/PoshCode/ConvertTo-CliXml_2.ps1
ConvertTo-CliXml_2.ps1
#requires -version 2.0 function ConvertTo-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [PSObject[]]$InputObject ) begin { $type = [type]::gettype("System.Management.Automation.Serializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null) $sw = new-object System.IO.StringWriter $xw = new-object System.Xml.XmlTextWriter $sw $serializer = $ctor.invoke($xw) $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") } process { try { [void]$method.invoke($serializer, $InputObject) } catch { write-warning "Could not serialize $($InputObject.gettype()): $_" } } end { [void]$done.invoke($serializer, @()) $sw.ToString() $xw.Close() $sw.Dispose() } }
PowerShellCorpus/PoshCode/Event Log SOX audit.ps1
Event Log SOX audit.ps1
$s = "Server01", "Server02", "Server03" foreach($server in $s) {$server #$computername = Get-Content env:computername $filter_Security = '<QueryList> <Query Id="0" Path="Security"> <Select Path="Security">(*[System[Provider[@Name="Microsoft-Windows-Security-Auditing"] and (Task = 13824 or Task = 13825 or Task = 13826 or Task = 13827 or Task = 13828 or Task = 13829 or Task = 13568 or Task = 13569 or Task = 13570 or Task = 13571 or Task = 13572) or (Task = 12544 and (band(Keywords,4503599627370496)))]]) or (*[System[Provider[@Name="Microsoft-Windows-Eventlog"] and Task = 104]]) </Select></Query></QueryList>' $filter_AcctManagement = '<QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[Provider[@Name="Microsoft-Windows-Security-Auditing"] and (Task = 13824 or Task = 13825 or Task = 13826 or Task = 13827 or Task = 13828 or Task = 13829)]] </Select></Query></QueryList>' $filter_AuditPolicyChanges = '<QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[Provider[@Name="Microsoft-Windows-Security-Auditing"] and (Task = 13568 or Task = 13569 or Task = 13570 or Task = 13571 or Task = 13572 or Task = 13573)]] </Select></Query></QueryList>' $filter_FailedLogins = '<QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[Provider[@Name="Microsoft-Windows-Security-Auditing"] and (Task = 12544 and (band(Keywords,4503599627370496)))]] </Select></Query></QueryList>' $filter_AuditCleared = '<QueryList> <Query Id="0" Path="Security"> <Select Path="Security">*[System[Provider[@Name="Microsoft-Windows-Eventlog"] and Task = 104]] </Select></Query></QueryList>' $filter_RDP = '<QueryList> <Query Id="0" Path="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational"> <Select Path="Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational">*[System[Provider[@Name="Microsoft-Windows-TerminalServices-RemoteConnectionManager"] and (EventID=1149)]] </Select></Query></QueryList>' Get-WinEvent -computername $server -FilterXml $filter_RDP | Export-Csv \\\\networkpath\\$server.RDP.csv Get-WinEvent -computername $server -FilterXml $filter_Security | Select-Object -Property 'Message','ID','Task','RecordID','LogName','ProcessID','ThreadID','MachineName','TimeCreated','TaskDisplayName' | Export-Csv \\\\networkpath\\$server.Security.csv
PowerShellCorpus/PoshCode/NFSMountUsingReference.ps1
NFSMountUsingReference.ps1
################################################################################################################ # VMWare Standard Scripts - PowerCLI # # Purpose: Mount NFS datastore on new host server using reference host datstore # Author: David Chung # Docs: NA # Date: 2/4/2012 # # # Instruction: Enter VI server name, Reference Host server name # Modify $hostincluster value either $true or $false # $false value will only update single ESX host server with NFS mount # ################################################################################################################ $HostinCluster = $false $viserver = Read-Host "Enter VI server" $refhost = Read-Host "Enter Reference host server" Connect-VIServer $viserver $REFHOST = Get-VMHost $refhost If ($HostinCluster) { $cluster = Read-Host "Enter Cluster that has new host servers" $NEWHosts = Get-Cluster $cluster | Get-VMHost | sort name foreach($nfs in (Get-VMhost $REFHOST | Get-Datastore | Where {$_.type -eq "NFS"} )){ [string]$remotePath = $nfs.extensiondata.info.nas.remotepath [string]$remoteHost = $nfs.extensiondata.info.nas.remotehost [string]$shareName = $nfs.Name Foreach ($NEWHost in $NEWHosts) { If ((Get-VMHost $NEWHOST | Get-Datastore | Where {$_.Name -eq $shareName -and $_.type -eq "NFS"} -ErrorAction SilentlyContinue )-eq $null){ Write-Host "NFS mount $shareName doesn't exist on $($NEWHOST.name)" -fore Red New-Datastore -Nfs -VMHost $NEWHost.name -Name $Sharename -Path $remotePath -NfsHost $remoteHost | Out-Null } } } } Else { $NEWHOST = Read-Host "Enter new host name" $Newhost = Get-VMHost $NEWHost foreach($nfs in ($REFHOST | Get-Datastore | Where {$_.type -eq "NFS"} )){ [string]$remotePath = $nfs.extensiondata.info.nas.remotepath [string]$remoteHost = $nfs.extensiondata.info.nas.remotehost [string]$shareName = $nfs.Name If (($NEWHOST | Get-Datastore | Where {$_.Name -eq $shareName -and $_.type -eq "NFS"} -ErrorAction SilentlyContinue )-eq $null){ Write-Host "NFS mount $shareName doesn't exist on $($NEWHOST.name)" -fore Red New-Datastore -Nfs -VMHost $NEWHost.name -Name $Sharename -Path $remotePath -NfsHost $remoteHost | Out-Null } } }
PowerShellCorpus/PoshCode/Get-ChildItemProxy.ps1
Get-ChildItemProxy.ps1
Function Get-ChildItemProxy { [CmdletBinding(DefaultParameterSetName='Items', SupportsTransactions=$true)] param( [Parameter(ParameterSetName='Items', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [System.String[]] ${Path}, [Parameter(ParameterSetName='LiteralItems', Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)] [Alias('PSPath')] [System.String[]] ${LiteralPath}, [Parameter(Position=1)] [System.String] ${Filter}, [System.String[]] ${Include}, [System.String[]] ${Exclude}, [Switch] ${Recurse}, [Switch] ${Force}, [Switch] ${Name}, [Switch] ${ContainersOnly}, [Switch] ${NoContainersOnly} ) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer) -and $outBuffer -gt 1024) { $PSBoundParameters['OutBuffer'] = 1024 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-ChildItem', [System.Management.Automation.CommandTypes]::Cmdlet) if ($ContainersOnly) { [Void]$PSBoundParameters.Remove("ContainersOnly") $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.PSIsContainer -eq $true}} } elseif ($NoContainersOnly) { [Void]$PSBoundParameters.Remove("NoContainersOnly") $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.PSIsContainer -eq $false}} } { $scriptCmd = {& $wrappedCmd @PSBoundParameters } } $steppablePipeline = $scriptCmd.GetSteppablePipeline() $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Get-ChildItem .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/PoshCode/Backup Rotation (7zip).ps1
Backup Rotation (7zip).ps1
First file RotateBackups_MasterList.txt RowNbr,BackupName,VersionsRetained,BackupType 1,TargetBackup,2,Folder 2,LstDefBackup,5,File 3,XMLBackup,3,File 4,SourceBackup,2,Folder 5,TXTBackup,8,File Second file RotateBackups_FolderList.txt RowNbr,BackupName,FolderName 1,TargetBackup,c:\\MyBooks\\target 2,SourceBackup,c:\\MyBooks\\source Third file RotateBackups_FileExtensions.txt RowNbr,BackupName,FileExtension,FolderLoc 1,LstDefBackup,*.def,c:\\MyBooks\\target 2,LstDefBackup,*.lst,c:\\MyBooks\\target 3,XMLBackup,*.xml,c:\\MyBooks\\target 4,TXTBackup,*.txt,c:\\MyBooks\\rfiles When executed, files are created in c:\\Zipfiles that have a name associated with the BackupName, a batch date-time. BackupName files are counted & compared to VersionsRetained value, and excess ones (oldest first) are marked for deletion upon next run of script. Can specify a delete to recycle bin (default) or a destructive delete of the backup. Use at your own risk. Script: function create-7zip([String] $aDirectory, [String] $aZipfile){ [string]$pathToZipExe = "C:\\Program Files\\7-zip\\7z.exe"; [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r"; & $pathToZipExe $arguments; } # Call it by using: #create-7zip "c:\\temp\\myFolder" "c:\\temp\\myFolder.zip" #************************************************************************************ #************************************************************************************ # Initialize variables $zipFolder = "C:\\ZipFiles" $nameConv = "{0:yyyyMMdd_HHmmss}" -f (Get-Date) + ".zip" $fileList = @{} $FileCountArray = @() $bkupTypeArr = @() $myDocFolder = "c:\\Documents and Settings\\MyPC\\My Documents\\" # Import text files for master, folder and file backup information $bkupRotateMasterArr = Import-Csv $myDocFolder"RotateBackups_MasterList.txt" $fldrBkupArray = Import-Csv $myDocFolder"RotateBackups_FolderList.txt" $fileExtBkupArr = Import-Csv $myDocFolder"RotateBackups_FileExtensions.txt" # Switch to delete Item or to send to recycle bin # delete is destructive and cannot recover file. # Recycle setting removes file from folder, but sends to recycle bin # and can be restored if needed. # Must be either "Kill" or "Recycle" $KillOrRecycle = "Recycle" #************************************************************************************ #************************************************************************************ # Load contents of master backup array $bkup_Counts = @{} $b = $null foreach($b in $bkupRotateMasterArr) { $bkup_Counts[$b.BackupName] = $b.VersionsRetained } #set Backup Types from the array we just defined $type = $null foreach ($type in $bkup_Counts.Keys) { $bkupTypeArr += $type } #create array of our filenames for this batch $type = $null $fArray = @{} foreach ($type in $bkupRotateMasterArr) { $fArray[$type.BackupName] = ($type.BackupName + $nameConv) } # if extension array not null, get list of files to back up if ($fileExtBkupArr) { # Gather the list of files to be backed up $f = $null foreach ($f in $fileExtBkupArr) { $arr = @() $arr = (Get-ChildItem $f.FolderLoc -Recurse -Include $f.FileExtension | Select-Object fullname) foreach ($a in $arr) { if ($a) { $fileList[$a] = $f.BackupName } # if $a not null } # end inner foreach } # end outer foreach } # if FileExtension Backup Array not null # if filelist count gt zero, then create zip file of them for appropriate backup if ($fileList.Count -gt 0) { # must have entries in hashtable $f = $null #Loop thru file list & associate file with the appropriate backup foreach ($f in $fileList.Keys) { $arcFile = $null if ($fileList.ContainsKey($f)) { if ($fArray.ContainsKey($fileList[$f])) { $arcFile = $fArray[$fileList[$f]] create-7zip $f.FullName $zipFolder\\$arcFile } #if key in fArray } # if key in Filelist } # end foreach } # if hastable not empty # if folder backup not null then back up folders if ($fldrBkupArray) { # check if array not null (no entries) $f = $null #Backup Folders now foreach ($f in $fldrBkupArray) { $arcFldr = $null #if ($fArray.ContainsKey($f[1])) { if ($fArray.ContainsKey($f.BackupName)) { $arcFldr = $fArray[$f.BackupName] create-7zip $f.FolderName $zipFolder\\$arcFldr } #end if } # end foreach } # end if $fldrBkupArray not null # if 7zip succeeded, we'll continue if ($LASTEXITCODE -gt 0) {Throw "7Zip failed" } ELSE { # if Exitcode = 0 then continue with job # Remove any files with Archive bit = False # we marked it for deletion in previous run Add-Type -AssemblyName Microsoft.VisualBasic $files=get-childitem -path $zipFolder # we'll delete all files that don't have the archive bit set Foreach($file in $files) { If((Get-ItemProperty -Path $file.fullname).attributes -band [io.fileattributes]::archive) { Write-output "$file is set to be retained" } ELSE { if ($KillOrRecycle = "Recycle") { Write-output "$file does not have the archive bit set. Deleting (Sent to recycle bin)." [Microsoft.VisualBasic.FileIO.Filesystem]::DeleteFile($file.fullname,'OnlyErrorDialogs','SendToRecycleBin') $output = $_.ErrorDetails } ELSE { Write-output "$file does not have the archive bit set. Deleting." remove-item -recurse $file.fullname $output =$_.ErrorDetails } } } #end Foreach # Export BackupCounts to XML $bkup_counts | Export-Clixml bkup_counts.xml # Get Number of ZIP files in folder $btype = $null foreach ($btype in $bkupTypeArr) { $FileCountArray += ,@(($btype),(dir $zipFolder\\$btype"*.zip").count) } # Import BkupCounts from XML $bkup_Counts= Import-Clixml bkup_counts.xml # set Attribute byte on ALL files in zipfolder so we know we'll get the right ones attrib $zipFolder"\\*" +a $row = $null # Get LST & DEF filenames in array & display count foreach ($row in $bkup_Counts.Keys) { Get-ChildItem -Path $zipFolder -Include $row"*" -Recurse #| (dir $zipFolder\\$row"*".zip).count - $bkup_Counts[$row] $delfiles = 0 $delfiles = (dir $zipFolder\\$row"*".zip).count - $bkup_Counts[$row] if ($delfiles -gt 0) { #sort folder by createdtime # if more than specified nbr of backups present, un-archive excess ones to delete next run. dir $zipFolder\\$row"*" | sort-object -property {$_.CreationTime} | select-object -first $delfiles | foreach-object { attrib $_.FULLNAME -A} } # end if delfiles gt 0 } # End foreach in bkup_counts } # End Else Last ExitCode = 0
PowerShellCorpus/PoshCode/View-Process.ps1
View-Process.ps1
function View-Process { param( [string[]]$ComputerNames, [string[]]$ProcessNames, $User ) ########################################################################################################### if ($User -is [String]) { $Connection = Get-Credential -Credential $User } ########################################################################################################### foreach ($int1 in $ComputerNames) { if ($ProcessNames -eq $null) { if ($Connection -eq $null) { $View_Process = gwmi "win32_process" -ComputerName $int1 | select __SERVER,Name,Handle } else { $View_Process = gwmi "win32_process" -ComputerName $int1 -Credential $Connection | select __SERVER,Name,Handle } $View_Process } else { foreach ($int2 in $ProcessNames) { if ($int2 -notlike "*.exe") {$int2 = $int2 + '.exe'} if ($Connection -eq $null) { $View_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" | select __SERVER,Name,Handle } else { $View_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" -Credential $Connection | select __SERVER,Name,Handle } $View_Process } } } ########################################################################################################### }
PowerShellCorpus/PoshCode/New-XVM_10.ps1
New-XVM_10.ps1
Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Try { Invoke-Expression -Command $command } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } End {} }
PowerShellCorpus/PoshCode/Reflection_1.ps1
Reflection_1.ps1
$nul = "<NULL>" function Get-AssembliesTree { [AppDomain]::CurrentDomain.GetAssemblies() | % { $nod = New-Object Windows.Forms.TreeNode $nod.Text = $_.GetName().Name $nod.Tag = $_ $tvAssem.Nodes.Add($nod) $nod.Nodes.Add($nul) } } function Add-Types { $_.Node.Nodes.Clear() try { foreach ($t in $_.Node.Tag.GetTypes()) { if ($t.IsPublic) { $node = $_.Node.Nodes.Add($t.FullName) $node.Tag = $t $node.Nodes.Add($nul) } } } catch {} } function Add-Members { try { foreach ($m in $_.Node.Tag.GetMembers()) { $node = $_.Node.Nodes.Add($m.Name) $node.Tag = $m.MemberType } } catch {} } $tvAssem_BeforeExpand= { Add-Types Add-Members } function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() $ico = [Drawing.Icon]::ExtractAssociatedIcon(( [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() + '\\MSBuild.exe' )) $frmMain = New-Object Windows.Forms.Form $tvAssem = New-Object Windows.Forms.TreeView $sbPanel = New-Object Windows.Forms.StatusBar # #tvAssem # $tvAssem.Dock = "Fill" $tvAssem.Sorted = $true $tvAssem.Add_AfterSelect({$sbPanel.Text = $_.Node.Tag}) $tvAssem.Add_BeforeExpand($tvAssem_BeforeExpand) # #sbPanel # $sbPanel.Font = New-Object Drawing.Font("Microsoft Sans Serif", 9, [Drawing.FontStyle]::Bold) $sbPanel.SizingGrip = $false # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(590, 550) $frmMain.Controls.AddRange(@($tvAssem, $sbPanel)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.Icon = $ico $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Reflection" $frmMain.Add_Load({Get-AssembliesTree}) [void]$frmMain.ShowDialog() } frmMain_Show
PowerShellCorpus/PoshCode/Spread-Mailboxes.ps1
Spread-Mailboxes.ps1
########################################################################### # # NAME: Spread-Mailboxes.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jer@powershell.no # # COMMENT: Script to spread mailboxes alphabetically across mailboxdatabases based on the first character in the user`s displayname. # For more information, see the following blog-post: http://blog.powershell.no/2010/05/14/script-to-spread-exchange-mailboxes-alphabetically-across-databases # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 14.05.2010 - Initial release # ########################################################################### #Add the Exchange Server 2010 Management Shell snapin Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue #Loop through each mailbox foreach ($mailbox in (Get-Mailbox -ResultSize unlimited)) { $displayname = $mailbox.Displayname #Determine which database the mailbox should reside on. Displaynames not matching [A-Z] on first character goes to the last database. switch -regex ($displayname.substring(0,1)) { "[A-F]" {$mailboxdatabase = "MDB A-F"} "[G-L]" {$mailboxdatabase = "MDB G-L"} "[M-R]" {$mailboxdatabase = "MDB M-R"} "[S-X]" {$mailboxdatabase = "MDB S-X" } "[Y-Z]" {$mailboxdatabase = "MDB Y-Z" } default {$mailboxdatabase = "MDB Y-Z" } } #Move mailbox to the correct database if not already correct. if (($mailbox.database.name) -ne $mailboxdatabase) {New-MoveRequest -Identity $mailbox -TargetDatabase $mailboxdatabase;Write-Host "Moving $displayname to $mailboxdatabase" -ForegroundColor Green} }
PowerShellCorpus/PoshCode/Dir for days_2.ps1
Dir for days_2.ps1
Function Create-DatePaths { Param ( [Parameter(Position=0,Mandatory=$True)] [DateTime] $Start, [Parameter(Position=1,Mandatory=$True)] [ValidateScript({$_ -gt $Start})] [DateTime] $End, $DestinationPath=(Join-Path $env:UserProfile "Test") ) 0..(New-TimeSpan $Start $End).Days | % { $TargetPath = Join-Path $DestinationPath $(Get-Date $Start -Format "yyyy\\\\MM-MMMM\\\\yyyy-MM-dd") If (!(Test-Path $TargetPath)) { New-Item $TargetPath -ItemType Directory } $Start = $Start.AddDays(1) } }
PowerShellCorpus/PoshCode/Get-LocalGroups_1.ps1
Get-LocalGroups_1.ps1
function Add-NoteProperty { <# .Synopsis Adds a NoteProperty member to an object. .Description This function makes adding a property a lot easier than Add-Member, assuming you want to add a NoteProperty, which I find is true about 90% of the time. .Parameter object The object to add the property to. .Parameter name The name of the new property. .Parameter value The object to add as the property. .Example # Create a new custom object and add some properties. PS> $custom_obj = New-Object PSObject PS> Add-NoteProperty $custom_obj Name 'Custom' PS> Add-NoteProperty $custom_obj Value 42 .Example # Add a NoteProperty by passing the object to be modified down the pipeline. PS> $bunch_of_objects | Add-NoteProperty -name 'meaning_of_life' -value 42 .Notes NAME: Add-NoteProperty AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] $object, [Parameter(Mandatory = $true, Position = 1)] [string]$name, [Parameter(Mandatory = $true, Position = 2)] $value) BEGIN{} PROCESS{ $object | Add-Member -MemberType NoteProperty ` -Name $name ` -Value $value } END{} } function Get-COMProperty{ <# .Synopsis Gets a property of a __ComObject object. .Description This function calls the InvokeMember static method of the class to get properties that aren't directly exposed to PowerShell, such as local group members found by calling Members() on a DirectoryServices group object. .Parameter com_object The object to retrieve the property from. .Parameter property_name The name of the property. .Example # Get the names of all members of a group. PS> [adsi]$computer = 'WinNT://servername' PS> $groups = $groups = $computer.psbase.children | >> ?{$_.psbase.schemaclassname -eq 'group'} PS> $groups[0].Members() | %{Get-COMProperty $_ 'Name'} .Notes NAME: Get-COMProperty AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, Position = 0)] $com_object, [Parameter(Mandatory = $true, Position = 1)] [string]$property_name) [string]$property = $com_object.GetType().InvokeMember($property_name, 'GetProperty', $null, $com_object, $null) Write-Output $property } function Get-LocalGroups{ <# .Synopsis Gets a list of objects with information about local groups and their members. .Description This function returns a list of custom PSObjects that are a list of local groups on a computer. Each object has a property called Members that is a list of PSObjects representing each member, with Name, Domain, and ADSPath. .Parameter computername The object to retrieve the property from. .Example # Get a list of groups from a server. PS> Get-LocalGroups servername .Notes NAME: Get-LocalGroups AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$computername = $env:computername) BEGIN{} PROCESS{ $output = @() [adsi]$computer = "WinNT://$computername" $groups = $computer.psbase.children | ?{$_.psbase.schemaclassname -eq 'group'} foreach ($group in $groups) { $members = @() $grp_obj = New-Object PSObject Add-NoteProperty $grp_obj 'Name' $group.Name.ToString() Add-NoteProperty $grp_obj 'aDSPath' $group.aDSPath.ToString() foreach ($user in $group.Members()){ $usr_obj = New-Object PSObject Add-NoteProperty $usr_obj 'aDSPath' (Get-COMProperty $user 'aDSPath') Add-NoteProperty $usr_obj 'Name' (Get-COMProperty $user 'Name') $path = $usr_obj.aDSPath.split('/') if ($path.Count -eq 4){ Add-NoteProperty $usr_obj 'Domain' $path[2] }elseif ($path.Count -eq 5) { Add-NoteProperty $usr_obj 'Domain' $path[3] }else{ Add-NoteProperty $usr_obj 'Domain' 'Unknown' } $members += $usr_obj } $members = @($members | Sort-Object -Property Domain, Name) Add-NoteProperty $grp_obj 'Members' $members Write-Output $grp_obj } } END{} }
PowerShellCorpus/PoshCode/Harley.ps1
Harley.ps1
### # Description: Add Voice to Powershell # Version: 1.1 (11 Nov 2008) # Mike Hays / www.mike-hays.net / blog.mike-hays.net # Virtualization, Powershell, and more... ### # This is the actual speaking part. I cheat by adding spaces # (This makes the word sound right). $spokenText = "Super ca li fragilistic expi alidocious" # Create an object that represents the COM SAPI.SpVoice $voice = New-Object -com SAPI.SpVoice # Get the list of available voices $voiceList = $voice.GetVoices() # This script prefers using LH Michelle as a stand-in for Mary Poppins, # but I can't be sure that she exists on all computers, so I check for that. # She comes with some installations of Microsoft Word 2003. $voiceDescList = @() for ($i=0; $i -lt $voiceList.Count; $i++) { $voiceDescList += $voiceList.Item($i).GetDescription() } if ($voiceDescList -contains "LH Michelle") { $voiceMember = "Name=LH Michelle" } else { # This is the default voice if LH Michelle doesn't exist. # This will probably be Microsoft Sam $voiceMember = "Name=" + $voiceDescList[0] } $voiceToUse = $voice.GetVoices($voiceMember) # This sets the voice property on the COM object $voice.Voice = $voiceToUse.Item(0) # This actually does the speaking. [void] $voice.Speak($spokenText) # She's no Julie Andrews, but she'll say what you want. # END
PowerShellCorpus/PoshCode/783e4a84-4d47-4c57-a257-2298ce2b32ff.ps1
783e4a84-4d47-4c57-a257-2298ce2b32ff.ps1
Function Get-DiskUsage { <# .SYNOPSIS A tribute to the excellent Unix command DU. .DESCRIPTION This command will output the full path and the size of any object and it's subobjects. Using just the Get-DiskUsage command without any parameters will result in an output of the directory you are currently placed in and it's subfolders. .PARAMETER Path If desired a path can be specified with the Path parameter. In no path is specified $PWD will be used. .PARAMETER h the -h paramater is the same as -h in Unix. It will list the folders and subfolders in the most appropriate unit depending on the size (i.e. Human Readable). .PARAMETER l The -l paramater will add the largest file to the end of the output. .PARAMETER Sort Allows you to sort by Folder or Size. If none i specified the default of Folder will be used. .PARAMETER Depth Depth will allow you to specify a maximum recursion depth. A depth of 1 would return the immediate subfolders under the root. .PARAMETER Force Works the same way as Get-ChildItem -force. .PARAMETER Descending Works the same way as Sort-Object -descending. .LINK http://www.donthaveasite.nu .NOTES Author: Jonas Hallqvist Developed with Powershell v3 #> [CmdletBinding( SupportsShouldProcess=$True )] param ( [String]$Path=$PWD, [Switch]$h, [Switch]$l, [String]$Sort="Folder", [Int]$Depth, [Switch]$Force, [Switch]$Descending ) $ErrorActionPreference = "silentlycontinue" function HumanReadable { param ($size) switch ($size) { {$_ -ge 1PB}{"{0:#'P'}" -f ($size / 1PB); break} {$_ -ge 1TB}{"{0:#'T'}" -f ($size / 1TB); break} {$_ -ge 1GB}{"{0:#'G'}" -f ($size / 1GB); break} {$_ -ge 1MB}{"{0:#'M'}" -f ($size / 1MB); break} {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break} #{$_ -eq $null}{"0B"} default {"{0}" -f ($size) + "B"} } } function LargestFolder { if ($h) { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } else { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } } function Max-Depth { param( [String]$Path = '.', [String]$Filter = '*', [Int]$Level = 0, [Switch]$Force, [Switch]$Descending, [int]$i=0 ) $results=@() $root = (Resolve-Path $Path).Path if ($root -notmatch '\\\\$') {$root += '\\'} if (Test-Path $root -PathType Container) { do { [String[]]$_path += $root + "$Filter" $Filter = '*\\' + $Filter $i++ } until ($i -eq $Level) $dirs=Get-ChildItem -directory $_path -Force:$Force foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.Fullname -recurse | Measure-Object -Property Length -Sum).Sum $results += New-Object psobject -Property @{Folder=$dir.fullname;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } } if ($Depth) { Max-Depth -Path $Path -Level $Depth -Force:$Force -Descending:$Descending } else { $results = @() $dirs=Get-ChildItem -directory $Path -Force:$Force -Recurse foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.FullName -Recurse | Measure-Object -Property Length -Sum).Sum $results+= New-Object psobject -Property @{Folder=$dir.FullName;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } }
PowerShellCorpus/PoshCode/List DHCP Clients .ps1
List DHCP Clients .ps1
$DHCP_EnumSubnetClients = @' [DllImport("dhcpsapi.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern uint DhcpEnumSubnetClients( string ServerIpAddress, uint SubnetAddress, ref uint ResumeHandle, uint PreferredMaximum, out IntPtr ClientInfo, ref uint ElementsRead, ref uint ElementsTotal); '@ $DHCP_Structs = @' namespace mystruct { using System; using System.Runtime.InteropServices; public struct CUSTOM_CLIENT_INFO { public string ClientName; public string IpAddress; public string MacAddress; } [StructLayout(LayoutKind.Sequential)] public struct DHCP_CLIENT_INFO_ARRAY { public uint NumElements; public IntPtr Clients; } [StructLayout(LayoutKind.Sequential)] public struct DHCP_CLIENT_UID { public uint DataLength; public IntPtr Data; } [StructLayout(LayoutKind.Sequential)] public struct DATE_TIME { public uint dwLowDateTime; public uint dwHighDateTime; public DateTime Convert() { if (dwHighDateTime== 0 && dwLowDateTime == 0) { return DateTime.MinValue; } if (dwHighDateTime == int.MaxValue && dwLowDateTime == UInt32.MaxValue) { return DateTime.MaxValue; } return DateTime.FromFileTime((((long) dwHighDateTime) << 32) | (UInt32) dwLowDateTime); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DHCP_HOST_INFO { public uint IpAddress; public string NetBiosName; public string HostName; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DHCP_CLIENT_INFO { public uint ClientIpAddress; public uint SubnetMask; public DHCP_CLIENT_UID ClientHardwareAddress; [MarshalAs(UnmanagedType.LPWStr)] public string ClientName; [MarshalAs(UnmanagedType.LPWStr)] public string ClientComment; public DATE_TIME ClientLeaseExpires; public DHCP_HOST_INFO OwnerHost; } } '@ $resumeHandle = 0 $clientInfo = 0 $ElementsRead = 0 $ElementsTotal = 0 Add-Type $DHCP_Structs Add-Type -MemberDefinition $DHCP_EnumSubnetClients -Name GetDHCPInfo -Namespace Win32DHCP $DHCPServerIP = "192.168.1.100" # change this to match your DHCP server IP [void][Win32DHCP.GetDHCPInfo]::DhcpEnumSubnetClients($DHCPServerIP,0,[ref]$resumeHandle,0,[ref]$clientInfo,[ref]$ElementsRead,[ref]$ElementsTotal) $clients = [system.runtime.interopservices.marshal]::PtrToStructure($clientInfo,[mystruct.DHCP_CLIENT_INFO_ARRAY]) [int]$size = $clients.NumElements [int]$current = $clients.Clients $ptr_array = new-object system.intptr[]($size) $current = new-object system.intptr($current) for ($i=0;$i -lt $size;$i++) { $ptr_array[$i] = [system.runtime.interopservices.marshal]::ReadIntPtr($current) $current = $current + [system.runtime.interopservices.marshal]::SizeOf([system.IntPtr]) } function uIntToIP { param ($intIP) $objIP = new-object system.net.ipaddress($intIP) $arrIP = $objIP.IPAddressToString.split(".") return $arrIP[3] + "." + $arrIP[2] + "." + $arrIP[1] + "." + $arrIP[0] } [array]$clients_array = new-object mystruct.CUSTOM_CLIENT_INFO for ($i=0;$i -lt $size;$i++) { $objDHCPInfo = New-Object psobject $current_element = [system.runtime.interopservices.marshal]::PtrToStructure($ptr_array[$i],[mystruct.DHCP_CLIENT_INFO]) add-member -inputobject $objDHCPInfo -memberType noteproperty -name ClientIP -value $(uIntToIP $current_element.ClientIpAddress) add-member -inputobject $objDHCPInfo -memberType noteproperty -name ClientName -value $current_element.ClientName add-member -inputobject $objDHCPInfo -memberType noteproperty -name OwnerIP -value $(uIntToIP $current_element.Ownerhost.IpAddress) add-member -inputobject $objDHCPInfo -memberType noteproperty -name OwnerName -value $current_element.Ownerhost.NetBiosName add-member -inputobject $objDHCPInfo -memberType noteproperty -name SubnetMask -value $(uIntToIP $current_element.SubnetMask) add-member -inputobject $objDHCPInfo -memberType noteproperty -name LeaseExpires -value $current_element.ClientLeaseExpires.Convert() $mac = [System.String]::Format( "{0:x2}-{1:x2}-{2:x2}-{3:x2}-{4:x2}-{5:x2}", [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data), [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data, 1), [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data, 2), [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data, 3), [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data, 4), [system.runtime.interopservices.marshal]::ReadByte($current_element.ClientHardwareAddress.Data, 5) ) add-member -inputobject $objDHCPInfo -memberType noteproperty -name MacAddress -value $mac $objDHCPInfo }
PowerShellCorpus/PoshCode/count-object.ps1
count-object.ps1
#a function to count how many items there are, whether its an array, a collection, or actually just # a single no array/non list/non collection object in which case it would be 1 function count ($InputObject) { if ($inputobject -eq $Null ) { return 0} if ($inputobject -is [system.array]) { return $inputobject.length } if ($inputobject -is [system.collections.ICollection] -or $inputobject -is [system.collections.IList] ) { return $inputobject.count } #strings are ienumerable, they also have a length, but i think we want to treat 1 string as one object if ($inputobject -is [string]) { return 1 } #-1 to show that it is enumerable, but we can't know its length, it could be infinate, #or take a long time even to enumerate without going over if ($inputobject -is [system.collections.IEnumerable]) { return -1 } #otherwise just return 1 return 1 } count (get-process) count (1,2,3) count "hello" count 3 $a = new-object system.collections.arraylist [void] $a.add(4); [void] $a.add("yo"); count $a
PowerShellCorpus/PoshCode/Start-ComputerJobs.ps1
Start-ComputerJobs.ps1
#requires -version 2.0 function Start-ComputerJobs{ <# .NOTES Name: Start-ComputerJobs Author: Tome Tanasovski Created: 6/25/2010 Version: 1.0 Website: http://powertoe.wordpress.com .SYNOPSIS Multithreads a scriptblock with jobs .DESCRIPTION The Start-ComputerJobs cmdlet runs a specified scriptblock within a maximum number of simultaneously spawned Powershell jobs. You must pass a list of ComputerNames to it. The names passed to the cmdlet will replace $computername within the scriptblock prior to starting each thread. This can be thought of as a multithreaded approach to a foreach loop. .PARAMETER ComputerName Specifies a list of computers that you wish to inject into your scriptblock. The list of computer names will replace $computername in the script block. This does not actually need to be a list of computer names. It can be anything you wish to inject into your scriptblock. .PARAMETER ScriptBlock Specifies the commands to run in the background jobs. Enclose the commands in braces ({}) or use $ExecutionContext.InvokeCommand.NewScriptBlock to create a scriptblock. The scriptblock must contain a $computername variable. $computername will be replaced by each entry into the pipeline or from the parameter ComputerName. .PARAMETER Threads Specifies the maximum number of jobs that can be simultaneously running at any given time. This defaults to 10 if nothing is specified. .EXAMPLE "computer1","computer2","computer3","computer4","computer5" |Start-ComputerJobs -ScriptBlock {dir \\\\$computername\\c$} .INPUTS System.String .OUTPUTS PSObject Returns the results of the commands in the job. It is the data returned from receive-job. If you're scriptblock contains write-host it will write that to the console as it is running. To avoid this you should just return objects within your scriptblock. i.e. Instead of write-host "text" just use "text" #> param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName, [Parameter(Mandatory=$true)] [ScriptBlock]$ScriptBlock, [Parameter(Mandatory=$false)] [ValidateScript({$_ -gt 0})] [int32]$Threads = 10, [Parameter(Mandatory=$false)] [ValidateScript({$_ -gt 0})] [int32]$Sleep = 5 ) BEGIN { $firstrun = $true $computers = @() $curthreads = 0 $jobs = @() $valid = $false } PROCESS { if ($firstrun) { $firstrun = $false # Validate scriptblock - Making sure it has a $computername variable to use if ($ScriptBlock -match '\\$computername') { $valid = $true } else { Write-Error 'You must specify a scriptblock that contains a variable called $computername' $valid = $false } } if ($valid) { foreach ($computer in $computername) { while ($jobs.count -eq $Threads) { $newjobs = @() $jobs |foreach { $_ |Receive-Job -NoRecurse if ($_.state -eq "Running" -or $_.HasMoreData) { $newjobs += $_ } else { $_ |Remove-Job } } $jobs = $newjobs if ($jobs.count -eq $Threads) { sleep $sleep } } $runscript = $ExecutionContext.InvokeCommand.NewScriptBlock(($ScriptBlock -replace '\\$computername', """$computer""")) Write-Verbose "Starting Job for computer: $computer" $jobs += Start-Job -ScriptBlock $runscript $curthreads++ } } } END { while ($jobs.count -ne 0) { $newjobs = @() $jobs |foreach { $_ |Receive-Job -NoRecurse if ($_.state -eq "Running" -or $_.HasMoreData) { $newjobs += $_ } else { $_ |Remove-Job } } $jobs = $newjobs if ($jobs.count -gt 0) { sleep $sleep } } } }
PowerShellCorpus/PoshCode/Is-Natural.ps1
Is-Natural.ps1
function is-natural{ param ($number) if($number -like "*.*" -or $number -like "*-*"){ return $false }else{return $true} }
PowerShellCorpus/PoshCode/UIAutomation _1.6.ps1
UIAutomation _1.6.ps1
## UI Automation v 1.7 -- REQUIRES the Reflection module (current version: http://poshcode.org/2480 ) ## # WASP 2.0 is getting closer, but this is still just a preview: # -- a lot of the commands have weird names still because they're being generated ignorantly # -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke # v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" $SWA = "System.Windows.Automation" # Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue # Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue # Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue # Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue # Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue # Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue # This is what requires the Reflection module: Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue ##### Conditions Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue ##### IDentifiers Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue ##### Patterns: $patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern #| Where { $_ -ne [System.Windows.Automation.InvokePattern] } Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Automation; using System.Runtime.InteropServices; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class StaticFieldAttribute : ArgumentTransformationAttribute { private Type _class; public override string ToString() { return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName); } public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) { if(inputData is string && !string.IsNullOrEmpty(inputData as string)) { System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public); if(field != null) { return field.GetValue(null); } } return inputData; } public StaticFieldAttribute( Type ofClass ) { OfClass = ofClass; } public Type OfClass { get { return _class; } set { _class = value; } } } public static class UIAutomationHelper { [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr FindWindow (string lpClassName, string lpWindowName); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SetForegroundWindow (IntPtr hWnd); public static AutomationElement RootElement { get { return AutomationElement.RootElement; } } ///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis> public static bool SetForeground(this AutomationElement element) { if(element == null) { throw new ArgumentNullException("element"); } // Get handle to the element IntPtr other = FindWindow (null, element.Current.Name); // // Get the Process ID for the element we are trying to // // set as the foreground element // int other_id = GetWindowThreadProcessId (other, IntPtr.Zero); // // // Get the Process ID for the current process // int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero); // // // Attach the current process's input to that of the // // given element. We have to do this otherwise the // // WM_SETFOCUS message will be ignored by the element. // bool success = AttachThreadInput(this_id, other_id, true); // Make the Win32 call IntPtr previous = SetForegroundWindow(other); return !IntPtr.Zero.Equals(previous); } } "@ -ReferencedAssemblies UIAutomationClient, UIAutomationTypes ## TODO: Write Get-SupportedPatterns or rather ... ## Get-SupportedFunctions (to return the names of the functions for the supported patterns) ## TODO: Support all the "Properties" too ## TODO: Figure out why Notepad doesn't support SetValue ## TODO: Figure out where the menus support went ForEach($pattern in $patterns){ $pattern | Add-Accelerator $PatternFullName = $pattern.FullName $PatternName = $Pattern.Name -Replace "Pattern","." $newline = "`n`t`t" New-Item "Function:ConvertTo-$($Pattern.Name)" -Value " param( [Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject ) process { trap { if(`$_.Exception.Message -like '*Unsupported Pattern.*') { Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue; } } Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current }" $pattern.GetMethods() | Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } | ForEach { $FunctionName = "Function:Invoke-$PatternName$($_.Name)" $Position = 1 if (test-path $FunctionName) { remove-item $FunctionName } $Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+ "$newline[Alias('Parent','Element','Root','AutomationElement')]"+ "$newline[AutomationElement]`$InputObject" ) + @( "[Parameter()]$newline[Switch]`$Passthru" ) + @($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" }) $Parameters = $Parameters -Join "$newline,$newline" $ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $') $definition = @" param( $Parameters ) process { ## trap { Write-Warning "`$(`$_)"; break } `$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues })) } if(`$passthru) { `$InputObject } } "@ trap { Write-Warning $_ Write-Host $definition -fore cyan } New-Item $FunctionName -value $definition } $pattern.GetProperties() | Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} | ForEach { $FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.') if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$pattern.'$($_.Name)' } }" } ## So far this seems to be restricted to Text (DocumentRange) elements $pattern.GetFields() | Where { $_.FieldType.Name -like "*TextAttribute"} | ForEach { $FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name)) }" } $pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } | ForEach { $Name = $_.Name -replace 'Event$' $FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement , [System.Windows.Automation.TreeScope]`$TreeScope = 'Element' , [ScriptBlock]`$EventHandler ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } [Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler ) }" } } $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue $AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties() Set-Alias Invoke-UIElement Invoke-Invoke.Invoke function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Get-ClickablePoint { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject ) process { $InputObject.GetClickablePoint() } } function Show-Window { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { Set-UIFocus $InputObject if($passthru) { $InputObject } } } function Set-UIFocus { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { try { [UIAutomationHelper]::SetForeground( $InputObject ) $InputObject.SetFocus() } catch { Write-Verbose "SetFocus fail, trying SetForeground" } if($passthru) { $InputObject } } } function Send-UIKeys { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Keys , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru , [Parameter()] [Switch]$Async ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } Set-UIFocus $InputObject if($Async) { [SendKeys]::Send( $Keys ) } else { [SendKeys]::SendWait( $Keys ) } if($passthru) { $InputObject } } } function Set-UIText { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Text , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } $valuePattern = $null if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) { Write-Verbose "Set via ValuePattern!" $valuePattern.SetValue( $Text ) } elseif($InputObject.Current.IsKeyboardFocusable) { Set-UIFocus $InputObject [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } if($passthru) { $InputObject } } } function Select-UIElement { [CmdletBinding(DefaultParameterSetName="FromParent")] PARAM ( [Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)] [Alias("MainWindowHandle","hWnd","Handle","Wh")] [IntPtr[]]$WindowHandle=[IntPtr]::Zero , [Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)] [System.Windows.Point[]]$Point , [Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)] [System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement , [Parameter(ParameterSetName="FromParent", Position="0")] [Alias("WindowName")] [String[]]$Name , [Parameter(ParameterSetName="FromParent", Position="1")] [Alias("Type","Ct")] [System.Windows.Automation.ControlType] [StaticField(([System.Windows.Automation.ControlType]))]$ControlType , [Parameter(ParameterSetName="FromParent")] [Alias("UId")] [String[]]$AutomationId , ## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle [Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )] [Alias("Id")] [Int[]]$PID , [Parameter(ParameterSetName="FromParent")] [Alias("Pn")] [String[]]$ProcessName , [Parameter(ParameterSetName="FromParent")] [Alias("Cn")] [String[]]$ClassName , [switch]$Recurse , [switch]$Bare ) process { Write-Debug "Parameters Found" Write-Debug ($PSBoundParameters | Format-Table | Out-String) $search = "Children" if($Recurse) { $search = "Descendants" } $condition = [System.Windows.Automation.Condition]::TrueCondition Write-Verbose $PSCmdlet.ParameterSetName switch -regex ($PSCmdlet.ParameterSetName) { "FromWindowHandle" { Write-Verbose "Finding from Window Handle $HWnd" $Element = $( foreach($hWnd in $WindowHandle) { [System.Windows.Automation.AutomationElement]::FromHandle( $hWnd ) } ) continue } "FromPoint" { Write-Verbose "Finding from Point $Point" $Element = $( foreach($pt in $Point) { [System.Windows.Automation.AutomationElement]::FromPoint( $pt ) } ) continue } "FromParent" { Write-Verbose "Finding from Parent!" ## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition [ScriptBlock[]]$filters = @() if($AutomationId) { [System.Windows.Automation.Condition[]]$current = $( foreach($aid in $AutomationId) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($PID) { [System.Windows.Automation.Condition[]]$current = $( foreach($p in $PID) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($ProcessName) { if($ProcessName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($p in Get-Process -Name $ProcessName) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($Name) { Write-Verbose "Name: $Name" if($Name -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($n in $Name){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ClassName) { if($ClassName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ClassName){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ControlType) { if($ControlType -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ControlType){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($conditions.Length -gt 1) { [System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions } elseif($conditions) { [System.Windows.Automation.Condition]$condition = $conditions[0] } else { [System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition } If($VerbosePreference -gt "SilentlyContinue") { function Write-Condition { param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0) process { Write-Debug ($Condition | fl * | Out-String) if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) { Write-Verbose ((" "*$indent) + $Condition.GetType().Name ) $condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4) } elseif($condition -is [System.Windows.Automation.PropertyCondition]) { Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")") } else { Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")") } } } Write-Verbose "CONDITIONS =============" $global:LastCondition = $condition foreach($c in $condition) { Write-Condition $c } Write-Verbose "============= CONDITIONS" } if($filters.Count -gt 0) { $Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item } } else { $Element = $Parent.FindAll( $search, $condition ) } } } Write-Verbose "Element Count: $(@($Element).Count)" if($Element) { foreach($el in $Element) { if($Bare) { Write-Output $el } else { $e = New-Object PSObject $el foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName) { ## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property $propName = [System.Windows.Automation.Automation]::PropertyName($prop) Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0 } foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName) { Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0 } Write-Output $e } } } } } # [Cmdlet(VerbsCommon.Add, "UIAHandler")] # public class AddUIAHandlerCommand : PSCmdlet # { # private AutomationElement _parent = AutomationElement.RootElement; # private AutomationEvent _event = WindowPattern.WindowOpenedEvent; # private TreeScope _scope = TreeScope.Children; # # [Parameter(ValueFromPipeline = true)] # [Alias("Parent", "Element", "Root")] # public AutomationElement InputObject { set { _parent = value; } get { return _parent; } } # # [Parameter()] # public AutomationEvent Event { set { _event = value; } get { return _event; } } # # [Parameter()] # public AutomationEventHandler ScriptBlock { set; get; } # # [Parameter()] # public SwitchParameter Passthru { set; get; } # # [Parameter()] # public TreeScope Scope { set { _scope = value; } get { return _scope; } } # # protected override void ProcessRecord() # { # Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock); # # if (Passthru.ToBool()) # { # WriteObject(InputObject); # } # # base.ProcessRecord(); # } # } Export-ModuleMember -cmdlet * -Function * -Alias *
PowerShellCorpus/PoshCode/Lab Manager Demo.ps1
Lab Manager Demo.ps1
# Demo showing how to connect to VMware Lab Manager. # Download LabManager.ps1 from http://www.poshcode.org/753. . .\\LabManager.ps1 # Run this command if your Lab Manager's certificate is untrusted but you # want to connect. Ignore-SslErrors # Connect to Lab Manager. $labManager = Connect-LabManager -server "demo.eng.vmware.com" ` -credential (get-credential) # Find out what operations there are. $labManager | gm | where { $_.MemberType -eq "Method" } # List all library configurations. $labManager.ListConfigurations(1) # Find all machines deployed from any library configuration. $labManager.ListConfigurations(1) | foreach { write-host ("For Configuration " + $_.id + ":") $labManager.ListMachines($_.id) } # See http://www.vmware.com/pdf/lm30_soap_api_guide.pdf for help on arguments.
PowerShellCorpus/PoshCode/Invoke-RemoteCommand_2.ps1
Invoke-RemoteCommand_2.ps1
<# # Script FileName: func_Invoke-RemoteCommand.ps1 # Current Version: A03 # Description: Run command on a remote computer as the currently logged on user. # Created By: Adam Listek # Version Notes # A01 - Initial Release # A02 - Conversion to Function # A03 - Abstracted to generic purpose #> Function Global:Invoke-RemoteCommand { [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact="Low" )] # Terminate CmdletBinding Param ( [Parameter( ValueFromPipeline=$true, Position=0)] [String]$computerName = "localhost", [Parameter(Position=1)][String]$inputCode, [Parameter(Position=2)][String]$outputFile = "C:\\Temp\\Output.ps1", [Switch]$passthru ) # Terminate Param Begin { If ($MyInvocation.BoundParameters.Verbose -match $true) { $local:VerbosePreference = "Continue" $local:ErrorActionPreference = "Continue" $local:verbose = $true } Else { $local:VerbosePreference = "SilentlyContinue" $local:ErrorActionPreference = "SilentlyContinue" $local:verbose = $false } # Terminate If - Verbose Parameter Check # Define Internal Functions Function local:Test-AdministratorPrivileges { Write-Verbose "Get user that script context is being run in." $identity = [Security.Principal.WindowsIdentity]::GetCurrent() Write-Verbose "Create a new Security Principal object to retrieve rights." $principal = new-object Security.Principal.WindowsPrincipal $identity Write-Verbose "Retrieve if user is currently in an Administrator role." $result = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) If ($result) { Write-Output $true } Else { Write-Output $false } # Terminate If - Result } # Terminate Function # Verify whether the current user context for the function is an Administrator If (Test-AdministratorPrivileges -Verbose:$verbose) { Write-Verbose "Function is being run as an Administrator." } Else { Write-Host "Current user, {0}, is not an Administrator." ` -F ([Security.Principal.WindowsIdentity]::GetCurrent()) ` -ForegroundColor Red Break } # Terminate Test for Administrative Privileges # Global Variables $servicePath = "C:\\Temp" $serviceName = "ps_service" } # Terminate Begin Process { # Required if running in Powershell ISE, will set for the shell also. If ($MyInvocation.BoundParameters.Debug -match $true) { # Must be set per pipeline run $local:DebugPreference = "Continue" } Else { $local:DebugPreference = "SilentlyContinue" } # Terminate If - Debug $scriptblock = { Param( $inputCode, $outputFile, $servicePath, $serviceName ) # Parse the results of the current sessions using the built-in executable, Query.exe. $results = c:\\windows\\system32\\query.exe session # Create object array of Query results $active = $results | %{ $line = $_.ToString().Split(" ") $array = $line | Where { $_ -ne "" } Switch ($array.count) { 3 { $sessionname = $array[0] $username = $null $id = $array[1] $state = $array[2] $type = $null Break } 4 { $sessionname = $array[0] $username = $array[1] $id = $array[2] $state = $array[3] $type = $null Break } 5 { $sessionname = $array[0] $username = $array[1] $id = $array[2] $state = $array[3] $type = $array[4] Break } } # Terminate Switch $object = New-Object PSObject -Property @{ sessionname = $sessionname username = $username ID = $id state = $state type = $type } Write-Output $object } | Where { $_.State -eq "Active" } If ($active) { # The data is the local Powershell script that you want to run on the remote system # Using a HereString @'' (does not parse variables within), @"" (will parse variables) Write-Verbose $outputFile Write-Verbose $inputCode # Generate the script file on the fly on the remote computer Out-File -FilePath $outputFile -InputObject $inputCode -Encoding ascii # We want to hide the powershell window and override the execution policy to make sure it runs $command = "powershell.exe -NonInteractive -WindowStyle hidden -NoLogo -File $outputFile -ExecutionPolicy RemoteSigned" $serviceDisplayName = "PS Emulate Session" Write-Verbose $command Write-Verbose $serviceDisplayName # The code to actually generate the service $source = @" using System; using System.Text; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Diagnostics; namespace PS { public class Emulate : System.ServiceProcess.ServiceBase { public Emulate() { this.ServiceName = "$serviceDisplayName"; } static void Main(string[] args) { System.ServiceProcess.ServiceBase.Run(new Emulate()); } protected override void OnStart(string[] args) { base.OnStart(args); EmulateSession.StartProcessInSession($($active.Id), @"$command"); } protected override void OnStop() { base.OnStop(); } public static void WriteToEventLog(string message) { string cs = "PS_Emulate_Service"; EventLog elog = new EventLog(); if (!EventLog.SourceExists(cs)) { EventLog.CreateEventSource(cs, "Application"); } elog.Source = cs; elog.EnableRaisingEvents = true; EventLog.WriteEntry(cs, message, EventLogEntryType.Information); } } static public class EmulateSession { /* structs, enums, and external functions defined at end of code */ public static System.Diagnostics.Process StartProcessInSession(int sessionID, String commandLine) { Emulate.WriteToEventLog("Inside StartProcessInSession"); Emulate.WriteToEventLog("Session ID: " + sessionID.ToString()); IntPtr userToken; if (WTSQueryUserToken(sessionID, out userToken)) { //note that WTSQueryUserToken only works when in context of local system account with SE_TCB_NAME IntPtr lpEnvironment; Emulate.WriteToEventLog("Token: " + userToken.ToString()); if (CreateEnvironmentBlock(out lpEnvironment, userToken, false)) { Emulate.WriteToEventLog("User Env: " + lpEnvironment.ToString()); StartupInfo si = new StartupInfo(); si.cb = Marshal.SizeOf(si); si.lpDesktop = "winsta0\\\\default"; si.dwFlags = STARTF.STARTF_USESHOWWINDOW; // Using the SW_HIDE will make the window hidden, see in the bottom section for more commands si.wShowWindow = ShowWindow.SW_HIDE; ProcessInformation pi; // Note the CreationFlags, they make this work as it must have both the CREATE_NEW_CONSOLE and CREATE_UNICODE_ENVIRONMENT if (CreateProcessAsUser(userToken, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, false, CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref si, out pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); //context.Undo(); try { return System.Diagnostics.Process.GetProcessById(pi.dwProcessId); } catch (ArgumentException) { // I had to remove the ArgumentException e (I removed the e), it threw up a compiler warning //The process ID couldn't be found - which is what always happens because it has closed return null; } } else { Emulate.WriteToEventLog("Could Not Create Process."); int err = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(err, "Could not create process.\\nWin32 error: " + err.ToString()); } } else { Emulate.WriteToEventLog("Could not create environment block."); int err = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(err, "Could not create environment block.\\nWin32 error: " + err.ToString()); } } else { Emulate.WriteToEventLog("No Token"); int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (err == 1008) return null; //There is no token throw new System.ComponentModel.Win32Exception(err, "Could not get the user token from session " + sessionID.ToString() + " - Error: " + err.ToString()); } } [DllImport("wtsapi32.dll", SetLastError = true)] static extern bool WTSQueryUserToken(Int32 sessionId, out IntPtr Token); [DllImport("userenv.dll", SetLastError = true)] static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation); [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hHandle); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct StartupInfo { public Int32 cb; public String lpReserved; public String lpDesktop; public String lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public STARTF dwFlags; public ShowWindow wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] internal struct ProcessInformation { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } /// <summary> /// The following process creation flags are used by the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, and CreateProcessWithTokenW functions. They can be specified in any combination, except as noted. /// </summary> [Flags] enum CreationFlags : int { /// <summary> /// Not specified by MSDN??? /// </summary> NONE = 0, /// <summary> /// The calling thread starts and debugs the new process and all child processes created by the new process. It can receive all related debug events using the WaitForDebugEvent function. /// A process that uses DEBUG_PROCESS becomes the root of a debugging chain. This continues until another process in the chain is created with DEBUG_PROCESS. /// If this flag is combined with DEBUG_ONLY_THIS_PROCESS, the caller debugs only the new process, not any child processes. /// </summary> DEBUG_PROCESS = 0x00000001, /// <summary> /// The calling thread starts and debugs the new process. It can receive all related debug events using the WaitForDebugEvent function. /// </summary> DEBUG_ONLY_THIS_PROCESS = 0x00000002, /// <summary> /// The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called. /// </summary> CREATE_SUSPENDED = 0x00000004, /// <summary> /// For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console. /// This value cannot be used with CREATE_NEW_CONSOLE. /// </summary> DETACHED_PROCESS = 0x00000008, /// <summary> /// The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console. /// This flag cannot be used with DETACHED_PROCESS. /// </summary> CREATE_NEW_CONSOLE = 0x00000010, /// <summary> /// The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process identifier of the new process group is the same as the process identifier, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a CTRL+BREAK signal to a group of console processes. /// If this flag is specified, CTRL+C signals will be disabled for all processes within the new process group. /// This flag is ignored if specified with CREATE_NEW_CONSOLE. /// </summary> CREATE_NEW_PROCESS_GROUP = 0x00000200, /// <summary> /// If this flag is set, the environment block pointed to by lpEnvironment uses Unicode characters. Otherwise, the environment block uses ANSI characters. /// </summary> CREATE_UNICODE_ENVIRONMENT = 0x00000400, /// <summary> /// This flag is valid only when starting a 16-bit Windows-based application. If set, the new process runs in a private Virtual DOS Machine (VDM). By default, all 16-bit Windows-based applications run as threads in a single, shared VDM. The advantage of running separately is that a crash only terminates the single VDM; any other programs running in distinct VDMs continue to function normally. Also, 16-bit Windows-based applications that are run in separate VDMs have separate input queues. That means that if one application stops responding momentarily, applications in separate VDMs continue to receive input. The disadvantage of running separately is that it takes significantly more memory to do so. You should use this flag only if the user requests that 16-bit applications should run in their own VDM. /// </summary> CREATE_SEPARATE_WOW_VDM = 0x00000800, /// <summary> /// The flag is valid only when starting a 16-bit Windows-based application. If the DefaultSeparateVDM switch in the Windows section of WIN.INI is TRUE, this flag overrides the switch. The new process is run in the shared Virtual DOS Machine. /// </summary> CREATE_SHARED_WOW_VDM = 0x00001000, /// <summary> /// The process is to be run as a protected process. The system restricts access to protected processes and the threads of protected processes. For more information on how processes can interact with protected processes, see Process Security and Access Rights. /// To activate a protected process, the binary must have a special signature. This signature is provided by Microsoft but not currently available for non-Microsoft binaries. There are currently four protected processes: media foundation, audio engine, Windows error reporting, and system. Components that load into these binaries must also be signed. Multimedia companies can leverage the first two protected processes. For more information, see Overview of the Protected Media Path. /// Windows Server 2003 and Windows XP/2000: This value is not supported. /// </summary> CREATE_PROTECTED_PROCESS = 0x00040000, /// <summary> /// The process is created with extended startup information; the lpStartupInfo parameter specifies a STARTUPINFOEX structure. /// Windows Server 2003 and Windows XP/2000: This value is not supported. /// </summary> EXTENDED_STARTUPINFO_PRESENT = 0x00080000, /// <summary> /// The child processes of a process associated with a job are not associated with the job. /// If the calling process is not associated with a job, this constant has no effect. If the calling process is associated with a job, the job must set the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit. /// </summary> CREATE_BREAKAWAY_FROM_JOB = 0x01000000, /// <summary> /// Allows the caller to execute a child process that bypasses the process restrictions that would normally be applied automatically to the process. /// Windows 2000: This value is not supported. /// </summary> CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, /// <summary> /// The new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. /// This feature is particularly useful for multi-threaded shell applications that run with hard errors disabled. /// The default behavior is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior. /// </summary> CREATE_DEFAULT_ERROR_MODE = 0x04000000, /// <summary> /// The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. /// This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS. /// </summary> CREATE_NO_WINDOW = 0x08000000, } [Flags] public enum STARTF : uint { STARTF_USESHOWWINDOW = 0x00000001, STARTF_USESIZE = 0x00000002, STARTF_USEPOSITION = 0x00000004, STARTF_USECOUNTCHARS = 0x00000008, STARTF_USEFILLATTRIBUTE = 0x00000010, STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms STARTF_FORCEONFEEDBACK = 0x00000040, STARTF_FORCEOFFFEEDBACK = 0x00000080, STARTF_USESTDHANDLES = 0x00000100, } public enum ShowWindow : short { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_FORCEMINIMIZE = 11, SW_MAX = 11 } } } "@ Write-Verbose $source # Using the OutputAssembly and OutputType we can make an executable out of this. It requires the System.ServiceProcess assembly also to inherit the ServiceBase class. Add-Type -TypeDefinition $source -Language CSharpVersion3 -OutputAssembly ("$servicePath$serviceName.exe") -OutputType ConsoleApplication -ReferencedAssemblies "System.ServiceProcess" # Use WMI to create the service, it does not require DesktopInteract # The computer is the localhost cause this code will be run on the remote computer locally. $computer = "." $class = "Win32_Service" $method = "Create" $mc = [wmiclass]"\\\\$computer\\ROOT\\CIMV2:$class" $inparams = $mc.PSBase.GetMethodParameters($method) $inparams.DesktopInteract = $false $inparams.DisplayName = $serviceDisplayName $inparams.ErrorControl = 0 $inparams.LoadOrderGroup = $null $inparams.LoadOrderGroupDependencies = $null $inparams.Name = $serviceDisplayName.Replace(" " ,"_") $inparams.PathName = ("$servicePath$serviceName.exe") $inparams.ServiceDependencies = $null $inparams.ServiceType = 16 $inparams.StartMode = "Automatic" # Will start as localsystem builtin if null $inparams.StartName = $null $inparams.StartPassword = $null # Invoke the WMI method to create a service $result = $mc.PSBase.InvokeMethod($method,$inparams,$null) Start-Service -DisplayName $serviceDisplayName # Loop until the child process of Powershell.exe is gone. $baseproc = Get-WMIObject Win32_Process | Where { $_.Name -eq $serviceName } While (Get-WMIObject Win32_Process | Where { $_.ParentProcessId -eq $baseproc.ProcessId }) { Sleep 1 } # Terminate While Stop-Service -DisplayName $serviceDisplayName # Use sc.exe to delete the service, if you only use WMI to do this, it will not disappear until next restart, this deletes it immediately C:\\Windows\\System32\\sc.exe delete $serviceDisplayName.Replace(" " ,"_") | Out-Null # Clean up created files Remove-Item -Path ("$servicePath$serviceName.exe") -Force Remove-Item -Path ("$servicePath$serviceName.pdb") -Force Remove-Item -Path $outputFile -Force } Else { Write-Host "No active sessions" } # Terminate If - Active User } # Terminate Scriptblock If (Test-Connection $computerName -Quiet) { Try { Invoke-Command ` -ComputerName $computerName ` -ScriptBlock $scriptblock ` -ArgumentList $inputCode,$outputFile,$servicePath,$serviceName } Catch { Write-Warning "Unable to create remote session: $($_.Exception.Message)" Break } # Terminate Try-Catch } # Terminate If - Test Connection } # Terminate Process <# .SYNOPSIS Invoke remote code impersonating the currently logged on user. .PARAMETER computername Computer to run the remote code on. .PARAMETER inputCode The code to run on the remote computer. .PARAMETER outputFile The output data from a file. .INPUTS The input is a computer. .OUTPUTS The output is the returned data from .EXAMPLE C:\\PS> $code = "Out-File -FilePath c:\\temp\\output.txt -InputObject ([Security.Principal.WindowsIdentity]::GetCurrent())" C:\\PS> Invoke-RemoteCommand -inputCode $code #> } # Terminate Function
PowerShellCorpus/PoshCode/Generate Random Data.ps1
Generate Random Data.ps1
$dictionaryWords = gc $dictionaryFile $azLower = 'abcdefghijklmnopqrstuvwxyz'.ToCharArray() $azUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.ToCharArray() $hex = '012345679ABCDEF'.ToCharArray() $digit = '0123456789'.ToCharArray() $alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.ToCharArray() function RandomVIN { $url = 'http://randomvin.com/getAjax.php?qry=random&str=random&p9=0' $client = New-Object System.Net.WebClient $client.DownloadString($url).SubString(4,17) } function RandomWord { $dictionaryWords | Get-Random } function RandomString([int] $len, [Array] $charSet = $azLower) { [String]::Join('', (1..$len | % { $charSet | Get-Random })) } function RandomPlate { (RandomString -len 3 -charset $azUpper) + "-" + (Get-Random -min 100 -max 999) } function RandomIPv4 { [IPAddress]::Parse([String] (Get-Random) ) } function RandomHexByte { "{0:X2}" -f (Get-Random -Minimum 0 -Maximum 255) } function RandomMAC { [String]::Join(":", (1..8 | % { RandomHexByte })) } function RandomDateTime { ([DateTime]::Now).AddYears((Get-Random -min -1 -max 1)).AddMonths((Get-Random -min -11 -max 11)).AddDays((Get-Random -min -30 -max 30)).AddHours((Get-Random -min -23 -max 23)).AddMinutes((Get-Random -min -59 -max 59)).AddSeconds((Get-Random -min -59 -max 59)) }
PowerShellCorpus/PoshCode/Select-ToString_2.ps1
Select-ToString_2.ps1
[CmdletBinding(DefaultParameterSetName='DefaultParameter')] param( [Parameter(ValueFromPipeline=$true)] [System.Management.Automation.PSObject] ${InputObject}, [Parameter(ParameterSetName='DefaultParameter', Position=0, Mandatory=$true)] [System.String[]] ${Property}, [Parameter(ParameterSetName='DefaultParameter')] [System.String[]] ${ExcludeProperty}, [Parameter(ParameterSetName='DefaultParameter')] [System.String] ${ExpandProperty}, [Switch] ${Unique}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Last}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${First}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Skip}, [Parameter(ParameterSetName='IndexParameter')] [ValidateRange(0, 2147483647)] [System.Int32[]] ${Index} ) begin { try { $propHash = @() foreach($Prop in $Property) { $propHash += @(@{Name=$Prop; Expression=$(iex "{if(`$_.'$Prop' -is [Array]){ ""{`$(`$_.'$Prop' -join "", "")}"" }else{ `$_.'$Prop' } }")}) } $PSBoundParameters['Property'] = $propHash $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Select-Object', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Select-Object .ForwardHelpCategory Cmdlet #>
PowerShellCorpus/PoshCode/Convert-BounceToX_9.ps1
Convert-BounceToX_9.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }