full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Compare 2 foldertrees.ps1
Compare 2 foldertrees.ps1
function Compare-Foldertrees { param( $path1, $path2 ) $len1 = $path1.length $len2 = $path2.length . Require-function Get-MD5 Write-Host "====== First path only =======`n" gci $path1 -rec | ? {! $_.PSISContainer} | % { $fileName1 = $_.fullName $fileName = $fileName1.substring($len1) $filename2 = $path2 + $fileName #$filename1 #$filename2 if (! (Test-Path $filename2)) { "$filename" } } Write-Host "`n====== Second path only =======`n" gci $path2 -rec | ? {! $_.PSISContainer} | % { $fileName2 = $_.fullName $fileName = $fileName2.substring($len2) $filename1 = $path2 + $fileName #$filename1 #$filename2 if (! (Test-Path $filename1)) { "$filename" } } Write-Host "`n====== Different =======`n" gci $path1 -rec | ? {! $_.PSISContainer} | % { $fileName1 = $_.fullName $fileName = $fileName1.substring($len1) $filename2 = $path2 + $fileName #$filename1 #$filename2 if ( (Test-Path $filename2)) { $md1 = Get-MD5($filename1) $md2 = Get-MD5($filename2) if ($md1 -ne $md2) { "$filename" } } } }
PowerShellCorpus/PoshCode/powershell ise config.ps1
powershell ise config.ps1
<configuration> <startup> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> <process> <rollForward enabled="false" /> </process> </startup> <runtime> <loadFromRemoteSources enabled="true"/> </runtime> </configuration>
PowerShellCorpus/PoshCode/Test-ADCredentials.ps1
Test-ADCredentials.ps1
Function Test-ADCredentials { Param($username, $password, $domain) Add-Type -AssemblyName System.DirectoryServices.AccountManagement $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct, $domain) New-Object PSObject -Property @{ UserName = $username; IsValid = $pc.ValidateCredentials($username, $password).ToString() } }
PowerShellCorpus/PoshCode/Get Active Sync devices .ps1
Get Active Sync devices .ps1
<# .SYNOPSIS Get-InactiveActiveSyncDevices pulls all user mailboxes with an Active Sync partnership and then selects the Active Sync devices that haven't synced in the specified period. These devices are sorted in ascending order and placed in a HTML table which is emailed to the specified user using a specified reply to address and SMTP server PLEASE TEST BEFORE RUNNING THIS SCRIPT IN PRODUCTION .DESCRIPTION The script 1st checks to see if Implicit remoting is needed to load the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010), this is done by seeing it the $ExchangeConnectionUri variable does not have a $NULL value. If it contains a URI then create a new PSsession using the current credentials and import the session. If Implict remoting isn't needed then verify that the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010) is loaded and if not try to load it locally. Then Get-InactiveActiveSyncDevices uses Get-CasMailbox to pull all the user mailboxes (Not Discovery or CAS mailboxes) with Active Sync device partnerships and saves them to a variable called $ActiveSyncMailboxes. It then walks through each mailbox and uses Get-ActiveSyncDeviceStatistics to pull DeviceType, DeviceUserAgent, DeviceID, LastSyncAttemptTime, LastSuccessSync for each mailboxís separate Active Sync device partnership and puts these properties in addition to the full name associated with the mailbox into a hashtable called $UserActiveSyncStats. The reason why Get- ActiveSyncDeviceStatistics isnít used exclusively is because it does not have a property that stores just the name of the user who owns the Active Sync device, only a full Active Directory path to the Active Sync device. This hash table is used to create a custom PowerShell Object which is then added to $ActiveSyncDeviceList. A variable called $MatchingActiveSyncDevices holds all the Active Sync devices in $ActiveSyncDeviceList that havenít synced to the Exchanger server in less than or equal to the number of hours specified in $HourInterval . $MatchingActiveSyncDevices is then checked to see if itís an empty array or not. If it contains items an HTML header is created to format the table for the HTML email report and saved in a variable called $HTMLHeader . Then The Body of the email contains all of the criteria matching Active Sync devices from $MatchingActiveSyncDevices in ascending order which is converted to HTML using the HTML header information created earlier in $HTMLHeader. Otherwise a the body contains a message stating that no devices matched the given criteria.. An Email is then sent out to the user specified in $to from the address specified in $from using the email server specified in $SmtpServer. The body is generated from the sorted Active Synce Devices in $ActiveSyncDeviceList. .PARAMETER to The email address the email report will go to .PARAMETER from The email address the email report will come from .PARAMETER SmtpServer The IP address or DNS name of the SMTP server that will be used to send the email report .PARAMETER HourInterval The interval in hours. Any mailbox that hasn't synced to the Exchnage server .PARAMETER ExchangeConnectionUri URI of Powershell Session on an Exchange 2010 server. Used if the PC running this script does not have the required PSsnapin loaded .EXAMPLE Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer Mail.company.com -HourInterval 24 Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com .EXAMPLE Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer 10.10.50.100 -HourInterval 24 Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com .EXAMPLE Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer 10.10.50.100 -HourInterval 24 -ExchangeConnectionUri http://mail.company.com/PowerShell/ Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com using the Exchange Connection Uri of http://mail.company.com/PowerShell/ in order to use implicit remoting to pull in the required PSsnapin .NOTES NAME: Get-InactiveActiveSyncDevices AUTHOR: John Mello AUTHOR WEBSITE: mellositmusings.com LASTEDIT: 02/17/2013 KEYWORDS: Exchange 2010, Active Synce .LINK Latest version can be found at : http://gallery.technet.microsoft.com/scriptcenter/Get-Active-Sync-devices-9bfb5116 #Requires -Version 2.0 #> [cmdletbinding()] Param ( [Parameter(Mandatory=$True,HelpMessage="Enter a email address to send the report too")] [string]$to, [Parameter(Mandatory=$True,HelpMessage="Enter the email address the report should come from")] [string]$from, [Parameter(Mandatory=$True,HelpMessage="Enter the IP or DNS name of the mail server that will send the report")] [string]$SmtpServer, [Parameter(Mandatory=$True,HelpMessage="Enter the hour interval to check against (e.g. 24)")] [int]$HourInterval, $ExchangeConnectionUri = $NULL ) Write-Verbose "Checking if implict remoting to an Exchnage 2010 server was specified" if ($ExchangeConnectionUri -eq $NULL) { Write-Verbose "Checking for Microsoft.Exchange.Management.PowerShell.E2010 PSSnapin" if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $NULL ) { Write-Verbose "Microsoft.Exchange.Management.PowerShell.E2010 not installed, intalling now" Add-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 } Else { Write-Verbose "Microsoft.Exchange.Management.PowerShell.E2010 PSSnapin is installed" } } Else { Write-Verbose "Creating Implict remoting to $ExchangeConnectionUri" $ExchangeImplictSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeConnectionUri -Authentication Kerberos Write-Verbose "Importing session" Import-PSSession $ExchangeImplictSession } Write-Verbose "Get all Mailboxes using Get-CASMailbox and filter by the HasActiveSyncDevicePartnership property but do not include CAS or Discovery Mailboxes" $ActiveSyncMailboxes = Get-CASMailbox -ResultSize unlimited -Filter{(HasActiveSyncDevicePartnership -eq $true) -AND (name -notlike "cas_*") -AND (name -notlike "DiscoverysearchMailbox*")} Write-Verbose "Start Processing list" $ActiveSyncDeviceList = $ActiveSyncMailboxes | ForEach-Object { Write-Verbose 'Pull the active sync device/devices from the current mailbox in $ActiveSyncMailboxes' $CurrentDevice = Get-ActiveSyncDeviceStatistics ñMailbox $_.Identity $VerboseNameHold=$_.Name Write-Verbose "Use an IF statement to check if the Mailbox belonging to $VerboseNameHold has multiple Active Sync Devices" If ($CurrentDevice -is [Array]) { Write-Verbose "User $VerboseNameHold has multiple Active Sync devices" $Index = 0 Write-Verbose "Active sync device index = $Index" $VerboseTotalDeviceHold = $CurrentDevice.count $VerboseIndexHold = $Index + 1 ForEach($Device in $CurrentDevice) { Write-Verbose "Current mailbox belonging to $VerboseNameHold has multiple devices currently on device # $VerboseIndexHold of $VerboseTotalDeviceHold" Write-Verbose "Putting Active Device Statistics into a hash table" $UserActiveSyncStats = @{ Name=$_.Name DeviceType=$CurrentDevice[$index].DeviceType DeviceUserAgent=$CurrentDevice[$index].DeviceUserAgent DeviceID=$CurrentDevice[$index].DeviceID LastSyncAttemptTime=$CurrentDevice[$index].LastSyncAttemptTime LastSuccessSync=$CurrentDevice[$index].LastSuccessSync } Write-Verbose 'Creating a new Object using the $UserActiveSyncStats hashtable to create the properties, this will become an array entry in $ActiveSyncDeviceList' New-Object -TypeName PSObject -Property $UserActiveSyncStats $index++ $VerboseIndexHold++ Write-Verbose "Active Sync Device index incremented to $index" } } Else { Write-Verbose "Current mailbox beloning to $VerboseNameHold does not have multiple devices" Write-Verbose "Putting Active Device Statistics into a hash table" $UserActiveSyncStats = @{ Name=$_.Name DeviceType=$CurrentDevice.DeviceType DeviceUserAgent=$CurrentDevice.DeviceUserAgent DeviceID=$CurrentDevice.DeviceID LastSyncAttemptTime=$CurrentDevice.LastSyncAttemptTime LastSuccessSync=$CurrentDevice.LastSuccessSync } Write-Verbose 'Creating a new Object using the $UserActiveSyncStats hashtable to create the properties, this will become an array entry in $ActiveSyncDeviceList' New-Object -TypeName PSObject -Property $UserActiveSyncStats } } $CurrentDateandTime = Get-date Write-Verbose "Saving Current date ($CurrentDateandTime) to a variable so that the same date is used for comparison to specified interval ($HoustsInterval)" $date = $CurrentDateandTime.AddHours(-$HourInterval) Write-Verbose "Subtracting ${HourInterval}hrs from todays date" Write-Verbose "Finding devices that haven't synced since $date" $MatchingActiveSyncDevices = $ActiveSyncDeviceList | Where-Object {$_.LastSuccessSync -le $date} Write-Verbose 'Checking $MatchingActiveSyncDevices to see if it contains any devices that match tne criteria' If ($MatchingActiveSyncDevices.count -gt 0) { Write-Verbose '$MatchingActiveSyncDevices is not an empty array, devices that match the criteria have been found' Write-Verbose "Creating html header for email body" $HTMLHeader = "<Style>" $HTMLHeader = $HTMLHeader + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse}" $HTMLHeader = $HTMLHeader + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: DarkGray}" $HTMLHeader = $HTMLHeader + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: PaleTurquoise}" $HTMLHeader = $HTMLHeader + "</Style>" Write-Verbose "Creating email body which incldues all devices that havent synced in the ${HourInterval}hrs" $body = $MatchingActiveSyncDevices | sort LastSuccessSync | ConvertTo-html -head $HTMLHeader -Property Name,LastSuccessSync,DeviceType,DeviceUserAgent,DeviceID,LastSyncAttemptTime | Out-String } Else { Write-Verbose '$MatchingActiveSyncDevices is an empty array, no devices that match the criteria have been found' $body = "All Active Sync devices have synced with the Exchange Server within the past ${HourInterval}hrs" } Write-Verbose "Creating Email Subject" $Subject = "Active Sync device report for " $Subject += $CurrentDateandTime.ToShortDateString() $Subject += " : " $Subject += $MatchingActiveSyncDevices.count $Subject += " devices haven't synced in the past ${HourInterval}hrs since " $Subject += $CurrentDateandTime.ToShortTimeString() $Subject += " today" Write-Verbose "Sending email from $from to $to via the following email server : $SmtpServer" Send-MailMessage -to $to -Subject $Subject -From $from -SmtpServer $SmtpServer -Body $Body -BodyAsHtml
PowerShellCorpus/PoshCode/vCenterRetentionPolicy.ps1
vCenterRetentionPolicy.ps1
function Get-vCenterRetentionPolicy { $settings = get-view -id OptionManager-VpxSettings if ($settings) { $maxAge = ($settings.Setting | where { $_.Key -eq "task.maxAge" }).Value $maxAgeEnabled = ($settings.Setting | where { $_.Key -eq "task.maxAgeEnabled" }).Value $obj = New-Object -TypeName PSObject $obj | Add-Member -MemberType NoteProperty -Name "MaxAge (Days)" -Value $maxAge $obj | Add-Member -MemberType NoteProperty -Name "Enabled" -Value $maxAgeEnabled Write-Output $obj } }
PowerShellCorpus/PoshCode/Out-DataTable_4.ps1
Out-DataTable_4.ps1
####################### function Get-Type { param($type) $types = @( 'System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal', 'System.Double', 'System.Guid', 'System.Int16', 'System.Int32', 'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32', 'System.UInt64') if ( $types -contains $type ) { Write-Output "$type" } else { Write-Output 'System.String' } } #Get-Type ####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-psdrive| Out-DataTable This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties v1.4 - Chad Miller - Corrected issue with DBNull v1.5 - Chad Miller - Updated example v1.6 - Chad Miller - Added column datatype logic with default to string .LINK http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx #> function Out-DataTable { [CmdletBinding()] param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) Begin { $dt = new-object Data.datatable $First = $true } Process { foreach ($object in $InputObject) { $DR = $DT.NewRow() foreach($property in $object.PsObject.get_properties()) { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $property.Name.ToString() if ($property.value) { if ($property.value -isnot [System.DBNull]) { $Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)") } } $DT.Columns.Add($Col) } if ($property.IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/Deploy Multiple VMs v1.ps1
Deploy Multiple VMs v1.ps1
############################################################# # Deploy-VM.ps1 v1.1 # David Summers 2011/8/2 # Script to deploy VM(s) from Template(s) and set appropriate # IP config for Windows VMs. Also sets # of CPUs, MemoryMB, # port group, and several custom attributes. # Moves deployed VM to specific VMs/Template blue folder. # Assumptions: # not connected to viserver before running # Customization spec and templates in place and tested ############################################################# # Syntax and sample for CSV File: # template,datastore,diskformat,vmhost,custspec,vmname,ipaddress,subnet,gateway,pdns,sdns,pwins,swins,datacenter,folder,dvpg,memsize,cpucount,appgroup,owner,techcontact,vmdescription,createdate,reviewdate,creator # template.2008ent64R2sp1,DS1,thick,host1.domain.com,2008r2CustSpec,Guest1,10.50.35.10,255.255.255.0,10.50.35.1,10.10.0.50,10.10.0.51,10.10.0.50,10.10.0.51,DCName,FldrNm,dvpg.10.APP1,2048,1,Monitoring,Road Runner,WE Coyote,App1 Prod Web,2011.07.28,2014.07.28,Elmer Fudd # $vmlist = Import-CSV "H:\\Flats\\Scripts\\Input\\deployVMserverinfo.csv" # Load PowerCLI $psSnapInName = "VMware.VimAutomation.Core" if (-not (Get-PSSnapin -Name $psSnapInName -ErrorAction SilentlyContinue)) { # Exit if the PowerCLI snapin can't be loaded Add-PSSnapin -Name $psSnapInName -ErrorAction Stop } connect-viserver virtualcenter.yourdom.com foreach ($item in $vmlist) { # Map variables $template = $item.template $datastore = $item.datastore $diskformat = $item.diskformat $vmhost = $item.vmhost $custspec = $item.custspec $vmname = $item.vmname $ipaddr = $item.ipaddress $subnet = $item.subnet $gateway = $item.gateway $pdns = $item.pdns $pwins = $item.pwins $sdns = $item.sdns $swins = $item.swins $datacenter = $item.datacenter $destfolder = $item.folder $dvpg = $item.dvpg $memsize = $item.memsize $cpucount = $item.cpucount $appgroup = $item.appgroup $owner = $item.owner $technicalcontact = $item.techcontact $description = $item.vmdescription $createdate = $item.createdate $reviewdate = $item.reviewdate $creator = $item.creator #Configure the Customization Spec info Get-OSCustomizationSpec $custspec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $ipaddr -SubnetMask $subnet -DefaultGateway $gateway -Dns $pdns,$sdns -Wins $pwins,$swins #Deploy the VM based on the template with the adjusted Customization Specification New-VM -Name $vmname -Template $template -Datastore $datastore -DiskStorageFormat $diskformat -VMHost $vmhost | Set-VM -OSCustomizationSpec $custspec -Confirm:$false #Move VM to Application Group's folder Get-vm -Name $vmname | move-vm -Destination $(Get-Folder -Name $DestFolder -Location $(Get-Datacenter $Datacenter)) #Set the Port Group Network Name (Match PortGroup names with the VLAN name) Get-VM -Name $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $dvpg -Confirm:$false #Set the number of CPUs and MB of RAM Get-VM -Name $vmname | Set-VM -MemoryMB $memsize -NumCpu $cpucount -Confirm:$false #Set the Custom Attribute Annotations #Comment out or adjust to fit your environment Set-annotation -Entity $vmname -CustomAttribute "App Group" -Value $AppGroup -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Owner" -Value $Owner -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Technical Contact" -Value $TechnicalContact -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Description" -Value $Description -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Create Date" -Value $CreateDate -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Review Date" -Value $ReviewDate -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Creator" -Value $Creator -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Timeline" -Value "New" -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Datacenter" -Value $item.datacenter -Confirm:$false }
PowerShellCorpus/PoshCode/Access Jira (REST).ps1
Access Jira (REST).ps1
param($Issue, $Credentials = $(Get-Credential), $BaseURI = "https://your.jira.server/jira") function ConvertTo-UnsecureString( [System.Security.SecureString][parameter(mandatory=$true)]$SecurePassword) { $unmanagedString = [System.IntPtr]::Zero; try { $unmanagedString = [Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($SecurePassword) return [Runtime.InteropServices.Marshal]::PtrToStringUni($unmanagedString) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($unmanagedString) } } function ConvertTo-Base64($string) { $bytes = [System.Text.Encoding]::UTF8.GetBytes($string); $encoded = [System.Convert]::ToBase64String($bytes); return $encoded; } function ConvertFrom-Base64($string) { $bytes = [System.Convert]::FromBase64String($string); $decoded = [System.Text.Encoding]::UTF8.GetString($bytes); return $decoded; } function Get-HttpBasicHeader($Credentials, $Headers = @{}) { $b64 = ConvertTo-Base64 "$($Credentials.UserName):$(ConvertTo-UnsecureString $Credentials.Password)" $Headers["Authorization"] = "Basic $b64" return $Headers } if($Issue) { $uri = "$BaseURI/rest/api/2/issue/$Issue" } else { $uri = "$BaseURI/rest/api/2/mypermissions" } $headers = Get-HttpBasicHeader $Credentials Invoke-RestMethod -uri $uri -Headers $headers -ContentType "application/json"
PowerShellCorpus/PoshCode/Get-Parameter 2.0.ps1
Get-Parameter 2.0.ps1
#Requires -version 2.0 #.Synopsys # Enumerates the parameters of one or more commands #.Notes # With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy # Version 0.* - By Hal Rottenberg http://poshcode.org/549 # Version 0.* - By Oisín Grehan http://poshcode.org/446 # - Added resolving aliases and avoided empty output # Version 1.* - By Joel Bennett http://poshcode.org/1592 # - Merged Oisín and Hal's code with my own implementation # - Added calculation of dynamic paramters # Version 2.0 - By Joel Bennett (this version): # - Now uses FormatData so the output is objects # - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation) #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter Name # The name of the command to get parameters for #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] ##This is just script-file nesting stuff, so that you can call the SCRIPT, and after it defines the global function, it will call it. param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) Function global:Get-Parameter { #.Synopsis # Enumerates the parameters of one or more commands #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter Name # The name of the command to get parameters for #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) begin { $PropertySet = @( "Name", @{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}}, "Aliases", @{n="Short";e={$_.Name}}, @{n="Type";e={$_.ParameterType.Name}}, @{n="ParameterSet";e={$paramset}}, @{n="Command";e={$command}}, @{n="Mandatory";e={$_.IsMandatory}}, @{n="Provider";e={$_.DynamicProvider}}, @{n="ValueFromPipeline";e={$_.ValueFromPipeline}}, @{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}} ) function Join-Object { Param( [Parameter(Position=0)] $First , [Parameter(ValueFromPipeline=$true,Position=1)] $Second ) begin { [string[]] $p1 = $First | gm -type Properties | select -expand Name } process { $Output = $First | Select $p1 foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) { Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p" } $Output } } } process{ foreach($cmd in $Name) { if($ModuleName) { $cmd = "$ModuleName\\$cmd" } $commands = @(Get-Command $cmd) foreach($command in $commands) { # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = @(Get-Command ($command.definition))[0] } if (-not $command) { continue } $Parameters = @{} foreach($provider in Get-PSProvider) { $drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters") $MoreParameters = Get-Command $command -Args $drive | Select -Expand Parameters $Dynamic = $MoreParameters | Select -Expand Values | Where { $_.IsDynamic } foreach($k in $Parameters.Keys | Where { $Dynamic.Keys -notcontains $_ } ){ $null = $MoreParameters.Remove($k) } $Parameters += $MoreParameters # Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)" if($dynamic) { foreach($d in $dynamic) { if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) { Write-Debug ("ADD:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name).DynamicProvider += $provider.Name } else { Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru } } } } ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else. foreach($p in $($Parameters.Keys)) { $shortest="^" foreach($char in [char[]]$p) { $shortest += $char $Matches = ($Parameters.Keys -match $Shortest).Count Write-Debug "$($shortest.SubString(1)) $Matches" if($Matches -eq 1) { $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru break } } } Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)" foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){ foreach($parameter in $Parameters.Keys | Sort) { Write-Verbose "Parameter: $Parameter" if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue } if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) { if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet } else { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets } Write-Output $Output | Select-Object $PropertySet | ForEach { $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata") $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx") Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")" $_ } } } } } } } } # Since you can't update format data without a file that has a ps1xml ending, let's make one up... $tempFile = "$([IO.Path]::GetTempFileName()).ps1xml" Set-Content $tempFile @' <?xml version="1.0" encoding="utf-8" ?> <Configuration> <Controls> <Control> <Name>ParameterGroupingFormat</Name> <CustomControl> <CustomEntries> <CustomEntry> <CustomItem> <Frame> <LeftIndent>4</LeftIndent> <CustomItem> <Text>Command: </Text> <ExpressionBinding> <ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock> </ExpressionBinding> <NewLine/> <Text>Set: </Text> <ExpressionBinding> <ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock> </ExpressionBinding> <NewLine/> </CustomItem> </Frame> </CustomItem> </CustomEntry> </CustomEntries> </CustomControl> </Control> </Controls> <ViewDefinitions> <View> <Name>ParameterMetadataEx</Name> <ViewSelectedBy> <TypeName>System.Management.Automation.ParameterMetadataEx</TypeName> </ViewSelectedBy> <GroupBy> <PropertyName>ParameterSet</PropertyName> <CustomControlName>ParameterGroupingFormat</CustomControlName> </GroupBy> <TableControl> <TableHeaders> <TableColumnHeader> <Label>Name</Label> <Width>22</Width> </TableColumnHeader> <TableColumnHeader> <Label>Aliases</Label> <Width>12</Width> </TableColumnHeader> <TableColumnHeader> <Label>Position</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>Mandatory</Label> <Width>9</Width> </TableColumnHeader> <TableColumnHeader> <Label>Pipeline</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>ByName</Label> <Width>6</Width> </TableColumnHeader> <TableColumnHeader> <Label>Provider</Label> <Width>15</Width> </TableColumnHeader> <TableColumnHeader> <Label>Type</Label> </TableColumnHeader> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Aliases</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Position</PropertyName--> <ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Mandatory</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipeline</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipelineByPropertyName</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Provider</PropertyName--> <ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Type</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> </ViewDefinitions> </Configuration> '@ Update-FormatData -Append $tempFile # This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that. Get-Parameter @PSBoundParameters
PowerShellCorpus/PoshCode/Set-Clipboard.ps1
Set-Clipboard.ps1
#############################################################################\n##\n## Set-Clipboard\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\nSends the given input to the Windows clipboard.\n\n.EXAMPLE\n\ndir | Set-Clipboard\nThis example sends the view of a directory listing to the clipboard\n\n.EXAMPLE\n\nSet-Clipboard "Hello World"\nThis example sets the clipboard to the string, "Hello World".\n\n#>\n\nparam(\n ## The input to send to the clipboard\n [Parameter(ValueFromPipeline = $true)]\n [object[]] $InputObject\n)\n\nbegin\n{\n Set-StrictMode -Version Latest\n $objectsToProcess = @()\n}\n\nprocess\n{\n ## Collect everything sent to the script either through\n ## pipeline input, or direct input.\n $objectsToProcess += $inputObject\n}\n\nend\n{\n ## Launch a new instance of PowerShell in STA mode.\n ## This lets us interact with the Windows clipboard.\n $objectsToProcess | PowerShell -NoProfile -STA -Command {\n Add-Type -Assembly PresentationCore\n\n ## Convert the input objects to a string representation\n $clipText = ($input | Out-String -Stream) -join "`r`n"\n\n ## And finally set the clipboard text\n [Windows.Clipboard]::SetText($clipText)\n }\n}
PowerShellCorpus/PoshCode/Check latest BIOS Rev.ps1
Check latest BIOS Rev.ps1
$BiosRev = Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName -Credential $Credentials # Shortened URL for the Dell Support page, fileid=441102, appears to be the identifier for BIOS downloads # I tested this on a few different models of Dell workstations. $DellBIOSPage = "http://support.dell.com/support/downloads/download.aspx?c=us&cs=RC956904&l=en&s=hied&releaseid=R294848&SystemID=PLX_960&servicetag=$($BiosRev.SerialNumber)&fileid=441102" # This HTML code immediately preceed's the actual service tag, you can see it when you 'view source' on the page $DellPageVersionString = "<span id=`"Version`" class=`"para`">" If ($BiosRev.Manufacturer -match "Dell") { $DellPage = (New-Object -TypeName net.webclient).DownloadString($DellBIOSPage) # Assuming that Dell BIOS rev's remain 3 characters, I find where my string starts and add the length to it # and the substring returns the BIOS rev. $DellCurrentBios = $DellPage.Substring($DellPage.IndexOf($DellPageVersionString)+$DellPageVersionString.Length,3) } If (($BiosRev.SMBIOSBIOSVersion -eq $DellCurrentBios) -eq $false) { # Something more interesting might go here, perhaps to actually download the latest installer Write-Host "For the latest bios for $($ComputerName)" Write-Host "Please visit $($DellBIOSPage)" }
PowerShellCorpus/PoshCode/VerifyCategoryRule_1.ps1
VerifyCategoryRule_1.ps1
## From Windows PowerShell Cookbook (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) Set-StrictMode -Version Latest if($message.Body -match "book") { [Console]::WriteLine("This is a message about the book.") } else { [Console]::WriteLine("This is an unknown message.") }
PowerShellCorpus/PoshCode/SqlProxy_8.psm1.ps1
SqlProxy_8.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 "Set-SqlLoginDefaultDatabase"=10 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" try { if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } catch { $message = $_.Exception.GetBaseException().Message write-error $message } } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } else { $server.Databases | where {$_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name=$name.Trim(), [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" try { $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase $login.LoginType = $logintype if ($logintype -eq 'SqlLogin') { if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } $login.Create($password) } else { $login.Create() } $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { if ($_.Exception.GetBaseException().Number -eq 15401 -and $psBoundParameters.name -match "\\\\" -and $global:Retry -ne $psBoundParameters.ChangeOrder) { $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' $splitName = $psBoundParameters.name -split "\\\\" if ($splitName[1] -cmatch $($splitName[1].ToUpper()) ) { $splitName[1] = $splitName[1].ToLower() } else { $splitName[1] = $splitName[1].ToUpper() } $psBoundParameters.name = $($splitName -join "\\") $global:Retry = $psBoundParameters.ChangeOrder Add-SqlLogin @psBoundParameters } else { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { if ($server.Information.Version.Major -eq '8') { $login.ChangePassword($password) } else { $login.ChangePassword($password,$true,$false) } $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | ?{$_.Key -ne 'password'} | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | ?{$_.Key -ne 'password'} | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLoginDefaultDatabase function changes a SQL Login default database. .INPUTS None You cannot pipe objects to Set-SqlLoginDefaultDatabase .OUTPUTS None This function does not generate any output. .EXAMPLE Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master' This command sets the default database for TestPSUnit login. .LINK Set-SqlLoginDefaultDatabase #> function Set-SqlLoginDefaultDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.DefaultDatabase = $DefaultDatabase $login.Alter() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLoginDefaultDatabase ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" try { $login = $server.Logins["$name"] if ($login) { $login.Rename("$newName") $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" try { $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login $loginObject = $sqlserver.Logins["$login"] if ($database.parent.Information.Version.Major -ne '8' -and $loginObject.LoginType -ne "WindowsGroup" ) { $user.DefaultSchema = $defaultschema } $user.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" try { $user = $database.Users[$name] if ($user) { $user.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "User $name does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.AddMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.DropMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.AddMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.DropMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog
PowerShellCorpus/PoshCode/Get-BogonList_2.ps1
Get-BogonList_2.ps1
function Get-BogonList { <# .SYNOPSIS Gets the bogon list. .DESCRIPTION The Get-BogonList function retrieves the bogon prefix list maintained by Team Cymru. A bogon prefix is a route that should never appear in the Internet routing table. A packet routed over the public Internet (not including over VPNs or other tunnels) should never have a source address in a bogon range. These are commonly found as the source addresses of DDoS attacks. Bogons are defined as Martians (private and reserved addresses defined by RFC 1918 and RFC 5735) and netblocks that have not been allocated to a regional internet registry (RIR) by the Internet Assigned Numbers Authority. Fullbogons are a larger set which also includes IP space that has been allocated to an RIR, but not assigned by that RIR to an actual ISP or other end-user. .PARAMETER Aggregated By default the unaggregated traditional bogon list is retrieved. Use this switch parameter to retrieve the aggregated list. .PARAMETER FullBogons Specifies that the full bogon list will be retrieved. .PARAMETER IPVersion Specifies which IP version of the full bogon list will be retrieved. The FullBogons parameter is required. .OUTPUTS PSObject .EXAMPLE Get-BogonList Retrieves the traditional unaggregated bogon list from Team Cymru. .EXAMPLE Get-BogonList -Aggregated Retrieves the traditional aggregated bogon list from Team Cymru. .EXAMPLE Get-BogonList -FullBogons Retrieves the full IPv4 bogon list from Team Cymru. .EXAMPLE Get-BogonList -FullBogons -IPVersion 6 Retrieves the full IPv6 bogon list from Team Cymru. .NOTES Name: Get-BogonList Author: Rich Kusak (rkusak@cbcag.edu) Created: 2010-01-31 LastEdit: 2011-05-05 23:45 Version: 1.2.0 #Requires -Version 2.0 .LINK http://www.team-cymru.org/Services/Bogons/ #> [CmdletBinding(DefaultParameterSetName='Traditional')] param ( [Parameter(ParameterSetName='Traditional')] [switch]$Aggregated, [Parameter(ParameterSetName='Full')] [switch]$FullBogons, [Parameter(ParameterSetName='Full')] [ValidateSet(4,6)] [int]$IPVersion = 4 ) # Create a web client object $webClient = New-Object System.Net.WebClient if ($psCmdlet.ParameterSetName -eq 'Traditional') { $referencePage = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/') -split "`n" $traditionalUpdated = $referencePage | Select-String 'Traditional Bogons Updated:' -SimpleMatch | ForEach {[regex]::Match($_, '\\d{2}\\s\\w+\\s\\d{4}').Value} $currentVersion = $referencePage | Select-String 'Current version:' -SimpleMatch | ForEach {[regex]::Match($_, '\\d+\\.\\d+').Value} # Display title, update, and version information Write-Host 'Team Cymru Traditional Bogon List' 'Updated: {0}' -f $traditionalUpdated 'Current version: {0}' -f $currentVersion # Retrieve and display the aggregated bogon list if ($Aggregated) { foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-agg.txt') -split "`n") { New-Object PSObject -Property @{'Aggregated Bogons' = $bogon} } # Retrieve and display the unaggregated bogon list } else { foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-nonagg.txt') -split "`n") { New-Object PSObject -Property @{'Unaggregated Bogons' = $bogon} } } } # if ($psCmdlet.ParameterSetName -eq 'Traditional') if ($psCmdlet.ParameterSetName -eq 'Full') { if (-not $FullBogons) { return Write-Error 'The FullBogons parameter is required to set the IPVersion.' } switch ($IPVersion) { 4 { $bogons = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/fullbogons-ipv4.txt') -split "`n" $propertyName = 'IPv4FullBogons' break } 6 { $bogons = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/fullbogons-ipv6.txt') -split "`n" $propertyName = 'IPv6FullBogons' break } } $fullUpdated = $bogons | Select -First 1 | ForEach {[regex]::Match($_, '\\(.+\\)').Value.Trim('()')} # Display title and update information Write-Host 'Team Cymru Full Bogon List' 'Updated: {0}' -f $fullUpdated # Create full bogon list output object foreach ($bogon in $bogons | Where {$_ -notmatch '#'}) { New-Object PSObject -Property @{$propertyName = $bogon} } } # if ($psCmdlet.ParameterSetName -eq 'Full') } # function Get-BogonList
PowerShellCorpus/PoshCode/NetBackup Backup Report.ps1
NetBackup Backup Report.ps1
################################################################################################### # # NAME: NBU-BackupReport.ps1 # # AUTHOR: Martijn Jonker # # COMMENT: Script to create a backup report from Netbackup jobs on windows platform. # Adjust variables below this section. # The script generates a report every weekday. Monday report covers the weekend. # To adjust this, edit lines 94-103 and 483-490 # # The script calls Netbackup commandline tools to gather information. # Job status is checked against three different arrays (Successful, partial, failed). # Depending on Status, Client, Policy, Schedule and EndTime lines are either added to or # removed from the arrays. # The script gathers statistics per policy/server about the backup operation, # (number of files backed up,size of files backed up and elapsed time), # so servers is multiple policies will show up multiple times in the statistics. # The script reports tape media and disk storage unit usage. # The script e-mails the result # # Run the script interactively, or as a scheduled task. # # The script requires "<Programdir>\\NetBackup\\bin\\admincmd" and # "<Programdir>\\NetBackup\\bin\\goodies" to be in the %path% ($Env:path) environment variable # # The script was tested with NetBackup 6.5, 6.5.5 and 7.0, # in a single master/media server environment. # # VERSION HISTORY: # 1.0: Transcoded from .vbs to .ps1 # 1.1: Added E-mail notification # 2.0: Rewrote logic for better efficiency # 2.1: Minor tweaks to date/time formatting # 3.0: Added Tape Media used for backup # Added Storage Unit Status # Added Backup statictics # 3.1: Documented script # Minor efficiency tweaks ################################################################################################### # --------------------------- Adjust variables below to suit your needs --------------------------- # $StartTime = "17:00:00" # Starttime for backup operation, in NBU format $Endtime = "17:00:00" # Endtime for backup operation, in NBU format $OutputPth = "C:\\scripts" # Path to $outputfile $OutputFile = "BackupReport.txt" # Name of outputfile $SmtpServer = "smtp.server" # Address of SMTP server $From = "netbackup@company.com" # From e-mail address $To = "report@company.com" # To e-mail address. Multiple addresses can be used, seperate by comma $CC = "CC-Recipients.txt" # Textfile containing e-mail addresses to CC, one per line. Located in $outputpth $ClientStringLength = 15 # Number of characters in the $client string, including whitespace $PolicyStringLength = 25 # Number of characters in the $Policy string, including whitespace $FileStringLength = 10 # Number of characters in the $Files string, including whitespace $KBStringLength = 12 # Number of characters in the $KBs string, including whitespace $ElapsedString = 10 # Number of characters in the $Elapsed string, including whitespace # # !> ---------------------------! Do not change anything beyond this point !--------------------------- <! # Switch (Test-Path $OutputPth) # Check if $OutputPth exists { False # If $OutputPth does not exist { New-Item $OutputPth -ItemType Directory | Out-Null # Create $OutputPth Write-Host "Output Path did not exist, it was created: $OutputPth" -ForegroundColor "White" # Write to console Write-Host "----------" -ForegroundColor "Yellow" # Write to console } } $OutputStr = $OutputPth + "\\" + $OutputFile # Combine $OutputPth and $OutputFile to a single string # --- $JobHeader = "STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED" # General header for backup job status $ClientNotReported = @("";"Servers that did not (yet) report any activity";"----------------------------------------------";("CLIENT"+" "*($ClientStringLength-6))+("POLICY"+" "*($PolicyStringLength-6))) # initialize array for servers that did not report activity at the time of running the report and add header $TotalOK = @() # Initialize array to contain the final results for all successful jobs $TotalPartial = @() # Initialize array to contain the final results for all partially successful jobs $TotalFail = @() # Initialize array to contain the final results for all failed jobs $UsedPolSched = @() # Initialize array to contain policies and schedules used during backup operation, used to report on disk storageunits. # --- $NBU_BaseTime = get-date "1/1/1970 00:00:00" # Netbackup Basetime, used to calculate elapsed time $TotalFiles = 0 # Initialize variable to contain the total number of files backed up $TotalKB = 0 # Initialize variable to contain the total KiloBytes backed up $NBUStats = @() # Initialize array to contain the backup operation statistics $NBUStatsHeader = @("";"BACKUP STATISTICS";("CLIENT"+" "*($ClientStringLength-6))+("POLICY"+" "*($PolicyStringLength-6))+("FILES"+" "*($FileStringLength-5))+("SIZE"+" "*($KBStringLength-4))+("ELAPSED"+" "*($ElapsedString-7))) # Array containing header for backup statistics $NBUStatsHeader += @("-"*$NBUStatsHeader[2].Length) # Add separator # --------------------------- Clear-Host # Set the console foreground color [console]::ForegroundColor = "White" # --------------------------- write to console Write-Host "" Write-Host "============================================================" -ForegroundColor "Yellow" Write-Host " NetBackup - Daily Report" Write-Host "============================================================" -ForegroundColor "Yellow" Write-Host "" Write-Host "" # --------------------------- $Now = Get-date # Store current date and time If (($Now.DayOfWeek -eq "Tuesday") -OR ($Now.DayOfWeek -eq "Wednesday") -OR ($Now.DayOfWeek -eq "Thursday") -OR ($Now.DayOfWeek -eq "Friday")) # For every weekday except monday { $StartDate = "{0:MM\\/dd\\/yyyy $StartTime}" -f ($Now.AddDays(-1)) # set the startdate back one day, using the previously set starttime } If ($Now.DayOfWeek -eq "Monday") # For every monday { $StartDate = "{0:MM\\/dd\\/yyyy $StartTime}" -f ($Now.AddDays(-3)) # set the startdate back three days (to encompass the weekend), using the previously set starttime } $EndDate = "{0:MM\\/dd\\/yyyy $Endtime}" -f ($Now) # set the enddate to today, using the previously set endtime # --------------------------- $NbuPolicyList = Invoke-Expression "bppllist" # Using NBU cmd get a list of all policies ForEach ($Policy in $NbuPolicyList) # Process all listed policies { # --- $OKHeader = @("";"Successful jobs during the $Policy backup") # header to add to below declared array $OKHeader += @("-"*$OKHeader[1].Length) # Add variable length horizontal separator $JobOK = New-Object System.Collections.ArrayList # Array to contain successful jobs $JobOK.Add($OKHeader) | Out-Null # Add header to array $JobOK.Add($JobHeader) | Out-Null # Add general header to array $JobOKCount=1 # Record count in array # --- $PartialHeader = @("";"Partially Successful jobs during the $Policy backup") # header to add to below declared array $PartialHeader += @("-"*$PartialHeader[1].Length) # Add variable length horizontal separator $JobPartial = New-Object System.Collections.ArrayList # Array to contain partially successful jobs $JobPartial.Add($PartialHeader) | Out-Null # Add header to array $JobPartial.Add($JobHeader) | Out-Null # Add general header to array $JobPartialCount=1 # Record count in array # --- $FailHeader = @("";"Failed jobs during the $Policy backup") # header to add to below declared array $FailHeader += @("-"*$FailHeader[1].Length) #Add variable length horizontal separator $JobFail = New-Object System.Collections.ArrayList # Array to contain failed jobs $JobFail.Add($FailHeader) | Out-Null # Add header to array $JobFail.Add($JobHeader) | Out-Null # Add general header to array $JobFailCount=1 # Record count in array # --- If ($Policy.Length -gt 16) # If policy name is longer than 16 chars { $PolicyFilter = $Policy.SubString(0,16).Trim() # Trim policy name down to 16 chars } Else { $PolicyFilter = $Policy } $PolicyDetails = Invoke-Expression "bppllist $Policy -L" # Using NBU cmd get policy details $PolicyActive = $PolicyDetails | Select-String "Active" | %{$_.ToString().SubString(19).Trim()} # From policy details, get the policy status $PolicyType = $PolicyDetails | Select-String "Policy Type:" | %{$_.ToString().SubString(19).Trim()} # From policy details, get the policy type If ($PolicyActive -eq "yes") # If policy is active, process it, inactive policies are not processed { $PolicyClientList = $PolicyDetails | select-String "Client/HW/OS/Pri:" | Sort-Object # From policy details, get the list of clients ForEach ($ClientStr in $PolicyClientList) { $Client = $ClientStr.ToString().Split()[2] # Extrapolate Client name If ($Client.Length -gt $ClientStringLength) # For report makeup check lenght of the string { $ClientStringLength = $Client.Length+3 # If necessary add three characters whitespace to the string } $ClientJobList = Invoke-Expression "bperror.exe -client $Client -U -backstat -s info -d $StartDate -e $EndDate 2>&1" | Select-String " $PolicyFilter" # Using NBU cmd get the jobs for currently processing client and narrow the selection of jobs to the currently processing policy #-- Start Statistics gathering for the currently processing policy and the currently processing client $ClientImages = Invoke-Expression "bpimagelist -client $Client -d $StartDate -e $EndDate 2>&1" | Select-String $Policy # Using NBU cmd get backup images for the currently processing client narrowed by the currently processing policy If (($ClientImages) -AND ($ClientImages.GetType().Name -ne "ErrorRecord")) # If backup images are available { ForEach ($Image in $ClientImages) # Process each backup image { $Image = $Image.ToString().Split() # Convert the current backup image line to a string and split the string at every space [Int32]$Files = $Image[19] # From the split string, get the number of files at row 19 [Int32]$KBs = $Image[18] # From the split string, get the KiloBytes at row 18 [Int32]$JobStart = $Image[13] # From the split string, get the start time (relative to the NBU_BaseTime in seconds) at row 13 [Int32]$JobEnd = ($JobStart+[Int32]$Image[14]) # From the split string, add the elapsed seconds at row 14 to the jobstart variable to get the endtime (relative to the NBU_BaseTime in seconds) $JobStartTime = $NBU_BaseTime.AddSeconds($JobStart) # Add the seconds from jobstart to NBU_BaseTime to get a datetime object for starttime $JobEndTime = $NBU_BaseTime.AddSeconds($JobEnd) # Add the seconds from jobend to NBU_BaseTime to get a datetime object for endtime $ElapsedTime = New-TimeSpan $JobStartTime $JobEndTime # Get a timespan for the elapsed time $TotalElapsedTime = ($TotalElapsedTime+$ElapsedTime) # Add the timespan to the total elapsed time for this policy $TotalFiles = ($TotalFiles+$Files) # Add the number of files to the total file count for this policy $TotalKB = ($TotalKB+$KBs) # Add the KiloBytes to the total KiloBytes for this policy } $TotalKB = ($TotalKB*1024) # mulitply by 1024 $GrandTotalKB = ($GrandTotalKB+$TotalKB) # Add totalkb to GrandTotalKB, aggregate for all policies $GrandTotalFiles = ($GrandTotalFiles+$TotalFiles) # Add totalfiles to GrandTotalFiles, aggregate for all policies If ($TotalKB -lt 1048576) # Format TotalKB to reflect: { $TotalKBs = "{0:N} KB" -f $($TotalKB/1KB) # KiloBytes or, } If (($TotalKB -ge 1048576) -AND ($TotalKB -lt 1073741824)) { $TotalKBs = "{0:N} MB" -f $($TotalKB/1MB) # MegaBytes or, } If (($TotalKB -ge 1073741824) -AND ($TotalKB -lt 1099511627776)) { $TotalKBs = "{0:N} GB" -f $($TotalKB/1GB) # GigaBytes or, } If ($TotalKB -ge 1099511627776) { $TotalKBs = "{0:N} TB" -f $($TotalKB/1TB) # TeraBytes } $TotalFiles = "{0:N0}" -f $TotalFiles # format the number for further processing $StatString = ($Client+" "*($ClientStringLength-$Client.Length))+($Policy+" "*($PolicyStringLength-$Policy.Length))+($TotalFiles+" "*($FileStringLength-$TotalFiles.Length))+($TotalKBs+" "*($KBStringLength-$TotalKBs.Length))+"$TotalElapsedTime" # Create a String per server, per policy with the following fields: CLIENT,POLICY,FILES,SIZE,ELAPSED $NBUStats += @($StatString) # Add the above string to the NBUStats array $TotalFiles = 0 # Reset variable $TotalKB = 0 # Reset variable $TotalKBs = 0 # Reset variable Clear-variable TotalElapsedTime # Reset variable } # --- End Statistics gathering If ($ClientJobList) # Process backup jobs for currently processing client if they are available { $ClientReported += @("$Client`t$PolicyType") # Add the client and policy name to array for checking ForEach ($Job in $ClientJobList) # Process each job { $Job = [String]$Job # Stringify the job $StatusCode = $Job.SubString(0,7).Trim() # From string $job, extract statuscode If (($StatusCode -eq "STATUS") -OR (!$StatusCode)) # If $statuscode equals "status" or is emtpy { Continue # Skip this job } Else { $StatusCode = [Int]$StatusCode # Set statuscode as integer } $JobClient = $Job.SubString(7,14).Trim() # From string $job, extract clientname $JobPolicy = $Job.SubString(21,17).Trim() # From string $job, extract policyname $JobSchedule = $Job.SubString(38,11).Trim() # From string $job, extract schedule If ($JobSchedule -match "Default") # If schedule matches "default", { Continue # skip this job } If ($UsedPolSched -notcontains "$Policy,$JobSchedule") # If this policy and schedule are not yet registered in the array, { $UsedPolSched += @("$Policy,$JobSchedule") # Register this policy and schedule in the array } $JobNBServer = $Job.SubString(49,12).Trim() # From string $job, extract NBU master server $JobTimeComplete = $Job.SubString(61).Trim() # From string $job, extract time completed # --- $ReadOKClient = $JobOK[$JobOKCount].SubString(7,14).Trim() # From the $JobOK array read the $JobOKCount row and extract client name $ReadOKPolicy = $JobOK[$JobOKCount].SubString(21,17).Trim() # From the $JobOK array read the $JobOKCount row and extract policy name $ReadOKSchedule = $JobOK[$JobOKCount].SubString(38,11).Trim() # From the $JobOK array read the $JobOKCount row and extract schedule $ReadOKTimeStamp = $JobOK[$JobOKCount].SubString(61).Trim() # From the $JobOK array read the $JobOKCount row and extract time completed # --- $ReadPartialClient = $JobPartial[$JobPartialCount].SubString(7,14).Trim() # From the $JobPartial array read the $JobPartialCount row and extract client name $ReadPartialPolicy = $JobPartial[$JobPartialCount].SubString(21,17).Trim() # From the $JobPartial array read the $JobPartialCount row and extract policy name $ReadPartialSchedule = $JobPartial[$JobPartialCount].SubString(38,11).Trim() # From the $JobPartial array read the $JobPartialCount row and extract schedule $ReadPartialTimeStamp = $JobPartial[$JobPartialCount].SubString(61).Trim() # From the $JobPartial array read the $JobPartialCount row and extract time completed # --- $ReadFailClient = $JobFail[$JobFailCount].SubString(7,14).Trim() # From the $JobFail array read the $JobFailCount row and extract client name $ReadFailPolicy = $JobFail[$JobFailCount].SubString(21,17).Trim() # From the $JobFail array read the $JobFailCount row and extract policy name $ReadFailSchedule = $JobFail[$JobFailCount].SubString(38,11).Trim() # From the $JobFail array read the $JobFailCount row and extract schedule $ReadFailTimeStamp = $JobFail[$JobFailCount].SubString(61).Trim() # From the $JobFail array read the $JobFailCount row and extract time completed # --- Write progress to console $ClntStr = $Client+" "*($ClientStringLength-$Client.Length) # For interactive use only, get client name and add whitespace Write-Host " Client: " -NoNewLine # Write to console, Write-Host $ClntStr -NoNewLine -ForeGroundColor "Cyan" # The currently processing client Write-Host "Status: " -NoNewLine # Write to console, Switch ($StatusCode) { 0 { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Green" # Status successful } 1 { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Yellow" # Status partially successful } Default { Write-Host $StatusCode -NoNewLine -ForeGroundColor "Red" # Status failed } } Write-Host "`tPolicy: " -NoNewLine # Write to console, Write-Host $Policy -ForeGroundColor "Cyan" # The currently processing clients' policy # --- Switch ($StatusCode) # Process jobs by statuscode { {$StatusCode -eq 0} # If statuscode equals 0 (Successful), process job { If ($JobOKCount -eq 1) # If row count of the $JobOK array equals 1 { $JobOK.Add($Job) | Out-Null # Add the currently processing job values to the array $JobOKCount++ # Increment the row count } ElseIf (($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobOK array, { $JobOK[$JobOKCount] = $Job # Replace the read values with the currently processing job values } Else { $JobOK.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobOKCount++ # Increment the row count } If (($JobPartialCount -gt 1) -AND ($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobPartial Array, if currently processing job time completed is greater than the value of time completed in $JobPartial, { $JobPartial.Remove($JobPartial[$JobPartialCount]) | Out-Null # Remove the read values from the array $JobPartialCount-- # Decrement the row count } If (($JobFailCount -gt 1) -AND ($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobFail Array, if currently processing job time completed is greater than the value of time completed in $JobFail, { $JobFail.Remove($JobFail[$JobFailCount]) | Out-Null # Remove the read job values from the array $JobFailCount-- # Decrement the row count } } {$StatusCode -eq 1} # If statuscode equals 1 (Partially successful), process job { If ($JobPartialCount -eq 1) # If row count of the $JobPartial array equals 1 { $JobPartial.Add($Job) | Out-Null # Add the currently processing job values to the array $JobPartialCount++ # Increment the row count } Else { If (($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobPartial array, { $JobPartial[$JobPartialCount] = $Job # Replace the read values with the currently processing job values } Else { $JobPartial.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobPartialCount++ # Increment the row count } } If (($JobOKCount -gt 1) -AND ($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobOK Array, if currently processing job time completed is greater than the value of time completed in $JobOK, { $JobOK.Remove($JobOK[$JobOKCount]) | Out-Null # Remove the read job $JobOK values from the array $JobOKCount-- # Decrement the row count } If (($JobFailCount -gt 1) -AND ($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobFail Array, if currently processing job time completed is greater than the value of time completed in $JobFail, { $JobFail.Remove($JobFail[$JobFailCount]) | Out-Null # Remove the read job $JobFail values from the array $JobFailCount-- # Decrement the row count } } {$StatusCode -gt 1} # If statuscode greater than 1 (Failed), process job { If ($JobFailCount -eq 1) { $JobFail.Add($Job) | Out-Null # Add the currently processing job values to the array $JobFailCount++ # Increment the row count } Else { If (($JobClient -eq $ReadFailClient) -AND ($JobPolicy -eq $ReadFailPolicy) -AND ($JobSchedule -eq $ReadFailSchedule) -AND ($JobTimeComplete -ge $ReadFailTimeStamp)) # If Client, Policy and Schedule are the same, but the time completed is greater than the values read from the $JobFail array, { $JobFail[$JobFailCount] = $Job # Replace the read values with the currently processing job values } Else { $JobFail.Add($Job) | Out-Null # If all above logic is not true, add the currently processing job values to the array $JobFailCount++ # Increment the row count } } If (($JobOKCount -gt 1) -AND ($JobClient -eq $ReadOKClient) -AND ($JobPolicy -eq $ReadOKPolicy) -AND ($JobSchedule -eq $ReadOKSchedule) -AND ($JobTimeComplete -ge $ReadOKTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobOK Array, if currently processing job time completed is greater than the value of time completed in $JobOK, { $JobOK.Remove($JobOK[$JobOKCount]) | Out-Null # Remove the read job $JobOK values from the array $JobOKCount-- # Decrement the row count } If (($JobPartialCount -gt 1) -AND ($JobClient -eq $ReadPartialClient) -AND ($JobPolicy -eq $ReadPartialPolicy) -AND ($JobSchedule -eq $ReadPartialSchedule) -AND ($JobTimeComplete -ge $ReadPartialTimeStamp)) # Check if client, policy and schedule are the same in the last row of the $JobPartial Array, if currently processing job time completed is greater than the value of time completed in $JobPartial, { $JobPartial.Remove($JobPartial[$JobPartialCount]) | Out-Null # Remove the read job $JobPartial values from the array $JobPartialCount-- # Decrement the row count } } } } } Else # If $ClientJobList is empty { If ($ClientReported -contains "$Client`t$PolicyType") # If client and schedule are present in the $ClientReported array { Continue # Continue } Else # If client and schedule are NOT present in the $ClientReported array (line 195) { $CNRString = ($Client+" "*($ClientStringLength-$Client.Length))+($Policy+" "*($PolicyStringLength-$Policy.Length)) # Format a string with client and policy values $ClientNotReported += @($CNRString) # Add the string value to the $ClientNotReported array Continue } } } If ($JobOK.Count -gt 2) # If the row count of $JobOK array is greater than 2, { $TotalOK += $JobOK # Add the values of $JobOK to $TotalOK If ($JobOK) {Clear-Variable JobOK} # Clear the array in preparation of processing the next policy } If ($JobPartial.Count -gt 2) # If the row count of $JobPartial array is greater than 2, { $TotalPartial += $JobPartial # Add the values of $JobPartial to $TotalPartial If ($JobPartial) {Clear-Variable JobPartial} # Clear the array in preparation of processing the next policy } If ($JobFail.Count -gt 2) # If the row count of $JobFail array is greater than 2, { $TotalFail += $JobFail # Add the values of $JobFail to $TotalFail If ($JobFail) {Clear-Variable JobFail} # Clear the array in preparation of processing the next policy } } } # --- $NBUStats = $NBUStats | Sort-Object # Sort the NBUStats array $GrandTotalFiles = "{0:N0}" -f $GrandTotalFiles # Format the value of GrandTotalFiles If ($GrandTotalKB -lt 1048576) # Format GrandTotalKB to reflect, { $GrandTotalKBs = "{0:N} KB" -f $($GrandTotalKB/1KB) # KiloBytes, } If (($GrandTotalKB -gt 1048576) -AND ($GrandTotalKB -lt 1073741824)) { $GrandTotalKBs = "{0:N} MB" -f $($GrandTotalKB/1MB) # MegaBytes, } If ($GrandTotalKB -gt 1073741824 -AND ($GrandTotalKB -lt 1099511627776)) { $GrandTotalKBs = "{0:N} GB" -f $($GrandTotalKB/1GB) # GigaBytes, or } If ($GrandTotalKB -gt 1099511627776) { $GrandTotalKBs = "{0:N} TB" -f $($GrandTotalKB/1TB) #TeraBytes } $NBUStats += @("";"Total Files backedup: $GrandTotalFiles";"Total Data backedup: $GrandTotalKBs") # Add the aggregate values to the NBUStats array # --------------------------- Write-Host "" # Write to console Write-Host "Checking for active jobs..." -ForegroundColor "Yellow" # Write to console $ActivejobList = Invoke-Expression "bpdbjobs -ignore_parent_jobs" | Select-String "Active" # Using NBU cmd check for active jobs at the time of reporting $ActiveJobs = @("";"Active jobs at the time of report") # Initialize ActiveJobs array and add header $ActiveJobs += @("-"*$ActiveJobs[1].Length) #Add variable length horizontal separator If ($ActivejobList) # If ActivejobList contains data { ForEach ($ActiveJob in $ActiveJobList) # Process active jobs { $ActiveClient = $Activejob.ToString().SubString(0,112) # Get the first 112 characters from the job string $ActiveJobs += @($ActiveClient) # Add it to the ActiveJobs array } } # --------------------------- Write-Host "" # Write to console Write-Host "Getting tape media used..." -ForegroundColor "Yellow" # Write to console $TapeMediaUsed = @("";"Tape Media used during backup") # Initialize array and add header $TapeMediaUsed += @("-"*$TapeMediaUsed[1].Length) # Add variable length horizontal separator $ColTapeMediaUsed = Invoke-Expression "bpimagelist -media -L -d $StartDate -e $EndDate" # Using NBU cmd get tape media used $TapeMediaUsedCount = ($ColTapeMediaUsed | Select-String "Media ID:").Count # From ColTapeMediaUsed get the number of media used [Int]$1=0 # Row number of "Media ID" in ColTapeMediaUsed [Int]$2=2 # Row number of "Last Time Written" in ColTapeMediaUsed [Int]$3=3 # Row number of "Times Written" in ColTapeMediaUsed [Int]$4=4 # Row number of "Kilobytes" in ColTapeMediaUsed For ($i=0; $i -le $TapeMediaUsedCount; $i++) # For the number of media used, { $TapeMediaUsed += @($ColTapeMediaUsed[$1,$2,$3,$4];"") # Write the values to the array $1=$1+7 # Increment the row number by 7 for the next media used $2=$2+7 # Increment the row number by 7 for the next media used $3=$3+7 # Increment the row number by 7 for the next media used $4=$4+7 # Increment the row number by 7 for the next media used } # --------------------------- Write-Host "" # Write to console Write-Host "Getting disk storage units used..." -ForegroundColor "Yellow" # Write to console $DiskStorageUnits = @("";"Disk Storage Units Status") # Initialize array and add header $DiskStorageUnits += @("-"*$DiskStorageUnits[1].Length) # Add variable length horizontal separator $ColDiskStorageUnits = Invoke-Expression "nbdevquery -listdv -stype BasicDisk -U" # Using NBU cmd to get disk storageunits ForEach ($PolSched in $UsedPolSched) # Process policies/schedules used during backup operation (see line 215,74) to extract disk storageunit usage { $PolSched=$PolSched.Split(",") # Split the $polSched string at the comma $UsedPolicy = $PolSched[0] # From the split string extract the Policyname $UsedSchedule = $PolSched[1] # From the split string extract the Schedule $UsedPolicyDetails = Invoke-Expression "bppllist $UsedPolicy -L" # Using NBU cmd get currently processing policy details $ScheduleStartLine = ($UsedPolicyDetails | Select-String "Schedule:.*$UsedSchedule").LineNumber-1 # From the policy details extract the linenumber where the used schedule details begin $Schedule = $UsedPolicyDetails[$ScheduleStartLine..$Usedpolicydetails.Count] # From above acquired linenumber select all lines to the last line of the policy details Try { $ScheduleEndLine = ($Schedule | Select-String "Schedule")[1].LineNumber-2 # Check if multiple schedule details are selected, by selecting the word "Schedule". If true acquire the linenumber of the second instance of the word "Schedule" and extract 2 lines } Catch { $ScheduleEndLine = $Usedpolicydetails.Count # If the above statement fails, it is the last schedule description in policy details, so the last line of the policydetails is also the last line of the schedule description } $Schedule = $Schedule[0..$ScheduleEndLine] # Final selection to acquire the schedule description $StorageUnitString = ($Schedule | Select-String "Residence:").ToString().SubString(19).Trim() # From the schedule details acquire the "residence" value If ($ColDiskStorageUnits -contains "Disk Pool Name : $StorageUnitString") # If previously collected disk storageunits data, contains the StorageUnitString, { [Int]$ColStorageUnitLineNumber = ($ColDiskStorageUnits | Select-String "Disk Pool Name .*$StorageUnitString").LineNumber-1 # Get the linenumber for the line that contains "Disk Pool Name .*$StorageUnitString" and extract 1 to compensate for the fact that powershell starts counting at 0 instead of 1 [Int]$1=$ColStorageUnitLineNumber # linenumber for "Disk Pool Name" [Int]$2=$ColStorageUnitLineNumber+4 # linenumber for "Total Capacity" [Int]$3=$ColStorageUnitLineNumber+5 # linenumber for "Free Space" [Int]$4=$ColStorageUnitLineNumber+6 # linenumber for "Use%" [Int]$5=$ColStorageUnitLineNumber+7 # linenumber for "Status" If ($DiskStorageUnits -notcontains "Disk Pool Name : $StorageUnitString") # If array DiskStorageUnits does not contain a line like "Disk Pool Name : $StorageUnitString", { $DiskStorageUnits += @($ColDiskStorageUnits[$1,$2,$3,$4,$5];"") # Add the disk storageunit details to the array } } } # --------------------------- Write-Host "" # Write to console Write-Host "Creating report..." -ForegroundColor "Yellow" # Write to console Set-Content $OutputStr "" # initialize the output file $ReportStart = "{0:dddd dd\\-MM\\-yyyy H:mm:ss}" -f $Now # Format date and time for the script start timestamp If (($Now.DayOfWeek -eq "Tuesday") -OR ($Now.DayOfWeek -eq "Wednesday") -OR ($Now.DayOfWeek -eq "Thursday") -OR ($Now.DayOfWeek -eq "Friday")) # For every weekday except monday { $ReportingDate = "{0:dddd dd\\-MM\\-yyyy}" -f ($Now.AddDays(-1)) # Set the date back one day and format the date for the date of the backup operation } If ($Now.DayOfWeek -eq "Monday") # For every monday { $ReportingDate = "{0:dddd dd\\-MM\\-yyyy}" -f ($Now.AddDays(-3)) # Set the date back three days and format the date for the date of the backup operation } $ReportHeader = @("Report Generated on $env:COMPUTERNAME, $ReportStart";"";"Backup report for $ReportingDate") # Array with multiline header Add-Content $OutputStr $ReportHeader # Add the header to the output file $ReportParts = @($TotalFail,$TotalPartial,$TotalOK) # Array containing the names of the arrays with the overall results of the backup operation ForEach ($Part in $ReportParts) # For each array, { If ($Part.Count -ge 3) # If the line count is greater than 3, { Add-Content $OutputStr $Part # Add the array to the output file } } If ($ActiveJobs.Count -gt 4) # If the line count is greater than 3, { Add-Content $OutputStr $ActiveJobs # Add the array to the output file } If ($ClientNotReported.Count -gt 4) # If the line count is greater than 4, { Add-Content $OutputStr $ClientNotReported # Add the array to the output file } If ($NBUStats.Count -ge 1) # If the line count is greater than 4, { Add-Content $OutputStr $NBUStatsHeader # Add the header array to the output file Add-Content $OutputStr $NBUStats # Add the array to the output file } If ($TapeMediaUsed.Count -gt 3) # If the line count is greater than 3, { Add-Content $OutputStr $TapeMediaUsed # Add the array to the output file } If ($DiskStorageUnits.Count -gt 3) # If the line count is greater than 3, { Add-Content $OutputStr $DiskStorageUnits # Add the array to the output file } Add-Content $OutputStr "" # Add blank line to the output file Add-Content $OutputStr "--------------------------------------------------" # Add a separator to the output file $ReportEnd = "{0:dddd dd\\-MM\\-yyyy H:mm:ss}" -f (Get-Date) # Get and format the current date and time $ReportFooter = @("Report finished on $env:COMPUTERNAME, $ReportEnd";"") # Array with multiline footer Add-Content $OutputStr $ReportFooter # Add the footer to the output file # --------------------------- Write-Host "" # Write to console Write-Host "Sending e-mail..." -ForegroundColor "Yellow" # Write to console $MailBody = Get-Content $OutputStr | %{ "$_`r" } # Read and parse the contents of the output file $CcRecipients = Get-Content ($OutputPth + "\\" + $CC) # read the contents of the file containing CC recipients $Attachment = $OutputStr # declare variable containing the path to the output file $Msg = New-Object Net.Mail.MailMessage # Create new e-mail message object $Att = New-Object Net.Mail.Attachment($Attachment) # Create new attachment object $Smtp = New-Object Net.Mail.SmtpClient($SmtpServer) # Create new smtp client object $Msg.From = $From # Add from address to the message $Msg.To.Add($To) # Add to address to the message $Msg.CC.Add($CcRecipients) # Add CC address(es) to the message $Msg.Subject = "Backup report for last $ReportingDate" # Set the message subject $Msg.Body = $MailBody # Add the bodytext to the message $Msg.Attachments.Add($Att) # Add the attachment to the message $Smtp.Send($Msg) # Send the message $Att.Dispose() # Clear memory of the attachment # --------------------------- #Write-EventLog -LogName "Scripts" -Source "Reporting_Script" -EventID 30 -Message "Backup Report: Mail Sent" -EntryType "Information" # --------------------------- # reset the colors back to default [console]::ResetColor() @@ End of Script @@ Below is an example of the actual output Report Generated on NBUSRV, monday 06-12-2010 8:30:07 Backup report for friday 03-12-2010 Failed jobs during the FileBackup backup ---------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 156 SRV001 FileBackup Week NBUSRV 12/04/2010 15:17:48 Failed jobs during the Linux_filebackup2 backup ----------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 71 SRV002 Linux_filebackup Week NBUSRV 12/03/2010 18:17:54 Partially Successful jobs during the FileBackup backup ------------------------------------------------------ STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 1 NBUSRV FileBackup Week NBUSRV 12/03/2010 23:56:46 Partially Successful jobs during the FileBackup2 backup ------------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 1 SRV003 FileBackup2 Week NBUSRV 12/03/2010 20:44:03 Partially Successful jobs during the NAS_FileBackup_SQL_WWW backup ------------------------------------------------------------------ STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 1 SRV004 NAS_FileBackup_S Full NBUSRV 12/04/2010 12:26:59 1 SRV005 NAS_FileBackup_S Full NBUSRV 12/04/2010 00:02:49 Partially Successful jobs during the PRTG backup ------------------------------------------------ STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 1 SRV006 PRTG Full NBUSRV 12/04/2010 13:28:54 Successful jobs during the CatalogBackup backup ----------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 NBUSRV CatalogBackup Daily NBUSRV 12/06/2010 08:11:56 Successful jobs during the ExchangeBackup backup ------------------------------------------------ STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV003 ExchangeBackup Week NBUSRV 12/04/2010 19:51:29 Successful jobs during the FileBackup backup -------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV007 FileBackup Week NBUSRV 12/04/2010 14:21:31 0 SRV008 FileBackup Week NBUSRV 12/03/2010 20:54:54 0 SRV009 FileBackup Week NBUSRV 12/04/2010 01:40:42 0 SRV010 FileBackup Week NBUSRV 12/04/2010 01:33:09 0 SRV004 FileBackup Week NBUSRV 12/03/2010 23:57:03 0 SRV011 FileBackup Week NBUSRV 12/04/2010 01:16:40 0 SRV012 FileBackup Week NBUSRV 12/04/2010 01:52:23 0 SRV013 FileBackup Week NBUSRV 12/04/2010 18:11:10 0 SRV014 FileBackup Week NBUSRV 12/04/2010 01:17:05 0 SRV015 FileBackup Week NBUSRV 12/04/2010 01:14:31 0 SRV016 FileBackup Week NBUSRV 12/04/2010 13:20:02 0 SRV017 FileBackup Week NBUSRV 12/04/2010 01:36:57 0 SRV005 FileBackup Week NBUSRV 12/04/2010 11:25:06 Successful jobs during the FileBackup2 backup --------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV018 FileBackup2 Week NBUSRV 12/05/2010 14:49:59 Successful jobs during the Linux_filebackup backup -------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV019 Linux_filebackup Week NBUSRV 12/03/2010 18:09:46 0 SRV020 Linux_filebackup Week NBUSRV 12/03/2010 20:55:21 0 SRV021 Linux_filebackup Week NBUSRV 12/03/2010 18:16:15 Successful jobs during the MailboxBackup backup ----------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV003 MailboxBackup Week NBUSRV 12/04/2010 02:22:32 Successful jobs during the NAS_Daily_SRV018 backup -------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV018 NAS_Daily_SRV018 Full NBUSRV 12/05/2010 06:19:59 Successful jobs during the NAS_FileBackup_Citrix backup ------------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV015 NAS_FileBackup_C Week NBUSRV 12/03/2010 19:49:17 0 SRV016 NAS_FileBackup_C Week NBUSRV 12/03/2010 19:48:46 0 SRV017 NAS_FileBackup_C Week NBUSRV 12/03/2010 19:49:29 Successful jobs during the NAS_FileBackup_DCs backup ---------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV007 NAS_FileBackup_D Week NBUSRV 12/03/2010 20:55:59 0 SRV008 NAS_FileBackup_D Week NBUSRV 12/03/2010 20:33:49 Successful jobs during the NAS_FileBackup_SQL_WWW backup -------------------------------------------------------- STATUS CLIENT POLICY SCHED SERVER TIME COMPLETED 0 SRV009 NAS_FileBackup_S Full NBUSRV 12/04/2010 00:31:03 0 SRV010 NAS_FileBackup_S Full NBUSRV 12/04/2010 10:21:18 0 SRV001 NAS_FileBackup_S Full NBUSRV 12/03/2010 23:42:43 0 SRV013 NAS_FileBackup_S Full NBUSRV 12/04/2010 00:23:24 Servers that did not (yet) report any activity ---------------------------------------------- CLIENT POLICY SRV022 FileBackup2 SRV023 ExchangeBackup SRV024 FileBackup BACKUP STATISTICS CLIENT POLICY FILES SIZE ELAPSED ------------------------------------------------------------------------ NBUSRV CatalogBackup 7.209 7,97 GB 00:11:29 NBUSRV FileBackup 32.870 25,60 GB 05:04:51 SRV001 FileBackup 312.592 118,36 GB 05:25:18 SRV001 NAS_FileBackup_SQL_WWW 189.777 84,10 GB 03:45:15 SRV002 Linux_filebackup2 98.381 3,81 GB 00:20:35 SRV003 ExchangeBackup 9 247,01 GB 09:59:45 SRV003 FileBackup2 51.021 9,15 GB 00:57:07 SRV003 MailboxBackup 192.399 5,45 GB 01:22:26 SRV004 FileBackup 111.210 56,53 GB 06:04:05 SRV004 NAS_FileBackup_SQL_WWW 61.901 28,16 GB 01:20:48 SRV005 FileBackup 102.547 185,43 GB 06:44:37 SRV005 NAS_FileBackup_SQL_WWW 43.621 78,96 GB 03:52:15 SRV006 PRTG 48.992 13,36 GB 01:16:57 SRV007 FileBackup 74.042 27,96 GB 03:01:21 SRV007 NAS_FileBackup_DCs 37.012 13,92 GB 01:06:18 SRV008 FileBackup 76.314 14,05 GB 01:47:51 SRV008 NAS_FileBackup_DCs 38.157 7,00 GB 00:40:53 SRV009 FileBackup 135.311 182,96 GB 11:30:10 SRV009 NAS_FileBackup_SQL_WWW 74.393 91,12 GB 02:18:39 SRV010 FileBackup 118.870 155,18 GB 08:16:04 SRV010 NAS_FileBackup_SQL_WWW 67.660 57,78 GB 01:27:28 SRV011 FileBackup 29.968 5,80 GB 00:52:46 SRV012 FileBackup 84.197 11,41 GB 01:20:36 SRV013 FileBackup 164.644 259,76 GB 10:42:15 SRV013 NAS_FileBackup_SQL_WWW 81.413 129,37 GB 04:12:44 SRV014 FileBackup 34.022 5,87 GB 00:51:19 SRV015 FileBackup 60.459 16,21 GB 01:10:15 SRV015 NAS_FileBackup_Citrix 30.224 8,07 GB 00:22:53 SRV016 FileBackup 73.496 39,25 GB 01:48:33 SRV016 NAS_FileBackup_Citrix 36.742 19,55 GB 00:26:46 SRV017 FileBackup 195.726 47,95 GB 02:22:57 SRV017 NAS_FileBackup_Citrix 97.863 23,88 GB 00:33:53 SRV018 FileBackup2 5.964.297 505,46 GB 1.06:46:30 SRV018 NAS_Daily_SRV018 5.921.262 496,49 GB 1.02:24:36 SRV019 Linux_filebackup 108.119 2,17 GB 00:11:06 SRV020 Linux_filebackup 127.037 6,28 GB 02:57:13 SRV021 Linux_filebackup 132.949 7,69 GB 00:18:09 Total Files backedup: 15.016.706 Total Data backedup: 2,93 TB Tape Media used during backup ----------------------------- Media ID: TAPE001 Last Time Written: 4-12-2010 12:47:33 (1291463253) Times Written: 2311 (within this time period) Kilobytes: 838688875 (within this time period) Media ID: TAPE002 Last Time Written: 3-12-2010 22:16:36 (1291410996) Times Written: 1018 (within this time period) Kilobytes: 139560051 (within this time period) Media ID: TAPE003 Last Time Written: 4-12-2010 12:47:29 (1291463249) Times Written: 501 (within this time period) Kilobytes: 481352638 (within this time period) Media ID: CATALOG Last Time Written: 6-12-2010 8:02:04 (1291618924) Times Written: 6 (within this time period) Kilobytes: 8360274 (within this time period) Disk Storage Units Status ------------------------- Disk Pool Name : DISK_POOL1 Total Capacity (GB) : 300.00 Free Space (GB) : 280.76 Use% : 6 Status : UP Disk Pool Name : DISK_POOL2 Total Capacity (GB) : 5526.45 Free Space (GB) : 2460.72 Use% : 55 Status : UP -------------------------------------------------- Report finished on NBUSRV, monday 06-12-2010 8:30:51
PowerShellCorpus/PoshCode/Get-ADSite-byIP.ps1
Get-ADSite-byIP.ps1
#get-site-byIP, ipv4 #written by Nathan Linley # http://myitpath.blogspot.com Param( [Parameter(Mandatory=$true,HelpMessage="IP Address")][validatepattern('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')]$ip, [Parameter(Mandatory=$false,HelpMessage="Netmask")]$nmask, [Parameter(Mandatory=$false,HelpMessage="Mask length")][validaterange(0,32)][int]$nmlength ) function check-ipformat([string]$ip) { #check for a properly formated IPv4 address being provided. Future update can include Ipv6 regex if (-not ($ip -match "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")) { write-error "The Ip address provided: $ip is not a valid IPv4 address format" return $false } else { $octetsegments = $ip.split(".") #Check the values of the ip address format to ensure it is between 0 and 255 foreach ($octet in $octetsegments) { if ([int]$octet -lt 0 -or [int]$octet -gt 254) { return $false } } return $true } } function get-networkID ([string]$ipaddr, [string]$subnetmask) { if (-not (&check-ipformat $ipaddr)) { Write-Host -ForegroundColor "yellow" "IP address provided is not a valid IPv4 address format" Write-Host return $null } if (-not (&check-subnetformat $subnetmask)) { Write-Host -ForegroundColor "yellow" "Subnet mask provided is not a valid format" Write-Host return $null } $ipoctets = $ipaddr.split(".") $subnetoctets = $subnetmask.split(".") $result = "" for ($i = 0; $i -lt 4; $i++) { $result += $ipoctets[$i] -band $subnetoctets[$i] $result += "." } $result = $result.substring(0,$result.length -1) return $result } function check-subnetformat([string]$subnet) { if (-not ($subnet -match "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")) { Write-Error "The subnet mask provided does not match IPv4 format" return $false } else { $octetsegments = $subnet.split(".") #Check each octet from last to first. If an octet does not contain 0, check to see #if it is valid octet value for subnet masks. Then check to make sure that all preceeding #octets are 255 $foundmostsignficant = $false for ($i = 3; $i -ge 0; $i--) { if ($octetsegments[$i] -ne 0) { if ($foundmostsignificant -eq $true -and $octetsegments[$i] -ne 255) { Write-Error "The subnet mask has an invalid value" return $false } else { if ((255,254,252,248,240,224,192,128) -contains $octetsegments[$i]) { $foundmostsignficant = $true } else { Write-Error "The subnet mask has an invalid value" return $false } } } } return $true } } function get-subnetMask-byLength ([int]$length) { if ($length -eq $null -or $length -gt 32 -or $length -lt 0) { Write-Error "get-subnetMask-byLength: Invalid subnet mask length provided. Please provide a number between 0 and 32" return $null } switch ($length) { "32" { return "255.255.255.255" } "31" { return "255.255.255.254" } "30" { return "255.255.255.252" } "29" { return "255.255.255.248" } "28" { return "255.255.255.240" } "27" { return "255.255.255.224" } "26" { return "255.255.255.192" } "25" { return "255.255.255.128" } "24" { return "255.255.255.0" } "23" { return "255.255.254.0" } "22" { return "255.255.252.0" } "21" { return "255.255.248.0" } "20" { return "255.255.240.0" } "19" { return "255.255.224.0" } "18" { return "255.255.192.0" } "17" { return "255.255.128.0" } "16" { return "255.255.0.0" } "15" { return "255.254.0.0" } "14" { return "255.252.0.0" } "13" { return "255.248.0.0" } "12" { return "255.240.0.0" } "11" { return "255.224.0.0" } "10" { return "255.192.0.0" } "9" { return "255.128.0.0" } "8" { return "255.0.0.0" } "7" { return "254.0.0.0"} "6" { return "252.0.0.0"} "5" { return "248.0.0.0"} "4" { return "240.0.0.0"} "3" { return "224.0.0.0"} "2" { return "192.0.0.0"} "1" { return "128.0.0.0"} "0" { return "0.0.0.0"} } } function get-MaskLength-bySubnet ([string]$subnet) { if ($subnet -eq $null -or (-not(&check-subnetformat $subnet))) { Write-Error "Invalid subnet passed to get-MaskLength-bySubnet in networklib" return $null } switch ($subnet) { "255.255.255.255" {return 32} "255.255.255.254" {return 31} "255.255.255.252" {return 30} "255.255.255.248" {return 29} "255.255.255.240" {return 28} "255.255.255.224" {return 27} "255.255.255.192" {return 26} "255.255.255.128" {return 25} "255.255.255.0" {return 24} "255.255.254.0" {return 23} "255.255.252.0" {return 22} "255.255.248.0" {return 21} "255.255.240.0" {return 20} "255.255.224.0" {return 19} "255.255.192.0" {return 18} "255.255.128.0" {return 17} "255.255.0.0" {return 16} "255.254.0.0" {return 15} "255.252.0.0" {return 14} "255.248.0.0" {return 13} "255.240.0.0" {return 12} "255.224.0.0" {return 11} "255.192.0.0" {return 10} "255.128.0.0" {return 9} "255.0.0.0" {return 8} "254.0.0.0" {return 7} "252.0.0.0" {return 6} "248.0.0.0" {return 5} "240.0.0.0" {return 4} "224.0.0.0" {return 3} "192.0.0.0" {return 2} "128.0.0.0" {return 1} "0.0.0.0" {return 0} } } $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $mytopleveldomain = $forest.schema.name $mytopleveldomain = $mytopleveldomain.substring($mytopleveldomain.indexof("DC=")) $mytopleveldomain = "LDAP://cn=subnets,cn=sites,cn=configuration," + $mytopleveldomain $de = New-Object directoryservices.DirectoryEntry($mytopleveldomain) $ds = New-Object directoryservices.DirectorySearcher($de) $ds.propertiestoload.add("cn") > $null $ds.propertiestoLoad.add("siteobject") > $null $startMaskLength = 32 #we can take network masks in both length and full octet format. #We need to use both. LDAP searches #use length, and network ID generation is by full octet format. if ($nmask -ne $null -or $nmlength -ne $null) { if ($nmask -ne $null) { if (-not(&check-subnetformat $nmask)) { Write-Error "Subnet provided is not a valid subnet" exit } else { $startmasklength = &get-MaskLength-bySubnet $nmask } } } for ($i = $startMaskLength; $i -ge 0; $i--) { #loop through netmasks from /32 to /0 looking for a subnet match in AD #Go through all masks from longest to shortest $mask = &get-subnetMask-byLength $i $netwID = &get-networkID $ip $mask #ldap search for the network $ds.filter = "(&(objectclass=subnet)(objectcategory=subnet)(cn=" + $netwID + "/" + $i + "))" $fu = $ds.findone() if ($fu -ne $null) { #if a match is found, return it since it is the longest length (closest match) Write-Verbose "Found Subnet in AD at site:" $result = $fu.properties.siteobject return $result } $fu = $null } #if we have arrived at this point, the subnet does not exist in AD return "Subnet_NOT_Assigned"
PowerShellCorpus/PoshCode/Monitor ESX with WS-MAN.ps1
Monitor ESX with WS-MAN.ps1
# WS-MAN monitoring of ESX with PowerShell. # This requires PowerShell v2 CTP3 and requires the new WS-MAN CTP # from MS (currently 64 bit only) # You will also need to allow basic auth. # (run winrm set winrm/config/client/auth @{Basic="true"} from command prompt) function Get-VMHostWSManInstance { param ( [Parameter(Mandatory=$TRUE,HelpMessage="VMHosts to probe")] [VMware.VimAutomation.Client20.VMHostImpl[]] $VMHost, [Parameter(Mandatory=$TRUE,HelpMessage="Resource URI")] [string] $resourceUri, [switch] $ignoreCertFailures ) if ($ignoreCertFailures) { $option = New-WSManSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck } else { $option = New-WSManSessionOption } foreach ($H in $VMHost) { $hView = $H | Get-View -property Value $ticket = $hView.AcquireCimServicesTicket() $password = convertto-securestring $ticket.SessionId -asplaintext -force $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $ticket.SessionId, $password $uri = "https`://" + $h.Name + "/wsman" Get-WSManInstance -Authentication basic -ConnectionURI $uri -Credential $credential -Enumerate -Port 443 -UseSSL -SessionOption $option -ResourceURI $resourceUri } } # Example # First, connect to your VI Server. # Connect-VIServer <your ESX or VC> # Now we're ready to enumerate stuff. This will get processor # information for all hosts. # Get-VMHostWSManInstance -VMHost (get-vmhost) ` # -resourceUri http`://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Processor ` # -ignoreCertFailures # Other resource URIs of note # http`://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Chassis # http`://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Processor # http`://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_Memory # http`://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareElement # Some of these may not be supported on your hardware.
PowerShellCorpus/PoshCode/find-localadmins.ps1
find-localadmins.ps1
<# .SYNOPSIS List users in specified local group .DESCRIPTION Created: March 17, 2011 Jeff Patton This script searches ActiveDirectory for computers. It then queries each computer for the list of users who are in the local Administrators group. .PARAMETER ADSPath The LDAP URI of the container you wish to pull computers from. .PARAMETER GroupName The name of the local group to pull membership pfrom. .EXAMPLE find-localadmins "LDAP://OU=Workstations,DC=company,DC=com" .NOTES You will need to run this script as an administrator or disable UAC to update the event-log You will need to have at least Read permissions in the AD container in order to get a list of computers. .LINK http://scripts.patton-tech.com/wiki/PowerShell/Production/FindLocalAdmins #> Param ( [Parameter(Mandatory=$true)] [string]$ADSPath, [Parameter(Mandatory=$true)] [string]$GroupName ) Begin { $ScriptName = $MyInvocation.MyCommand.ToString() $LogName = "Application" $ScriptPath = $MyInvocation.MyCommand.Path $Username = $env:USERDOMAIN + "\\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message # Dotsource in the AD functions . .\\includes\\ActiveDirectoryManagement.ps1 } Process { $computers = Get-ADObjects $ADSPath foreach ($computer in $computers) { if ($computer -eq $null){} else { $groups = Get-LocalGroupMembers $computer.Properties.name $GroupName If ($groups -ne $null) { write-host "Accounts with membership in $GroupName on: " $computer.Properties.name $groups | Format-Table -autosize } } } } End { $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message }
PowerShellCorpus/PoshCode/ConvertTo-JaggedObjects.ps1
ConvertTo-JaggedObjects.ps1
function ConvertTo-JaggedObjects { ################################################################################################### # .Synopsis # Convert a hashtable full of arrays into formattable objects # .Description # When you have multiple arrays that you need to somehow group together for output, ConvertTo-JaggedObjects is your solution. It takes a hashtable of arrays (strictly so that you can give a name to each array), and produces a series of objects which have a property for each source array. # .Parameter Hash # The hashtable which applies names to arrays. For example: @{English=@("one","two"); Spanish=@("uno","dos")} # .Example # $a = "one","two","three" # $b = "uno","dos","tres","cuatro" # $c = "un","deux","trois" # # ConvertTo-JaggedObjects @{English=$a; Spanish=$b; French=$c} # # .Example # It now sorts alphabetically, so you can do something like: # # $a = "one","two","three" # $b = "uno","dos","tres","cuatro" # $c = "un","deux","trois" # # ConvertTo-JaggedObjects @{"1 English"=$a; "2 Spanish"=$b; "3 French"=$c} # # Will have output like: # # 1 English 2 Spanish 3 French # --------- --------- -------- # one uno un # two dos deux # three tres trois # cuatro ################################################################################################### Param([HashTable]$hash) $max = ($hash.Values | Measure Length -Max).Maximum ForEach($i in 0..($max-1)) { $o = New-Object PSObject foreach($name in $hash.Keys | Sort) { Add-Member -in $o -Type NoteProperty -Name $name -Value $hash[$name][$i] } Write-Output $o } }
PowerShellCorpus/PoshCode/SearchZIP_1.psm1 .ps1
SearchZIP_1.psm1 .ps1
function SearchZIPfiles { <# .SYNOPSIS Search for (filename) strings inside compressed ZIP or RAR files (V2.2). .DESCRIPTION In any directory containing a large number of ZIP/RAR compressed Web Page files this procedure will search each individual file name for simple text strings, listing both the source RAR/ZIP file and the individual file name containing the string. The relevant RAR/ZIP can then be subsequently opened in the usual way. Using the '-Table' switch will show the results with the Out-GridView display. .EXAMPLE extract -find 'library' -path d:\\scripts Searching for 'library' - please wait... (Use CTRL+C to quit) [Editor.zip] File: Windows 7 Library Procedures.mht [Editor.rar] File: My Library collection from 1974 Idi Amin.html [Test2.rar] File: Playlists from library - Windows 7 Forums.mht [Test3.rar] File: Module library functions UserGroup.pdf A total of 4 matches for 'library' found in folder 'D:\\Scripts'. .EXAMPLE extract -find 'backup' -path desktop Searching for 'backup' - please wait... (Use CTRL+C to quit) [Web.zip] File: How To Backup User and System Files.mht [Pages.rar] File: Create an Image Backup.pdf A total of 2 matches for 'backup' found in folder 'C:\\Users\\Sam\\Desktop'. .NOTES The first step will find any lines containing the selected pattern (which can be anywhere in the line). Each of these lines will then be split into 2 headings: Source and Filename. Note that there may be the odd occasion where a 'non-readable' character in the returned string slips through the net! .LINK Web Address Http://www.SeaStarDevelopment.BraveHost.com #> [CmdletBinding()] param([string][string][Parameter(Mandatory=$true)]$Find, [string][ValidateNotNullOrEmpty()]$path = $pwd, [switch][alias("GRIDVIEW")]$table) [int]$count = 0 if ($path -like 'desk*') { $path = Join-Path $home 'desktop\\*' } else { $xpath = Join-Path $path '*' -ea 0 if (!($?) -or !(Test-Path $path)) { Write-Warning "Path '$path' is invalid - resubmit" return } $path = $xpath } $folder = $path.Replace('*','') $lines = @{} $regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*\\\\(?<file>.*\\.(mht|html?|pdf))(.*)$' Get-ChildItem $path -include '*.rar','*.zip' | Select-String -SimpleMatch -Pattern $find | foreach-Object ` -begin { Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)" } ` -process { $_ = $_ -replace '/','\\' if ( $_ -match $regex ) { $source = $matches.zip -replace [regex]::Escape($folder) $file = $matches.file $file = $file -replace '\\s+',' ' #Single space words. $file = $file -replace '\\p{S}',' ' #Remove some 'Dingbats'. if ($table) { $key = "{0:D4}" -f $count $lines["$key $source"] = $file #Create a unique key. } else { Write-Host "[$source] File: $file" } $count++ } } ` -end { $title = "A total of $($count) matches for '$find' found in host folder '$($path.Replace('\\*',''))'." if ($table -and $lines.count -gt 0) { $lines.GetEnumerator() | Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}}, @{name = 'File' ;expression = {$_.Value}} | Sort-Object File | Out-GridView -Title $title } else { Write-Host $title } } } #End function. New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR' Export-ModuleMember -Function SearchZIPfiles -Alias Extract
PowerShellCorpus/PoshCode/Set-IISLogLocation.ps1
Set-IISLogLocation.ps1
Function Set-IISLogLocation { <# .SYNOPSIS This command will allow you to set the IIS log location on a server or multiple servers. .DESCRIPTION This command will allow you to set the IIS log location on a server or multiple servers. .PARAMETER computer Name of computer to set log location on .PARAMETER logdir Location to set IIS logs to write to .PARAMETER website Name of website to change the log location. .NOTES Name: Set-IISLogLocation Author: Boe Prox DateCreated: 20Aug2010 .LINK http://boeprox.wordpress.com .EXAMPLE Set-IISLogLocation -computer <server> -logdir "D:\\logs" Description ----------- This command will change the IIS log locations for each website on the server. .EXAMPLE Set-IISLogLocation -computer <server> -logdir "D:\\logs" -website "Default Web Site" Description ----------- This command will change the IIS log locations for only the Default Web Site on a server. #> [cmdletbinding( SupportsShouldProcess = $True, DefaultParameterSetName = 'default', ConfirmImpact = 'low' )] param( [Parameter( Mandatory = $False, ParameterSetName = '', ValueFromPipeline = $True)] [string]$computer, [Parameter( Mandatory = $False, ParameterSetName = '', ValueFromPipeline = $False)] [string]$logdir, [Parameter( Mandatory = $False, ParameterSetName = 'site', ValueFromPipeline = $False)] [string]$website ) Process { ForEach ($c in $Computer) { If (Test-Connection -comp $c -count 1) { $sites = [adsi]"IIS://$c/W3SVC" $children = $sites.children ForEach ($child in $children) { Switch ($pscmdlet.ParameterSetName) { "default" { If ($child.KeyType -eq "IIsWebServer") { If ($pscmdlet.ShouldProcess($($child.servercomment))) { $child.Put("LogFileDirectory",$logdir) $child.SetInfo() Write-Host -fore Green "$($child.servercomment): Log location set to $logdir" } } } "site" { If ($child.KeyType -eq "IIsWebServer" -AND $child.servercomment -eq $website) { If ($pscmdlet.ShouldProcess($($child.servercomment))) { $child.Put("LogFileDirectory",$logdir) $child.SetInfo() Write-Host -fore Green "$($child.servercomment): Log location set to $logdir" } } } } } } } } }
PowerShellCorpus/PoshCode/Parse nmap XML output.ps1
Parse nmap XML output.ps1
#################################################################################### # Script: parse-nmap.ps1 # Purpose: Parse the XML output file of the nmap port scanner and emit custom # objects with properties containing data from XML file. # Example: dir *.xml | .\\parse-nmap.ps1 # Author: Jason Fossen (www.EnclaveConsulting.com) # Version: 2.0 # Updated: 15.Jun.2009 # Notes: Pipe one or more file objects into script. Don't pipe file contents. # Script is slow, e.g., a 20MB XML log with 65k entries requires 103 seconds # to process on a 2.16GHz T2600 Intel CPU (about 630 entries per second). # LEGAL: PUBLIC DOMAIN. SCRIPT PROVIDED "AS IS" WITH NO WARRANTIES OR GUARANTEES OF # ANY KIND, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY AND/OR FITNESS FOR # A PARTICULAR PURPOSE. ALL RISKS OF DAMAGE REMAINS WITH THE USER, EVEN IF # THE AUTHOR, SUPPLIER OR DISTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF # ANY SUCH DAMAGE. IF YOUR STATE DOES NOT PERMIT THE COMPLETE LIMITATION OF # LIABILITY, THEN DELETE THIS FILE SINCE YOU ARE NOW PROHIBITED TO HAVE IT. #################################################################################### if ($args -ne $null) { "`nThis script takes no arguments, please pipe one or more files into it." "Example: dir *.xml | .\\parse-nmap.ps1 | export-csv -path c:\\file.csv`n" exit } # Set $ShowProgress to $false if you do not want progress info sent to StdErr. $ShowProgress = $true ForEach ($file in $input) { If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Starting $file" ) } $xmldoc = new-object System.XML.XMLdocument $xmldoc.Load($file) $i = 1 #Counter for <host> nodes processed. # Process each of the <host> nodes from the nmap report. $xmldoc.nmaprun.host | foreach-object { $hostnode = $_ # $hostnode is a <host> node in the XML. # Init variables, with $entry being the custom object for each <host>. $service = " " #service needs to be a single space. $entry = ($entry = " " | select-object FQDN, HostName, Status, IPv4, IPv6, MAC, Ports, OS) # Extract state element of status: $entry.Status = $hostnode.status.state.Trim() if ($entry.Status.length -eq 0) { $entry.Status = "<no-status>" } # Extract fully-qualified domain name(s). $hostnode.hostnames | foreach-object { $entry.FQDN += $_.hostname.name + " " } $entry.FQDN = $entry.FQDN.Trim() if ($entry.FQDN.Length -eq 0) { $entry.FQDN = "<no-fullname>" } # Note that this code cheats, it only gets the hostname of the first FQDN if there are multiple FQDNs. if ($entry.FQDN.Contains(".")) { $entry.HostName = $entry.FQDN.Substring(0,$entry.FQDN.IndexOf(".")) } elseif ($entry.FQDN -eq "<no-fullname>") { $entry.HostName = "<no-hostname>" } else { $entry.HostName = $entry.FQDN } # Process each of the <address> nodes, extracting by type. $hostnode.address | foreach-object { if ($_.addrtype -eq "ipv4") { $entry.IPv4 += $_.addr + " "} if ($_.addrtype -eq "ipv6") { $entry.IPv6 += $_.addr + " "} if ($_.addrtype -eq "mac") { $entry.MAC += $_.addr + " "} } if ($entry.IPv4 -eq $null) { $entry.IPv4 = "<no-ipv4>" } else { $entry.IPv4 = $entry.IPv4.Trim()} if ($entry.IPv6 -eq $null) { $entry.IPv6 = "<no-ipv6>" } else { $entry.IPv6 = $entry.IPv6.Trim()} if ($entry.MAC -eq $null) { $entry.MAC = "<no-mac>" } else { $entry.MAC = $entry.MAC.Trim() } # Process all ports from <ports><port>, and note that <port> does not contain an array if it only has one item in it. if ($hostnode.ports.port -eq $null) { $entry.Ports = "<no-ports>" } else { $hostnode.ports.port | foreach-object { If ($_.service.name -eq $null) { $service = "unknown" } else { $service = $_.service.name } $entry.Ports += $_.state.state + ":" + $_.protocol + ":" + $_.portid + ":" + $service + " " } $entry.Ports = $entry.Ports.Trim() } # Extract fingerprinted OS type and percent of accuracy. $hostnode.os.osmatch | foreach-object {$entry.OS += $_.name + " <" + ([String] $_.accuracy) + "%-accuracy> "} $entry.OS = $entry.OS.Trim() if ($entry.OS -eq "<%-accuracy>") { $entry.OS = "<no-os>" } # Emit custom object from script. $entry $i++ #Progress counter... } If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Finished $file, processed $i entries." ) } }
PowerShellCorpus/PoshCode/Compare Table & DataRow.ps1
Compare Table & DataRow.ps1
function Compare-DataRow { param( $a, $b) # @bernd_k http://pauerschell.blogspot.com/ $diff = '' $a_columncount = $a.Table.columns.count $b_columncount = $b.Table.columns.count if ( $a_columncount -ne $b_columncount) { Write-host "Tables have different number of columns" } foreach ( $i in 0..($a_columncount - 1)) { if ($a.item($i) -ne $b.item($i)) { $diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';' } } $diff } function Compare-Table { param( $a, $b) # @bernd_k http://pauerschell.blogspot.com/ $diff = '' $a_rowcount = $a.Rows.count $b_rowcount = $b.Rows.count if ( $a_rowcount -ne $b_rowcount1) { Write-host "Tables have different number of columns" } foreach ( $i in 0..($a_rowcount - 1)) { Compare-DataRow $a.rows[$i] $b.rows[$i] } $diff } Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0] Compare-Table ($a.tables[0]) ($b.tables[0])
PowerShellCorpus/PoshCode/Get-ExchangeDBSizes_1.ps1
Get-ExchangeDBSizes_1.ps1
<# .SYNOPSIS Get-ExchangeDBSizes - Gather data on Exchange 2007 / 2010 Mailbox Databases. .DESCRIPTION Gathers data from Exchange mailbox servers. These data include: Server\\StorageGroup\\Database (2007) or Database (2010), Total Size (in GB) of the disk, Size of the .edb file (in GB), Free disk space, Percent Disk Free, Total Mailboxes on the database, White Space, Total Free disk space, Total Percent Free disk space .EXAMPLE Get-ExchangeDBSizes .LINK http://unlockpowershell.wordpress.com/ http://poshcode.org/1901 #> Function Get-MountPointInfo($ServerName) { $Summary = @() $VolumeHash = @{} $VolumeCapacityHash = @{} $DatabaseSizeHash = @{} $DatabaseFreeHash = @{} $MountPoints = Get-WmiObject -Class Win32_Mountpoint -ComputerName $ServerName $MailboxDatabases = Get-MailboxDatabase -Server $ServerName $Volumes = Get-WmiObject -Class Win32_Volume -ComputerName $ServerName | Where-Object {$_.DriveType -eq 3}| Select-Object Name,FreeSpace,Capacity $DatabaseLetters = $MailboxDatabases | Select-Object edbfilepath foreach ($Volume in $Volumes) { $VolumeHash.Add($Volume.name.TrimEnd("\\"),$Volume.FreeSpace) $VolumeCapacityHash.Add($Volume.name.TrimEnd("\\"),$Volume.Capacity) } foreach ($drive in $DatabaseLetters) { $letter = $drive.EdbFilePath.Substring(0,$drive.EdbFilePath.lastIndexOf("\\")) $DatabaseSizeHash.Add($letter.TrimEnd("\\"),$VolumeCapacityHash[$letter]) $DatabaseFreeHash.Add($letter.TrimEnd("\\"),$VolumeHash[$letter]) } $VolumeHash.Clear() $VolumeCapacityHash.Clear() #Now I have all mailbox databases, along with the OS reported free space and capacity foreach ($MP in $Mountpoints) { $MP.directory = $MP.directory.replace("\\\\","\\").Split("=")[1].Replace("`"","") if($DatabaseSizeHash[$MP.directory]) { #This mountpoint is a database $Record = new-Object PSObject $OSfree = $DatabaseFreeHash[$MP.directory] $OSCapacity = $DatabaseSizeHash[$MP.directory] $DestFolder = "\\\\"+$ServerName + "\\" + $MP.directory $colItems = (Get-ChildItem $destfolder.Replace(":","$") -Recurse| where{$_.length -ne $null} |Measure-Object -property length -sum) if($colItems.sum -eq $null) { $fsize = 0 } else { $fsize = $colItems.sum } $TotFolderSize = $fsize + $OSfree $percFree = "{0:P0}" -f ( $OSfree/$TotFolderSize) $Record | add-Member -memberType noteProperty -name Server -Value $ServerName $Record | add-Member -memberType noteProperty -name "Mount Point" -Value $MP.directory $Record | add-Member -memberType noteProperty -name "Capacity" -Value ("{0:N2}" -f ($OSCapacity /1gb)) $Record | add-Member -memberType noteProperty -name "Used" -Value ("{0:N2}" -f ($fsize / 1gb)) $Record | add-Member -memberType noteProperty -name "Free" -Value ("{0:N2}" -f ($OSfree / 1gb)) $Record | add-Member -memberType noteProperty -name "Percent Free" -Value $percFree $Summary += $Record } } return $Summary } function Get-ExchangeWhiteSpace { param( $ComputerName = $(throw "ComputerName cannot be empty.") ) # Convert Dates to WMI CIM dates $tc = [System.Management.ManagementDateTimeconverter] $Start =$tc::ToDmtfDateTime( (Get-Date).AddDays(-1).Date ) $End =$tc::ToDmtfDateTime( (Get-Date).Date) $whiteSpace = @{} # Create two claculated properties for InsertionStrings values $DB = @{Name="DB";Expression={$_.InsertionStrings[1]}} $FreeMB = @{Name="FreeMB";Expression={[int]$_.InsertionStrings[0]}} $freespace = Get-WMIObject Win32_NTLogEvent -ComputerName $ComputerName -Filter "LogFile='Application' AND EventCode=1221 AND TimeWritten>='$Start' AND TimeWritten<='$End'" | Select-Object $DB,$FreeMB | Sort-Object DB –Unique –Descending $freespace | ForEach-Object {$whiteSpace.Add($_.DB,$_.FreeMB)} #Preceding function from Shay Levy http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/08/13/exchange-white-space.aspx } $AllServers = @() $ServerVersion = @{} foreach ($server in Get-MailboxServer) { $ServerName = $server.name $version = Get-ExchangeServer -Identity $ServerName | Select-Object AdminDisplayVersion if($version.admindisplayversion.major) { $ServerVersion.Add($ServerName,$version.admindisplayversion.major) } else { $ServerVersion.Add($ServerName,$version.admindisplayversion.Split()[1].split(".")[0]) } } foreach ($server in Get-MailboxServer) { $ServerName = $server.Name if ([int]$ServerVersion[$ServerName] -gt 8) { #An Exchange 2010 server, so use Get-MailboxDatabase <database> -Status | Select-Object AvailableNewMailboxSpace $whiteSpace = @{} $Free = Get-MailboxDatabase -Server $ServerName -Status | Select-Object Server,Name,AvailableNewMailboxSpace foreach ($item in $free) { $db = $ServerName+"\\"+$item.Name $whiteSpace.Add($item.Name,[int]$item.AvailableNewMailboxSpace.split("(")[1].Split()[0]/1mb) } } Else {#not an Exchange 2010 server . Get-ExchangeWhiteSpace $ServerName } $MountPoint = . Get-MountPointInfo $ServerName foreach ($objItem in Get-MailboxDatabase -Server $ServerName) { $edbfilepath = $objItem.edbfilepath $path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.Split(":")[0] + "$"+ $objItem.EdbFilePath.Split(":")[1] $dbsize = Get-ChildItem $path $dbpath=(Split-Path $edbfilepath.Split(":")[1] -Leaf).trimend(".edb") if (!$MountPoint) { $mailboxpath = $ServerName + $edbfilepath.Split(":")[1].trimend(".edb") $size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.Split("\\")[0]} |select-object deviceID, Freespace, Size $freespace = ($size.freespace / 1GB) $total = ($size.size / 1GB) } if ($MountPoint) { $mailboxpath = "$ServerName\\$dbpath" $MPPath = $EdbFilePath.Substring(0,$EdbFilePath.LastIndexOf("\\")) $freespace = $DatabaseFreeHash[$MPPath ] /1GB $total = $DatabaseSizeHash[$MPPath] /1GB } $PercentFree = "{0:n2}" -f ($freespace / $total *100) if (!$MountPoint) { $mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object } if($MountPoint) { $mailboxcount = Get-MailboxStatistics -database $mailboxpath.Split("\\")[1] |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object } $ReturnedObj = New-Object PSObject $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Server\\StorageGroup\\Database" -Value $objItem.Identity $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Size (GB)" -Value ("{0:n2}" -f ($total)) $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Used Space (GB)" -Value ("{0:n2}" -f ($dbsize.Length/1024MB)) $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Free Space (GB)" -Value ("{0:n2}" -f ($freespace)) $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Percent Disk Free" -Value $percentfree $ReturnedObj | Add-Member -MemberType NoteProperty -Name "User Mailbox Count" -Value $mailboxcount.count if ($objitem.Identity.Split("\\").Count -eq 3){$dbasename = $objitem.Identity.Substring($objitem.Identity.IndexOf("\\")+1)} else{$dbasename = $objitem.Identity} $ReturnedObj | Add-Member -MemberType NoteProperty -Name "White Space (GB)" -Value ("{0:n2}" -f ($whiteSpace[$dbasename]/1024)) $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Free (GB)" -Value ("{0:n2}" -f ($freespace + $whiteSpace[$dbasename]/1024)) $TotalPercent = ($freespace + $whiteSpace[$dbasename]/1024) / $total *100 $ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Percent Free" -Value ("{0:n2}" -f ($TotalPercent)) $AllServers += $ReturnedObj } } $AllServers |Export-Csv C:\\scripts\\MailboxDatabaseSizeReport.csv -NoTypeInformation
PowerShellCorpus/PoshCode/Search-Twitter.ps1
Search-Twitter.ps1
##############################################################################\n##\n## Search-Twitter\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\nSearch Twitter for recent mentions of a search term\n\n.EXAMPLE\n\nSearch-Twitter PowerShell\nSearches Twitter for the term "PowerShell"\n\n#>\n\nparam(\n ## The term to search for\n $Pattern = "PowerShell"\n)\n\nSet-StrictMode -Version Latest\n\n## Create the URL that contains the Twitter search results\nAdd-Type -Assembly System.Web\n$queryUrl = 'http://integratedsearch.twitter.com/search.html?q={0}'\n$queryUrl = $queryUrl -f ([System.Web.HttpUtility]::UrlEncode($pattern))\n\n## Download the web page\n$wc = New-Object System.Net.WebClient\n$wc.Encoding = [System.Text.Encoding]::UTF8\n$results = $wc.DownloadString($queryUrl)\n\n## Extract the text of the messages, which are contained in\n## segments that look like "<div class='msg'>...</div>"\n$matches = $results |\n Select-String -Pattern '(?s)<div[^>]*msg[^>]*>.*?</div>' -AllMatches\n\nforeach($match in $matches.Matches)\n{\n ## Replace anything in angle brackets with an empty string,\n ## leaving just plain text remaining.\n $tweet = $match.Value -replace '<[^>]*>', ''\n\n ## Output the text\n [System.Web.HttpUtility]::HtmlDecode($tweet.Trim()) + "`n"\n}
PowerShellCorpus/PoshCode/PoSh Email Tester GUI.ps1
PoSh Email Tester GUI.ps1
<# .NOTES Name : PoSh Email Tester GUI Author : Bryan Jaudon <bryan.jaudon@gmail.com> Version : 1.0 Date : 10/30/2012 .Description GUI Email tester program utilizing PowerShell Send-MailMessage cmdlet. #> #requires -version 2 #region IconExtrator TypeDef $code = @" using System; using System.Drawing; using System.Runtime.InteropServices; namespace System { public class IconExtractor { public static Icon Extract(string file, int number, bool largeIcon) { IntPtr large; IntPtr small; ExtractIconEx(file, number, out large, out small, 1); try { return Icon.FromHandle(largeIcon ? large : small); } catch { return null; } } [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons); } } "@ Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing #endregion #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() #endregion #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 # Generated On: 10/30/2012 8:26 AM # Generated By: bjaudon ######################################################################## #region Generated Form Objects $frmTester = New-Object System.Windows.Forms.Form $lnkCredential = New-Object System.Windows.Forms.LinkLabel $lblCredential = New-Object System.Windows.Forms.Label $cbSSL = New-Object System.Windows.Forms.CheckBox $tbSMTPServer = New-Object System.Windows.Forms.TextBox $lblSMTPServer = New-Object System.Windows.Forms.Label $lblAttachment = New-Object System.Windows.Forms.Label $btnBrowse = New-Object System.Windows.Forms.Button $tbAttachment = New-Object System.Windows.Forms.TextBox $btnSend = New-Object System.Windows.Forms.Button $btnExit = New-Object System.Windows.Forms.Button $tbBody = New-Object System.Windows.Forms.TextBox $tbSubject = New-Object System.Windows.Forms.TextBox $lblSubject = New-Object System.Windows.Forms.Label $tbFrom = New-Object System.Windows.Forms.TextBox $lblFrom = New-Object System.Windows.Forms.Label $tbTo = New-Object System.Windows.Forms.TextBox $lblTo = New-Object System.Windows.Forms.Label $pbIcon = New-Object System.Windows.Forms.PictureBox $lblTitle = New-Object System.Windows.Forms.Label $openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $handler_lnkCredential_LinkClicked= { #TODO: Place custom script here try { $script:Credentials=Get-Credential -Message "Please enter your SMTP Server credentials." } catch { $script:Credentials=$null } finally { if ($script:Credentials -eq $null) { $lnkCredential.Text = "Anonymous" } else { $lnkCredential.Text = $script:Credentials.UserName } } } $btnBrowse_OnClick= { #TODO: Place custom script here $tbAttachment.Text=OpenFile-Dialog } $btnSend_OnClick= { #TODO: Place custom script here $GUID=[guid]::NewGuid() try { SendMail -To $tbTo.Text -From $tbFrom.Text -Subject $tbSubject.Text -SMTPServer $tbSMTPServer.Text -Attachment $tbAttachment.Text -Body "$($tbBody.Text)`r`n`r`nEmail ID: $GUID" -SSL $cbSSL.Checked -Credential $Script:Credentials } catch { ShowPrompt -Message $_ -Icon Error -Buttons OK; return } ShowPrompt -Message "Email was sent successfully!`n`nEmail ID: $GUID" -Icon Information -Buttons OK } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $frmTester.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 469 $System_Drawing_Size.Width = 553 $frmTester.ClientSize = $System_Drawing_Size $frmTester.DataBindings.DefaultDataSourceUpdateMode = 0 $frmTester.FormBorderStyle = 1 $frmTester.Name = "frmTester" $frmTester.Text = "PoSh Email Tester" $frmTester.Icon = [System.IconExtractor]::Extract("shell32.dll",156,$true) $lnkCredential.AutoEllipsis = $True $lnkCredential.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 392 $System_Drawing_Point.Y = 68 $lnkCredential.Location = $System_Drawing_Point $lnkCredential.Name = "lnkCredential" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 146 $lnkCredential.Size = $System_Drawing_Size $lnkCredential.TabIndex = 1 $lnkCredential.TabStop = $True $lnkCredential.Text = "Anonymous" $lnkCredential.TextAlign = 16 $lnkCredential.VisitedLinkColor = [System.Drawing.Color]::FromArgb(255,0,0,255) $lnkCredential.add_LinkClicked($handler_lnkCredential_LinkClicked) $frmTester.Controls.Add($lnkCredential) $lblCredential.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 327 $System_Drawing_Point.Y = 68 $lblCredential.Location = $System_Drawing_Point $lblCredential.Name = "lblCredential" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 59 $lblCredential.Size = $System_Drawing_Size $lblCredential.TabIndex = 15 $lblCredential.Text = "Credential:" $lblCredential.TextAlign = 16 $frmTester.Controls.Add($lblCredential) $cbSSL.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 434 $cbSSL.Location = $System_Drawing_Point $cbSSL.Name = "cbSSL" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 140 $cbSSL.Size = $System_Drawing_Size $cbSSL.TabIndex = 6 $cbSSL.Text = "Send &using SSL/TLS" $cbSSL.UseVisualStyleBackColor = $True $frmTester.Controls.Add($cbSSL) $tbSMTPServer.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 94 $System_Drawing_Point.Y = 71 $tbSMTPServer.Location = $System_Drawing_Point $tbSMTPServer.Name = "tbSMTPServer" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 216 $tbSMTPServer.Size = $System_Drawing_Size $tbSMTPServer.TabIndex = 0 $frmTester.Controls.Add($tbSMTPServer) $lblSMTPServer.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 69 $lblSMTPServer.Location = $System_Drawing_Point $lblSMTPServer.Name = "lblSMTPServer" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $lblSMTPServer.Size = $System_Drawing_Size $lblSMTPServer.TabIndex = 14 $lblSMTPServer.Text = "SMTP Server:" $lblSMTPServer.TextAlign = 16 $frmTester.Controls.Add($lblSMTPServer) $lblAttachment.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 204 $lblAttachment.Location = $System_Drawing_Point $lblAttachment.Name = "lblAttachment" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $lblAttachment.Size = $System_Drawing_Size $lblAttachment.TabIndex = 13 $lblAttachment.Text = "Attachment:" $lblAttachment.TextAlign = 16 $frmTester.Controls.Add($lblAttachment) $btnBrowse.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 463 $System_Drawing_Point.Y = 207 $btnBrowse.Location = $System_Drawing_Point $btnBrowse.Name = "btnBrowse" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $btnBrowse.Size = $System_Drawing_Size $btnBrowse.TabIndex = 4 $btnBrowse.Text = "B&rowse..." $btnBrowse.UseVisualStyleBackColor = $True $btnBrowse.add_Click($btnBrowse_OnClick) $frmTester.Controls.Add($btnBrowse) $tbAttachment.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 94 $System_Drawing_Point.Y = 208 $tbAttachment.Location = $System_Drawing_Point $tbAttachment.Name = "tbAttachment" $tbAttachment.ReadOnly = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 363 $tbAttachment.Size = $System_Drawing_Size $tbAttachment.TabIndex = 0 $tbAttachment.TabStop = $False $frmTester.Controls.Add($tbAttachment) $btnSend.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 382 $System_Drawing_Point.Y = 434 $btnSend.Location = $System_Drawing_Point $btnSend.Name = "btnSend" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $btnSend.Size = $System_Drawing_Size $btnSend.TabIndex = 7 $btnSend.Text = "&Send" $btnSend.UseVisualStyleBackColor = $True $btnSend.add_Click($btnSend_OnClick) $frmTester.Controls.Add($btnSend) $btnExit.DataBindings.DefaultDataSourceUpdateMode = 0 $btnExit.DialogResult = 2 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 463 $System_Drawing_Point.Y = 434 $btnExit.Location = $System_Drawing_Point $btnExit.Name = "btnExit" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $btnExit.Size = $System_Drawing_Size $btnExit.TabIndex = 8 $btnExit.Text = "E&xit" $btnExit.UseVisualStyleBackColor = $True $frmTester.Controls.Add($btnExit) $tbBody.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 241 $tbBody.Location = $System_Drawing_Point $tbBody.Multiline = $True $tbBody.Name = "tbBody" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 173 $System_Drawing_Size.Width = 526 $tbBody.Size = $System_Drawing_Size $tbBody.TabIndex = 5 $tbBody.Text = "This is a test email message from PoSh Email Tester. " $frmTester.Controls.Add($tbBody) $tbSubject.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 94 $System_Drawing_Point.Y = 167 $tbSubject.Location = $System_Drawing_Point $tbSubject.Name = "tbSubject" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 445 $tbSubject.Size = $System_Drawing_Size $tbSubject.TabIndex = 3 $tbSubject.Text = "PoSh Email Tester - Test Email" $frmTester.Controls.Add($tbSubject) $lblSubject.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 165 $lblSubject.Location = $System_Drawing_Point $lblSubject.Name = "lblSubject" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $lblSubject.Size = $System_Drawing_Size $lblSubject.TabIndex = 6 $lblSubject.Text = "Subject:" $lblSubject.TextAlign = 16 $frmTester.Controls.Add($lblSubject) $tbFrom.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 94 $System_Drawing_Point.Y = 102 $tbFrom.Location = $System_Drawing_Point $tbFrom.Name = "tbFrom" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 445 $tbFrom.Size = $System_Drawing_Size $tbFrom.TabIndex = 1 $tbFrom.Text = "test@test.com" $frmTester.Controls.Add($tbFrom) $lblFrom.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 100 $lblFrom.Location = $System_Drawing_Point $lblFrom.Name = "lblFrom" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $lblFrom.Size = $System_Drawing_Size $lblFrom.TabIndex = 4 $lblFrom.Text = "From:" $lblFrom.TextAlign = 16 $frmTester.Controls.Add($lblFrom) $tbTo.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 94 $System_Drawing_Point.Y = 134 $tbTo.Location = $System_Drawing_Point $tbTo.Name = "tbTo" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 445 $tbTo.Size = $System_Drawing_Size $tbTo.TabIndex = 2 $frmTester.Controls.Add($tbTo) $lblTo.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 132 $lblTo.Location = $System_Drawing_Point $lblTo.Name = "lblTo" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $lblTo.Size = $System_Drawing_Size $lblTo.TabIndex = 2 $lblTo.Text = "To:" $lblTo.TextAlign = 16 $frmTester.Controls.Add($lblTo) $pbIcon.BackgroundImageLayout = 3 $pbIcon.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 9 $pbIcon.Location = $System_Drawing_Point $pbIcon.Name = "pbIcon" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 48 $System_Drawing_Size.Width = 48 $pbIcon.Size = $System_Drawing_Size $pbIcon.SizeMode = 1 $pbIcon.TabIndex = 1 $pbIcon.TabStop = $False $pbIcon.Image = [System.IconExtractor]::Extract("shell32.dll",156,$true) $frmTester.Controls.Add($pbIcon) $lblTitle.DataBindings.DefaultDataSourceUpdateMode = 0 $lblTitle.Font = New-Object System.Drawing.Font("Trebuchet MS",9.75,1,3,1) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 76 $System_Drawing_Point.Y = 21 $lblTitle.Location = $System_Drawing_Point $lblTitle.Name = "lblTitle" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 463 $lblTitle.Size = $System_Drawing_Size $lblTitle.TabIndex = 0 $lblTitle.Text = "PoSh Email Tester 1.0" $lblTitle.TextAlign = 16 $frmTester.Controls.Add($lblTitle) $openFileDialog1.Filter = "All Files (*.*)|*.*" $openFileDialog1.ShowHelp = $True #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $frmTester.WindowState #Init the OnLoad event to correct the initial state of the form $frmTester.add_Load($OnLoadForm_StateCorrection) #Show the Form $frmTester.ShowDialog()| Out-Null } #End Function Function OpenFile-Dialog { $open=$OpenFileDialog1.ShowDialog() #If the Open button is pressed if ($open -eq "OK") { #If our source and destination are the same file #Set our source to the chosen file return $OpenFileDialog1.FileName } #If cancel is pressed else { return } } Function ShowPrompt { param ($Message,$Buttons,$Icon,$DefaultButton="button1") return [System.Windows.Forms.MessageBox]::Show($Message,$frmTester.Text,$Buttons,$Icon,$DefaultButton) } Function SendMail { param ($To,$From,$Subject,$Attachment,$SMTPServer,$Body,$SSL,$Credential) $MailMessageParams=@{ "To"=$To "From"=$From "Subject"=$Subject "SMTPServer"=$SMTPServer "Body"=$Body "UseSSL"=$SSL } if ($Attachment) { $MailMessageParams.Add("Attachment",$Attachment) } if ($Credential) { $MailMessageParams.Add("Credential",$Credential) } Send-MailMessage @MailMessageParams -ErrorAction STOP } #Call the Function GenerateForm
PowerShellCorpus/PoshCode/PowerShell Template_2.ps1
PowerShell Template_2.ps1
Function New-Script { $strName = $env:username $date = get-date -format d $name = Read-Host "Filename" if ($name -eq "") { $name="NewTemplate" } $email = Read-Host "eMail Address" if ($email -eq "") { $email="genemagerr@hotmail.com" } $comment=@(); while($s = (Read-Host "Comment").Trim()){$comment+="$s`r`n#"} $file = New-Item -type file "$name.ps1" -force $template=@" ########################################################################### # # NAME: $name.ps1 # # AUTHOR: $strName # EMAIL: $email # # COMMENT: $comment # # 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 $date - Initial release # ########################################################################### "@ | out-file $file ii $file
PowerShellCorpus/PoshCode/Scan VB6 Code.ps1
Scan VB6 Code.ps1
#requires -version 2 # some PowerShell Functions to scan VB 6 Projects for patterns # e.g. some SQL calls # by Bernd Kriszio http://pauerschell.blogspot.com/ function Get-VBProject ($file) { # this is developed for use with Visual Basic 6 # to extract the files the contain VB Code pushd (Split-path $file) foreach ($line in (gc $file)) { if ($line -match "Class=\\S+;\\s+(\\S+.cls)") { gi $matches[1] } elseif ($line -match "Form=(\\S+.frm)") { gi $matches[1] } elseif ($line -match "Module=\\S+;\\s*(\\S+.BAS)") { gi $matches[1] } } popd } function Get-VBLines ($file) { # VB 6 uses _ at end of line as line continuation character # we build logical VB lines, especially to get complete signatures of functions and subroutines $oFile = gi $file $SourceLineNumber = 0 foreach ($line in (gc $file)) { $SourceLineNumber++ if ($continue) { $buffer += "`r`n" + $line if ($line -notmatch '_$') { $continue = $False $o = New-Object object Add-Member -InputObject $o -MemberType NoteProperty -Name LineNumber -Value $LineNumber Add-Member -InputObject $o -MemberType NoteProperty -Name VBLine -Value $buffer Add-Member -InputObject $o -MemberType NoteProperty -Name file -Value $oFile.Name Add-Member -InputObject $o -MemberType NoteProperty -Name filepath -Value $oFile.FullName $o } } else { $buffer = $line $LineNumber = $SourceLineNumber if ($line -match '_$') { $continue = $True } else { $o = New-Object object Add-Member -InputObject $o -MemberType NoteProperty -Name LineNumber -Value $LineNumber Add-Member -InputObject $o -MemberType NoteProperty -Name VBLine -Value $buffer Add-Member -InputObject $o -MemberType NoteProperty -Name file -Value $oFile.Name Add-Member -InputObject $o -MemberType NoteProperty -Name filepath -Value $oFile.FullName $o } } } } function Get-VB_CodeObject () { param ( [Parameter(Position = 0, Mandatory=$true, ValueFromPipeline=$True)] $file ) PROCESS { $inObject = $False $lines = @() $comments = @() $inDeclareations = $True #write-Host "--- $file ----" Get-VBLines $file | % { if ($inObject) { if ($_.VBLine -match "^End $end") { $lines += $_.VBLine $inObject = $False if ($inDeclareations){ $o = New-Object object Add-Member -InputObject $o -MemberType NoteProperty -Name LineNumber -Value 1 Add-Member -InputObject $o -MemberType NoteProperty -Name Code -Value $comments Add-Member -InputObject $o -MemberType NoteProperty -Name Comments -Value '' Add-Member -InputObject $o -MemberType NoteProperty -Name file -Value $_.file Add-Member -InputObject $o -MemberType NoteProperty -Name filepath -Value $_.filepath Add-Member -InputObject $o -MemberType NoteProperty -Name acces -Value '' Add-Member -InputObject $o -MemberType NoteProperty -Name typ -Value '' Add-Member -InputObject $o -MemberType NoteProperty -Name name -Value 'Declarations' $inDeclareations = $false $o $comments = @() } $o = New-Object object Add-Member -InputObject $o -MemberType NoteProperty -Name LineNumber -Value $LineNumber Add-Member -InputObject $o -MemberType NoteProperty -Name Code -Value $lines Add-Member -InputObject $o -MemberType NoteProperty -Name Comments -Value $comments Add-Member -InputObject $o -MemberType NoteProperty -Name file -Value $_.file Add-Member -InputObject $o -MemberType NoteProperty -Name filepath -Value $_.filepath Add-Member -InputObject $o -MemberType NoteProperty -Name acces -Value $acces Add-Member -InputObject $o -MemberType NoteProperty -Name typ -Value $typ Add-Member -InputObject $o -MemberType NoteProperty -Name name -Value $name $o $lines = @() } else { # collect lines $lines += $_.VBLine } } else { if ($_.VBLine -match "^(Public|Private)?\\s*Property\\s+(Get|Set)\\s+([^\\s\\(]+)") { $acces = $matches[1] $typ = 'Property ' + $matches[2] $name = $matches[3] $end = 'Property' $inObject = $True #$acces + " " + $typ + " " + $name $comments = $lines $lines = (, $_.VBLine) $LineNumber = $_.LineNumber } elseif ($_.VBLine -match "^(Public|Private)?\\s*(Function|Sub)\\s+([^\\s\\(]+)") { $acces = $matches[1] $typ = $matches[2] $name = $matches[3] $end = $matches[2] $inObject = $True #$acces + " " + $typ + " " + $name $comments = $lines $lines = (, $_.VBLine) $LineNumber = $_.LineNumber } else { $lines += $_.VBLine } } } } } filter Select-VBCode_String ($pattern) { $o = New-Object object Add-Member -InputObject $o -MemberType NoteProperty -Name LineNumber -Value $_.LineNumber Add-Member -InputObject $o -MemberType NoteProperty -Name Comments -Value $_.comments Add-Member -InputObject $o -MemberType NoteProperty -Name file -Value $_.file Add-Member -InputObject $o -MemberType NoteProperty -Name filepath -Value $_.filepath Add-Member -InputObject $o -MemberType NoteProperty -Name acces -Value $_.acces Add-Member -InputObject $o -MemberType NoteProperty -Name typ -Value $_.typ Add-Member -InputObject $o -MemberType NoteProperty -Name name -Value $_.name $patternFound = $False $lines = @() foreach ($l in $_.Code) { if ($l -match $pattern) { $lines += $l $patternFound = $True } } if ( $patternFound) { Add-Member -InputObject $o -MemberType NoteProperty -Name Code -Value $lines $o } } <# $myVBProject = 'myDirtyVb6Project.vbp' $vbp = Get-VBProject $myVBProject | Get-VB_CodeObject # Now you search your VB Project for patterns # look for sql SELECT-Statements $vbp | Select-VBCode_String('"select') |% { $_.code } # or the location of Vb EXIT Statments $vbp| Select-VBCode_String('EXIT') | fl $vbp| select file, acces, typ, name #>
PowerShellCorpus/PoshCode/Help Differ 10000 v_2.01.ps1
Help Differ 10000 v_2.01.ps1
# These functions are meant to help generate a table that shows differences between # cmdlets among different versions of a module. # You will need a MoinMoin wiki to render the output. # If you don't have a MoinMoin wiki you might be able to use the sandbox at http://moinmo.in/WikiSandBox # Extracts some data from a module's help for use with Diff-HelpXml function Get-HelpXml { param ($module) get-command -pssnapin $module | % { $allParams = $_.parametersets | % { $_.parameters | select -unique Name } $obj = new-object psobject $obj | add-member -type noteproperty -name name -value $_.Name $obj | add-member -type noteproperty -name parameters -value $allParams # Pull some things out of help. $h = $_ | get-help $obj | add-member -type noteproperty -name description -value $h.Description $obj | add-member -type noteproperty -name paramDescriptions -value $h.parameters $obj } } # Diff a help XML and output the results in Moinmoin wiki format. # You can then copy to a MoinMoin wiki to do HTML rendering. function Diff-HelpXml { param ($beforeFile, $afterFile) # The XML files should be generated with makexml.ps1 $before = import-clixml $beforeFile $after = import-clixml $afterFile $titleColor = "<bgcolor=`"#72AEC0`">" $color1 = "<bgcolor=`"#C2DEF0`">" $color2 = "<bgcolor=`"#ffffff`">" echo "= New cmdlets in this release =" echo " ||$titleColor Name ||$titleColor Description ||" foreach ($a in $after) { $match = $before | where { $_.Name -eq $a.Name } if ($match -eq $null) { $name = $a.Name $desc = $a.Description[0].Text $desc = $desc.replace("`n", " ") $desc = $desc.replace("`r", " ") echo " || $name || $desc ||" } } echo "" echo "= New cmdlet parameters in this release =" $color = $color1 echo " ||$titleColor Cmdlet Name ||$titleColor Parameter Name ||$titleColor Description ||" foreach ($a in $after) { $match = $before | where { $_.Name -eq $a.Name } if ($match) { $noMatches = $true foreach ($p in $a.parameters) { $matchPar = $match.parameters | where { $_.Name -eq $p.Name } if ($matchPar -eq $null) { $cmdletName = "" $pName = $p.Name if ($noMatches) { $cmdletName = $a.Name $noMatches = $false if ($color -eq $color1) { $color = $color2 } else { $color = $color1 } } # Find the help for this switch. $matchDesc = $a.paramDescriptions.parameter | where { $_.Name -eq $pName } $pDesc = $matchDesc.description[0].text $pDesc = $pDesc -replace "[^A-Za-z1-9\\.`"``, ]", " " echo " ||$color $cmdletName ||$color $pName ||$color $pDesc ||" } } } } } # Sample usage: ## Install VI Toolkit 1.0 # Get-HelpXml -module vmware.vimautomation.core | export-clixml before.xml ## Install VI Toolkit 1.5 # Get-HelpXml -module vmware.vimautomation.core | export-clixml after.xml # Diff-HelpXml -before before.xml -after after.xml | set-content diffsInMoinMoin.txt
PowerShellCorpus/PoshCode/Format-PoshTable.ps1
Format-PoshTable.ps1
function Format-PoshTable { #.Synopsis # Format-PoshTable puts the output in a WPF DataGrid (inline in PoshConsole) #.Description # Outputs a WPF datagrid of the objects (and properties) specified. # This grid can be sorted, rearranged, etc [CmdletBinding()] param( [parameter(ValueFromPipeline=$true)] [Array]$InputObject , [Parameter(Position=1)] [String[]]$Property = "*" , [Parameter(Position=2)][Alias("Type")] [Type]$BaseType # a type to use as the generic in the collection , [Parameter()] [Switch]$Popup = (![bool]$Host.PrivateData.WpfConsole) ) Begin { $global:theFormatPoshTableDataGrid = $null if (!(Get-Command datagrid) ) { Import-Module PowerBoots Add-BootsFunction 'C:\\Program Files (x86)\\WPF Toolkit\\*\\WPFToolkit.dll' } } Process { # Create the window here instead of in BEGIN because we need to know the TYPE for the datagrid if(!$global:theFormatPoshTableDataGrid) { if(!$BaseType) { $BaseType = $InputObject[0].GetType().FullName } # We're going to create a special collection ... $global:ObservableCollection = new-object System.Collections.ObjectModel.ObservableCollection[$BaseType] foreach($i in $InputObject) { $ObservableCollection.Add($i) > $null } boots { Param($ItemCollection, $Property) datagrid -RowBackground "AliceBlue" -AlternatingRowBackground "LightBlue" -On_AutoGeneratingColumn { Param($Source,$SourceEventArgs) $header = $SourceEventArgs.Column.Header.ToString() $Cancel = $true # If it matches any of the properties, don't cancel it. foreach($h in $Source.Tag) { if($header -like $h) { $Cancel = $false } } $SourceEventArgs.Cancel = $Cancel } -ColumnHeaderStyle { Style -Setters { Setter -Property ([System.Windows.Controls.ListView]::FontWeightProperty) -Value ([System.Windows.FontWeights]::ExtraBold) } } -ItemsSource $ItemCollection -ov global:theFormatPoshTableDataGrid -tag $Property } $ObservableCollection $Property -Inline:(!$Popup) -Popup:$Popup } else { @($global:theFormatPoshTableDataGrid)[0].Dispatcher.Invoke( "Normal", ([Action]{ foreach($i in @($InputObject)) { $global:ObservableCollection.Add($i) > $null } }) ) } } }
PowerShellCorpus/PoshCode/824c3a01-0fdd-4a67-90af-bd398fb95b05.ps1
824c3a01-0fdd-4a67-90af-bd398fb95b05.ps1
# Description: Create Events in Application log # Date: 03-05-2007 # Author: Stefan Stranger & Ken # Explanation: If you only wish to write to the event log you must do two things. The first is to create or specify a Source. # The second is to call the WriteEntry method. The source would be your application name, by default, # if you create a source that is new then your log entry will be written to the Application Log. To WriteEntry method does the actual writing to the Event Log. # ev.WriteEntry(&#65533;My event text&#65533;, System.Diagnostics.EventLogEntryType.Information, myeventid) # Changes: Ken made changes in the Write-Eventlog function: 1) modified it so that you can log events in any Event Log using the Source to look up which log to use, # added a check in to ask if the user wants to create the missing Source in the Application log rather than just creating it, # never know when you will msispell a source ;) 3) Modified the question for description to also say or Params/Param[1]. #Check if user is admin function get-Admin { $ident = [Security.Principal.WindowsIdentity]::GetCurrent() foreach ( $groupIdent in $ident.Groups ) { if ( $groupIdent.IsValidTargetType([Security.Principal.SecurityIdentifier]) ) { $groupSid = $groupIdent.Translate([Security.Principal.SecurityIdentifier]) if ( $groupSid.IsWellKnown("AccountAdministratorSid") -or $groupSid.IsWellKnown("BuiltinAdministratorsSid")){ return $true } } } return $false } $Result = get-Admin if ($Result -eq $False) { write-host "Better be an admin for this script." #exit } function Write-EventLog { param ([string]$source = $(read-host "Please enter Event Source"), [string]$type = $(read-host "Please enter Event Type [Information, Warning, Error]"), [int]$eventid = $(read-host "Please enter EventID"), [string]$msg = $(read-host "Please enter Event Description or Params/Param[1] value")) #Create the source, if it does not already exist. if(![System.Diagnostics.EventLog]::SourceExists($source)) { #Create based on user response [string]$create = $(read-host "Source doesn't exist. Do you want to create in the Application Log? [Yes or No]") if(($create -eq "Yes") -or ($create -eq "Y")) { [System.Diagnostics.EventLog]::CreateEventSource($source,'Application') $logfile = 'Application' write-host "Source created and registered in the $logfile Log" } else { write-host "** Script Terminated ** User didn't want to create missing Source" exit 0 } } else { $logfile = [System.Diagnostics.EventLog]::LogNameFromSourceName($source,'.') write-host "Source exists and is registered in the $logfile Log" } #Check if Event Type is correct switch ($type) { "Information" {} "Warning" {} "Error" {} default {"Event type is invalid";exit} } $log = New-Object System.Diagnostics.EventLog $log.set_log($logfile) $log.set_source($source) $log.WriteEntry($msg,$type,$eventid) } Write-Eventlog Write-Host "Event created"
PowerShellCorpus/PoshCode/Out-DataTable_2.ps1
Out-DataTable_2.ps1
####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-Alias | Out-DataTable This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties v1.4 - Chad Miller - Corrected issue with DBNull .LINK http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx #> function Out-DataTable { [CmdletBinding()] param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) Begin { $dt = new-object Data.datatable $First = $true } Process { foreach ($object in $InputObject) { $DR = $DT.NewRow() foreach($property in $object.PsObject.get_properties()) { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $property.Name.ToString() if ($property.value) { if ($property.value -isnot [System.DBNull]) { $Col.DataType = $property.value.gettype() } } $DT.Columns.Add($Col) } if ($property.IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/powershell ise config_3.ps1
powershell ise config_3.ps1
<configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> </startup> <runtime> <loadFromRemoteSources enabled="true"/> </runtime> </configuration>
PowerShellCorpus/PoshCode/PowerChart 0.52.ps1
PowerChart 0.52.ps1
function New-PowerChart() { #.Synopsis # Create a chart using the WPF DataVisualization Toolkit (WPFToolkit) #.Example # New-PowerChart Area { ls | ? {!$_.PSIsContainer} } -IndependentValue Name -DependentValue Length -Show #.Example # New-PowerChart Pie { ps | sort WS -desc | select -first 10 } Name WS -Show -Interval "0:0:5" [CmdletBinding(DefaultParameterSetName='DataTemplate')] param( [Parameter(Position=0, Mandatory=$true)] [ValidateSet("Area","Bar","Bubble","Column","Line","Pie","Scatter")] [String[]] ${ChartType} , [Parameter(Position=1, Mandatory=$true, HelpMessage='The data for the chart ...')] [System.Management.Automation.ScriptBlock[]] ${ItemsSource} , [Parameter(Position=2, Mandatory=$true, HelpMessage='The property name for the independent values ...')] [String[]] ${IndependentValuePath} , [Parameter(Position=3, Mandatory=$true, HelpMessage='The property name for the dependent values ...')] [String[]] ${DependentValuePath} , [Parameter(Position=4, HelpMessage='The property name for the size values ...')] [String[]] ${SizeValuePath} , [TimeSpan] ${Interval} , [Switch] $Show ) begin { Chart -ControlNale PowerChart -Tag @{Interval=$Interval; ItemsSource=$ItemsSource} -On_Loaded { $Interval = $this.Tag.Interval if($Interval) { Register-PowerShellCommand -ScriptBlock { $i=0 $Window.Content.Series | ForEach{ $_.ItemsSource = &$($Window.Content.Tag.ItemsSource[$i++]) } } -in $Interval -run } } -Series { $Series = @() # Write-Host "Three" -Fore Cyan for($c=0; $c -lt $ChartType.length; $c++) { $chartType = $ChartType[$c].ToLower() if($SizeValuePath -and $ChartType[$c] -eq "Bubble") { $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -SizeValuePath $($SizeValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix") } elseif($ChartType[$c] -eq "Pie") { $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #$Series[-1].StylePalette = $this.FindResource("$($chartType)PaletteTooltipsFix") } else { Write-Verbose "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #A$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix") } } Write-Verbose "There are $($Series.Count) Series!" $Series } -Background Transparent -BorderThickness 0 -Show:$Show } }
PowerShellCorpus/PoshCode/Select-Xml 2.1.ps1
Select-Xml 2.1.ps1
#requires -version 2.0 # Select-Xml 2.1 and Remove-XmlNamespace function Select-Xml { #.Synopsis # This improved version of the Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. # # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # Note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { Select-Node (Remove-XmlNamespace ([Xml]($XmlContent.ToString()))) $XPath $NSM } } } function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform # [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(ParameterSetName="Content",Mandatory=$true)] [String[]]$Content , [Parameter(Position=0,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [String[]]$Path , [Parameter(Position=0,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true)] [Alias("IO","InputObject")] [System.Xml.XmlDocument[]]$Xml ) BEGIN { $xslt = New-Object System.Xml.Xsl.XslCompiledTransform $xslt.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { [System.Xml.XmlDocument[]]$Xml = @( [Xml]($Content -Join "`n") ) } "Path" { [System.Xml.XmlDocument[]]$Xml = @() foreach($file in Get-ChildItem $Path) { $Xml += [Xml](Get-Content $file) } } "Xml" { } } foreach($input in $Xml) { $Output = New-Object System.Xml.XmlDocument $writer =$output.CreateNavigator().AppendChild() $xslt.Transform( $input.CreateNavigator(), $null, $writer ) $writer.Close() # $writer.Dispose() Write-Output $output } } }
PowerShellCorpus/PoshCode/vmrc remote connector.ps1
vmrc remote connector.ps1
#region Global var $script:viserver = "esx.local" $script:vmrc = "C:\\Program Files\\VMwareVMRC\\vmware-vmrc.exe" $script:vm = "" $script:vmt = "" $script:vmcon = "" $script:selectvm = "" $script:multiple = $FALSE #Set to TRUE for multiple VMRC Instances #endregion $vmcon = Connect-VIServer -Server $script:viserver -Protocol https -Credential (Get-Credential) if (!$vmcon) { Write-Output "No Connection!" break } $script:vmt = Get-VM function GenerateForm { #region Import the Assembles [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $form1 = New-Object System.Windows.Forms.Form $btnConnect = New-Object System.Windows.Forms.Button $txtEntity = New-Object System.Windows.Forms.TextBox $chkIP = New-Object System.Windows.Forms.CheckBox $comboBox1 = New-Object System.Windows.Forms.ComboBox #endregion Generated Form Objects $btnConnect_OnClick= { #region Check User Inputs if (!$txtEntity.Text -eq "" -and !$comboBox1.Text -eq "") { Write-Host "Bitte nur eine Option anwählen!" break } #endregion if ($txtEntity.Text -eq "") { $script:selectvm = $comboBox1.Text } else { $script:selectvm = $txtEntity.Text } if ($chkIP.Checked) { $script:chk = "FALSE" foreach ($script:vm in $script:vmt) { $vmg = Get-VMGuest $script:vm if ($vmg.IPAddress -eq $script:selectvm) { $script:chk = "" break } } } If (!$script:selectvm -eq "" -and !$chkIP.Checked) { $script:vm = Get-VM $script:selectvm if($script:vm.Count) { Write-Output "Define only one host!" break } else { if (!$script:vm.id) { Write-Output "No VM found" $script:chk = "FALSE"; break } } } if (!$script:chk) { if (!$script:vm -eq "") { if (!($script:gvm = Get-View $script:vm.id) -eq "") { if (($multiple) -or (!($multiple) -and $script:gvm.Runtime.NumMksConnections -lt 1)) { $vmrcargs = '-h ' + $script:vm.Host + ' -m "' + $script:gvm.Config.Files.VmPathName + '"' [Diagnostics.Process]::Start($script:vmrc, $vmrcargs) } } } } } #---------------------------------------------- #region Generated Form Code $form1.Text = 'VMware Remote Connector' $form1.Name = 'form1' $form1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 193 $System_Drawing_Size.Width = 281 $form1.ClientSize = $System_Drawing_Size $form1.FormBorderStyle = 1 $btnConnect.TabIndex = 2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $btnConnect.Size = $System_Drawing_Size $btnConnect.Name = 'btnConnect' $btnConnect.UseVisualStyleBackColor = $True $btnConnect.Text = 'Verbinden' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 97 $System_Drawing_Point.Y = 115 $btnConnect.Location = $System_Drawing_Point $btnConnect.DataBindings.DefaultDataSourceUpdateMode = 0 $btnConnect.add_Click($btnConnect_OnClick) $form1.Controls.Add($btnConnect) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 17 $txtEntity.Location = $System_Drawing_Point $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 261 $txtEntity.Size = $System_Drawing_Size $txtEntity.DataBindings.DefaultDataSourceUpdateMode = 0 $txtEntity.Name = 'txtEntity' $txtEntity.TabIndex = 1 $form1.Controls.Add($txtEntity) $chkIP.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 19 $System_Drawing_Size.Width = 160 $chkIP.Size = $System_Drawing_Size $chkIP.Name = 'chkIP' $chkIP.UseVisualStyleBackColor = $True $chkIP.Text = 'IP Adresse' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 43 $chkIP.Location = $System_Drawing_Point $chkIP.DataBindings.DefaultDataSourceUpdateMode = 0 $form1.Controls.Add($chkIP) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 73 $comboBox1.Location = $System_Drawing_Point $comboBox1.DataBindings.DefaultDataSourceUpdateMode = 0 $comboBox1.FormattingEnabled = $True $comboBox1.Name = 'comboBox1' $comboBox1.TabIndex = 0 #Get all VM foreach ($cvm in $script:vmt) { $comboBox1.Items.Add($cvm.Name) | Out-Null } $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 261 $comboBox1.Size = $System_Drawing_Size $form1.Controls.Add($comboBox1) #endregion Generated Form Code #Show the Form $form1.ShowDialog()| Out-Null } GenerateForm
PowerShellCorpus/PoshCode/4a37ac19-31f0-4d25-80a3-98a05980e63e.ps1
4a37ac19-31f0-4d25-80a3-98a05980e63e.ps1
#requires -version 2.0\nAdd-Type @"\npublic class Shift {\n public static int Right(int x, int count) { return x >> count; }\n public static uint Right(uint x, int count) { return x >> count; }\n public static long Right(long x, int count) { return x >> count; }\n public static ulong Right(ulong x, int count) { return x >> count; }\n public static int Left(int x, int count) { return x << count; }\n public static uint Left(uint x, int count) { return x << count; }\n public static long Left(long x, int count) { return x << count; }\n public static ulong Left(ulong x, int count) { return x << count; }\n} \n"@\n\n\n\n#.Example \n# Shift-Left 16 1 ## returns 32\n#.Example \n# 8,16 |Shift-Left ## returns 16,32\nfunction Shift-Left {\nPARAM( $x=1, $y )\nBEGIN {\n if($y) {\n [Shift]::Left( $x, $y )\n }\n}\nPROCESS {\n if($_){\n [Shift]::Left($_, $x)\n }\n}\n}\n\n\n#.Example \n# Shift-Right 8 1 ## returns 4\n#.Example \n# 2,4,8 |Shift-Right 2 ## returns 0,1,2\nfunction Shift-Right {\nPARAM( $x=1, $y )\nBEGIN {\n if($y) {\n [Shift]::Right( $x, $y )\n }\n}\nPROCESS {\n if($_){\n [Shift]::Right($_, $x)\n }\n}\n}function Write-FileByte {\n################################################################\n#.Synopsis\n#  Overwrites or creates a file with an array of raw bytes.\n#.Parameter ByteArray\n#  System.Byte[] array of bytes to put into the file.  If you\n#  pipe this array in, you must pipe the [Ref] to the array.\n#.Parameter Path\n#  Path to the file as a string or as System.IO.FileInfo object.\n#  Path as a string can be relative, absolute, or a simple file\n#  name if the file is in the present working directory.\n#.Example\n#  write-filebyte -bytearray $bytes -path outfile.bin\n#.Example\n#  [Ref] $bytes | write-filebyte -path c:\\temp\\outfile.bin\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter(Mandatory = $True)] $Path\n)\n\nif ($Path -is [System.IO.FileInfo])\n { $Path = $Path.FullName }\nelseif ($Path -notlike "*\\*") #Simple file name.\n { $Path = "$pwd" + "\\" + "$Path" }\nelseif ($Path -like ".\\*")  #pwd of script\n { $Path = $Path -replace "^\\.",$pwd.Path }\nelseif ($Path -like "..\\*") #parent directory of pwd of script\n { $Path = $Path -replace "^\\.\\.",$(get-item $pwd).Parent.FullName }\nelse\n { throw "Cannot resolve path!" }\n[System.IO.File]::WriteAllBytes($Path, $ByteArray)\n}\nfunction Convert-HexStringToByteArray {\n################################################################\n#.Synopsis\n#  Convert a string of hex data into a System.Byte[] array. An\n#  array is always returned, even if it contains only one byte.\n#.Parameter String\n#  A string containing hex data in any of a variety of formats,\n#  including strings like the following, with or without extra\n#  tabs, spaces, quotes or other non-hex characters:\n#     0x41,0x42,0x43,0x44\n#     \\x41\\x42\\x43\\x44\n#     41-42-43-44\n#     41424344\n#  The string can be piped into the function too.\n################################################################\n[CmdletBinding()]\nParam ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [String] $String )\n\n#Clean out whitespaces and any other non-hex crud.\n$String = $String.ToLower() -replace '[^a-f0-9\\\\\\,x\\-\\:]',''\n\n#Try to put into canonical colon-delimited format.\n$String = $String -replace '0x|\\\\x|\\-|,',':'\n\n#Remove beginning and ending colons, and other detritus.\n$String = $String -replace '^:+|:+$|x|\\\\',''\n\n#Maybe there's nothing left over to convert...\nif ($String.Length -eq 0) { ,@() ; return } \n\n#Split string with or without colon delimiters.\nif ($String.Length -eq 1)\n{ ,@([System.Convert]::ToByte($String,16)) }\nelseif (($String.Length % 2 -eq 0) -and ($String.IndexOf(":") -eq -1))\n{ ,@($String -split '([a-f0-9]{2})' | foreach-object { if ($_) {[System.Convert]::ToByte($_,16)}}) }\nelseif ($String.IndexOf(":") -ne -1)\n{ ,@($String -split ':+' | foreach-object {[System.Convert]::ToByte($_,16)}) }\nelse\n{ ,@() }\n#The strange ",@(...)" syntax is needed to force the output into an\n#array even if there is only one element in the output (or none).\n}\nfunction Convert-ByteArrayToHexString {\n################################################################\n#.Synopsis\n#  Returns a hex representation of a System.Byte[] array as\n#  one or more strings.  Hex format can be changed.\n#.Parameter ByteArray\n#  System.Byte[] array of bytes to put into the file.  If you\n#  pipe this array in, you must pipe the [Ref] to the array.\n#  Also accepts a single Byte object instead of Byte[].\n#.Parameter Width\n#  Number of hex characters per line of output.\n#.Parameter Delimiter\n#  How each pair of hex characters (each byte of input) will be\n#  delimited from the next pair in the output.  The default\n#  looks like "0x41,0xFF,0xB9" but you could specify "\\x" if\n#  you want the output like "\\x41\\xFF\\xB9" instead.  You do\n#  not have to worry about an extra comma, semicolon, colon\n#  or tab appearing before each line of output.  The default\n#  value is ",0x".\n#.Parameter Prepend\n#  An optional string you can prepend to each line of hex\n#  output, perhaps like '$x += ' to paste into another\n#  script, hence the single quotes.\n#.Parameter AddQuotes\n#  An switch which will enclose each line in double-quotes.\n#.Example\n#  [Byte[]] $x = 0x41,0x42,0x43,0x44\n#  Convert-ByteArrayToHexString $x\n#\n#  0x41,0x42,0x43,0x44\n#.Example\n#  [Byte[]] $x = 0x41,0x42,0x43,0x44\n#  Convert-ByteArrayToHexString $x -width 2 -delimiter "\\x" -addquotes\n#\n#  "\\x41\\x42"\n#  "\\x43\\x44"\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [Int] $Width = 10,\n [Parameter()] [String] $Delimiter = ",0x",\n [Parameter()] [String] $Prepend = "",\n [Parameter()] [Switch] $AddQuotes\n)\n\nif ($Width -lt 1) { $Width = 1 }\nif ($ByteArray.Length -eq 0) { Return }\n$FirstDelimiter = $Delimiter -Replace "^[\\,\\;\\:\\t]",""\n$From = 0\n$To = $Width - 1\nDo\n{\n $String = [System.BitConverter]::ToString($ByteArray[$From..$To])\n $String = $FirstDelimiter + ($String -replace "\\-",$Delimiter)\n if ($AddQuotes) { $String = '"' + $String + '"' }\n if ($Prepend -ne "") { $String = $Prepend + $String }\n $String\n $From += $Width\n $To += $Width\n} While ($From -lt $ByteArray.Length)\n}\nfunction Convert-ByteArrayToString {\n################################################################\n#.Synopsis\n#  Returns the string representation of a System.Byte[] array.\n#  ASCII string is the default, but Unicode, UTF7, UTF8 and\n#  UTF32 are available too.\n#.Parameter ByteArray\n#  System.Byte[] array of bytes to put into the file.  If you\n#  pipe this array in, you must pipe the [Ref] to the array.\n#  Also accepts a single Byte object instead of Byte[].\n#.Parameter Encoding\n#  Encoding of the string: ASCII, Unicode, UTF7, UTF8 or UTF32.\n#  ASCII is the default.\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [String] $Encoding = "ASCII"\n)\n\nswitch ( $Encoding.ToUpper() )\n{\n "ASCII"   { $EncodingType = "System.Text.ASCIIEncoding" }\n "UNICODE" { $EncodingType = "System.Text.UnicodeEncoding" }\n "UTF7"    { $EncodingType = "System.Text.UTF7Encoding" }\n "UTF8"    { $EncodingType = "System.Text.UTF8Encoding" }\n "UTF32"   { $EncodingType = "System.Text.UTF32Encoding" }\n Default   { $EncodingType = "System.Text.ASCIIEncoding" }\n}\n$Encode = new-object $EncodingType\n$Encode.GetString($ByteArray)\n}\nfunction Get-FileHex {\n################################################################\n#.Synopsis\n#  Display the hex dump of a file.\n#.Parameter Path\n#  Path to file as a string or as a System.IO.FileInfo object;\n#  object can be piped into the function, string cannot.\n#.Parameter Width\n#  Number of hex bytes shown per line (default = 16).\n#.Parameter Count\n#  Number of bytes in the file to process (default = all).\n#.Parameter NoOffset\n#  Switch to suppress offset line numbers in output.\n#.Parameter NoText\n#  Switch to suppress ASCII translation of bytes in output.\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]\n [Alias("FullName","FilePath")] $Path,\n [Parameter()] [Int] $Width = 16,\n [Parameter()] [Int] $Count = -1,\n [Parameter()] [Switch] $NoOffset,\n [Parameter()] [Switch] $NoText\n)\n\n$linecounter = 0        # Offset from beginning of file in hex.\n$placeholder = "."      # What to print when byte is not a letter or digit.\n\nget-content $path -encoding byte -readcount $width -totalcount $count |\nforeach-object {\n $paddedhex = $asciitext = $null\n $bytes = $_        # Array of [Byte] objects that is $width items in length.\n\n foreach ($byte in $bytes) {\n $byteinhex = [String]::Format("{0:X}", $byte)     # Convert byte to hex, e.g., "F".\n $paddedhex += $byteinhex.PadLeft(2,"0") + " "     # Pad with zero to force 2-digit length, e.g., "0F ".\n } \n\n # Total bytes in file unlikely to be evenly divisible by $width, so fix last line.\n # Hex output width is '$width * 3' because of the extra spaces added around hex characters.\n if ($paddedhex.length -lt $width * 3)\n { $paddedhex = $paddedhex.PadRight($width * 3," ") }\n\n foreach ($byte in $bytes) {\n if ( [Char]::IsLetterOrDigit($byte) -or\n [Char]::IsPunctuation($byte) -or\n [Char]::IsSymbol($byte) )\n { $asciitext += [Char] $byte }\n else\n { $asciitext += $placeholder }\n }\n\n $offsettext = [String]::Format("{0:X}", $linecounter) # Linecounter in hex too.\n $offsettext = $offsettext.PadLeft(8,"0") + "h:"       # Pad linecounter with left zeros.\n $linecounter += $width                                # Increment linecounter, each line representing $width bytes.\n\n if (-not $NoOffset) { $paddedhex = "$offsettext $paddedhex" }\n if (-not $NoText) { $paddedhex = $paddedhex + $asciitext }\n $paddedhex\n}\n}\nfunction Toggle-Endian {\n################################################################\n#.Synopsis\n#  Swaps the ordering of bytes in an array where each swappable\n#  unit can be one or more bytes, and, if more than one, the\n#  ordering of the bytes within that unit is NOT swapped. Can\n#  be used to toggle between little- and big-endian formats.\n#  Cannot be used to swap nibbles or bits within a single byte.\n#.Parameter ByteArray\n#  System.Byte[] array of bytes to be rearranged.  If you\n#  pipe this array in, you must pipe the [Ref] to the array, but\n#  a new array will be returned (originally array untouched).\n#.Parameter SubWidthInBytes\n#  Defaults to 1 byte.  Defines the number of bytes in each unit\n#  (or atomic element) which is swapped, but no swapping occurs\n#  within that unit.  The number of bytes in the ByteArray must\n#  be evenly divisible by SubWidthInBytes.\n#.Example\n#  $bytearray = toggle-endian $bytearray\n#.Example\n#  [Ref] $bytearray | toggle-endian -SubWidthInBytes 2\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [Int] $SubWidthInBytes = 1\n)\n\nif ($ByteArray.count -eq 1 -or $ByteArray.count -eq 0) { $ByteArray ; return } \n\nif ($SubWidthInBytes -eq 1) { [System.Array]::Reverse($ByteArray); $ByteArray ; return } \n\nif ($ByteArray.count % $SubWidthInBytes -ne 0)\n{ throw "ByteArray size must be an even multiple of SubWidthInBytes!" ; return }  \n\n$newarray = new-object System.Byte[] $ByteArray.count \n\n# $i tracks ByteArray from head, $j tracks NewArray from end.\nfor ($($i = 0; $j = $newarray.count - 1) ;\n $i -lt $ByteArray.count ;\n $($i += $SubWidthInBytes; $j -= $SubWidthInBytes))\n{\n for ($k = 0 ; $k -lt $SubWidthInBytes ; $k++)\n { $newarray[$j - ($SubWidthInBytes - 1) + $k] = $ByteArray[$i + $k] }\n}\n$newarray\n}\nfunction PushToTcpPort\n{\n param ([Byte[]] $bytearray, [String] $ipaddress, [Int32] $port)\n $tcpclient = new-object System.Net.Sockets.TcpClient($ipaddress, $port) -ErrorAction "SilentlyContinue"\n trap { "Failed to connect to $ipaddress`:$port" ; return }\n $networkstream = $tcpclient.getstream()\n #write(payload,starting offset,number of bytes to send)\n $networkstream.write($bytearray,0,$bytearray.length)\n $networkstream.close(1) #Wait 1 second before closing TCP session.\n $tcpclient.close()\n}\n
PowerShellCorpus/PoshCode/Get-FileEncoding_6.ps1
Get-FileEncoding_6.ps1
<# .SYNOPSIS Gets file encoding. .DESCRIPTION The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM). Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx .EXAMPLE Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} This command gets ps1 files in current directory where encoding is not ASCII .EXAMPLE Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII} Same as previous example but fixes encoding using set-content #> function Get-FileEncoding { [CmdletBinding()] Param ( [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path ) [byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf ) { Write-Output 'UTF8' } elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff) { Write-Output 'Unicode' } elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff) { Write-Output 'UTF32' } elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76) { Write-Output 'UTF7'} else { Write-Output 'ASCII' } }
PowerShellCorpus/PoshCode/Add Voice to Powershell_1.ps1
Add Voice to Powershell_1.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/Test-Port_7.ps1
Test-Port_7.ps1
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose) # Test-Port.ps1 # Does a TCP connection on specified port (135 by default) $ErrorActionPreference = "SilentlyContinue" # Create TCP Client $tcpclient = new-Object system.Net.Sockets.TcpClient # Tell TCP Client to connect to machine on Port $iar = $tcpclient.BeginConnect($srv,$port,$null,$null) # Set the wait time $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false) # Check to see if the connection is done if(!$wait) { # Close the connection and report timeout $tcpclient.Close() if($verbose){Write-Host "Connection Timeout"} Return $false } else { # Close the connection and report the error if there is one $error.Clear() $tcpclient.EndConnect($iar) | out-Null if(!$?){if($verbose){write-host $error[0]};$failed = $true} $tcpclient.Close() } # Return $true if connection Establish else $False if($failed){return $false}else{return $true}
PowerShellCorpus/PoshCode/LetterDiamondOneliner v2.ps1
LetterDiamondOneliner v2.ps1
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z
PowerShellCorpus/PoshCode/FindNewVirtualMachines.ps1
FindNewVirtualMachines.ps1
#requires -pssnapin VMware.Vimautomation.Core Param( [int] $LastDays ) Process { $EventFilterSpecByTime = New-Object VMware.Vim.EventFilterSpecByTime If ($LastDays) { $EventFilterSpecByTime.BeginTime = (get-date).AddDays(-$($LastDays)) } $EventFilterSpec = New-Object VMware.Vim.EventFilterSpec $EventFilterSpec.Time = $EventFilterSpecByTime $EventFilterSpec.DisableFullMessage = $False $EventFilterSpec.Type = "VmCreatedEvent","VmDeployedEvent","VmClonedEvent","VmDiscoveredEvent","VmRegisteredEvent" $EventManager = Get-View EventManager $NewVmTasks = $EventManager.QueryEvents($EventFilterSpec) Foreach ($Task in $NewVmTasks) { # If VM was deployed from a template then record which template. If ($Task.Template -and $Task.SrcTemplate.Vm) { $srcTemplate = Get-View $Task.SrcTemplate.Vm -Property name | Select -ExpandProperty Name } Else { $srcTemplate = $null } write-output ""|Select-Object @{ Name="Name" Expression={$Task.Vm.name} }, @{ Name="Created" Expression={$Task.CreatedTime} }, @{ Name="UserName" Expression={$Task.UserName} }, @{ Name="Type" Expression={$Task.gettype().name} }, @{ Name="Template" Expression={$srcTemplate} } } }
PowerShellCorpus/PoshCode/New-TiedVariable.ps1
New-TiedVariable.ps1
function New-TiedVariable { #.Synopsis # Creates a ReadOnly variable that recalculates it's value each time it's read #.Description # Create a variable tied to a scriptblock by using a breakpoint ;-) #.Notes # New-TiedVariable uses breakpoints to trigger the automatic recalculation of the variables, so the use of a command like Get-PSBreakPoint | Remove-PSBreakPoint will break any variables created using New-TiedVariable param( # The name of the variable to create [String]$Name, # The scriptblock to use to calculate the value each time [ScriptBlock]$Value ) Set-Variable $Name -Value (.$Value) -Option ReadOnly, AllScope -Scope Global -Force $null = Set-PSBreakpoint -Variable $Name -Mode Read -Action { Set-Variable $Name (. $Value) -Option ReadOnly, AllScope -Scope Global -Force }.GetNewClosure() }
PowerShellCorpus/PoshCode/Unlock & Password Reset_1.ps1
Unlock & Password Reset_1.ps1
<# Author: Matt Schmitt Date: 12/4/12 Version: 2.0 From: USA Email: ithink2020@gmail.com Website: http://about.me/schmittmatt Twitter: @MatthewASchmitt Description A script checking for Locked Account, checking where a user is locked out, unlocking the user's account and for resetting a user's password. UPDATED 12/4/12 Cleaned up Checking LockedOut Status code - replaced with foreach statement that looks at $Servers array Cleaned up Unlock code - replaced with foreach statement that looks at $Servers array Cleaned up Get pwdlastset date - rewrote to use the method I was using for other lookups for AD properties. #> 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 "" #Assing Domain Controllers to $servers Array #IMPORTANT ---> Need to Update with DCs chagnes $servers = "AUSDC01.intranet.theknot.com", "AUSDC02.intranet.theknot.com", "AUSDC03.intranet.theknot.com", "CORPDC01.intranet.theknot.com", "LADC03.intranet.theknot.com", "NYCDC04.intranet.theknot.com", "NYCDC05.intranet.theknot.com", "omadc01.intranet.theknot.com", "omadc02.intranet.theknot.com", "REDDC02.intranet.theknot.com" # Not includeing BJDC03.intranet.theknot.com, BJDC02.intranet.theknot.com #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 Name, @{Expression={$_.SamAccountName};Label="Username"},@{Expression={$_.physicalDeliveryOfficeName};Label="Office Location"},@{Expression={$_.TelephoneNumber};Label="Phone Number"},@{Expression={$_.LastLogonDate};Label="Last Logon Date"} | 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" cls Write-Host "" Write-Host "" $Name = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand DisplayName) $phone = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand telephoneNumber) Write-Host "$Name's phone number is: $phone" Write-Host "" Write-Host "" [datetime]$today = (get-date) #Get pwdlastset date from AD and set it to $passdate $passdate2 = [datetime]::fromfiletime((Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand pwdlastset)) #Write-Host "passdate2: $passdate2" <# ----> REMOVE - Replaced with above line $searcher=New-Object DirectoryServices.DirectorySearcher $searcher.Filter="(&(samaccountname=$user))" $results=$searcher.findone() $passdate = [datetime]::fromfiletime($results.properties.pwdlastset[0]) Write-Host "passdate: $passdate" #> $PwdAge = ($today - $passdate2).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 U.S. Domain Controllers:" #Get Lockedout status and set it to $Lock foreach ($object in $servers) { switch (Get-ADUser -server $object -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"$object `t `t Not Locked"} "True" {"$object `t `t LOCKED"} } } 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" { foreach ($object in $servers) { Write-Host "Unlocking account on $object" Unlock-ADAccount -Identity $user -server $object } #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 += 5 $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 CORPDC01" Write-Host "" Set-ADAccountPassword -Server CORPDC01.intranet.theknot.com -Identity $user -NewPassword $newpass Write-Host "" Write-Host "Press any key to Exit." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $y += 5 } "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 CORPDC01 - for faster replication..." Write-Host "" Set-ADAccountPassword -Server CORPDC01.intranet.theknot.com -Identity $user -NewPassword $newpass Write-Host "" Write-Host "Password for $user has been reset." Write-Host "" foreach ($object in $servers) { Write-Host "Unlocking account on $object" Unlock-ADAccount -Identity $user -server $object } #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 += 5 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } "4" { #exit code $y += 5 } 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/hex2dec_4.ps1
hex2dec_4.ps1
@echo off ::interactive mode if "%1" equ "" ( if not defined run goto:interactive goto:error ) ::null results for %%i in ("0" "x0" "0x0") do if "%1" equ "%%~i" goto:null ::parsing argument(s) setlocal enabledelayedexpansion ::checking number of arguments set "arg=0" for %%i in (%*) do set /a "arg+=1" if "%arg%" neq "1" if not defined run goto:help if "%arg%" neq "1" if defined run goto:error ::get length of argument set "i=0" set "str=%1" for /l %%i in (0, 1, 255) do ( set "chr=!str:~%%i!" if defined chr set /a "i+=1" ) ::is it prefix or hex number starts without him if !i! equ 2 ( if "%str:~0,1%" equ "x" set "str=0%str%" & goto:check ) if !i! gtr 2 ( if "%str:~0,1%" equ "0" if "%str:~1,1%" neq "x" goto:error if "%str:~0,1%" equ "0" if "%str:~1,1%" equ "x" goto:hex2dec if "%str:~0,1%" equ "x" set "str=0%str%" && goto:check ) for %%i in (a b c d e f) do if "%str:~0,1%" equ "%%i" set "str=0x%str%" & goto:hex2dec :check 2>nul set /a "res=%str%" if "%errorlevel%" equ "0" ( if "%str%" equ "%res%" goto:dec2hex goto:hex2dec ) echo "%str%" | findstr /r [0-9a-f] > nul if "%errorlevel%" equ "0" set "str=0x%str%" && goto:hex2dec goto:error :dec2hex set "map=0123456789ABCDEF" for /l %%i in (1, 1, 8) do ( set /a "res=str & 15, str >>=4" for %%j in (!res!) do set "hex=!map:~%%j,1!!hex!" ) for /f "tokens=* delims=0" %%i in ("!hex!") do set "hex=0x%%i" echo %1 = !hex! & goto:eof :hex2dec 2>nul set /a "res=%str%" if "%errorlevel%" gtr "0" goto:error for /f "tokens=2,3" %%i in ('findstr "# " "%~dpnx0"') do set "str=!str:%%i=%%j!" if "%res%" neq "" if "%res%" neq "0" (echo %str% = %res%) else goto:error endlocal exit /b :error echo =^>err exit /b 1 :null echo =^>nil exit /b 0 :help ::Hex2dec v2.03 - converts hex to decimal and vice versa ::Copyright (C) 2012-2013 greg zakharov ::For bug reports - gregzakh@gmail.com :: ::Usage: hex2dec [decimal | hexademical] :: ::Example 1: :: C:\\>hex2dec 0x017a :: 0x017A = 378 ::You'll got the same result with x17a or 17a. :: ::Example 2: :: C:\\>hex2dec 13550 :: 13550 = 0x34EE :: ::Example 3: :: C:\\>hex2dec 23f :: 0x23F = 575 :: ::Note: hex2dec starts with interactive mode if there is ::no argument. for /f "tokens=* delims=:" %%i in ('findstr "^::" "%~dpnx0"') do echo.%%i exit /b 0 rem :: Upper case chart :: # a A # b B # c C # d D # e E # f F rem :: End of chart :: :interactive ::interactive mode on echo Hex2dec v2.03 - converts hex to decimal and vice versa echo. echo Enter decimal or hexademical number and press Enter to echo take result. Use "exit" or "clear" commands to quit or echo to make host clear. echo. setlocal ::already launched marker set "run=true" :begin set /p "ask=>>> " cmd /c "%~dpnx0" %ask% if "%ask%" equ "clear" cls if "%ask%" equ "exit" cls & goto:eof echo. goto:begin endlocal exit /b
PowerShellCorpus/PoshCode/TabExpansion_11.ps1
TabExpansion_11.ps1
## Tab-Completion ################# ## For V2CTP3. ## This won't work on V1 and V2CTP and V2CTP2. ## 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 charactors ## [<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> ### 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" iex (@' function prompt { 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 'NoteProperty' CommandType $f.CommandType -P | Add-Member 'NoteProperty' Definition $a.Definition -P | Add-Member 'NoteProperty' Description $a.Description -P | Add-Member 'NoteProperty' Key $e.Key -P | Add-Member 'NoteProperty' Location $c.Location -P | Add-Member 'NoteProperty' LocationName $c.LocationName -P | Add-Member 'NoteProperty' Options $a.Options -P | Add-Member 'NoteProperty' ReferencedCommand $a.ReferencedCommand -P | Add-Member 'NoteProperty' ResolvedCommand $a.ResolvedCommand -P | Add-Member 'NoteProperty' ScriptBlock $f.ScriptBlock -P | Add-Member 'NoteProperty' StoreNames $c.StoreNames -P | Add-Member 'NoteProperty' SubKeyCount $h.SubKeyCount -P | Add-Member 'NoteProperty' Value $e.Value -P | Add-Member 'NoteProperty' ValueCount $h.ValueCount -P | Add-Member 'NoteProperty' Visibility $a.Visibility -P | Add-Member 'NoteProperty' Property $h.Property -P | Add-Member 'NoteProperty' ResolvedCommandName $a.ResolvedCommandName -P | Add-Member 'ScriptMethod' Close {} -P | Add-Member 'ScriptMethod' CreateSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKeyTree {} -P | Add-Member 'ScriptMethod' DeleteValue {} -P | Add-Member 'ScriptMethod' Flush {} -P | Add-Member 'ScriptMethod' GetSubKeyNames {} -P | Add-Member 'ScriptMethod' GetValue {} -P | Add-Member 'ScriptMethod' GetValueKind {} -P | Add-Member 'ScriptMethod' GetValueNames {} -P | Add-Member 'ScriptMethod' IsValidValue {} -P | Add-Member 'ScriptMethod' OpenSubKey {} -P | Add-Member 'ScriptMethod' SetValue {} -P } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Mode $f.Mode -P | Add-Member 'NoteProperty' Assembly $t.Assembly -P | Add-Member 'NoteProperty' AssemblyQualifiedName $t.AssemblyQualifiedName -P | Add-Member 'NoteProperty' Attributes $f.Attributes -P | Add-Member 'NoteProperty' BaseType $t.BaseType -P | Add-Member 'NoteProperty' ContainsGenericParameters $t.ContainsGenericParameters -P | Add-Member 'NoteProperty' CreationTime $f.CreationTime -P | Add-Member 'NoteProperty' CreationTimeUtc $f.CreationTimeUtc -P | Add-Member 'NoteProperty' DeclaringMethod $t.DeclaringMethod -P | Add-Member 'NoteProperty' DeclaringType $t.DeclaringType -P | Add-Member 'NoteProperty' Exists $f.Exists -P | Add-Member 'NoteProperty' Extension $f.Extension -P | Add-Member 'NoteProperty' FullName $f.FullName -P | Add-Member 'NoteProperty' GenericParameterAttributes $t.GenericParameterAttributes -P | Add-Member 'NoteProperty' GenericParameterPosition $t.GenericParameterPosition -P | Add-Member 'NoteProperty' GUID $t.GUID -P | Add-Member 'NoteProperty' HasElementType $t.HasElementType -P | Add-Member 'NoteProperty' IsAbstract $t.IsAbstract -P | Add-Member 'NoteProperty' IsAnsiClass $t.IsAnsiClass -P | Add-Member 'NoteProperty' IsArray $t.IsArray -P | Add-Member 'NoteProperty' IsAutoClass $t.IsAutoClass -P | Add-Member 'NoteProperty' IsAutoLayout $t.IsAutoLayout -P | Add-Member 'NoteProperty' IsByRef $t.IsByRef -P | Add-Member 'NoteProperty' IsClass $t.IsClass -P | Add-Member 'NoteProperty' IsCOMObject $t.IsCOMObject -P | Add-Member 'NoteProperty' IsContextful $t.IsContextful -P | Add-Member 'NoteProperty' IsEnum $t.IsEnum -P | Add-Member 'NoteProperty' IsExplicitLayout $t.IsExplicitLayout -P | Add-Member 'NoteProperty' IsGenericParameter $t.IsGenericParameter -P | Add-Member 'NoteProperty' IsGenericType $t.IsGenericType -P | Add-Member 'NoteProperty' IsGenericTypeDefinition $t.IsGenericTypeDefinition -P | Add-Member 'NoteProperty' IsImport $t.IsImport -P | Add-Member 'NoteProperty' IsInterface $t.IsInterface -P | Add-Member 'NoteProperty' IsLayoutSequential $t.IsLayoutSequential -P | Add-Member 'NoteProperty' IsMarshalByRef $t.IsMarshalByRef -P | Add-Member 'NoteProperty' IsNested $t.IsNested -P | Add-Member 'NoteProperty' IsNestedAssembly $t.IsNestedAssembly -P | Add-Member 'NoteProperty' IsNestedFamANDAssem $t.IsNestedFamANDAssem -P | Add-Member 'NoteProperty' IsNestedFamily $t.IsNestedFamily -P | Add-Member 'NoteProperty' IsNestedFamORAssem $t.IsNestedFamORAssem -P | Add-Member 'NoteProperty' IsNestedPrivate $t.IsNestedPrivate -P | Add-Member 'NoteProperty' IsNestedPublic $t.IsNestedPublic -P | Add-Member 'NoteProperty' IsNotPublic $t.IsNotPublic -P | Add-Member 'NoteProperty' IsPointer $t.IsPointer -P | Add-Member 'NoteProperty' IsPrimitive $t.IsPrimitive -P | Add-Member 'NoteProperty' IsPublic $t.IsPublic -P | Add-Member 'NoteProperty' IsSealed $t.IsSealed -P | Add-Member 'NoteProperty' IsSerializable $t.IsSerializable -P | Add-Member 'NoteProperty' IsSpecialName $t.IsSpecialName -P | Add-Member 'NoteProperty' IsUnicodeClass $t.IsUnicodeClass -P | Add-Member 'NoteProperty' IsValueType $t.IsValueType -P | Add-Member 'NoteProperty' IsVisible $t.IsVisible -P | Add-Member 'NoteProperty' LastAccessTime $f.LastAccessTime -P | Add-Member 'NoteProperty' LastAccessTimeUtc $f.LastAccessTimeUtc -P | Add-Member 'NoteProperty' LastWriteTime $f.LastWriteTime -P | Add-Member 'NoteProperty' LastWriteTimeUtc $f.LastWriteTimeUtc -P | Add-Member 'NoteProperty' MemberType $t.MemberType -P | Add-Member 'NoteProperty' MetadataToken $t.MetadataToken -P | Add-Member 'NoteProperty' Module $t.Module -P | Add-Member 'NoteProperty' Name $t.Name -P | Add-Member 'NoteProperty' Namespace $t.Namespace -P | Add-Member 'NoteProperty' Parent $f.Parent -P | Add-Member 'NoteProperty' ReflectedType $t.ReflectedType -P | Add-Member 'NoteProperty' Root $f.Root -P | Add-Member 'NoteProperty' StructLayoutAttribute $t.StructLayoutAttribute -P | Add-Member 'NoteProperty' TypeHandle $t.TypeHandle -P | Add-Member 'NoteProperty' TypeInitializer $t.TypeInitializer -P | Add-Member 'NoteProperty' UnderlyingSystemType $t.UnderlyingSystemType -P | Add-Member 'NoteProperty' PSChildName $f.PSChildName -P | Add-Member 'NoteProperty' PSDrive $f.PSDrive -P | Add-Member 'NoteProperty' PSIsContainer $f.PSIsContainer -P | Add-Member 'NoteProperty' PSParentPath $f.PSParentPath -P | Add-Member 'NoteProperty' PSPath $f.PSPath -P | Add-Member 'NoteProperty' PSProvider $f.PSProvider -P | Add-Member 'NoteProperty' BaseName $f.BaseName -P | Add-Member 'ScriptMethod' Clone {} -P | Add-Member 'ScriptMethod' CompareTo {} -P | Add-Member 'ScriptMethod' Contains {} -P | Add-Member 'ScriptMethod' CopyTo {} -P | Add-Member 'ScriptMethod' Create {} -P | Add-Member 'ScriptMethod' CreateObjRef {} -P | Add-Member 'ScriptMethod' CreateSubdirectory {} -P | Add-Member 'ScriptMethod' Delete {} -P | Add-Member 'ScriptMethod' EndsWith {} -P | Add-Member 'ScriptMethod' FindInterfaces {} -P | Add-Member 'ScriptMethod' FindMembers {} -P | Add-Member 'ScriptMethod' GetAccessControl {} -P | Add-Member 'ScriptMethod' GetArrayRank {} -P | Add-Member 'ScriptMethod' GetConstructor {} -P | Add-Member 'ScriptMethod' GetConstructors {} -P | Add-Member 'ScriptMethod' GetCustomAttributes {} -P | Add-Member 'ScriptMethod' GetDefaultMembers {} -P | Add-Member 'ScriptMethod' GetDirectories {} -P | Add-Member 'ScriptMethod' GetElementType {} -P | Add-Member 'ScriptMethod' GetEnumerator {} -P | Add-Member 'ScriptMethod' GetEvent {} -P | Add-Member 'ScriptMethod' GetEvents {} -P | Add-Member 'ScriptMethod' GetField {} -P | Add-Member 'ScriptMethod' GetFields {} -P | Add-Member 'ScriptMethod' GetFiles {} -P | Add-Member 'ScriptMethod' GetFileSystemInfos {} -P | Add-Member 'ScriptMethod' GetGenericArguments {} -P | Add-Member 'ScriptMethod' GetGenericParameterConstraints {} -P | Add-Member 'ScriptMethod' GetGenericTypeDefinition {} -P | Add-Member 'ScriptMethod' GetInterface {} -P | Add-Member 'ScriptMethod' GetInterfaceMap {} -P | Add-Member 'ScriptMethod' GetInterfaces {} -P | Add-Member 'ScriptMethod' GetLifetimeService {} -P | Add-Member 'ScriptMethod' GetMember {} -P | Add-Member 'ScriptMethod' GetMembers {} -P | Add-Member 'ScriptMethod' GetMethod {} -P | Add-Member 'ScriptMethod' GetMethods {} -P | Add-Member 'ScriptMethod' GetNestedType {} -P | Add-Member 'ScriptMethod' GetNestedTypes {} -P | Add-Member 'ScriptMethod' GetObjectData {} -P | Add-Member 'ScriptMethod' GetProperties {} -P | Add-Member 'ScriptMethod' GetProperty {} -P | Add-Member 'ScriptMethod' GetTypeCode {} -P | Add-Member 'ScriptMethod' IndexOf {} -P | Add-Member 'ScriptMethod' IndexOfAny {} -P | Add-Member 'ScriptMethod' InitializeLifetimeService {} -P | Add-Member 'ScriptMethod' Insert {} -P | Add-Member 'ScriptMethod' InvokeMember {} -P | Add-Member 'ScriptMethod' IsAssignableFrom {} -P | Add-Member 'ScriptMethod' IsDefined {} -P | Add-Member 'ScriptMethod' IsInstanceOfType {} -P | Add-Member 'ScriptMethod' IsNormalized {} -P | Add-Member 'ScriptMethod' IsSubclassOf {} -P | Add-Member 'ScriptMethod' LastIndexOf {} -P | Add-Member 'ScriptMethod' LastIndexOfAny {} -P | Add-Member 'ScriptMethod' MakeArrayType {} -P | Add-Member 'ScriptMethod' MakeByRefType {} -P | Add-Member 'ScriptMethod' MakeGenericType {} -P | Add-Member 'ScriptMethod' MakePointerType {} -P | Add-Member 'ScriptMethod' MoveTo {} -P | Add-Member 'ScriptMethod' Normalize {} -P | Add-Member 'ScriptMethod' PadLeft {} -P | Add-Member 'ScriptMethod' PadRight {} -P | Add-Member 'ScriptMethod' Refresh {} -P | Add-Member 'ScriptMethod' Remove {} -P | Add-Member 'ScriptMethod' Replace {} -P | Add-Member 'ScriptMethod' SetAccessControl {} -P | Add-Member 'ScriptMethod' Split {} -P | Add-Member 'ScriptMethod' StartsWith {} -P | Add-Member 'ScriptMethod' Substring {} -P | Add-Member 'ScriptMethod' ToCharArray {} -P | Add-Member 'ScriptMethod' ToLower {} -P | Add-Member 'ScriptMethod' ToLowerInvariant {} -P | Add-Member 'ScriptMethod' ToUpper {} -P | Add-Member 'ScriptMethod' ToUpperInvariant {} -P | Add-Member 'ScriptMethod' Trim {} -P | Add-Member 'ScriptMethod' TrimEnd {} -P | Add-Member 'ScriptMethod' TrimStart {} -P | Add-Member 'NoteProperty' Chars $s.Chars -P } 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) 'NoteProperty' Action '' -P | Add-Member 'NoteProperty' Command '' -P | Add-Member 'NoteProperty' Enabled '' -P | Add-Member 'NoteProperty' HitCount '' -P | Add-Member 'NoteProperty' Id '' -P | Add-Member 'NoteProperty' Script '' -P } 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 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; } # 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; } # Ctrl+R $Host.UI.RawUI. 18 { '$Host.UI.RawUI.' '$Host.UI.RawUI' break; } # 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; } } 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 variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } 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; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[(\\w+(\\.\\w*)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ('"$0"') $fse = $fse -replace '([\\[\\]])', '````$1' -replace '^.*([\\[\\]]).*$', ('"$0"') $fse = $fse -replace '""', '"' $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_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 } } else { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # 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($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[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] # now get the info object for it... $_cmdlet = @(Get-Command -type 'All' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'All' $_cmdlet.Definition)[0] } if ( $_cmdlet.name -eq "powershell.exe" ) { if ( $global:_PSexeOption ) { $global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } else { ($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } break; } if ( $_cmdlet.CommandType -eq "Cmdlet" ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { ( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace ` '^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ } } break; } elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$') { $_pat = $Matches[2] + '*' "regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1' break; } elseif ( $_cmdlet -eq $null ) { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # Tab complete against history either #<pattern> or #<id> '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;]')[-1] if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' ) { if ( $Matches[6] -ne $nul ) { $brackets = "[]" } '['+ $global:_enum + $brackets + ']' break; } if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' ) { $_pat = $Matches[7] + '*' $_type = @(iex $Matches[1])[0].GetType() if ( $_type.IsEnum ) { $global:_enum = $_type.FullName [Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"' break; } } $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) #elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line -match '(function|filter)\\s+(\\w*)$') { $_pat = 'function:\\' + $Matches[2] + '*' Get-ChildItem $_pat| % { $_.Name } break; } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { # 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($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[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] # now get the info object for it... $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { #$_opt = $Matches[1] + '*' $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { $Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" | % { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } | ? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ } } break; } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $pattern = $command + "*" "begin {", "break", "catch {", "continue", "data {", "do {", "else {", "elseif (", "end {", "exit", "filter ", "for (", "foreach ", "from", "function ", "if (", "in", "param (", "process {", "return", "switch ", "throw ", "trap ", "until (", "while (" ` -like $pattern | % { $_base + $_ } gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/New-ODataServiceProxy_1.ps1
New-ODataServiceProxy_1.ps1
function New-ODataServiceProxy { #.Synopsis # Creates a proxy class for an odata web service # YOU NEED TO BE VERY CAREFUL NOT TO OUTPUT THE PROXY OBJECT TO THE POWERSHELL HOST! #.Description # Uses the data service client utility (DataSvcUtil.exe) to generate a proxy class (and types for all objects) for an OData web service. # WARNING: Outputting this object to the PowerShell host will result in queriying all the object collections on the service. #.Parameter URI # The URI for the web service #.Parameter Passthru # Causes the method to output all of the types defined by the service metadata as well as the actual service object. #.Example # $proxy = New-ODataServiceProxy http://odata.netflix.com/Catalog/ # $AdventuresInOdyssey = $proxy.Titles.AddQueryOption('$filter',"substringof('Adventures in Odyssey',Name)") # $AdventuresInOdyssey | Format-List Name, ReleaseYear, Url, Synopsis #.Link http://msdn.microsoft.com/en-us/library/ee383989.aspx #.Notes # I can't stress enough that you should not output the object or any property that returns a System.Data.Services.Client.DataServiceQuery[T] without a filter unless you're sure that's what you want. # # ADO.NET Data Service Client Utility http://msdn.microsoft.com/en-us/library/ee383989.aspx # AddQueryOption http://msdn.microsoft.com/en-us/library/cc646860.aspx # NetFlix Catalog http://developer.netflix.com/docs/oData_Catalog # Data Services Update for .Net 3.5 SP1 http://support.microsoft.com/kb/982307 # # VERSION HISTORY: # v1.0 - 2010 Aug 02 - First Version http://poshcode.org/2039 # v1.1 - 2010 Aug 03 - This Version # - Added a type cache to make it easier to find proxies you've already compiled (because we can't recompile them) # param( $URI = "http://odata.netflix.com/Catalog/", [switch]$Passthru ) if(!(Test-Path Variable::Global:ODataServices)){ ## You can only use this on .Net 4 or .Net 3.5 SP1 ## For .Net 3.5 SP1 you need to download http://support.microsoft.com/kb/982307 ## If you don't have it, this won't succeed [Reflection.Assembly]::Load("System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") | Out-Null $global:ODataServices = @{} } $normalized = ([uri]$URI).AbsoluteUri.TrimEnd("/") if($global:ODataServices.ContainsKey($normalized)) { New-Object $global:ODataServices.$normalized.ContextType $URI if($Passthru) { $global:ODataServices.$normalized.OtherTypes } return } ## Find the right DataSvcUtil for this version of .Net switch($PSVersionTable.ClrVersion.Major) { 4 { # PoshConsole and modded .Net4 PowerShell_ISE etc. Set-Alias Get-ODataServiceDefinition (Get-ChildItem ([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) DataSvcUtil.exe) break } 2 { # PowerShell.exe and everyone else $FrameworkPath = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() | Split-Path Set-Alias Get-ODataServiceDefinition (Get-ChildItem $FrameworkPath\\v3.5\\DataSvcUtil.exe) break } } ## Get the service definition into a string via a temp file $temp = [IO.Path]::GetTempFileName() Get-ODataServiceDefinition -out:$temp -uri:$URI -nologo | Out-Null $code = @(Get-Content $temp) -join "`n" # -Delim ([char]0) Remove-Item $temp $Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" -Language CSharpVersion3 -Passthru $ContextType = $Types | Where-Object { $_.BaseType -eq [System.Data.Services.Client.DataServiceContext] } $global:ODataServices.$normalized = New-Object PSObject -Property @{ContextType=$ContextType; OtherTypes=$([Type[]]($Types|Where-Object{$_.BaseType -ne [System.Data.Services.Client.DataServiceContext]}))} $ctx = new-object $ContextType $URI Write-Output $ctx if($Passthru) { Write-Output $types } } # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUSq4znHc6Cix23VtPNHaAqfbB # 2/eggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # 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 # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBQpBamAvk2k # TpZahjyjWtx7E7BscDANBgkqhkiG9w0BAQEFAASCAQCRPD5IJetAL7W+uLUAnKNr # ACZ8XY9rkrb5rldNnLZQr7cxz0ARCeyRbJrh5znBirrro+PekR4IOrKRJbZPNnLw # lefWikq8R1QTpq+N8Tvqfi+j0/f07bbSNSXByhoCXheapxOE7cZBDtgaKmqBsGZi # s5mhWGXkrsYJotyHWQQHZAGmuZuYbYSB/WrG+LlScrLf2f4qr4lTwL3IszWd5Nz2 # 0Uw1yfo7bPltjS+euidPl6d1EIue8kc848FbLypuPSMyB1ThRgjxiysIUTur0urS # 6IIo4+CNYryba4OM+MWCy8xvYeSt8xwSoRAKqpGWMGOTgCpQLFeLfEPzv79MfGOe # SIG # End signature block
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_6.ps1
Get Twitter RSS Feed_6.ps1
param ([String] $ScreenName) $client = New-Object System.Net.WebClient $idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName" $data = $client.DownloadString($idUrl) $start = 0 $findStr = '"id":' do { $start = $data.IndexOf($findStr, $start + 1) if ($start -gt 0) { $start += $findStr.Length $end = $data.IndexOf(',', $start) $userId = $data.SubString($start, $end-$start) } } while ($start -le $data.Length -and $start -gt 0) $feed = "http://twitter.com/statuses/user_timeline/$userId.rss" $feed
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object_3.ps1
h20 -Hashtables 2 object_3.ps1
#hashtable to object function. #used to be able to make custom objects with math inside the pipeline #examples # 1..10 | h20 { @{karl = $_;dude = $_+1} } #modify the incoming data with an expression # gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} } #easily flatten data with subexpressions # get-command -verb get | h20 { @{ name = $_.name; type = $_.commandtype; synopsis = ($_ | get-help).synopsis ; } } #don't lose the incoming pipeline data when you don't explicitly include it in the hashtable. Its automatically stored in the property ".." #below, while the expression just includes string properties from the get-help object, the actual commandinfo object is stored in ".." # $a = get-command -verb ("get","set") | h20 { $_ | get-help | % { @{name = $_.name ; synopsis = $_.synopsis} } } # a[0].".." function h20([scriptblock]$sb, [switch]$dontkeepreference = $false) { begin {} process{ if ($sb -ne $null) { $local:obj = $_; $local:ht = &$sb; if ($local:ht -is [hashtable]) { if (!$dontkeepreference) { $local:ht.".." = $local:obj; } New-Object PSObject -Property $local:ht } } if ($local:ht -is [object[]]) { $local:ht | where { $_ -is [hashtable]} | % { if (!$dontkeepreference) {$_.".." = $local:obj} New-Object PSObject -Property $_ } } } end{} }
PowerShellCorpus/PoshCode/Get-ADMapObject.ps1
Get-ADMapObject.ps1
# Author: Steven Murawski http://www.mindofroot.com # This script requires the Show-NetMap script from Doug Finke and the NetMap files # These can be found at http://dougfinke.com/blog/?p=465 # # Also required are the Quest AD Cmdlets. #requires -pssnapin Quest.ActiveRoles.ADManagement function Write-Help() { $ExampleUsage = @' To use this script, you will need the Show-Netmap script from Doug Finke, along with the NetMap DLLs (included with the Show-NetMap script on Doug's blog). Downloadable from http://dougfinke.com/blog/?p=465 Usage: . .\\Get-ADMapObject.ps1 Get-ADMapObject ([Object Class Name] | [Array of Object Class Names]) | % { New-SourceTarget $_.Name $_.Parent } | Show-NetMap Example: . .\\Get-ADMapObject.ps1 Get-ADMapObject group | % { New-SourceTarget $_.Name $_.Parent } | Show-NetMap -layoutType G Get-ADMapObject ou, group, user | % { New-SourceTarget $_.Name $_.Parent } | Show-NetMap -layoutType S If you would like to get a listing (or array) of the Object Class Names, use the Get-ADObjectClassName function $classes = Get-ADObjectClassName '@ Write-Host $ExampleUsage } #Check to see if the required files are present to run the script. function Test-Prerequisites() { $required = @{ShowNetMap = 'Show-Netmap.ps1'; NetMapApp = 'Microsoft.NetMap.ApplicationUtil.dll'; NetMapControl = 'Microsoft.NetMap.Control.dll'; NetMapCore = 'Microsoft.NetMap.Core.dll'; NetMapUtil = 'Microsoft.NetMap.Util.dll'; NetMapVisual = 'Microsoft.NetMap.Visualization.dll' } $report = @() foreach ($key in $required.Keys) { $file = $required[$($key)] if (Test-Path $file ) { Write-Debug "Found $file" } else { $report += "Missing $file" } } if ($report.count -eq 0) { Write-Debug "All prerequisites were found." return $true } else { Write-Help Write-Host "Missing files: " $report | ForEach-Object { Write-Host "`tMissing $_" } throw "Please move the needed files into the current directory!" } } #If all the prereq's are in the local directory and the script was not run #with the -help switch, load everything up! if (Test-Prerequisites) { #Add the Show-Netmap functions from Doug Finke . .\\Show-NetMap.ps1 #This is just a helper function to find the parent of an object based on the parent's distinguished name function Get-ParentFromDN() { PROCESS { $root = '^DC=(\\w+),DC=(\\w+)$' $pattern = '^(OU|CN)=(\\w+?),.*?DC=\\w+?,DC=\\w+?$' $dn = $_ if ($dn -notmatch $root) { $dn -replace $pattern, '$2' } else { $dn -replace $root, '$1.$2' } } } #This will return an array of all the Object Classes in your Active Directory function Get-ADObjectClassName() { Get-QADObject | Select-Object -property @{name='Name';Expression={$_.type}} -unique | Sort-Object } function Get-ADMapObject() { param($TypesToMap=$(Throw 'One (or more object types as an array) are required to run this function'), [switch]$help) if ($help) { Write-Help } if ($TypesToMap -is [string]) { Get-QADObject -Type $TypesToMap | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}} } else { foreach ( $type in $TypesToMap ) { Get-QADObject -Type $type | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}} } } } #Helper function stolen from Doug Finke and used to create the objects to feed to #Show-Netmap function New-SourceTarget ($s,$t) { New-Object PSObject | Add-Member -pass noteproperty source $s | Add-Member -pass noteproperty target $t } } Write-Help
PowerShellCorpus/PoshCode/Get-ImageMetaData.ps1
Get-ImageMetaData.ps1
## Get-ImageMetaData -- pull EXIF, XMP, and other data from images using the BitmapMetaData ## Usage: ls *.jpg | Get-ImageMetaData | ft Length, LastWriteTime, Name, "36867" ## Note that '36867' is the decimal value of (0x9003) the EXIF tag for DateTimeOriginal ## For more information see: http://owl.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html ##################################################################################################### ## History: ## - v1.0 - First release, retrieves all the data and stacks it somehow onto a FileInfo object ##################################################################################################### # filter Get-ImageMetadata { PARAM($file) BEGIN { $null = [Reflection.Assembly]::LoadWithPartialName("PresentationCore"); function Get-ImageMetadata { PARAM([System.Windows.Media.Imaging.BitmapFrame]$bitmapFrame, [string]$path) PROCESS { if($path -is [string]) { ## To read metadata, you use GetQuery. To write metadata, you use SetQuery ## To WRITE metadata, you need a writer, ## but first you have to open the file ReadWrite, instead of Read only # $writer = $bitmapFrame.CreateInPlaceBitmapMetadataWriter(); # if ($writer.TrySave()){ # $writer.SetQuery("/tEXt/{str=Description}", "Have a nice day."); # } else { # Write-Host "Couldn't save data" -Fore Red # } $next=$bitmapFrame.MetaData.GetQuery($path); if($next.Location){ $next | ForEach-Object { Get-ImageMetadata $bitmapFrame "$($next.Location)$_" } } else { if($path.Split("/")[-1] -match "{ushort=(?<code>\\d+)}") { # $path = "0x{0:X}" -f [int]$matches["code"] $path = [int]$matches["code"] } Add-Member -in ($Global:ImageMetaData) -Type NoteProperty -Name $path -value $next -Force # @{$path=$next} } } else { $bitmapFrame.Metadata | ForEach-Object { Get-ImageMetadata $bitmapFrame $_ } } } } } PROCESS { if($_) { $file = $_ } if($file -is [IO.FileInfo]) { $file = [string]$file.FullName; } elseif($file -is [String]) { $file = [string](Resolve-Path $file) } $Global:ImageMetaData = New-Object IO.FileInfo $file $stream = new-object IO.FileStream $file, ([IO.FileMode]::Open), ([IO.FileAccess]::Read), ([IO.FileShare]::Read); & { $decoder = [System.Windows.Media.Imaging.BitmapDecoder]::Create( $stream, "None", "Default" ) $bitmapFrame = $decoder.Frames[0]; $bitmapFrame.Metadata | ForEach-Object { Get-ImageMetadata $bitmapFrame $_ } } trap { Write-Error "WARNING: $_" continue; } $stream.Close() $stream.Dispose() Write-Output $Global:ImageMetaData }
PowerShellCorpus/PoshCode/Object ProxyAddress Scan.ps1
Object ProxyAddress Scan.ps1
Param ( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, HelpMessage="Enter SMTP address to search for in Active-Directory." )] [string]$objSMTP ) Function Get-ProxyAddresses ([string]$Address){ $objAD = $null $objAD = Get-QADObject -LdapFilter "(proxyAddresses=*$Address*)" -IncludeAllProperties -SizeLimit 0 -ErrorAction SilentlyContinue Write-Output $objAD }#Close Function #Validate Quest PSSnapin is loaded Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue #Run Function to search AD for SMTP address $Results = $null $Results = Get-ProxyAddresses -Address $objSMTP | Select-Object Name,DisplayName,ObjectClass,Email,AccountisDisabled,AccountisLockedOut,MailNickName,LegacyExchangeDN -ErrorAction SilentlyContinue IF($Results -eq $null){ Write-Host "" Write-Host "No Object Found with .attribute[proxyAddress] containing $objSMTP."} Else{$Results | Format-List *} #End
PowerShellCorpus/PoshCode/RDC RemoteApp PassMan.ps1
RDC RemoteApp PassMan.ps1
################################################## # ENV Setup ################################################## #------------------------------------------------- # Initialize-ENV #------------------------------------------------- # Usage: Used to build the execution ENV. # **Function is not for interactive execution.** #------------------------------------------------- function Initialize-ENV { Import-Module .\\WPK # Modify these variables to meet your needs. The MinPasswordAge # and MaxPasswordAge variables can be pulled from AD. But, for this # version they are hardcoded. The ApplicationPath is the application # that you want to start after the PassMan screen. $Global:MinPasswordAge = 30 #Number of days to start warning. $Global:MaxPasswordAge = 40 #Number of days to force password change. $Global:ApplicationPath = "C:\\Program Files\\Windows NT\\Accessories\\wordpad.exe" } ################################################## # Functions ################################################## # Note: These functions are used to complete the various # automation tasks for this script. #------------------------------------------------- # Get-CurrentIdentity #------------------------------------------------- # Usage: Used to get the identiy for the currently # logged on user. #------------------------------------------------- function Get-CurrentIdentity { $CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() New-Object System.Security.Principal.WindowsPrincipal($CurrentUser) } function Get-ADUser { param ([string]$UserName) $ADDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $Root = [ADSI] "LDAP://$($ADDomain.Name)" $Searcher = New-Object System.DirectoryServices.DirectorySearcher $Root $Searcher.Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=$UserName))" $Searcher.FindOne() } ################################################## # Main ################################################## try { Initialize-ENV $Global:UserIdentity = Get-CurrentIdentity $Global:UsersAMAccountName = (($UserIdentity.Identity.Name).Split("\\"))[1] $Global:UserObject = Get-ADUser $UsersAMAccountName $Global:PwdLastSet = [datetime]::FromFileTime($UserObject.properties.pwdlastset[0]) $Global:PwdLastSetDays = (([System.DateTime]::Now) - $PwdLastSet).TotalDays $Global:PwdExpire = "{0:N0}" -f ($MaxPasswordAge - $PwdLastSetDays) $Global:ExistingPassword $Global:NewPassword1 $Global:NewPassword2 if ($PwdLastSetDays -ge $MinPasswordAge){ New-Window -Title "Password change for $($UsersAMAccountName)" ` -WindowStartupLocation CenterScreen ` -Width 320 -Height 255 -Show ` -ResizeMode NoResize { $BColor = New-SolidColorBrush -Color "#E0E0E0" New-Grid -Rows 'Auto', 'Auto', 'Auto', 'Auto', 'Auto', 'Auto' ` -Columns 'Auto', '150' -Background $BColor { New-Label -Name rtbHeader ` -VerticalContentAlignment Top ` -HorizontalContentAlignment Left ` -Row 0 -Column 0 -ColumnSpan 2 ` -Margin "10 10 0 0" -Width 320 -Height 30 ` -Foreground Red -FontWeight Bold New-TextBlock -Name rtbMessage ` -HorizontalAlignment Left ` -VerticalContentAlignment Top ` -HorizontalContentAlignment Left ` -Row 1 -Column 0 -ColumnSpan 2 ` -Margin "10 0 0 0" -Width 275 -Height 80 ` -Foreground Red -FontWeight Bold -TextWrapping "0" New-Label -Content "Existing password:" ` -Row 2 -Column 0 -Margin "10 0 0 0" New-PasswordBox -Name pbExistingPassword ` -Row 2 -Column 1 -Width 130 ` -VerticalContentAlignment Center ` -HorizontalAlignment Left -PasswordChar "*" ` -On_PasswordChanged {$pbNewPassword1.IsEnabled = $True; $pbNewPassword2.IsEnabled = $True; $btnChange.IsEnabled =$True; $ExistingPassword = $this.password} New-Label -Content "New password:" ` -Row 3 -Column 0 -Margin "10 0 0 0" New-PasswordBox -Name pbNewPassword1 ` -Row 3 -Column 1 -Width 130 ` -VerticalContentAlignment Center ` -HorizontalAlignment Left -PasswordChar "*" ` -On_PasswordChanged {$NewPassword1 = $this.password} New-Label -Content "Retype New password:" ` -Row 4 -Column 0 -Margin "10 0 0 0" New-PasswordBox -Name pbNewPassword2 ` -Row 4 -Column 1 -Width 130 ` -VerticalContentAlignment Center ` -HorizontalAlignment Left -PasswordChar "*" ` -On_PasswordChanged {$NewPassword2 = $this.password} New-Button -Name btnChange -Content "_Change" ` -HorizontalAlignment Left ` -Row 5 -Column 2 ` -Margin "0 10 0 0" -Width 50 New-Button -Name btnCancel -Content "_Cancel" ` -On_Click {$Window.Close(); Start-Process $ApplicationPath} ` -HorizontalAlignment Left ` -Row 5 -Column 2 ` -Margin "55 10 0 0" -Width 50 } } -On_Loaded { if (($PwdLastSetDays -ge $MinPasswordAge) -or ($PwdLastSetDays -ge $MaxPasswordAge)) { $rtbHeader = $Window | Get-ChildControl rtbHeader $rtbMessage = $Window | Get-ChildControl rtbMessage $pbNewPassword1 = $Window | Get-ChildControl pbNewPassword1 $pbNewPassword2 = $Window | Get-ChildControl pbNewPassword2 $btnChange = $Window | Get-ChildControl btnChange $btnCancel = $Window | Get-ChildControl btnCancel # Disable relevate controls $pbNewPassword1.IsEnabled = $false $pbNewPassword2.IsEnabled = $false $btnChange.IsEnabled = $false # If we haven't gotten to the MaxPasswordAge The user can change their password. if ($PwdLastSetDays -ge $MinPasswordAge) { $rtbHeader.Content = "***WARNING***" $rtbMessage.Text = "Your password will expire in $($PwdExpire) days. Please change your password now or click Cancel to continue." } # If we are at the MaxPasswordAge. The user must change their password. if ($PwdLastSetDays -ge $MaxPasswordAge) { $rtbHeader.Content = "***WARNING***" $rtbMessage.Text = "Your password is about to expire. You must change your password now." $btnCancel.IsEnabled = $false } # Here is the password change logic. $Command = {if (!($NewPassword1 -eq $NewPassword2)){ $rtbHeader.Foreground = "Red" $rtbHeader.Content = "***WARNING***" $rtbMessage.Foreground = "Red" $rtbMessage.Text = "Passwords do not match, please try again." } else { $rtbHeader.Foreground = "Black" $rtbHeader.Content = "Progress..." $rtbMessage.Foreground = "Black" $rtbMessage.Text = "Please wait, trying to change password." try{ $User = $UserObject.GetDirectoryEntry() $User.psbase.invoke("ChangePassword",$ExistingPassword, $NewPassword1) # Nothing to do, start application Start-Process $ApplicationPath } catch { $rtbHeader.Foreground = "Red" $rtbHeader.Content = "***ERROR***" $rtbMessage.Foreground = "Red" $rtbMessage.Text = $_.Exception.InnerException.Message } } } $btnChange.Add_Click($Command) } } } else{ # Nothing to do, start application Start-Process $ApplicationPath } } catch { # Nothing to do, start application Start-Process $ApplicationPath }
PowerShellCorpus/PoshCode/set-localpwd_1.ps1
set-localpwd_1.ps1
# Sets local account passwords on one or more computers # usage [computerName1,computerName2,... | ] ./set-localpwd.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...] param( [string] $User , [string] $Password , [string[]] $ComputerNames = @() ) $ComputerNames += @($input) if (! $ComputerNames) { $ComputerNames = $env:computername } function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) { "*** Setting password for $ChangeComputer/$ChangeUser" & { $ErrorActionPreference="silentlycontinue" ([ADSI] "WinNT://$ChangeComputer/$ChangeUser").SetPassword($ChangePassword) if ($?) { " Success" } else { " Failed: $($error[0])" } } } function ShowUsage { @' usage [computerName1,computerName2,... | ] ./set-localpwd.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...] '@ } if ($user -match '^$|-\\?|/\\?|-help' -or ! $password) { ShowUsage; break; } ForEach ($computer in $ComputerNames) { ChangePassword $computer $user $password }
PowerShellCorpus/PoshCode/Test-WebDAV_1.ps1
Test-WebDAV_1.ps1
function Test-WebDav () { param ( $Url = "$( throw 'URL parameter is required.')" ) $xhttp = New-Object -ComObject msxml2.xmlhttp $xhttp.open("OPTIONS", $url, $false) $xhttp.send() if ( $xhttp.getResponseHeader("DAV") ) { $true } else { $false } }
PowerShellCorpus/PoshCode/Find Local Group Members_3.ps1
Find Local Group Members_3.ps1
# Author: Hal Rottenberg # Purpose: Find matching members in a local group # Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx # Change these two to suit your needs $ChildGroups = "Domain Admins", "group two" $LocalGroup = "Administrators" $error.clear() $MemberNames = @() # uncomment this line to grab list of computers from a file $Servers = Get-Content serverlist.txt # $Servers = $env:computername # for testing on local computer foreach ( $Server in $Servers ) { $MemberNames = @() $Group= [ADSI]"WinNT://$Server/$LocalGroup,group" $Members = @($Group.psbase.Invoke("Members")) $Members | ForEach-Object { $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } $errCount = $error.count $ChildGroups | ForEach-Object { $output = "" | Select-Object Server, Group, InLocalAdmin $output.Server = $Server $output.Group = $_ If ($errCount -gt 0){$output.InLocalAdmin = "Connection Error!"}ELSE{$output.InLocalAdmin = $MemberNames -contains $_} Write-Output $output } $error.clear() }
PowerShellCorpus/PoshCode/Get-WebVideoFile.ps1
Get-WebVideoFile.ps1
<# .SYNOPSIS Download video-files from the specified RSS-feed URL, based on HTML scraping and a regular expression. .DESCRIPTION Download video-files from the specified RSS-feed URL, based on HTML scraping and a regular expression for finding the download URL. Joel Bennett`s Get-WebFile function from poshcode.org, which provides progress status during download, is used for downloading the files. The script was originally created for downloading wmv-files from Microsoft TechNet Edge (http://technet.microsoft.com/en-us/edge). .PARAMETER RssUrl The URL for the RSS feed to process .PARAMETER destination The destination-folder for the downloaded video files. If not specified, the downloaded files will be placed in the current user`s Video-folder ($home\\Videos). .PARAMETER UseOriginalFileName Switch-parameter to specify usage of original filenames. If not specified the RSS title will be used as filename. .PARAMETER UrlRegex A regular expression used to search for video URL`s. If not specified a regular expression for finding wmv-files on TechNet Edge is used. .EXAMPLE .\\Get-WebVideoFile.ps1 -RssUrl "http://technet.microsoft.com/en-us/edge/SyndicationGetTopics/cc543196.aspx?field=Category&value=System Center 2012&ancestor=ff524487&version=MSDN.10" .EXAMPLE .\\Get-WebVideoFile.ps1 -Destination "C:\\TechNet Edge Videos\\" -RssUrl "http://technet.microsoft.com/en-us/edge/SyndicationGetTopics/cc543196.aspx?field=Category&value=System Center 2012&ancestor=ff524487&version=MSDN.10" .EXAMPLE .\\Get-WebVideoFile.ps1 -UseOriginalFileName -RssUrl "http://technet.microsoft.com/en-us/edge/SyndicationGetTopics/cc543196.aspx?field=Category&value=System Center 2012&ancestor=ff524487&version=MSDN.10" .EXAMPLE .\\Get-WebVideoFile.ps1 -Verbose -RssUrl "http://technet.microsoft.com/en-us/edge/SyndicationGetTopics/cc543196.aspx?field=Category&value=System Center 2012&ancestor=ff524487&version=MSDN.10" .NOTES Name: Get-WebVideoFile.ps1 Author: Jan Egil Ring Website: http://blog.powershell.no Usage: 1) Find and browse to the category you want to download files from. Available categories: http://technet.microsoft.com/en-us/edge/ff701756 2) Find the RSS URL by clicking the RSS-icon next to the category title on the top of the website 3) Specify the URL on the URL-parameter: .\\Get-WebVideoFile.ps1 -RssUrl "http://technet.microsoft.com/en-us/edge/Syndication..." 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 05.05.2012 - Initial release #Requires -Version 2.0 #> Param( [Parameter(Mandatory=$true)] [string]$RssUrl, [string]$Destination = "$home\\Videos\\", [switch]$UseOriginalFileName, [regex]$UrlRegex = "(?<url>http://content\\d.catalog.video.msn.com/../../[0-f]{8}-[0-f]{4}-[0-f]{4}-[0-f]{4}-[0-f]{12}(?<file>[^>]*?wmv))" ) # Get-WebFile function from http://poshcode.org/3219 function Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) if($url.contains("http")) { $req = [System.Net.HttpWebRequest]::Create($url); } else { $URL_Format_Error = [string]"Connection protocol not specified. Recommended action: Try again using protocol (for example 'http://" + $url + "') instead. Function aborting..."; Write-Error $URL_Format_Error; return; } $req.CookieContainer = New-Object System.Net.CookieContainer try{ $res = $req.GetResponse(); } catch { Write-Error $error[0].Exception.InnerException.Message; return; } 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 (Get-Location -PSProvider "FileSystem") $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [long]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { try{ $writer = new-object System.IO.FileStream $fileName, "Create" } catch{ Write-Error $error[0].Exception.InnerException.Message; return; } } [byte[]]$buffer = new-object byte[] 4096 [long]$total = [long]$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 } } $wc = New-Object net.webclient [xml]$xml = $wc.DownloadString($rssurl) $itemcount = $xml.rss.channel.item.count $count = 0 $xml.rss.channel.item | foreach { $count ++ Write-Verbose "Processing RSS item $count of $itemcount : $($_.title)" $string = $wc.DownloadString($_.link) if ($string -match $urlregex) { Write-Verbose "URL regex matched" $url = $matches.url } else { Write-Verbose "URL regex did not match" return } if ($UseOriginalFileName) { $file = $url.split("/")[-1] } else { $file = $_.Title # Remove illegal filename characters / ? * : ; { } \\ | foreach ($character in ('/','?','*',':',';','{','}','\\','|')) { $file = $file.Replace($character,'') } $file = $file + '.' + $url.split(".")[-1] } if ($url) { $filepath = "$destination$file" if (Test-Path $filepath) {Write-Verbose "$file is already present"} else { Write-Verbose "Downloading $file" Get-WebFile -url $url -filename $filepath } } }
PowerShellCorpus/PoshCode/SetDefaultPrinter_2.ps1
SetDefaultPrinter_2.ps1
<# .SYNOPSIS Sets the Default Printer for any user on any machine in active directory. .DESCRIPTION Search AD for Computername; Select User Account and Printer and make that printer the default printer for that user on that computer. .PARAMETER Hostnme This parameter is required and should reflect the computer name (or names) you wish to inventory. This is basically a search criteria because the first thing the script will do is search Active Directory for computer names matching this input. .NOTES Author: Brad Blaylock Version: 3.2 Date: October 3, 2011 Contact: brad.blaylock@gmail.com Details: This Script accepts an AD Query (Computername) in the form of an entire computer name or partial computername as in sbcomp* or *2471wk1 and will find any listed computers that match the criteria in AD. This list will be presented to the user. The user will select the computer they are needing, and click [LOAD]. Load will find all user accounts that have ever had a profile on that computer; Load will also list all printers installed on that computer. The user will then select the user account and printer and click [Set Default]. SetDefault will make the selected printer default for the selected user on the selected computer. 3.0 -If the selected user is not logged into the selected computer at the time, SetDefault will Load the selected user's NTUSER.DAT registry Hive and make the selected changes offline. 3.2 -Added Current User Display Issues: None Discovered as of Yet. } #> #~~~~~~~~Global \\ Script Variables~~~~~~# $Script:ping = new-object System.Net.NetworkInformation.Ping $Script:tcpClient = New-Object System.Net.Sockets.TcpClient $Script:Search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”) $Script:hku = 2147483651 $Script:hklm = 2147483650 $Script:UserPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList" $Script:PrinterPath = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Printers" $Script:domain = $env:USERDOMAIN #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #~~~~~~~~~~~CUSTOM FUNCTIONS~~~~~~~~~~~~# function Test-Alive($comp) { $stat=$ping.Send("$comp") $reply = $stat.status trap { $False continue; } if($reply -eq "Success") {$True} } function Ping-Port([string]$server, [int]$port) { trap { $False continue; } $tcpClient.Connect($server,$port) if ($tcpClient.Connected) {$True} } Function ADSearch { $Input = $Args[0] $Search.filter = "(&(objectClass=Computer)(Name=$Input))" $Results = $Search.Findall() foreach ($i in $Results) { $Item = $i.properties $lbxServers.Items.Add("$($Item.cn)") } } function LoadUsers { $UserWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Accounts = $UserWMI.EnumKey($hklm,$UserPath) foreach ($Account in $Accounts.snames) { $User = $UserWMI.GetStringValue($hklm,"$UserPath\\$Account","ProfileImagePath") $UserName = ($User.svalue).split("\\")[2] $cbxUserAccount.Items.Add($Username) } $currentuser = (gwmi win32_ComputerSystem -computername $Computer | select UserName).UserName $tbxCurrentUser.Text = $currentuser } Function LoadPrinters { $PrinterWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Printers = $PrinterWMI.EnumKey($hklm,$PrinterPath) foreach ($Printer in $Printers.snames) { $Print = $PrinterWMI.GetStringValue($hklm,"$PrinterPath\\$Printer","Name") $PrinterName = $Print.svalue $cbxPrinter.Items.Add($PrinterName) } } Function SetWithLocalRegHive { #<# #Test OS Version (2000, XP or Vista\\7\\8) $ostest = (gwmi win32_operatingsystem -computername $Computer | select Version | %{$_ -replace "@{Version=", ""} | %{$_ -replace "}", ""}) $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) Switch -wildcard ($ostest) { "5.0*" {$tbxStatus.Text = "Windows 2000"; $profileroot = "Documents and Settings"} "5.1*" {$tbxStatus.Text = "Windows XP"; $profileroot = "Documents and Settings"} "6.0*" {$tbxStatus.Text = "Windows Vista"; $profileroot = "Users" } "6.1*" {$tbxStatus.Text = "Windows 7"; $profileroot = "Users"} } Reg Load HKLM\\TemporaryHive \\\\$Computer\\C$\\$profileroot\\$UserName\\NTUSER.DAT $LocalDefPrinter = (New-Object -ComObject Wscript.shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device") $localDetailsTest = Test-Path "HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices" If (!$LocalDetailsTest) { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "Incomplete User Profile" } Else { $LocalDefPrinterDetails = (New-Object -ComObject Wscript.Shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices\\$PrinterName") $LocalDefaultPrinter = ($LocalDefPrinter).split(",")[0] $Localspool = ($LocalDefPrinterDetails).split(",")[0] $LocalPort = ($LocalDefPrinterDetails).split(",")[1] $LocalNewDefPrinter = $PrinterName + "," + $Localspool + "," + $LocalPort (New-Object -comobject Wscript.Shell).regWrite("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device", "$LocalNewDefPrinter", "REG_SZ") Reg Unload HKLM\\TemporaryHive $tbxStatus.Text = "Default Printer Changed!" } } Function SetDefaultPrinter { Get-service -ComputerName $Computer -Include 'RemoteRegistry' | Start-Service $ntAccount = new-object System.Security.Principal.NTAccount($domain, $UserName) $sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]) $ActionPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows" $DevicesPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices" $ActionWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $DefPrinter = $ActionWMI.GetStringValue($hku,"$ActionPath","Device") $DefPrinterDetails = $ActionWMI.GetStringValue($hku,"$DevicesPath","$PrinterName") $testRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hku,$Computer) $testReg = $testRegKey.OpenSubKey("$sid") If (!$testReg) { SetWithLocalRegHive } Else { $DefaultPrinter = ($DefPrinter.svalue).split(",")[0] $spool = ($DefPrinterDetails.svalue).split(",")[0] $Port = ($DefPrinterDetails.svalue).split(",")[1] $NewDefPrinter = $PrinterName + "," + $spool + "," + $Port $ActionWMI.SetStringValue($HKU,"$ActionPath","Device","$NewDefPrinter") #SET THE DEFAULT PRINTER# $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Default Printer Changed!" } $cbxUserAccount.ResetText() $cbxPrinter.ResetText() } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.8.0 # Generated On: 2/28/2011 11:35 AM # Generated By: bwblaylock ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms.VisualStyles") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() #endregion #region Generated Form Objects $FrmMain = New-Object System.Windows.Forms.Form $pgbProgress = New-Object System.Windows.Forms.ProgressBar $lblPrinter = New-Object System.Windows.Forms.Label $lblUserAccount = New-Object System.Windows.Forms.Label $lblSearch = New-Object System.Windows.Forms.Label $btnSearch = New-Object System.Windows.Forms.Button $tbxSearch = New-Object System.Windows.Forms.TextBox $btnClose = New-Object System.Windows.Forms.Button $btnLoad = New-Object System.Windows.Forms.Button $tbxServer = New-Object System.Windows.Forms.TextBox $tbxStatus = New-Object System.Windows.Forms.TextBox $tbxCurrentUser = New-Object System.Windows.Forms.TextBox $lbxServers = New-Object System.Windows.Forms.ListBox $btnSetDefault = New-Object System.Windows.Forms.Button $cbxPrinter = New-Object System.Windows.Forms.ComboBox $cbxUserAccount = New-Object System.Windows.Forms.ComboBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $btnClose_OnClick= { $FrmMain.Close() } $lbxServers.add_SelectedIndexChanged({ $tbxStatus.Text = $Null $tbxStatus.Refresh() $tbxServer.Text = $lbxServers.SelectedItem $tbxServer.Refresh() $tbxCurrentUser.Text = $null $tbxCurrentUser.Refresh() $cbxPrinter.Items.clear() $cbxPrinter.Text = $null $cbxPrinter.Refresh() $cbxUserAccount.Items.clear() $cbxUserAccount.Text = $null $cbxUserAccount.Refresh() }) $btnLoad_OnClick= { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,255,0) $tbxStatus.Text = "Loading..." $tbxStatus.Refresh() $Computer = $tbxServer.Text If (Test-Alive $Computer) { if ( (ping-port $Computer 135) -and (ping-port $Computer 445) ) { LoadUsers $Computer LoadPrinters $Computer $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Ready..." } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "RPC Server Not Available" } } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "Server Offline" } $pgbProgress.Visible = $False } $btnSetDefault_OnClick= { $Script:Computer = $tbxServer.Text $Script:UserName = $cbxUserAccount.SelectedItem $Script:PrinterName = $cbxPrinter.SelectedItem SetDefaultPrinter } $btnSearch_OnClick= { $lbxServers.Items.Clear() $Criteria = $tbxSearch.Text ADSearch $Criteria } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $FrmMain.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code #Main Form $FrmMain.CancelButton = $btnClose $FrmMain.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $FrmMain.Text = "Set Default Printer" $FrmMain.Name = "FrmMain" $FrmMain.KeyPreview = $True $FrmMain.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 439 $System_Drawing_Size.Height = 272 $FrmMain.ClientSize = $System_Drawing_Size $FrmMain.AcceptButton = $btnSearch $FrmMain.FormBorderStyle = 2 #Search Label $lblSearch.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 14 $lblSearch.Size = $System_Drawing_Size $lblSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 9 $lblSearch.Location = $System_Drawing_Point $lblSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $lblSearch.Name = "lblSearch" $FrmMain.Controls.Add($lblSearch) #Printer Label $lblPrinter.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 12 $lblPrinter.Size = $System_Drawing_Size $lblPrinter.Text = "Printer:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 185 $lblPrinter.Location = $System_Drawing_Point $lblPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $lblPrinter.Name = "lblPrinter" $FrmMain.Controls.Add($lblPrinter) #UserAccount Label $lblUserAccount.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 13 $lblUserAccount.Size = $System_Drawing_Size $lblUserAccount.Text = "User Account:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 145 $lblUserAccount.Location = $System_Drawing_Point $lblUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $lblUserAccount.Name = "lblUserAccount" $FrmMain.Controls.Add($lblUserAccount) #Progress Bar $pgbProgress.DataBindings.DefaultDataSourceUpdateMode = 0 $pgbProgress.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $pgbProgress.ForeColor = [System.Drawing.Color]::FromArgb(255,0,255,0) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 191 $System_Drawing_Size.Height = 8 $pgbProgress.Size = $System_Drawing_Size $pgbProgress.Step = 1 $pgbProgress.TabIndex = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 246 $System_Drawing_Point.Y = 105 $pgbProgress.Location = $System_Drawing_Point $pgbProgress.Style = [System.Windows.Forms.ProgressBarStyle]::Marquee #2 $pgbProgress.MarqueeAnimationSpeed = 50 $pgbProgress.Visible = $False $pgbProgress.Name = "pgbProgress" $FrmMain.Controls.Add($pgbProgress) #Status Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxStatus.Size = $System_Drawing_Size $tbxStatus.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxStatus.TextAlign = 2 $tbxStatus.BorderStyle = 0 $tbxStatus.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,0) $tbxStatus.Name = "tbxStatus" $tbxStatus.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 88 $tbxStatus.Location = $System_Drawing_Point $tbxStatus.TabIndex = 20 $FrmMain.Controls.Add($tbxStatus) #Server Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxServer.Size = $System_Drawing_Size $tbxServer.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxServer.TextAlign = 2 $tbxServer.BorderStyle = 0 $tbxServer.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,1) $tbxServer.Name = "tbxServer" $tbxServer.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 32 $tbxServer.Location = $System_Drawing_Point $tbxServer.TabIndex = 19 $FrmMain.Controls.Add($tbxServer) #CurrentUser Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxCurrentUser.Size = $System_Drawing_Size $tbxCurrentUser.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxCurrentUser.TextAlign = 2 $tbxCurrentUser.BorderStyle = 0 $tbxCurrentUser.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Italic') #0,3,1) $tbxCurrentUser.Name = "tbxCurrentUser" $tbxCurrentUser.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 60 $tbxCurrentUser.Location = $System_Drawing_Point $tbxCurrentUser.TabIndex = 20 $FrmMain.Controls.Add($tbxCurrentUser) #Search Button $btnSearch.TabIndex = 2 $btnSearch.Name = "btnSearch" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnSearch.Size = $System_Drawing_Size $btnSearch.UseVisualStyleBackColor = $True $btnSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 180 $System_Drawing_Point.Y = 26 $btnSearch.Location = $System_Drawing_Point $btnSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSearch.add_Click($btnSearch_OnClick) $FrmMain.Controls.Add($btnSearch) #Load Button $btnLoad.TabIndex = 4 $btnLoad.Name = "btnLoad" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnLoad.Size = $System_Drawing_Size $btnLoad.UseVisualStyleBackColor = $True $btnLoad.Text = "Load" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 310 $System_Drawing_Point.Y = 120 $btnLoad.Location = $System_Drawing_Point $btnLoad.DataBindings.DefaultDataSourceUpdateMode = 0 $btnLoad.add_Click($btnLoad_OnClick) $FrmMain.Controls.Add($btnLoad) #Close Button $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 351 $System_Drawing_Point.Y = 236 $btnClose.Location = $System_Drawing_Point $btnClose.DataBindings.DefaultDataSourceUpdateMode = 0 $btnClose.DialogResult = 2 $btnClose.add_Click($btnClose_OnClick) $FrmMain.Controls.Add($btnClose) #SetDefault Button $btnSetDefault.TabIndex = 7 $btnSetDefault.Name = "btnSetDefault" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnSetDefault.Size = $System_Drawing_Size $btnSetDefault.UseVisualStyleBackColor = $True $btnSetDefault.Text = "Set Default" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 236 $btnSetDefault.Location = $System_Drawing_Point $btnSetDefault.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSetDefault.add_Click($btnSetDefault_OnClick) $FrmMain.Controls.Add($btnSetDefault) #Search Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 161 $System_Drawing_Size.Height = 20 $tbxSearch.Size = $System_Drawing_Size $tbxSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxSearch.Name = "tbxSearch" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 29 $tbxSearch.Location = $System_Drawing_Point $tbxSearch.TabIndex = 1 $FrmMain.Controls.Add($tbxSearch) $btnClose.TabIndex = 8 $btnClose.Name = "btnClose" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnClose.Size = $System_Drawing_Size $btnClose.UseVisualStyleBackColor = $True $btnClose.Text = "Close" #Servers Listbox #$lbxServers.UseCompatibleStateImageBehavior = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 227 $System_Drawing_Size.Height = 205 $lbxServers.Size = $System_Drawing_Size $lbxServers.DataBindings.DefaultDataSourceUpdateMode = 0 $lbxServers.Name = "lbxServers" #$lbxServers.View = 3 $lbxServers.TabIndex = 3 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 55 $lbxServers.Location = $System_Drawing_Point $FrmMain.Controls.Add($lbxServers) #Printer Combobox $cbxPrinter.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxPrinter.Size = $System_Drawing_Size $cbxPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxPrinter.Name = "cbxPrinter" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 200 $cbxPrinter.Location = $System_Drawing_Point $cbxPrinter.TabIndex = 6 $FrmMain.Controls.Add($cbxPrinter) #UserAccount Combobox $cbxUserAccount.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxUserAccount.Size = $System_Drawing_Size $cbxUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxUserAccount.Name = "cbxUserAccount" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 161 $cbxUserAccount.Location = $System_Drawing_Point $cbxUserAccount.TabIndex = 5 $FrmMain.Controls.Add($cbxUserAccount) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $FrmMain.WindowState #Init the OnLoad event to correct the initial state of the form $FrmMain.add_Load($OnLoadForm_StateCorrection) #Show the Form $FrmMain.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/get-windowsproductkey.ps1
get-windowsproductkey.ps1
function get-windowsproductkey([string]$computer) { $Reg = [WMIClass] ("\\\\" + $computer + "\\root\\default:StdRegProv") $values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue) $lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9") $keyStartIndex = [int]52; $keyEndIndex = [int]($keyStartIndex + 15); $decodeLength = [int]29 $decodeStringLength = [int]15 $decodedChars = new-object char[] $decodeLength $hexPid = new-object System.Collections.ArrayList for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) } for ( $i = $decodeLength - 1; $i -ge 0; $i--) { if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'} else { $digitMapIndex = [int]0 for ($j = $decodeStringLength - 1; $j -ge 0; $j--) { $byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]); $hexPid[$j] = [byte] ([math]::Floor($byteValue / 24)); $digitMapIndex = $byteValue % 24; $decodedChars[$i] = $lookup[$digitMapIndex]; } } } $STR = '' $decodedChars | % { $str+=$_} $STR } get-windowsproductkey .
PowerShellCorpus/PoshCode/Roman Numeral Clock.ps1
Roman Numeral Clock.ps1
function RomanNumeral($Num,$Pos) { [array]$RomanFormat="9","0","00","000","01","1","10","100","1000","02" [array]$RomanColumns="I","V","X","X","L","C" $Format=$RomanFormat[$num] $NumberOfCharacters=$Format.Length If ( $Format -ne "9" ) { For ($Counter=0;$Counter -lt ($numberOfCharacters);$counter++) { [int]$ColumnPosition=[convert]::toint16($Format[$Counter],10) Write-Host $RomanColumns[$Columnposition+(3*$Pos)] -nonewline } } } function convertToRoman ($Number) { $NumberString=$number.tostring() $NumberOfDigits=$NumberString.Length For ($NumberPosition=0;$numberPosition -lt $NumberString.length;$NumberPosition++) { $NumbertoSend=[convert]::toint16(($NumberString[$NumberPosition]),10) $position=($NumberOfDigits-1)-$NumberPosition RomanNumeral $NumberToSend $position } } do { $current=get-date $thehour=$current.hour $theminute=$current.minute $theseconds=$current.second IF ($thehour -eq 0 ) { $thehour=12 } IF ($thehour -gt 12) { $thehour=$thehour-12 } $Location=$HOST.UI.RAWUI.CursorPosition converttoroman $thehour write-host ":" -nonewline converttoroman $theminute write-host ":" -nonewline converttoroman $theseconds write-host " " start-sleep -seconds 1 $HOST.UI.RAWUI.CursorPosition=$Location } until ($FALSE)
PowerShellCorpus/PoshCode/TabExpansion_6.ps1
TabExpansion_6.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. ## Some features(relate to '$_' expansion) require the latest Get-PipelineObject.ps1 in a same diretory. (from http://poshcode.org/author/foobar) ## ## 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 expansion ## [Dec<tab> ## [Microsoft.PowerShell.Com<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.Management.Auto<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 -Err <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 ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion ## 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 -Error 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 -exp <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 ## [ 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 ### Generate ProgIDs list... if ($_ProgID -eq $null) { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") [Object[]] $_ProgID = $null foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID += $_i.GetValue("") } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Get-Content -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;' } ### Generate TypeNames list... if ( $_TypeNames -eq $null ) { [Object[]] $_TypeNames = $null foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames += $_type.FullName } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Get-Content -Path $PSHOME\\TypeNames.txt;' } if ( $_TypeNames_System -eq $null ) { [Object[]] $_TypeNames_System = $null foreach ( $_type in $_TypeNames -like "System.*" ) { $_TypeNames_System += $_type.Substring(7) } '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Get-Content -Path $PSHOME\\TypeNames_System.txt;' } ### Generate WMIClasses list... if ( $_WMIClasses -eq $null ) { [Object[]] $_WMIClasses = $null foreach ( $_class in gwmi -List ) { $_WMIClasses += $_class.Name } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_WMIClasses = Get-Content -Path $PSHOME\\WMIClasses.txt;' } $global:_snapin = $null # Load Get-PipeLineObject function for $_ and property name expansion. $_scriptpath = gi $MyInvocation.MyCommand.Path iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1")) 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 -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 variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } 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; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[((\\w+\\.?)+)$' { $_opt = $matches[1] + '*' foreach ( $_exp in $_TypeNames_System -like $_opt ) { '[' + $_exp } foreach ( $_exp in $_TypeNames -like $_opt ) { '[' + $_exp } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # 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($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[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] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet.Definition)[0] } if ( $_cmdlet.CommandType -eq "Cmdlet" ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { ( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace ` '^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ } } break; } elseif ( $_command -eq $null ) { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;]')[-1] if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' ) { if ( $Matches[6] -ne $nul ) { $brackets = "[]" } '['+ $global:_enum + $brackets + ']' break; } if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' ) { $_pat = $Matches[7] + '*' $_type = @(iex $Matches[1])[0].GetType() if ( $_type.IsEnum ) { $global:_enum = $_type.FullName [Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"' break; } } $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) #elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] # 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 ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System $_TypeNames break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { # 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($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[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] # now get the info object for it... $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { #$_opt = $Matches[1] + '*' $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) # 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 ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } if ( $_cmdlet.Name -like "*WMI*" ) { $_WMIClasses -like $_opt break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) # 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($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[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] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", " New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { $_WMIClasses -like $_opt break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { $Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" | % { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } | ? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ } } break; } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $pattern = $command + "*" gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/Invoke-ElevatedCommand.ps1
Invoke-ElevatedCommand.ps1
Function Invoke-ElevatedCommand { <# .DESCRIPTION Invokes the provided script block in a new elevated (Administrator) powershell process, while retaining access to the pipeline (pipe in and out). Please note, "Write-Host" output will be LOST - only the object pipeline and errors are handled. In general, prefer "Write-Output" over "Write-Host" unless UI output is the only possible use of the information. Also see Community Extensions "Invoke-Elevated"/"su" .EXAMPLE Invoke-ElevatedCommand {"Hello World"} .EXAMPLE "test" | Invoke-ElevatedCommand {$input | Out-File -filepath c:\\test.txt} .EXAMPLE Invoke-ElevatedCommand {$one = 1; $zero = 0; $throwanerror = $one / $zero} .PARAMETER Scriptblock A script block to be executed with elevated priviledges. .PARAMETER InputObject An optional object (of any type) to be passed in to the scriptblock (available as $input) .PARAMETER EnableProfile A switch that enables powershell profile loading for the elevated command/block .PARAMETER DisplayWindow A switch that enables the display of the spawned process (for potential interaction) .SYNOPSIS Invoke a powershell script block as Administrator .NOTES Originally from "Windows PowerShell Cookbook" (O'Reilly), by Lee Holmes, September 2010 at http://poshcode.org/2179 Modified by obsidience for enhanced error-reporting, October 2010 at http://poshcode.org/2297 Modified by Tao Klerks for code formatting, enhanced/fixed error-reporting, and interaction/hanging options, January 2012 at https://gist.github.com/gists/1582185 and at http://poshcode.org/, followup to http://poshcode.org/2297 SEE ALSO: "Invoke-Elevated" (alias "su") in PSCX 2.0 - simpler "just fire" elevated process runner. #> param ( ## The script block to invoke elevated. NOTE: to access the InputObject/pipeline data from the script block, use "$input"! [Parameter(Mandatory = $true)] [ScriptBlock] $Scriptblock, ## Any input to give the elevated process [Parameter(ValueFromPipeline = $true)] $InputObject, ## Switch to enable the user profile [switch] $EnableProfile, ## Switch to display the spawned window (as interactive) [switch] $DisplayWindow ) begin { Set-StrictMode -Version Latest $inputItems = New-Object System.Collections.ArrayList } process { $null = $inputItems.Add($inputObject) } end { ## Create some temporary files for streaming input and output $outputFile = [IO.Path]::GetTempFileName() $inputFile = [IO.Path]::GetTempFileName() $errorFile = [IO.Path]::GetTempFileName() ## Stream the input into the input file $inputItems.ToArray() | Export-CliXml -Depth 1 $inputFile ## Start creating the command line for the elevated PowerShell session $commandLine = "" if(-not $EnableProfile) { $commandLine += "-NoProfile " } if(-not $DisplayWindow) { $commandLine += "-Noninteractive " $processWindowStyle = "Hidden" } else { $processWindowStyle = "Normal" } ## Convert the command into an encoded command for PowerShell $commandString = "Set-Location '$($pwd.Path)'; " + "`$output = Import-CliXml '$inputFile' | " + "& {" + $scriptblock.ToString() + "} 2>&1 ; " + "Out-File -filepath '$errorFile' -inputobject `$error;" + "Export-CliXml -Depth 1 -In `$output '$outputFile';" $commandBytes = [System.Text.Encoding]::Unicode.GetBytes($commandString) $encodedCommand = [Convert]::ToBase64String($commandBytes) $commandLine += "-EncodedCommand $encodedCommand" ## Start the new PowerShell process $process = Start-Process -FilePath (Get-Command powershell).Definition ` -ArgumentList $commandLine ` -Passthru ` -Verb RunAs ` -WindowStyle $processWindowStyle $process.WaitForExit() $errorMessage = $(gc $errorFile | Out-String) if($errorMessage) { Write-Error -Message $errorMessage } else { ## Return the output to the user if((Get-Item $outputFile).Length -gt 0) { Import-CliXml $outputFile } } ## Clean up Remove-Item $outputFile Remove-Item $inputFile Remove-Item $errorFile } }
PowerShellCorpus/PoshCode/chkhash_23.ps1
chkhash_23.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 } function WriteFileNameEnd ( ) { if ($global:oldctop -eq $null) {return} [console]::cursortop=$global:oldctop [console]::cursorleft=0 write-host "" } function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call writefilenameend when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length if ($global:lastlen -gt $writestr.length) { $writestr = $writestr + (" " * ($global:lastlen-$writestr.length)) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # don't ask. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:lastlen = $oldwritestrlen $global:oldctop=([console]::cursortop) [console]::cursortop=$ctop [console]::cursorleft=0 } $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, minus directories and minus files in excluded paths 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 | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} WriteFileNameEnd $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 -literalpath $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) {WriteFileNameEnd; "Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue WriteFileName "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 } WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..." $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 WriteFileNameEnd if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } WriteFileNameEnd # restore cursor position after last write string 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/PowerShell Talk Chickens_2.ps1
PowerShell Talk Chickens_2.ps1
#The PowerShell Talk #Virtualization Congress 2009 # #The Chicken Counter Script #Get our cretendials #More on credential stores: http://professionalvmware.com/2009/04/09/posh-article-of-the-week-secure-credential-storage/ $credentials = Get-VICredentialStoreItem -File "c:\\scripts\\really_secure_file.xml" #Setup Our Counters $datacenters = @{ Name = "Datacenters" Expression = { Get-Datacenter | Measure-Object} } $hosts = @{ Name = "Hosts" Expression = { Get-VMHost | Measure-Object } } $vms = @{ Name = "VMs" Expression = { Get-VM | Measure-Object } } $clusters = @{ Name = "Clusters" Expression = { Get-Cluster | Measure-Object } } #Connect to each vCenter in the credentials file ForEach ($creds in $credentials) { #Connect, Count, Disconnect connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password $output = $datacenter | Select-Object $datacenters, $hosts, $vms, $clusters @@$output = $datacenters | Select-Object $datacenters, $hosts, $vms, $clusters disconnect-viserver -confirm:$false #Add this to the mail $Body += "`nvCenter: " + $creds.Host $Body += "`nDatacenters: " + $output.Datacenterss.count $Body += "`nDatacenters: " + $output.Datacenters.count $Body += "`nHosts: " + $output.Hosts.Count $Body += "`nVMs: " + $output.VM.Count $Body += "`nVMs: " + $output.VMS.Count $Body += "`nClusters: " + $output.Clusters.Count #Totals $totalHosts += $output.Hosts.count $totalVM += $output.VM.count $totalVM += $output.VMS.count $totalDatacenters += $output.Datacenters.count $totalClusters += $output.Clusters.count } #Setup & Send our Mail $SmtpClient = new-object Net.Mail.SmtpClient("localhost") $From = "The Farm Hand <chicken_counter@professionalvmware.com>" #Change these for your environment $To = "Your Pointy Haired Boss <The_Boss@professionalvmware.com>" #Change these for your environment $Title = "Direct from your local VC: Weekly Statistics" $Body += "`n`nTotals:`n" $Body += "`nDatacenters: " + $totalDatacenters $Body += "`nHosts: " + $totalHosts $Body += "`nVMs: " + $totalVM $Body += "`nClusters: " + $totalClusters $SmtpClient.Send($From, $To, $Title, $Body)
PowerShellCorpus/PoshCode/Claimtypes, ADFS SP2010.ps1
Claimtypes, ADFS SP2010.ps1
Add-PSSnapin -Name Microsoft.SharePoint.PowerShell $claim = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming $claim2 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" -IncomingClaimTypeDisplayName "Role" -SameAsIncoming $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\\path-to-certificate\\certificate.cer") $realm = "urn:" + $env:ComputerName + ":adfs" $signinurl = "https://signin.domain.com/adfs/ls/" $ap = New-SPTrustedIdentityTokenIssuer -Name "ADFS20Server" -Description "ADFS 2.0 Federated Server" -Realm $realm -ImportTrustCertificate $cert -ClaimsMappings $claim,$claim2 -SignInUrl $signinurl -IdentifierClaim $claim.InputClaimType $ap.AddClaimTypeInformation($claim) $ap.AddClaimTypeInformation($claim2) $uri = new-object System.Uri("https://someuri.domain.com/") $ap.ProviderRealms.Add($uri, “urn:" + $env:ComputerName + ":adfssite”) $ap.Update()
PowerShellCorpus/PoshCode/Tac (reverse cat)_1.ps1
Tac (reverse cat)_1.ps1
# From "Unix like command for tac?" thread on posh NG # solution by Keith Hill param([string]$path) $fs = New-Object System.IO.FileStream ((Resolve-Path $path), 'Open', 'Read') trap { $fs.Close(); break } $pos = $fs.Length $sb = New-Object System.Text.StringBuilder while (--$pos -ge 0) { [void]$fs.Seek($pos, 'Begin') $ch = [char]$fs.ReadByte() if ($ch -eq "`n" -and $sb.Length -gt 0) { $sb.ToString().TrimEnd() $sb.Length = 0 } [void]$sb.Insert(0, [char]$ch) } $sb.ToString().TrimEnd()
PowerShellCorpus/PoshCode/ScriptSVN.ps1
ScriptSVN.ps1
# # Script from SVN Utility # ~~~~~~~~~~~~~~~~~~~~~~~ # This script processes template files and produces and output file. # Its a simple macro processor really. # We use it to extract the latest version of our database procedurrads and functions # from our source code control server to create deployment scripts. # # This will assume you have svn command line client in your path. # This currently cannot authenticate with svn to retrieve data. So just simple svn: supported. # This is written and tested with Microsoft Windows Powershell v1.0. # # When run it will look for all files with ".dro" extension in the current # directory and process them. If the ".dro" file does not specify the # OuputFile directive then the output file will have the same name as the # input file with ".dro" replaced by ".out" # # GETTING STARTED # ~~~~~~~~~~~~~~~ # Go to a directory containing a .dro file and execute "ScriptSVN.ps1" It will process all .dro files it finds. # Look at $exampleInputFile below to see a sample input file content. # # This example will fail to get this example to work you will need # 1. SVN Server called sccserver. # 2. Files under the following path on SVN server # svn://sccserver/trunk/database/maindb/Procedure/ProcedureA.sql # svn://sccserver/trunk/database/maindb/Procedure/ProcedureB.sql # svn://sccserver/trunk/database/maindb/Procedure/ProcedureD.sql # 3. The ProcedureD file must have a revision 43 available. # # File Format SYNTAX # ~~~~~~~~~~~~~~~~~~ # 1. '#' marks start of script comment # Comments characters are converted to $comment on output to match output format. # Currently understands Single Quote strings and will mostly not identify a # in a string as a comment. # 2. '{' '}' mark start and end of a script directive. # Only recognised if the '{' is first non white space on a line. [simplifies search match a lot] # Only recognised if both start and end on same line. # The result of the directive is output to the file. # The output result is bracketed before and after by comments identifying the directive and parameters. # White space preceding a directive is prepended to each line output from directive [maintains indenting]. # Extra data following a directive is completely ignored at the moment. # 3. Other lines are output as they are # # A directive may have parameters. # Directive parameters must use double quotes to quote things with spaces. # For simplicity will always end up with a newline as last char in file. # Simple understanding of single quoted strings wont find comment characters inside single quoted strings. # Single quoted strings are supported because this was primarilly setup for SQL rollout scripts. # Double quoted strings are not supported anywhere but inside directives. # # DIRECTIVES # ~~~~~~~~~~ # OutputFile # set the name of file to write output. # No lines that produce output in file must precede the line its on [so make it first] # Or only after SourceControl line. # SourceControl # Set the source control access string base path. # Must have trailing slash [ no it does not check it has it ] # eg. svn://scc/project/trunk/Database/DBName/ for DBName procedures # Reference # Extract a file from SourceControl with given path. eg. path "Procedures/spnEmailMessageInsert.sql" # First parameter is path to file to fetch from source control. # Second parameter is an optional revision to retrieve of that file # Third paremter is an optional string to output to file as well [not sure how useful this is] # Inside this third parameter the string is processed for some special characters # "\\n" represents a new line. useful for "GO\\n". # "\\t" represents a tab. # The conversion only occurs for output data not for the trace data output to file. # # Example. Build.cmd file that converts the .dro file(s) into our file # "powershell C:\\Scripts\\rollscript.ps1" # # HISTORY # 2008/12/11 rluiten Created. # 2008/12/15 rluiten Setup a v3.2 folder to test and fixed a bug or three. # Useful now maybe. # 2008/12/17 rluiten Added explicit revision retrieval to Reference. # Reference now looks up the revision to be able to output to file. # 2009/02/23 rluiten Corrected end of line outputs to CRLF. # # SOME EXTRA NOTES # ~~~~~~~~~~~~~~~~ # We export our procedures and functions as a unit that drop themseles if they exist # create themselves and then set permissions. This is the functional block of code we manage # and track in our source code control server. This allows us to export the code from SQL again # with another small script and do a file comparison to check we havnt missed a change or # something hasnt snuck out to production without being in source control. # # Dont put identation in front of a {Reference} directive to a procedure as it will add indenting # to the start of every line and your exported code if you wish to diff your database back to # your source code control server will cause every line to be different. # # This utility is general and could be used for other stuff than SQL. # However the single quote processing of strings not inside directives may limit some scenarios. # This is the first script I have written so probably lots of things I can do better. # Happy to have feedback. # Hope someone finds this useful saves us here a lot of time keeping our deployment scripts # correct as we work. # $exampleInputFile = @" {SourceControl "svn://sccserver/trunk/database/maindb/"} {OutputFile "Test2.sql"} #{hello world} {Reference "Procedure/ProcedureA.sql" } {Reference "Procedure/ProcedureB.sql" "" "print 'dont forget to do job 222'\\n"} #{Reference "Procedure/ProcedureC.sql" } -- commented out for now {Reference "Procedure/ProcedureD.sql" "43"} -- extract specific revision file select 'This is a test' select 'What a nice day.' #{Me to} # not here -- Zzzz ' this and # that ' # and here -- Aaaa# ' foiousf ds' # and here -- Bbbb # ' foiousf ds # and here --select 'Yyyy' "@ $commentStart = "#" $comment = "--" $version = "3" # directives must be first non white space on line and not be empty. # doesnt matter what follows a directive # the content of the directive will always be group 3 of regex. # group 4 is data following directive $matchDirective=[Regex]"^(\\s*)({([^{]+)})(.*)$" # matching only single quote strings for now - and assume a string goes from first quote on line to last quote on line. # groups 0 whole match, 1 - before string, 2 - string, 3 - after string $matchSingleQuoteString=[Regex]@" ^([^']*)(['].*?['])([^']*)$ "@ # returns array. # array 0 - prefix string to directive. [will always be whitespace] # array 1 - directive text inside brackets # array 2 - post fix data after directive function split-directive([string]$str) { $myMatches = $matchDirective.match($str) if ($myMatches.Success) { return $myMatches.Groups[1], $myMatches.Groups[3], $myMatches.Groups[4] } } # return the index of the comment character on the line. -1 if no comment on line function get-commentindex([string]$str) { $startCommentIndex = -1 $myMatches = $matchSingleQuoteString.match($str) # check for comment char before and after string in group 1 and 3. if ($myMatches.Success) # found a string in our line so look around it for comments { $commentIndex = ([string]$myMatches.Groups[1]).IndexOf($commentStart) if ($commentIndex -gt -1) { # comment in group 1 $startCommentIndex = $myMatches.Groups[1].Index + $commentIndex } else { $commentIndex = ([string]$myMatches.Groups[3]).IndexOf($commentStart) if ($commentIndex -gt -1) { $startCommentIndex = $myMatches.Groups[3].Index + $commentIndex } } } else # no string so just first index of comment { $startCommentIndex = $str.IndexOf($commentStart) } return $startCommentIndex } # returns array # array 0 - non comment part of line # array 1 - comment part of line including comment char function split-comment([string]$str) { $startCommentIndex = get-commentindex $str if ($startCommentIndex -gt -1) { return $str.Substring(0, $startCommentIndex), $str.Substring($startCommentIndex) } else { return $str } } ## got from http://poshcode.org/496 thank you Jaykul :) ################################################################################ ## Convert-Delimiter - A function to convert between different delimiters. ## E.g.: commas to tabs, tabs to spaces, spaces to commas, etc. ################################################################################ ## Written primarily as a way of enabling the use of Import-CSV when ## the source file was a columnar text file with data like services.txt: ## ip service port ## 13.13.13.1 http 8000 ## 13.13.13.2 https 8001 ## 13.13.13.1 irc 6665-6669 ## ## Sample Use: ## Get-Content services.txt | Convert-Delimiter " +" "," | Set-Content services.csv ## would convert the file above into something that could passed to: ## Import-Csv services.csv ## ## Get-Content Delimited.csv | Convert-Delimiter "," "`t" | Set-Content Delimited.tab ## would convert a simple comma-separated-values file to a tab-delimited file ################################################################################ ## Version History ## Version 1.0 ## First working version ## Version 2.0 ## Fixed the quoting so it adds quotes in case they're neeeded ## Version 2.1 ## Remove quotes which aren't needed ## Version 2.2 ## Trim spaces off the ends, they confuse things ## Version 2.3 ## Allow empty columns: as in: there,are,six,"comma, delimited",,columns ## Version 2.3 ## Replaced Trim() with regex to do similar job. ## if a parameter is "" <-- empty string this captures the "Quotes" as its value not empty string ??? Function Convert-Delimiter([regex]$from,[string]$to) { begin { $z = [char](222) } process { #$_ = $_.Trim() # converted Trim into regex replace as powershell 1 does not have it ? $_ = $_ -replace "^\\s+", "" -replace "\\s+$", "" $_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z$to" $_ = $_ -replace "$z(?:$to|$z)?`$","$z" $_ = $_ -replace "`"`"","`"" -replace "`"","`"`"" $_ = $_ -replace "$z((?:[^$z`"](?!$to))+)$z($to|`$)","`$1`$2" $_ = $_ -replace "$z","`"" -replace "$z","`"" $_ } } # Use source code control client [svn] to retrieve referenced file. Function get-reference([string]$scc, [string]$filePath, [string]$rev, [string]$post, [string]$whiteSpacePre) { $svn = 'svn.exe' if ($rev -eq $null -or $rev -eq "") { # figure out the revision of head if we dont have it. $result = @(& $svn info $scc$filePath) # ensure its an array even if only one $revResult = @($result -like "Revision: *") if ($revResult.Length -eq 1) { $tmp = $revResult[0] $regexRevision = [regex]"^Revision: (\\d+)$" $myMatches = $regexRevision.match($tmp) if ($myMatches.Success) { $rev = $myMatches.Groups[1] } } else { write-error "Cannot find revision for $scc$filePath." exit } } # example of svn 'svn -r 1234 cat svn://scc/project/trunk/database/DBName/Procedure/procedure.sql' write-host "Reference [$rev] $filePath" #write-host "$svn -r $rev cat $scc$filePath" $result = & $svn -r $rev cat $scc$filePath # prefix each line for ($i = 0; $i -lt $result.Length; $i++) { $result[$i] = $whiteSpacePre + $result[$i] } $fileContent = [string]::join("`r`n", $result) append-outputString "$comment ** Start Reference [$scc] [$filePath] [$rev] [$post]`r`n"; append-outputString "$fileContent`r`n" # additional newline after data if ($post -ne $null -and $post -ne "") { $convertedPost = $post -replace "\\\\n", "`r`n" -replace "\\\\t", "`t" append-outputString $convertedPost } append-outputString "$comment ** End Reference [$scc] [$filePath] [$rev] [$post]`r`n"; } # procedures to wrap up global string buffer for processed output. function init-outputString() { $global:outputString = "" $global:sourceControl = "" $global:outputFile = "" } function append-outputString([string]$str) { $global:outputString += $str } function write-outputString([string]$file) { write-output $global:outputString | out-file -filePath $file -encoding oem } function execute-directive($splitDirective, [string]$whiteSpacePre) { $keyword = $splitDirective[0] switch ($keyword) { "SourceControl" { write-host "$comment $keyword `"$($splitDirective[1])`"" append-outputString "$whiteSpacePre$comment $keyword `"$($splitDirective[1])`"" $global:sourceControl = $splitDirective[1] } "OutputFile" { append-outputString "$whiteSpacePre$comment $keyword `"$($splitDirective[1])`"" $global:outputFile = $splitDirective[1] } "Reference" { get-reference $global:sourceControl $splitDirective[1] $splitDirective[2] $splitDirective[3] $whiteSpacePre } default { write-error "Unknown directive `"$keyword`" exiting..." exit } } } function process-directive([string]$directive, [string]$whiteSpacePre) { $reDelimit = $directive | Convert-Delimiter " " "!" $splitDirective = $reDelimit.Split("!") for ($i = 0; $i -lt $splitDirective.Length; $i++) { $tmp = $splitDirective[$i] if ($tmp -eq "`"`"`"`"") # convert """" to empty string -- side effect of Convert-Delimiter { $splitDirective[$i] = ""; # empty string } } execute-directive $splitDirective $whiteSpacePre } function process-file([string]$inputFile, [string]$outputFile) { init-outputString $global:outputFile = $outputFile if (!(test-path -pathType Leaf $inputFile)) { write-error "Cannot open input file `"$inputFile`"" exit } $outmsg = "$comment ScriptSVN $version processing file `"$inputFile`"" write-host $outmsg append-outputString "$outmsg`r`n" $inputLines = @(get-content -path $inputFile) # read file @ to ensure we get an array foreach ($line in $inputLines) { $activeStr, $commentStr = split-comment $line $whiteSpacePre, $directive, $poststr = split-directive $activeStr if ($directive -eq $null -or $directive.Length -eq 0) { append-outputString "$activeStr" # no directive to just output the line } else { process-directive $directive $whiteSpacePre } # output comment if ($commentStr.Length -gt 0) { # convert input comment format to output format $afterComment = $commentStr.Substring($commentStart.Length) append-outputString "$comment$afterComment`r`n" } else { append-outputString "`r`n" # just new line } } write-host "$comment OutputFile `"$($global:outputFile)`"" write-outputString $global:outputFile } # by default process all file ending in file extension in current directory $files = @(get-childitem "*.dro") if ($files.Length -eq 0) { write-host "No files found for processing." write-host "This utility processes files ending in `".dro`" " } foreach ($f in $files) { $outFile = $f -replace ".dro",".out" process-file $f $outFile }
PowerShellCorpus/PoshCode/8b29c3c3-9f8f-4a19-83de-cdc6f2129025.ps1
8b29c3c3-9f8f-4a19-83de-cdc6f2129025.ps1
#========================================================================== # NAME: getunknownsids.ps1 # # AUTHOR: Stephen Wheet # Version: 4.0 # Date: 6/11/10 # # COMMENT: # This script was created to find unknown SIDs or old domain permissions # on folders. It ignores folders where inheirtance is turned on. # # This works on NETAPPS and WINDOWS servers. You will need the DLL's # # Version 2: completely changed the query method and ACL removal # Version 3: Added ability to query AD for servers, and handles getting # getting shares automatically from: # NETAPP FILERS # Windows servers # Version 4: Cleaned up folder checking and added checking for local # account checking so we could ignore. # #========================================================================== Function checkshare { Param($PassedShareName) Process { $path = "\\\\$serverFQDN\\$PassedShareName" $filename = $path.Replace("\\","-") + ".csv" #Place Headers on out-put file $list = "Task,Path,Access Entity," $list | format-table | Out-File "c:\\reports\\unknownsids\\$filename" #Populate Folders Array Write-Host "Writing results to : $filename" $date = Get-Date Write-Host $date Write-Host "Getting Folders in: $Path" #PSIscontainer means folders only [Array] $folders = Get-ChildItem -path $path -recurse | ? {$_.PSIsContainer} #Process data in array ForEach ($folder in [Array] $folders) { #Check to see if there are any folders If ($folder.pspath){ #Convert Powershell Provider Folder Path to standard folder path $PSPath = (Convert-Path $folder.pspath) Write-Host "Checking Dir: $PSPath" #Check to make sure valid If ($PSPath){ #Get the ACL's from each folder $error.clear() $acl = Get-Acl -Path $PSPath #Write log if no access if (!$?) { $errmsg = "Error,$PSPath,ACCESS DENIED" $errmsg | format-table | Out-File -append "$filename" } #end IF $ACL.Access | ?{!$_.IsInherited} | ?{ $_.IdentityReference -like $unknownsid -or $_.IdentityReference -like $olddomain } | % {$value = $_.IdentityReference.Value #Check for Local account $localsid = 0 If ($value -like $unknownsid){ $checkforlocal = $value.split("-") $total =$checkforlocal.count -1 if ($checkforlocal[$total] -match "100?" -or $checkforlocal[$total] -match "500"){ $localsid = 1 # You can uncomment the below if you want to report on local accounts. #$list = ("Local,$PSPath,$value") #$list | format-table | Out-File -append "$filename" } #end IF } #end IF If (!$localsid){ Write-host "Found - $PSPath - $value" $list = ("Found,$PSPath,$value") $list | format-table | Out-File -append "$filename" #Remove Bad SID if ($removeacl) { $ACL.RemoveAccessRuleSpecific($_) Write-host "Deleting - $PSPath - $value" $list = ("Deleting,$PSPath,$value") $list | format-table | Out-File -append "$filename" }#end IF if ($removeacl -and $value) { $date = Get-Date Write-Host $date Write-host "Setting - $PSPath" $list = ("Setting,$PSPath") $list | format-table | Out-File -append "$filename" Set-ACL $PSpath $ACL $value = "" } #end IF } #end if } #end foreachobj } #end if } #end if } #end ForEach }#end Process } #end function get-pssnapin -registered | add-pssnapin -passthru [void][Reflection.Assembly]::LoadFile('C:\\reports\\ManageOntap.dll') #Need this DLL from netapp 3.5SDK $ReqVersion = [version]"1.2.2.1254" $QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version #Need Quest plugins installed if($QadVersion -lt $ReqVersion) { throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version" } #end If #Set variables $value = "" $unknownsid = "*S-1-5-21-*" #Broken SID Verify the Broken SID number on your system and replace $olddomain = "Domain.local*" #Old w2k/nt4 domain $ErrorActionPreference = "SilentlyContinue" $removeacl = 0 #change to 1 if you want to remove the SID, 0 for only logging $localsid = 0 #Get all the servers from the specified OU $Servers = get-QADComputer -SearchRoot 'domain.local/ou/Server' # change the container. Foreach ($server in $Servers ) { $serverFQDN = $server.dnsname write-host $serverFQDN #Test ping server to make sure it's up before querying it $ping = new-object System.Net.NetworkInformation.Ping $Reply = $ping.Send($serverFQDN) if ($Reply.status -eq "Success"){ Write-Host "Online" #Check for Netapp .. if found get the shares differently If ($serverFQDN -like "*netapp*"){ $server = new-object netapp.manage.naserver($serverFQDN,1,0) #pass authentication $server.Style = "RPC" # Issue command to get the shares $NaElement = New-Object NetApp.Manage.NaElement("system-cli") $arg = New-Object NetApp.Manage.NaElement("args") $arg.AddNewChild('arg','cifs') $arg.AddNewChild('arg','shares') $NaElement.AddChildElement($arg) $CifsString = $server.InvokeElem($NaElement).GetChildContent("cli-output") # Split the returned txt up .. the $null makes it skip a line $null,$null,$Lines = $CifsString.Split("`n") Foreach ($line in $Lines ) { # Had to trick it so skip the line with permissions, then exclude ETC$ adn c$ if (!$line.startswith(" ") -and $line -notlike "*Etc$*" -and $line -notlike "*C$*"){ $l= $line.Split(" ") checkshare -PassedShareName $l[0] #Pass share to function } #end if } #end foreach } #end if Else{ #Else if a Windows server query via WMI Get-WMIObject Win32_Share -Computer $serverFQDN | where {$_.Name -like "*$*" -and $_.Name -notlike "*ADMIN*" -and $_.Name -notlike "*IPC*" -and $_.Name -notlike "*lib*"} | %{ #Set path $sharename = $_.name checkshare -PassedShareName $sharename #Pass share to function } #end ForEachObj } #End Else } #End If } #end ForEach
PowerShellCorpus/PoshCode/Search Files by Date_1.ps1
Search Files by Date_1.ps1
<# Author: Matt Schmitt Date: 11/30/12 Version: 1.0 From: USA Email: ithink2020@gmail.com Website: http://about.me/schmittmatt Twitter: @MatthewASchmitt Description A script for finding files in a directory by Last Accessed Date. #> Write-Host "Enter Root Directory you would like to search" Write-Host "" Write-Host "Example: C:\\Users\\testuser" Write-Host "" $directory = Read-Host ">>" cls Write-Host "Enter "From" Date" Write-Host "" Write-Host "Example: 1/1/12" Write-Host "" $startDate = Read-Host '>>' cls Write-Host "Enter "To" Date" Write-Host "" Write-Host "Example: 11/30/12" Write-Host "" $endDate = Read-Host '>>' cls Write-Host "Enter where you would like the CSV file to be exported" Write-Host "" Write-Host "Example: C:\\Files.csv" Write-Host "" $outPutFile = Read-Host '>>' cls Write-Host "" Write-Host "" Write-Host "Searching for files in '$directory' from '$startDate' to '$endDate'..." Get-ChildItem -path $directory -Recurse | where { $_.lastaccesstime -ge [datetime]$startDate -and $_.lastaccesstime -lt [datetime]$endDate} | select fullname | Export-CSV -Path $outPutFile Write-Host "" Write-Host "Results have been exported!" Write-Host "" Write-Host "Press any key to Exit." #Code to wait for user to press a key. $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
PowerShellCorpus/PoshCode/Wrapper 1 Select-String .ps1
Wrapper 1 Select-String .ps1
[CmdletBinding()] param( [Parameter(ParameterSetName='Object', Mandatory=$true, ValueFromPipeline=$true)] [AllowEmptyString()] [AllowNull()] [System.Management.Automation.PSObject] ${InputObject}, [Parameter(Mandatory=$true, Position=0)] [System.String[]] ${Pattern}, [Parameter(ParameterSetName='File', Mandatory=$true, Position=1, ValueFromPipelineByPropertyName=$true)] [Alias('PSPath')] [System.String[]] ${Path}, [Switch] ${SimpleMatch}, [Switch] ${CaseSensitive}, [Switch] ${Quiet}, [Switch] ${List}, [ValidateNotNullOrEmpty()] [System.String[]] ${Include}, [ValidateNotNullOrEmpty()] [System.String[]] ${Exclude}, [Switch] ${NotMatch}, [Switch] ${AllMatches}, [ValidateSet('unicode','utf7','utf8','utf32','ascii','bigendianunicode','default','oem')] [ValidateNotNullOrEmpty()] [System.String] ${Encoding}, [ValidateNotNullOrEmpty()] [ValidateCount(1, 2)] [ValidateRange(0, 2147483647)] [System.Int32[]] ${Context}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Select-String', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } # wrapper generated by New-ProxyCommand # http://blogs.msdn.com/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx # ------- modification added by Bernd Kriszio -- http://pauerschell.blogspot.com/ # # if (! $Encoding) { # it is ridiculous to call a parameter default which is not $PSBoundParameters.Encoding = 'default' <# # finally I want a values default_or_oem for -Encoding # to find strings in unicode, ansii and oem coded files # but it is not that simple @(Select-String * -pattern Ärger -encoding default) + @(Select-String * -pattern Ärger -encoding oem) |sort-object | Get-Unique #> } # --------------------------------------------------------------------- $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Select-String .ForwardHelpCategory Cmdlet #>
PowerShellCorpus/PoshCode/ConvertFrom-Property.ps1
ConvertFrom-Property.ps1
<# .SYNOPSIS Converts data from flat or single-level property files into PSObjects .DESCRIPTION Converts delimited string data into objects .PARAMETER PropertyText The text to be parsed .PARAMETER Separator The value separator string used between name=value pairs. Allows regular expressions. Defaults to "=" and is usually either "=" or ":" or ";" .PARAMETER Delimiter The property separator string used between sets of name=value pairs. Allows regular expressions. Defaults to "\\n\\s*\\n?" and is usually either "`n" or "`n`n" or "\\n\\s*\\n" .PARAMETER RecordSeparator The record separator string is used between records or sections in a text file. Defaults to "\\n\\[(.+)\\]\\s*\\n" for ini files, and is usually either "\\n\\s*\\n" or "\\n\\[(.*)\\]\\s*\\n" To support named sections or records, make sure to use a regular expression here that has a capture group defined. .EXAMPLE ConvertFrom-PropertyString config.ini Reads in an ini file (which has key=value pairs), using the default settings .EXAMPLE @" ID:3468 Type:Developer StartDate:1998-02-01 Code:SWENG3 Name:Baraka ID:11234 Type:Management StartDate:2005-05-21 Code:MGR1 Name:Jax "@ |ConvertFrom-PropertyString -sep ":" -RecordSeparator "\\r\\n\\s*\\r\\n" | Format-Table Code StartDate Name ID Type ---- --------- ---- -- ---- SWENG3 1998-02-01 Baraka 3468 Developer MGR1 2005-05-21 Jax 11234 Management Reads records from a key:value property file with records separated by blank lines. .EXAMPLE ConvertFrom-PropertyString data.txt -Separator ":" Reads in a property file which has key:value pairs .EXAMPLE Get-Content data.txt -Delimiter "`r`n`r`n" | ConvertFrom-PropertyString -Separator ";" Reads in a property file with key;value pairs, and sections separated by blank lines, and converts it to objects .EXAMPLE ConvertFrom-PropertyString data.txt -delimiter '\\r\\n\\r\\n' -Separator ";" Reads in a property file with key;value pairs, and sections separated by blank lines, and converts it to objects .EXAMPLE ConvertFrom-PropertyString data.txt -RecordSeparator "^;(.*?)\\r*\\n" -Separator ";" Reads in a property file with key:value pairs, and sections with a header that starts with the comment character ';' #> #function ConvertFrom-PropertyString { [CmdletBinding(DefaultParameterSetName="Data")] param( [Parameter(Position=99, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Data")] [Alias("Data","Content")] [string]$RecordText , [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")] [Alias("PSPath","FileName")] [string]$InputFile , [Parameter()][Alias("ValueSeparator")] [String]$Separator='=' , [Parameter()][Alias("PropertySeparator")] [String]$Delimiter='(?:\\s*\\n+\\s*)+' , [Parameter()] [String]$RecordSeparator='(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n' , [Parameter(ParameterSetName="Data")] [Alias("MultiRecords","MR")] [Switch]$MultipleRecords ) begin { $Splitter = New-Object System.Text.RegularExpressions.Regex ([System.String]$RecordSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } process { Write-Verbose "ParameterSet: $($PSCmdlet.ParameterSetName)" $InputData = @{} if($PSCmdlet.ParameterSetName -eq "File") { $MultipleRecords = $true $RecordText = Get-Content $InputFile -Delimiter ([char]0) } if($PsBoundParameters.ContainsKey("RecordSeparator")) { $MultipleRecords = $true } if($MultipleRecords) { $Records = $splitter.Split( $RecordText ) | ? { $_ } if($Splitter.GetGroupNumbers().Count -gt 1) { while($Records) { $key,$value,$Records = $Records $InputData.$Key += @($value) } } else { $InputData."" = $Records } } else { $InputData."" = @($RecordText) } foreach($key in $InputData.Keys) { foreach($record in $InputData.$key) { Write-Verbose "Record: $record" if($Key) { $output = @{"PSName"=$key} } elseif($InputFile) { $output = @{"PSName"=((get-item $InputFile).PSChildName)} } else{ $output = @{} } foreach($line in $record -split $Delimiter) { [string[]]$data = $line -split $Separator,2 | foreach { $_.Trim() } | where { $_ } Write-Verbose "Line: $Line | Data: $($data -join '--')" switch($data.Count) { 1 { $output.($Data[0]) = $null } 2 { $output.($Data[0]) = $Data[1] } } } if($output.Count) { New-Object PSObject -Property $output } } } } #}
PowerShellCorpus/PoshCode/TabExpansion_13.ps1
TabExpansion_13.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 charactors ## [<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 charactor after Ctrl+X until the charactor ## 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> ## # PSDrive and item name expansion in variable notation ## ${fu<tab> ## ${function:cl<tab> ## ${c:*<tab>\\*<tab> ## ${c:\\win<tab>/sys<tab>/<tab> ### 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+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+X cut words with a charactor after Ctrl+X until the charactor 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; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^((.*[=/;,\\)}])?((\\[(\\w+(\\.\\w*)*)\\])*))(\\[(\\w*(\\.\\w*)*))$' { $_base = $matches[1] $_opt = $matches[8] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' | % { $_base + $_ } } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' | % { $_base + $_ } Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' | % { $_base + $_ } Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' | % { $_base + $_ } } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ('"$0"') $fse = $fse -replace '([\\[\\]])', '````$1' -replace '^.*([\\[\\]]).*$', ('"$0"') $fse = $fse -replace '""', '"' $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_buf = $global:_cmdstack.Pop() if( $_buf.Contains("'") ) { $line = ($line.SubString(0, $line.Length-1) + $_buf) -replace '([[\\]\\(\\)+
PowerShellCorpus/PoshCode/Get-PSVersion.ps1
Get-PSVersion.ps1
Set-Alias Ver Get-PSVersion function Get-PSVersion { [string]$Major = ($PSVersionTable).PSVersion.Major [string]$Minor = ($PSVersionTable).PSVersion.Minor [string]$Out = $Major + '.' + $Minor Write-Output $Out }
PowerShellCorpus/PoshCode/Kill-Process.ps1
Kill-Process.ps1
function Kill-Process() { param( [string[]]$ComputerNames, [string[]]$ProcessNames, $User ) ########################################################################################################### if ($ProcessNames -eq $null) {Write-Error 'The parametre "ProcessNames" cannot be empty';break} ########################################################################################################### if ($User -is [String]) { $Connection = Get-Credential -Credential $User } ########################################################################################################### foreach ($int1 in $ComputerNames){ foreach ($int2 in $ProcessNames) { if ($int2 -notlike "*.exe") {$int2 = $int2 + '.exe'} if ($Connection -eq $null) {$count = 0 $Process_Kill = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" | ForEach-Object {$_.terminate();$count++} $Process_Kill = "" | select @{e={$int1};n='&#1050;&#1086;&#1084;&#1087;&#1100;&#1102;&#1090;&#1077;&#1088;'},` @{e={$int2};n='&#1055;&#1088;&#1086;&#1094;&#1077;&#1089;&#1089;'}, @{e={$count};n='&#1050;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086;'} } else {$count = 0 $Process_Kill = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" | ForEach-Object {$_.terminate();$count++} $Process_Kill = "" | select @{e={$int1};n='&#1050;&#1086;&#1084;&#1087;&#1100;&#1102;&#1090;&#1077;&#1088;'},` @{e={$int2};n='&#1055;&#1088;&#1086;&#1094;&#1077;&#1089;&#1089;'}, @{e={$count};n='&#1050;&#1086;&#1083;&#1080;&#1095;&#1077;&#1089;&#1090;&#1074;&#1086;'} } $Process_Kill } } ########################################################################################################### }
PowerShellCorpus/PoshCode/Invoke-CmdScript.ps1
Invoke-CmdScript.ps1
##############################################################################\n##\n## Invoke-CmdScript\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\nInvoke the specified batch file (and parameters), but also propigate any\nenvironment variable changes back to the PowerShell environment that\ncalled it.\n\n.EXAMPLE\n\nPS >type foo-that-sets-the-FOO-env-variable.cmd\n@set FOO=%*\necho FOO set to %FOO%.\n\nPS >$env:FOO\nPS >Invoke-CmdScript "foo-that-sets-the-FOO-env-variable.cmd" Test\n\nC:\\Temp>echo FOO set to Test.\nFOO set to Test.\n\nPS > $env:FOO\nTest\n\n#>\n\nparam(\n ## The path to the script to run\n [Parameter(Mandatory = $true)]\n [string] $Path,\n\n ## The arguments to the script\n [string] $ArgumentList\n)\n\nSet-StrictMode -Version Latest\n\n$tempFile = [IO.Path]::GetTempFileName()\n\n## Store the output of cmd.exe. We also ask cmd.exe to output\n## the environment table after the batch file completes\ncmd /c " `"$Path`" $argumentList && set > `"$tempFile`" "\n\n## Go through the environment variables in the temp file.\n## For each of them, set the variable in our local environment.\nGet-Content $tempFile | Foreach-Object {\n if($_ -match "^(.*?)=(.*)$")\n {\n Set-Content "env:\\$($matches[1])" $matches[2]\n }\n}\n\nRemove-Item $tempFile
PowerShellCorpus/PoshCode/Get-Hostname_3.ps1
Get-Hostname_3.ps1
# .SYNOPSIS # Print the hostname of the system. # .DESCRIPTION # This function prints the hostname of the system. You can additionally output the DNS # domain or the FQDN by using the parameters as described below. # .PARAMETER Short # (Default) Print only the computername, i.e. the same value as returned by $env:computername # .PARAMETER Domain # If set, print only the DNS domain to which the system belongs. Overrides the Short parameter. # .PARAMETER FQDN # If set, print the fully-qualified domain name (FQDN) of the system. Overrides the Domain parameter. param ( [switch]$Short = $true, [switch]$Domain = $false, [switch]$FQDN = $false ) $ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() if ( $FQDN ) { return "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName } if ( $Domain ) { return $ipProperties.DomainName } if ( $Short ) { return $ipProperties.HostName }
PowerShellCorpus/PoshCode/POC-adding custom PS job.ps1
POC-adding custom PS job.ps1
#this is just a quite proof of concept, totally useless in of itself, with functions not fleshed out function get-jobrepository { [CmdletBinding()] param() $pscmdlet.JobRepository } function add-job { [CmdletBinding()] param($job) $pscmdlet.JobRepository.add($job) } $src = @" using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; namespace bkg1 { public class BackgroundJob : Job { public BackgroundJob(string command) : base(command) { } public override bool HasMoreData { get { throw new NotImplementedException(); } } public override string Location { get { throw new NotImplementedException(); } } public override string StatusMessage { get { throw new NotImplementedException(); } } public override void StopJob() { throw new NotImplementedException(); } } } "@ add-type -typedefinition $src $a = new-object bkg1.BackgroundJob {1..10} add-job $a get-job
PowerShellCorpus/PoshCode/Demo-Confirm.ps1
Demo-Confirm.ps1
### NOTE: the <#PS ... #> is the prompt! <#PS [40] #> $ConfirmPreference High <#PS [41] #> function get-confirmed { [CmdletBinding(SupportsShouldProcess=$true)]param() $ConfirmPreference } <#PS [42] #> get-confirmed High <#PS [43] #> get-confirmed -confirm Low <#PS [44] #> get-confirmed -confirm:$false None <#PS [45] #> $ConfirmPreference = "Medium" <#PS [46] #> get-confirmed Medium <#PS [47] #> get-confirmed -confirm Low <#PS [48] #> get-confirmed -confirm:$false None
PowerShellCorpus/PoshCode/Get-PerformanceHistory _2.ps1
Get-PerformanceHistory _2.ps1
##requires -version 2.0 ## Get-PerformanceHistory.ps1 ############################################################################################################## ## Lets you see the amount of time recent commands in your history have taken ## History: ## v2.53 - added back the Lines, Words, and Characters .... ## v2.52 - added regex-based iteration counting to calculate averages ## v2.51 - removed PsParser features to make it v1 compatible ## v2.5 - added "average" calculation if the first thing in your command line is a range: 1..x ## v2 - added measuring the scripts involved in the command, (uses Tokenizer) ## - adds a ton of parsing to make the output pretty ############################################################################################################## function Get-PerformanceHistory { param( [int]$count=1, [int[]]$id=@((Get-History -count 1| Select Id).Id) ) ## Removed to make this v1 compatible ## $Parser = [System.Management.Automation.PsParser] function FormatTimeSpan($ts) { if($ts.Minutes) { if($ts.Hours) { if($ts.Days) { return "{0:##}d {1:00}:{2:00}:{3:00}.{4:00000}" -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:##}:{1:00}:{2:00}.{3:00000}" -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:##}:{1:00}.{2:00000}" -f $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:#0}.{1:00000}" -f $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } # if there's only one id, then the count counts, otherwise we just use the ids # ... basically: { 1..$count | % { $id += $id[-1]-1 } } if($id.Count -eq 1) { $id = ($id[0])..($id[0]-($count-1)) } # so we can call it with just the IDs Get-History -id $id | ForEach { $msr = $null $cmd = $_ # default formatting values $avg = 7; $len = 8; $count = 1 ## Removed to make this v1 compatible ## $tok = $Parser::Tokenize( $cmd.CommandLine, [ref]$null ) ## if( ($tok[0].Type -eq "Number") -and ## ($tok[0].Content -le 1) -and ## ($tok[2].Type -eq "Number") -and ## ($tok[1].Content -eq "..") ) ## { ## $count = ([int]$tok[2].Content) - ([int]$tok[0].Content) + 1 ## } ## ## $com = @( $tok | where {$_.Type -eq "Command"} | ## foreach { ## $Local:ErrorActionPreference = "SilentlyContinue" ## get-command $_.Content ## $Local:ErrorActionPreference = $Script:ErrorActionPreference ## } | ## where { $_.CommandType -eq "ExternalScript" } | ## foreach { $_.Path } ) ## ## # If we actually got a script, measure it out ## if($com.Count -gt 0){ ## $msr = Get-Content -path $com | Measure-Object -Line -Word -Char ## } else { $msr = Measure-Object -in $cmd.CommandLine -Line -Word -Char ## } ## V1 Averages: $min, $max = ([regex]"^\\s*(?:(?<min>\\d+)\\.\\.(?<max>\\d+)\\s+\\||for\\s*\\([^=]+=\\s*(?<min>\\d+)\\s*;[^;]+\\-lt\\s*(?<max>\\d+)\\s*;[^;)]+\\)\\s*{)").match( $cmd.CommandLine ).Groups[1,2] | % { [int]$_.Value } $count = $max - $min if($count -le 0 ) { $count = 1 } "" | Select @{n="Id"; e={$cmd.Id}}, @{n="Duration"; e={FormatTimeSpan ($cmd.EndExecutionTime - $cmd.StartExecutionTime)}}, @{n="Average"; e={FormatTimeSpan ([TimeSpan]::FromTicks( (($cmd.EndExecutionTime - $cmd.StartExecutionTime).Ticks / $count) ))}}, @{n="Lines"; e={$msr.Lines}}, @{n="Words"; e={$msr.Words}}, @{n="Chars"; e={$msr.Characters}}, @{n="Type"; e={if($com.Count -gt 0){"Script"}else{"Command"}}}, @{n="Commmand"; e={$cmd.CommandLine}} } | # I have to figure out what the longest time string is to make it look its best Foreach { $avg = [Math]::Max($avg,$_.Average.Length); $len = [Math]::Max($len,$_.Duration.Length); $_ } | Sort Id | Format-Table @{l="Duration";e={"{0,$len}" -f $_.Duration}},@{l="Average";e={"{0,$avg}" -f $_.Average}},Lines,Words,Chars,Type,Commmand -auto }
PowerShellCorpus/PoshCode/ListCmdletParameters.ps1
ListCmdletParameters.ps1
# To use # Save script as LISTPARAMETERS.PS1 # # To get the parameters from a Powershell cmdlet just execute # # ./LISTPARAMETERS.PS1 -helpdata (GET-HELP GET-CHILDITEM) # # To list in a clean column, all of the parameters for GET-CHILDITEM # # ./LISTPARAMETERS.PS1 -helpdata (GET-HELP SET-QADUSER) # # To list in a clean column, all of the parameters for SET-QADUSER # # I find it handy for Cmdlets that have so many available parameters, it's hard to tell where to start # param($HelpData) ($HelpData).Syntax | SELECT-OBJECT –ExpandProperty SyntaxItem | SELECT-OBJECT –ExpandProperty parameter | SELECT-OBJECT name
PowerShellCorpus/PoshCode/new get-childitem.ps1
new get-childitem.ps1
Function Get-ChildItem { <# .ForwardHelpTargetName Get-ChildItem .ForwardHelpCategory Cmdlet #> [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}, [System.String] ${Pattern}, [Switch] ${Recurse}, [Switch] ${BinarySizeInHumanReadableFormat}, [Switch] ${Force}, [Switch] ${Name}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\\Get-ChildItem', [System.Management.Automation.CommandTypes]::Cmdlet) $cmd = "" if($BinarySizeInHumanReadableFormat) { $PSBoundParameters.Remove('BinarySizeInHumanReadableFormat') | Out-Null $cmd = @" | ForEach-Object { `$_length=Switch(`$_.length) { { `$_ -lt 1kb } { '{0}B' -f (`$_) ;break } { `$_ -lt 1MB } { '{0}KB' -f ([math]::round(`$(`$_/ 1kb)), 2) ;break } { `$_ -lt 1gb } { '{0}MB' -f ([math]::round(`$(`$_/ 1mb), 2)) ;break } defaut { { '{0}GB' -f ([math]::round(`$(`$_/ 1gb), 2)) ;break } } } if(`$_.PSISContainer) { `$_length=`$null } `$_ | Add-Member noteproperty size `$_.length -Pass | Add-Member noteproperty length `$_length -PassThru -Force } "@ } if($PSBoundParameters['Pattern']) { if($Filter -or $Include) { throw "les paramčtres Pattern et Filter/Include sont mutuellemnt exculsive" } else { $PSBoundParameters.Remove('Pattern') | Out-Null $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where { $_.Name -imatch "$Pattern" } } } } else { $scriptCmd = {& $wrappedCmd @PSBoundParameters } } $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock( $scriptCmd.ToString() + $cmd ) $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } }
PowerShellCorpus/PoshCode/Replace-InTextFile.ps1
Replace-InTextFile.ps1
# Replace-InTextFile.ps1 # Replace Strings in files param ( [string] $Path = "." , [string] $Filter # Select no files, by default.... , [string] $pattern = $(Read-Host "Please enter a pattern to match") , [string] $replace = $(Read-Host "Please enter a replacement string") , [switch] $recurse = $false , [switch] $caseSensitive = $false ) if ($pattern -eq $null -or $pattern -eq "") { Write-Error "Please provide a search pattern!" ; return } if ($replace -eq $null -or $replace -eq "") { Write-Error "Please provide a replacement string!" ; return } function CReplace-String( [string]$pattern, [string]$replacement ) { process { $_ -creplace $pattern, $replacement } } function IReplace-String( [string]$pattern, [string]$replacement ) { process { $_ -ireplace $pattern, $replacement } } $files = Get-ChildItem -Path $Path -recurse:$recurse -filter:$Filter foreach($file in $files) { Write-Host "Processing $($file.FullName)" if( $caseSensitive ) { $str = Get-Content $file.FullName | CReplace-String $pattern $replace Write-Host $str Set-Content $file.FullName $str } else { $str = Get-Content $file.FullName | IReplace-String $pattern $replace Write-Host $str Set-Content $file.FullName $str } } if($files.Length -le 0) { Write-Warning "No matching files found" }
PowerShellCorpus/PoshCode/Findup_18.ps1
Findup_18.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, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-regex", false }, { "-noerr", false } }; public static void Main(string[] args) { Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine(" "); string optionspathskey = "-paths"; List<FileInfo> files = new List<FileInfo>(); long numOfDupes = 0; // number of duplicate files found. long dupeBytes = 0; // number of bytes in duplicates. 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> <file/directory #2> ... <file/directory #N> [-recurse] [-noerr] [-x] <files/directories/regx> [-regex]"); 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(" -x - eXcludes if full file path starts with (or RegEx matches if -regex supplied) 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 -regex supplied) one of the items following this switch until another switch is used."); Console.WriteLine(" -xd - eXcludes all directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -regex - Use Regex notation for exclude (-x) and include (-i) option."); 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(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); 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 -x \\"(jim)\\" -regex"); 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\\\\bobsmithquarter.doc -x \\"[bf]\\" -i \\"(smith)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); Console.WriteLine(" -xd,-id,-xf,-if are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa."); Console.WriteLine(" if for instance you wanted all files that contained the letter \\"d\\" on your D: drive but didn't want the d:\\\\ to cause all files on the d:\\\\ "); Console.WriteLine(" drive to be included, you would specify:"); Console.WriteLine(" findup.exe d:\\\\ -recurse -noerr -regex -if \\"[d]\\" "); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionspathskey = "-paths"; continue; } if (optionspaths.ContainsKey(argitem)) { optionspathskey = argitem; continue; } optionspaths[optionspathskey].Add(argitem); } 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"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>(); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) { continue; } var breakout = false; while (true) { var _SHA512 = SHA512.Create(); try { using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } System.Text.Encoding enc = System.Text.Encoding.ASCII; string SHA512string = enc.GetString(_SHA512.Hash); if (SizeHashName.ContainsKey(files[i].Length)) { if (!SizeHashName[files[i].Length].ContainsKey(SHA512string)) { SizeHashName[files[i].Length][SHA512string] = new List<string>() {}; } } else { SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>()); SizeHashName[files[i].Length][SHA512string] = new List<string>() {}; } SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } if (files[i].Length != files[i + 1].Length) { breakout = true; } } } Console.WriteLine("Completed!"); foreach (var SizeGroup in SizeHashName) { foreach (var HashGroup in SizeGroup.Value) { if (HashGroup.Value.Count > 1) { Console.WriteLine("Duplicates (size: {0:N0} Bytes) - ", (long)SizeGroup.Key); foreach (var FileName in HashGroup.Value) { Console.WriteLine(FileName); numOfDupes++; dupeBytes += (long)SizeGroup.Key; } } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); return; // Exit after displaying statistics. } private static void WriteErr(string Str) { if (optionsbools["-noerr"] == false) Console.WriteLine(Str); } private static Boolean CheckAll(string full) { if (!CheckWorker(full, optionspaths["-x"])) return false; if ((optionspaths["-i"].Count > 0) == CheckWorker(full, optionspaths["-i"])) return false; var filePart = Path.GetFileName(full); var dirPart = Path.GetDirectoryName(full); if (!CheckWorker(filePart, optionspaths["-xf"])) return false; if (!CheckWorker(dirPart, optionspaths["-xd"])) return false; if ((optionspaths["-if"].Count > 0) == CheckWorker(filePart, optionspaths["-if"])) return false; if ((optionspaths["-id"].Count > 0) == CheckWorker(dirPart, optionspaths["-id"])) return false; return true; } private static Boolean CheckWorker(string full, List<string> pathsitems) { foreach (var x in pathsitems) { if (optionsbools["-regex"] == true) { try { Regex rgx = new Regex(x); if (rgx.IsMatch(full)) return false; } catch (Exception e) { WriteErr("Invalid regex used: " + x + " exception: " + e); } } else { if (full.ToLower().StartsWith(x)) { return false; } } } return true; } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } 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) && CheckAll(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); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckAll(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { 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/OpsMgr State Changes.ps1
OpsMgr State Changes.ps1
# Description: State Changes for specified OpsMgr Monitor # Date: 09-12-2009 # Author: Stefan Stranger # Explanation: If you want to know the State Changes for a specific Monitor you can run the next PowerShell script # You need to have db permissions to the OperationsManagerdw database to run this Script. # You need to run the script from the OpsMgr Command Shell because it uses the Get-Monitor Cmdlet. param ([string]$monitor = $(read-host "Please enter Monitor Name"), [string]$server = $(read-host "Please enter servername hosting OperationsManagerdw database")) $MonitorDefaultName = "'" + (get-monitor | where {$_.DisplayName -like $monitor}).DisplayName + "'" if ($MonitorDefaultName -eq "''") {Write-host "No Monitor found"} else { $sqlConnString = "Server=$server;DataBase=OperationsManagerdw;Integrated Security=SSPI" $connection = New-Object System.Data.SqlClient.SqlConnection($sqlConnString) $cmd = New-Object System.Data.SqlClient.SqlCommand $sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $connection.Open() | Out-Null $cmd.CommandTimeout = 30 $cmd.Connection = $connection $startsql = @' SELECT COUNT(*) AS StateChanges, vMonitor.MonitorDefaultName, vManagementPack.ManagementPackDefaultName FROM State.vStateRaw INNER JOIN vManagedEntityMonitor ON State.vStateRaw.ManagedEntityMonitorRowId = vManagedEntityMonitor.ManagedEntityMonitorRowId INNER JOIN vMonitor ON vManagedEntityMonitor.MonitorRowId = vMonitor.MonitorRowId INNER JOIN vMonitorManagementPackVersion ON vManagedEntityMonitor.MonitorRowId = vMonitorManagementPackVersion.MonitorRowId INNER JOIN vManagementPack ON vMonitor.ManagementPackRowId = vManagementPack.ManagementPackRowId WHERE (MonitorDefaultName = '@ $endsql = @' ) AND (vMonitorManagementPackVersion.UnitMonitorInd = 1) GROUP BY vMonitor.MonitorDefaultName, vManagementPack.ManagementPackDefaultName ORDER BY StateChanges DESC '@ $totalsqlquery = $startsql + $MonitorDefaultName + $endsql #Write-host $totalsqlquery $cmd.CommandText = $totalsqlquery $sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlAdapter.SelectCommand = $cmd $ds = New-Object System.Data.DataSet $sqlAdapter.Fill($ds) | Out-Null foreach ($table in $ds.Tables) { $table | Format-Table -auto; } $connection.Close() }
PowerShellCorpus/PoshCode/Add-NetworkPrinter.ps1
Add-NetworkPrinter.ps1
###########################################################################" # # NAME: Add-NetworkPrinter.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: Windows PowerShell script to map a network printer based on Active Directory group membership. # The get-GroupMembership function are created by Andy Grogan, see his blogpost for more information on this function: # http://www.telnetport25.com/component/content/article/15-powershell/127-quick-tip-determining-group-ad-membership-using-powershell.html # Also see this blogpost for more information: # http://blog.powershell.no/2009/11/28/mapping-printers-based-on-active-directory-group-membership-using-windows-powershell # Tested with Windows PowerShell v 1.0/2.0 and Windows XP/Vista/7. # # 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 28.11.2009 - Initial release # ###########################################################################" $strName = $env:username function get-GroupMembership($DNName,$cGroup){ $strFilter = "(&(objectCategory=User)(samAccountName=$strName))" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.Filter = $strFilter $objPath = $objSearcher.FindOne() $objUser = $objPath.GetDirectoryEntry() $DN = $objUser.distinguishedName $strGrpFilter = "(&(objectCategory=group)(name=$cGroup))" $objGrpSearcher = New-Object System.DirectoryServices.DirectorySearcher $objGrpSearcher.Filter = $strGrpFilter $objGrpPath = $objGrpSearcher.FindOne() If (!($objGrpPath -eq $Null)){ $objGrp = $objGrpPath.GetDirectoryEntry() $grpDN = $objGrp.distinguishedName $ADVal = [ADSI]"LDAP://$DN" if ($ADVal.memberOf.Value -eq $grpDN){ $returnVal = 1 return $returnVal = 1 }else{ $returnVal = 0 return $returnVal = 0 } }else{ $returnVal = 0 return $returnVal = 0 } } $result = get-groupMembership $strName "Printer_group_01" if ($result -eq '1') { Invoke-Expression 'rundll32 printui.dll,PrintUIEntry /in /q /n"\\\\print-server\\printer-share"' }
PowerShellCorpus/PoshCode/Remove-FTPFile_1.ps1
Remove-FTPFile_1.ps1
function Remove-FTPFile ($Source,$UserName,$Password) { #Create FTP Web Request Object to handle connnection to the FTP Server $ftprequest = [System.Net.FtpWebRequest]::Create($Source) # set the request's network credentials for an authenticated connection $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password) $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile # send the ftp request to the server $ftpresponse = $ftprequest.GetResponse() $ftpresponse }
PowerShellCorpus/PoshCode/Add-TnsAdminEntry.ps1
Add-TnsAdminEntry.ps1
param ( [string] $Name = $(Read-Host "Provide a value for parameter 'Name'"), [string] $Protocol = 'TCP', [string] $Hostname = $(Read-Host "Provide a value for parameter 'Hostname'"), [string] $Port = '1521', [string] $Sid = $(Read-Host "Provide a value for parameter 'Sid'"), [System.IO.FileInfo] $File = $(Read-Host "Provide the tnsnames.ora file path") ) function Get-OracleDataSources { [System.reflection.assembly]::LoadWithPartialName("System.Data") $f = [System.Data.Common.DbProviderFactories]::GetFactory("Oracle.DataAccess.Client") if ($f.CanCreateDataSourceEnumerator) { $e = $f.CreateDataSourceEnumerator() $e.GetDataSources() } } function Out-TnsAdminFile { param ( [System.Object[]] $Entries, [System.IO.FileInfo] $File = $(throw "Parameter -File <System.IO.FileInfo> is required.") ) begin { if ($File.Exists) { $originalEntries = @(Get-TnsAdminEntries $File.FullName) } } process { if ($_) { $Entries = @($_) } $Entries | % { $entry = $_ $existingEntry = $originalEntries | ? {$_.Name -eq $entry.Name} if ($existingEntry) { $existingEntry.Name = $entry.Name $existingEntry.Protocol = $entry.Protocol $existingEntry.Host = $entry.Host $existingEntry.Port = $entry.Port $existingEntry.Service = $entry.Service } else { $originalEntries += $entry } } $originalEntries | % { $entry = $_ $Name = $entry.Name $Protocol = $entry.Protocol $Hostname = $entry.Host $Port = $entry.Port $Service = $entry.Service [string] $text += @" $Name = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = $Protocol)(HOST = $Hostname)(PORT = $Port)) ) (CONNECT_DATA = (SERVICE_NAME = $Service) ) ) "@ } $text | Out-File $File.FullName -Encoding ASCII Remove-Variable text } end {} } function Get-TnsAdminEntries { param ( [System.IO.FileInfo] $File ) begin {} process { if ($_) { $File = [System.IO.FileInfo] $_ } if (!$File) { Write-Error "Parameter -File <System.IO.FileInfo> is required." break } if (!$File.Exists) { Write-Error "'$File.FullName' does not exist." break } [string] $data = gc $File.FullName | ? {!$_.StartsWith('#')} $pattern = '(?<name>^(\\w)+[\\s]*?)|\\)\\)(?<name>\\w+)|HOST=(?<host>\\w+)|PORT=(?<port>\\d+)|PROTOCOL=(?<protocol>\\w+)|SERVICE_NAME=(?<service>\\w+)' $patternMatches = [regex]::Matches($data.Replace(" ", ""), $pattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) $tnsEntries = @() for ($i = 0; $i -lt $patternMatches.Count; $i++) { if ($i -eq 0 -or $i % 5 -eq 0) { $tnsEntry = New-Object System.Object $tnsEntry | Add-Member -type NoteProperty -name Name -value $patternMatches[$i + 0].Groups["name"].value $tnsEntry | Add-Member -type NoteProperty -name Protocol -value $patternMatches[$i + 1].Groups["protocol"].value $tnsEntry | Add-Member -type NoteProperty -name Host -value $patternMatches[$i + 2].Groups["host"].value $tnsEntry | Add-Member -type NoteProperty -name Port -value $patternMatches[$i + 3].Groups["port"].value $tnsEntry | Add-Member -type NoteProperty -name Service -value $patternMatches[$i + 4].Groups["service"].value $tnsEntries += $tnsEntry } } $tnsEntries } end {} } $tnsEntry = New-Object System.Object $tnsEntry | Add-Member -type NoteProperty -name Name -value $Name $tnsEntry | Add-Member -type NoteProperty -name Protocol -value $Protocol $tnsEntry | Add-Member -type NoteProperty -name Host -value $Hostname $tnsEntry | Add-Member -type NoteProperty -name Port -value $Port $tnsEntry | Add-Member -type NoteProperty -name Service -value $Sid $tnsEntry | Out-TnsAdminFile -File $File
PowerShellCorpus/PoshCode/Get-Entropy_2.ps1
Get-Entropy_2.ps1
function Get-Entropy { <# .SYNOPSIS Calculate the entropy of a byte array. Author: Matthew Graeber (@mattifestation) .PARAMETER ByteArray Specifies the byte array containing the data from which entropy will be calculated. .EXAMPLE C:\\PS> $RandArray = New-Object Byte[](10000) C:\\PS> foreach ($Offset in 0..9999) { $RandArray[$Offset] = [Byte] (Get-Random -Min 0 -Max 256) } C:\\PS> $RandArray | Get-Entropy Description ----------- Calculates the entropy of a large array containing random bytes. .EXAMPLE C:\\PS> 0..255 | Get-Entropy Description ----------- Calculates the entropy of 0-255. This should equal exactly 8. .INPUTS System.Byte[] Get-Entropy accepts a byte array from the pipeline .OUTPUTS System.Double Get-Entropy outputs a double representing the entropy of the byte array. .LINK http://www.exploit-monday.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)] [Byte[]] $ByteArray ) BEGIN { $FrequencyTable = @{} $ByteArrayLength = 0 } PROCESS { foreach ($Byte in $ByteArray) { $FrequencyTable[$Byte]++ $ByteArrayLength++ } } END { $Entropy = 0.0 foreach ($Byte in 0..255) { $ByteProbability = ([Double] $FrequencyTable[[Byte]$Byte]) / $ByteArrayLength if ($ByteProbability -gt 0) { $Entropy += -$ByteProbability * [Math]::Log($ByteProbability, 2) } } Write-Output $Entropy } }
PowerShellCorpus/PoshCode/New-Zip.ps1
New-Zip.ps1
Function New-Zip { <# .SYNOPSIS Create a Zip File from any files piped in. .DESCRIPTION Requires that you have the SharpZipLib installed, which is available from http://www.icsharpcode.net/OpenSource/SharpZipLib/ .NOTES File Name : PowerZip.psm1 Author : Christophe CREMON (uxone) - http://powershell.codeplex.com Requires : PowerShell V2 .PARAMETER Source Set the name of the source to zip (file or directory) .PARAMETER ZipFile Set the name of the zip file to create .PARAMETER Recurse Browse the source recursively .PARAMETER Include Include only items you specify .PARAMETER Exclude Exclude items you specify .PARAMETER AbsolutePaths Preserve the absolute path name of each item in the zip container .PARAMETER DeleteAfterZip Delete source items after successful zip .EXAMPLE New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP #> param ( [ValidateNotNullOrEmpty()] [Parameter( Mandatory = $true) ] [string] $Source, [Parameter( Mandatory = $true) ] [string] $ZipFile, [switch] $Recurse, [array] $Include, [array] $Exclude, [switch] $AbsolutePaths, [switch] $DeleteAfterZip ) [int] $ExitCode = 1 $LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib") if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" } if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" } if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" } if ( $AbsolutePaths -eq $true ) { $AbsolutePathsArgument = "-AbsolutePaths" } if ( $DeleteAfterZip -eq $true ) { $DeleteAfterZipArgument = "-DeleteAfterZip" } if ( $Include ) { $Include = $Include -join "," $IncludeArgument = "-Include $Include" } if ( $Exclude ) { $Exclude = $Exclude -join "," $ExcludeArgument = "-Exclude $Exclude" } $RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path if ( -not $RootPath ) { throw "! Source not found {$Source}" } if ( $Include ) { $GetCommand = "Get-ChildItem -Path $Source\\* $RecurseArgument $IncludeArgument $ExcludeArgument -Force -ErrorAction SilentlyContinue" } else { $GetCommand = "Get-ChildItem -Path $Source $RecurseArgument $IncludeArgument $ExcludeArgument -Force -ErrorAction SilentlyContinue" } $ItemsToZip = Invoke-Expression -Command $GetCommand -ErrorAction SilentlyContinue $SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum $SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } if ( -not $SizeBeforeZip ) { Write-Output "NOTHING TO ZIP" break } $StartTime = Get-Date Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n" Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n" Write-Output "Initializing ZIP File {$ZipFile} ...`n" $CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue if ( -not $CreateZIPContainer ) { throw "! Unable to create ZIP container {$ZipFile}" } $oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile)) [byte[]] $Buffer = New-Object Byte[] 4096 foreach ( $Item in $ItemsToZip ) { if ( $Item.FullName -ne $ZipFile ) { if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue ) { $ZipEntry = $Item.FullName if ( -not $AbsolutePaths ) { $ReplacePath = [Regex]::Escape( $RootPath+"\\" ) $ZipEntry = $Item.FullName -replace $ReplacePath,"" } if ( $Item.psIsContainer -eq $true ) { if ( $Recurse -eq $true ) { Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..." $OldErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/") $oZipOutputStream.PutNextEntry($oZipEntry) if ( $? -ne $true ) { $ItemsNotZipped += @($Item.FullName) $ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}") } $ErrorActionPreference = $OldErrorActionPreference } } else { Write-Output "Processing ZIP of File {$($Item.FullName)} ..." $OldErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $FileStream = [IO.File]::OpenRead($Item.FullName) $oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry") $oZipOutputStream.PutNextEntry($oZipEntry) [ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer) if ( $? -ne $true ) { $ItemsNotZipped += @($Item.FullName) $ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}") } $FileStream.Close() } } } } $oZipOutputStream.Finish() $oZipOutputStream.Close() if ( $? -eq $true ) { $ErrorActionPreference = $OldErrorActionPreference if ( $DeleteAfterZip ) { $ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object { if ( $_.psIsContainer -ne $true ) { if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue ) { Write-Output "Processing Delete of File {$($_.FullName)} ..." $RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue if ( $? -ne $true ) { $ErrorsArray += @("! Unable to Delete File {$($_.FullName)}") } } } } if ( $Recurse ) { $ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object { if ( $_.psIsContainer -eq $true ) { if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue ) { Write-Output "Processing Delete of Directory {$($_.FullName)} ..." $RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue if ( $? -ne $true ) { $ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}") } } } } } } Write-Output "`nZIP File Created {$ZipFile} ...`n" $ExitCode = 0 } else { $ErrorActionPreference = $OldErrorActionPreference $ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n") } if ( $ErrorsArray ) { Write-Output "`n[ ERRORS OCCURED ]" $ErrorsArray $ExitCode = 1 } else { $SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum $SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n" $Gain = ( $SizeBeforeZip - $SizeAfterZip ) $GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } if ( $Gain -gt 0 ) { $GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ } Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n" } } $EndTime = Get-Date $ExecutionTime = ($EndTime-$StartTime) Write-Output "`nExecution Time : $ExecutionTime`n" Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n" exit $ExitCode } Export-ModuleMember -Function New-Zip
PowerShellCorpus/PoshCode/rss2email.ps1
rss2email.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Checks an RSS feed and sends the feed information through email if it hasn't ### been seen before. ### </Description> ### <Usage> ### ./rss2email.ps1 'mailrelay.acme.com' "$ProfileDir\\guidcache.txt" "myemail@acme.com" "http://rss.cnn.com/rss/cnn_topstories.rss/ ### </Usage> ### </Script> # --------------------------------------------------------------------------- param ($smtpServer, $rssCacheFile, $recipients, $rssUrl) ####################### function Get-MD5 { param ($str) $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider] $hashAlgorithm = new-object $cryptoServiceProvider $byteArray = [Text.Encoding]::UTF8.GetBytes($str) $hashByteArray = $hashAlgorithm.ComputeHash($byteArray) $hex = $null $hashByteArray | foreach {$hex += $_.ToString("X2")} $hex } #Get-MD5 ####################### function Get-Rss { $feed = [xml](new-object System.Net.WebClient).DownloadString($rssUrl) #Set the description to the empty string, since it contains html markup $feed.rss.channel.Item | foreach {$_.description = ""} #Convert the rss.channel item to a string $results = $feed.rss.channel.Item | Out-String $title = $feed.rss.channel.title #if guid available we could do something like $feed.rss.GetElementsByTagName("guid") | % {$_.get_InnerXml()} #however some rss feeds don't have guids so we'll generate hex hash to uniquely identify the rss feed #return a hash table with array @{$(Get-MD5 $results) = @($title,$results)} } #Get-Rss ####################### function Send-RssEmail { param ($recipients,$subject,$message) $smtpmail = [System.Net.Mail.SMTPClient]("$smtpServer") $smtpmail.Send($recipients, $recipients, $subject, $message) } #Send-RssEmail ####################### function Get-RssCache { if (test-path $rssCacheFile) { $guidcache = Get-Content $rssCacheFile } else { $guidcache = @() } return $guidcache } #Get-RssCache ####################### $rss = $(Get-Rss $rssUrl) $guidcache = $(Get-RssCache) #If we haven't read seen this rss feed, send an email then add the feed MD5 hash to our cache file so we won't send it again if (!($guidcache -contains $rss.keys)) { Send-RssEmail $recipients $($rss.values)[0] $($rss.values)[1] $rss.keys >> $rssCacheFile }
PowerShellCorpus/PoshCode/New-Task.ps1
New-Task.ps1
<# .SYNOPSIS Creates a task in Outlook .DESCRIPTION Allows for the creation of tasks in Microsoft Outlook from Windows PowerShell. The majority of task options available can be configured with the function. .LINK http://www.leeholmes.com/blog/GettingThingsDoneOutlookTaskAutomationWithPowerShell.aspx .EXAMPLE C:\\PS>New-Task -Subject "Create PowerShell script to create Outlook tasks" Description ----------- This example just a simple Outlook Task with the specified subject. .EXAMPLE C:\\PS>New-Task -Subject "Create powershell script to create outlook calendar entries" -Categories "%PowerShell" -DueDate "2/01/2009" -Status "InProgress" -Display Description ----------- This example demonstrates the creation of task using additional options. The '-display' parameter brings up the Outlook task form at the end to allow you make additional changes in the UI. .INPUTTYPE .RETURNVALUE .COMPONENT .ROLE .FUNCTIONALITY .PARAMETER Subject Sets the subject of the task. .PARAMETER Body Sets the body of the task. .PARAMETER Categories Sets the categories for the task. Comma seperate the values for multiple categories. .PARAMETER StartDate Sets the start date of the task. Must be in a format that can be converted to [datetime] object. .PARAMETER DueDate Sets the due date of the task. Must be in a format that can be converted to [datetime] object. .PARAMETER PercentComplete Sets the percent complete for the new task. Value must be an int from 0 to 100. .PARAMETER ReminderTime Sets the reminder time of the task. Must be in a format that can be converted to [datetime] object. .PARAMETER Status Sets the the status of the new task. Valid values are "Completed", "Deferred", "InProgress","Waiting" .PARAMETER Priority Sets the priority value of the new task. Valid values are "Low", "Medium", "High" .PARAMETER Display Displays the Outlook task form after saving. .NOTES Name: New-Task Author: Mark E. Schill Date Created: 01/24/2009 Date Revised: 01/24/2009 Version: 1.0 History: 1.0 01/24/2009 - Initial Revision #> [CmdletBinding()] # TODO: Handle the status and priority param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [string] $Subject , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [string] $Body , # TODO: Be able to specify "today, tomorrow, next week, etc" and convert that to appropriate date. # http://refactormycode.com/codes/488-parse-relative-date [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [DateTime] $StartDate , # TODO: Be able to specify "today, tomorrow, next week, etc" and convert that to appropriate date. [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [DateTime] $DueDate , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [string] $Status , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [string] $Priority , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [int] $PercentComplete = 0 , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [DateTime] $ReminderTime , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [string] $Categories , [Parameter(Mandatory=$false, ValueFromPipeline=$false)] [switch] $Display ) Begin { $olTaskItem = "olTaskItem" <# 3 #> $olFolderTasks = "olFolderTasks" <# 13 #> $Outlook = New-Object -ComObject Outlook.Application } Process { $Task = $Outlook.Application.CreateItem($olTaskItem) $ContainsError = $false $Task.Subject = $Subject $Task.PercentComplete = $PercentComplete $Task.Body = $Body if ( $Categories ) { $Task.Categories = $Categories } if ( $StartDate ) { $Task.StartDate = $StartDate } if ( $DueDate ) { $Task.DueDate = $DueDate } switch ( $Status ) { "Completed" { $Task.Status = [Microsoft.Office.Interop.Outlook.OlTaskStatus]::olTaskComplete $Task.PercentComplete = 100 # Overrides PercentComplete if specified } "Deferred" { $Task.Status = [Microsoft.Office.Interop.Outlook.OlTaskStatus]::olTaskDeferred } "InProgress" { $Task.Status = [Microsoft.Office.Interop.Outlook.OlTaskStatus]::olTaskInProgress } "Waiting" { $Task.Status = [Microsoft.Office.Interop.Outlook.OlTaskStatus]::olTaskWaiting } default { $Task.Status = [Microsoft.Office.Interop.Outlook.OlTaskStatus]::TaskNotStarted } } switch ($Priority ) { "Low" { $Task.Importance = [Microsoft.Office.Interop.Outlook.OlImportance]::olImportanceLow } "High" { $Task.Importance = [Microsoft.Office.Interop.Outlook.OlImportance]::olImportanceHigh } default { $Task.Importance = [Microsoft.Office.Interop.Outlook.OlImportance]::olImportanceNormal } } if ( $ReminderTime ) { $Task.ReminderTime = $ReminderTime $Task.ReminderSet = $True } if ( -not $ContainsError) { $Task.Save() if ($Display ) { $Task.Display() } } } End { $Outlook = $Null }
PowerShellCorpus/PoshCode/sudo for Powershell.ps1
sudo for Powershell.ps1
# sudo.ps1 # # Authors: Brian Marsh, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell # # Sources: # http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell # http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta # # Version: # 1.0 Initial version # 1.1 added -ps flag, cleaned up passed $file/$script full path # 1.2 Comments # 1.3 Fixed passing working directory to powershell/auto closing param( [switch]$ps, # Switch for running args as powershell script [string]$file, # Script/Program to run [string]$arguments = $args # Arguments to program/script ) # Find our powershell full path $powershell = (get-command powershell).definition # Get current directory $dir = get-location #If we're running this as a elevated powershell script if ($ps){ # Script verification if([System.IO.File]::Exists("$(get-location)\\$file")) { # Set the $script to full path of the ps script $script = (get-childitem $file).fullname } # Create a powershell process $psi = new-object System.Diagnostics.ProcessStartInfo $powershell $psi.WorkingDirectory = Get-Location # Combine the script and its arguments $sArgs = $script + " " + $arguments # Set the arguments to be the ps script and it's arguments $psi.Arguments = "-noexit -command set-location $dir; $sArgs" # Magic to run as elevated $psi.Verb = "runas"; } # We're running something other than a powershells script else { # File verification if([System.IO.File]::Exists("$(get-location)\\$file")) { # Get full path $file = (get-childitem $file).fullname } # Same as above, create proccess/working directory/arguments/runas $psi = new-object System.Diagnostics.ProcessStartInfo $file $psi.Arguments = $arguments $psi.Verb = "runas" } # Start the process [System.Diagnostics.Process]::Start($psi)
PowerShellCorpus/PoshCode/Get-FirewallStatus.ps1
Get-FirewallStatus.ps1
# returns true if windows firewall is enabled, false if it is disabled filter global:get-firewallstatus ([string]$computer = $env:computername) { if ($_) { $computer = $_ } $HKLM = 2147483650 $reg = get-wmiobject -list -namespace root\\default -computer $computer | where-object { $_.name -eq "StdRegProv" } $firewallEnabled = $reg.GetDwordValue($HKLM, "System\\ControlSet001\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile","EnableFirewall") [bool]($firewallEnabled.uValue) }
PowerShellCorpus/PoshCode/Import-CmdEnvironment.ps1
Import-CmdEnvironment.ps1
# .SYNOPSIS # Import environment variables from cmd to PowerShell # .DESCRIPTION # Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell # .EXAMPLE # Import-CmdEnvironment "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat" x86 # # Imports the x86 Visual Studio 2010 Command Tools environment # .EXAMPLE # Import-CmdEnvironment "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat" x86_amd64 # # Imports the x64 Cross Tools Visual Studio 2010 Command environment #function Import-CmdEnvironment { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [string]$Command = "echo" , [Parameter(Position=0,Mandatory=$False,ValueFromRemainingArguments=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Parameters ) ## If it's an actual file, then we should quote it: if(Test-Path $Command) { $Command = "`"$(Resolve-Path $Command)`"" } $setRE = new-Object System.Text.RegularExpressions.Regex '^(?<var>.*?)=(?<val>.*)$', "Compiled,ExplicitCapture,MultiLine" $OFS = " " [string]$Parameters = $Parameters $OFS = "`n" ## Execute the command, with parameters. Write-Verbose "EXECUTING: cmd.exe /c `"$Command $Parameters > nul && set`"" ## For each line of output that matches, set the local environment variable foreach($match in $setRE.Matches((cmd.exe /c "$Command $Parameters > nul && set")) | Select Groups) { Set-Content Env:\\$($match.Groups["var"]) $match.Groups["val"] -Verbose } #}
PowerShellCorpus/PoshCode/ConvertTo-Hex_3.ps1
ConvertTo-Hex_3.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/Install-Bginfo.ps1
Install-Bginfo.ps1
#Install and run BGInfo at startup using registry method as described here: #http://forum.sysinternals.com/bginfo-at-startup_topic2081.html #Setup #1. Download BgInfo http://technet.microsoft.com/en-us/sysinternals/bb897557 #2. Create a bginfo folder and copy bginfo.exe #3. Create a bginfo.bgi file by running bginfo.exe and saving a bginfo.bgi file and placing in same directory as bginfo if (Test-Path "C:\\WINDOWS\\system32\\bginfo") { remove-item -path "C:\\WINDOWS\\system32\\bginfo" -Recurse } #Change \\\\Z001\\d$\\sw\\bginfo to your SW distrib share copy-item \\\\Z001\\d$\\sw\\bginfo -Destination C:\\Windows\\system32 -Recurse Set-ItemProperty -path "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" -name "BgInfo" -value "C:\\WINDOWS\\system32\\bginfo\\Bginfo.exe C:\\WINDOWS\\system32\\bginfo\\bginfo.bgi /TIMER:0 /NOLICPROMPT"
PowerShellCorpus/PoshCode/New-Script.ps1
New-Script.ps1
## New-Script function ## Creates a new script from the most recent commands in history ################################################################################################## ## Example Usage: ## New-Script ScriptName 4 ## creates a script from the most recent four commands ## New-Script ScriptName -id 10,11,12,14 ## creates a script from the specified commands in history ## New-Script Clipboard 2 ## sends the most recent two commands to the clipboard ################################################################################################## ## As a tip, I use a prompt function something like this to get the ID into the prompt: ## ## function prompt { ## return "`[{0}]: " -f ((get-history -count 1).Id + 1) ## } ################################################################################################## #function New-Script { param( [string]$script=(Read-Host "A name for your script"), [int]$count=1, [int]$id=((Get-History -count 1| Select Id).Id) ) if($script -eq "clipboard") { if( @(Get-PSSnapin -Name "pscx").Count ) { Get-History -count $count -id $id | &{process{ $_.CommandLine }} | out-clipboard }elseif(@(gcm clip.exe).Count) { Get-History -count $count -id $id | &{process{ $_.CommandLine }} | clip } } else { # default to putting it in my "Windows PowerShell\\scripts" folder which I have in my path... $folder = Split-Path $script if(!$folder) { $folder = Join-Path (Split-Path $Profile) "Scripts" } if(!(Test-Path $folder)) { Throw (new-object System.IO.DirectoryNotFoundException "Cannot find path '$folder' because it does not exist.") } # add the ps1 extension if it's not already there ... $file = Join-Path $folder (Split-Path $script -leaf) if(!(([IO.FileInfo]$file).Extension)) { $file = "$file.ps1" } Get-History -count $count -id $id | &{process{ $_.CommandLine }} | set-content $file } #}
PowerShellCorpus/PoshCode/FixInvalidVMs.ps1
FixInvalidVMs.ps1
#====================================================================================== # File Name : FixInvalidVMs.ps1 # Original Author : Kenneth C. Mazie # Description : Resets all "invald" or "inaccessible" virtual machines # : # Notes : Will cycle through an entire Virtual Center instance and # : identify any virtual machines that are "invald" or # : "inaccessible" as a result of a host crash where running # : VMs were left with lock files in place. The script must # : have PUTTY installed and configured. A local status echo # : as well as a date and time stamped log file is written # : in the folder that this script is executed from if the # : options are set below. # Process : VMs that are processed are removed from inventory, then # : the ESX host is connected to and the associated lock files # : are deleted. ONLY files named ".lckxxxxxxx" are deleted, and # : ONLY in the specific folder and datastore that the target # : VM resides in. The VM is then re-registered in Virtual # : Center and moved back into the original folder it came # : from. # : # Testing : The only way I found to simulate invalid VMs is to rename # : the VM folder on the datastore and then restart the ESX host. # : # Warnings : The script connects to an ESX host and performs delete # : operations on hidden lock files. You were warned. # : NOTE: all harmfull operations are commented out by default # : via the "LIVEOPS" variable. This script was written for # : and tested in my environment, yours may require significant # : changes to the script to function properly. # : $LiveOps = $False #--[ Change to $True to enable all destructive operations ]-- # : # Legal : Script provided "AS IS" without warranties or guarantees of any # : kind. USE AT YOUR OWN RISK. Public domain, no rights reserved. # : Please keep this header in tact if at all possible. # : # Credits : Code snippets and/or ideas came from many sources including but # : not limited to the following: # : Kevin Markwardt: http://www.kevinmarkwardt.com/script.php?id=15 # : LucD: http://communities.vmware.com/thread/213290 # : Anders Mikkelsen: http://www.amikkelsen.com/?p=357 # : # Legal : Script provided "AS IS" without warranties or guarantees of any # : kind. USE AT YOUR OWN RISK. Public domain, no rights reserved. # : # Last Update by : Kenneth C. Mazie # Version History : v1.0 - 03-04-11 - Original # Change History : v1.1 - 00-00-00 - # : #======================================================================================= #--[ Clear the screen, disable error notification ]-- Clear-Host $ErrorActionPreference = "SilentlyContinue" #--[ Load the VMWare snapin if not already ]-- $out = Get-PSSnapin | Where-Object {$_.Name -like "vmware.vimautomation.core"} if ($out -eq $null){Add-PSSnapin vmware.vimautomation.core} #--[ Connect to the Virtual Center server ]-- Connect-VIServer -Server <YOUR-VC-SERVER> -User <VC-USER> -Password <PASSWORD> | out-null #--[ Get Current Script Path ]-- $ScriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition #--[ Set status / logging options ]-- $StatEcho = $True #--[ True to echo to screen ]-- $StatLog = $True #--[ True to write a log file ]-- #--[ Get VM Folder Function ]-- filter Get-FolderPath { $_ | Get-View | % { $row = "" | select Name, Path $row.Name = $_.Name $current = Get-View $_.Parent #$path = $_.Name # Uncomment out this line if you do want the VM Name to appear at the end of the path $path = "" do { $parent = $current if($parent.Name -ne "vm"){$path = $parent.Name + "\\" + $path} $current = Get-View $current.Parent } while ($current.Parent -ne $null) $row.Path = $path $row } } function BldPuttyCmd ($x) { #--[ The linked commands that PUTTY executes ]-- #--[ This is called from 2 places. Alter the commands to change what is done by PUTTY ]-- #--[ As written it runs 2 chained Linux commends that will CD into the target VM folder ]-- #--[ and delete higgen lock files. ]-- return "`"cd $x && rm –rf .lck*`"" } #--[ Initialize Variables ]-- $Target = "" $Plink = "`"C:\\Program Files (x86)\\PuTTY\\plink.exe`"" #--[ Complete path to PUTTY ]-- $PuttyUsername = "root" #--[ Set to your ESX host username ]-- $PuttyHostname = "192.168.1.1" #--[ Set to the hostname/Ip of an appropriate ESX host ]-- $PuttyPassword = "PASSWORD" #--[ Set to your ESX host user password ]-- $PuttyLogon = $PuttyUsername +"@"+ $PuttyHostname $PuttyCommand = BldPuttyCmd "<FullPathToVMX>" #--[ Inserts temporary text into the PUTTY command string ]-- #--[ Initailize Status Log ]-- If ($StatEcho -eq $True){ Write-Host "Starting run..." Write-Host "============================================" Write-Host "ESX Logon = $PuttyUsername" Write-Host "ESX Host = $PuttyHostname" Write-Host "Putty executable path = $Plink" Write-Host "Putty command = $PuttyCommand" Write-Host "Script executed from: `"$ScriptPath`"" Write-Host "============================================"} If ($StatLog -eq $True){ $LogFile = $ScriptPath+"\\LogFile-{0:dd-MM-yyyy_HHmm}.log" -f (Get-Date) add-content $LogFile "Starting run..." add-content $LogFile "============================================" add-content $LogFile "ESX Logon = $PuttyUsername" add-content $LogFile "ESX Host = $PuttyHostname" add-content $LogFile "Putty executable path = $Plink" add-content $LogFile "Putty command = $PuttyCommand" Add-Content $LogFile "Script executed from: `"$ScriptPath`"" add-content $LogFile "============================================"} #--[ Do It ]-- $Invalid = Get-View -ViewType VirtualMachine | Where {-not $_.Config.Template} | Where{$_.Runtime.ConnectionState -eq “invalid” -or $_.Runtime.ConnectionState -eq “inaccessible”} | sort Name foreach ($vm in $Invalid){ If ($StatLog -eq $True){add-content $LogFile "--------------------------------------------"} If ($StatEcho -eq $True){Write-Host "--------------------------------------------"} #--[ Gather Target Info ]-- $Target = get-vm $vm.name $TargetDataCenter = Get-Datacenter -VM $Target $TargetView = $Target | Get-View $TargetESXHost = $Target.host.name $TargetCluster = Get-Cluster -VM $Target $Datastores = Get-Datastore | select Name, Id $TargetDatastore = ($Datastores | where {$_.ID -match (($TargetView.Datastore | Select -First 1) | Select Value).Value} | Select Name).Name $TargetVCFolder = ($Target | Get-Folderpath).Path.Split("\\") $VmxFullPath = "/vmfs/volumes/"+$TargetDatastore+"/"+$vm.name+"/" $TargetESX = Get-VMHost $TargetESXhost | Get-View $TargetResourcePool = Get-VMHost $TargetESXHost | Get-ResourcePool | Get-View $TargetFolder = Get-View (Get-Datacenter -Name $TargetDatacenter | Get-Folder -Name "vm").id $vmx = "[$TargetDatastore] "+$Target+"/"+$Target+".vmx" If ($StatEcho -eq $True){ Write-Host "Identified $Target as INVALID or INACCESSIBLE" Write-Host "ESX Host = " $TargetESXhost Write-Host "DataCenter = $TargetDataCenter" Write-Host "Cluster = " $TargetCluster Write-Host "vCenter Folder = " $TargetVCFolder[1] Write-Host "Datastore = "$TargetDatastore Write-Host Full path to virtual disk = $VmxFullPath} If ($StatLog -eq $True){ add-content $LogFile "Identified $Target as INVALID or INACCESSIBLE" add-content $LogFile "ESX Host = $TargetESXhost" add-content $LogFile "DataCenter = $TargetDataCenter" add-content $LogFile "Cluster = $TargetCluster" add-content $LogFile "vCenter Folder = $TargetVCFolder[1]" add-content $LogFile "Datastore = [$TargetDatastore]" Add-Content $LogFile "Full path to virtual disk = $VmxFullPath"} #--[ Remove the VM from inventory ]-- If ($LiveOps -eq $True){ If ($StatEcho -eq $True){write-host "Removing $Target from vCenter inventory..."} If ($StatLog -eq $True){add-content $LogFile "Removing $Target from vCenter inventory..."} Get-vm -Name $Target | remove-vm -Confirm:$false }else{ If ($StatEcho -eq $True){write-host `t"LiveOps disabled: Simulating Removing $Target from vCenter inventory..."} If ($StatLog -eq $True){add-content $LogFile `t"LiveOps disabled: Simulating Removing $Target from vCenter inventory..."} Get-vm -Name $Target | remove-vm -Confirm:$false -WhatIf } #--[ Delete lock files ]-- $PuttyCommand = BldPuttyCmd $VmxFullPath #--[ Regenerate the PUTTY comand line ]-- If ($LiveOps -eq $True){ If ($StatEcho -eq $True){write-host "Invoking PUTTY, Deleting all `".lck`" files in folder..."} If ($StatLog -eq $True){add-content $LogFile "Invoking PUTTY, Deleting all `".lck`" files in folder..."} Start-Process $plink -ArgumentList "$PuttyLogon","-pw $PuttyPassword","$PuttyCommand" | Out-Null }else{ If ($StatEcho -eq $True){write-host `t"LiveOps disabled: " $plink -ArgumentList "$PuttyLogon","-pw $PuttyPassword","$PuttyCommand"} If ($StatLog -eq $True){add-content $LogFile `t"LiveOps disabled: " $plink -ArgumentList "$PuttyLogon","-pw $PuttyPassword","$PuttyCommand"} } #--[ Re-register the target VM ]-- If ($LiveOps -eq $True){ if((Get-VM $Target -ea SilentlyContinue) -eq $null){ #--[ Check if VM is already registered ]-- If ($StatEcho -eq $True){Write-Host "Registering $Target into Virtual Center..."} If ($StatLog -eq $True){add-content $LogFile "Registering $Target into Virtual Center..."} $Task1 = $TargetFolder.RegisterVM_Task($vmx,$Target,$FALSE,$TargetResourcePool.MoRef,$TargetESX.MoRef) #--[ Wait untill VM is registered ]-- $Task2 = Get-View $Task1 while($Task1.info.state -eq "running" -or $Task1.info.state -eq "queued"){ $Task2 = Get-View $Task1 } #--[ Test the return code of the RegisterVM_Task for error state ]-- if($Task1.info.error -eq $null){ #--[ No error ]-- }else{ #--[ error ]-- If ($StatEcho -eq $True){Write-Host "Registration of $Target errored out!!! Something went wrong!!!"} If ($StatLog -eq $True){add-content $LogFile "Registration of $Target errored out!!! Something went wrong!!!"} # break #--[ Optional break ]-- } }else{ If ($StatEcho -eq $True){Write-Host "$Target VM Already Registered!!! Something went wrong!!!"} If ($StatLog -eq $True){add-content $LogFile "$Target VM Already Registered!!! Something went wrong!!!"} # break #--[ Optional break ]-- } }else{ If ($StatEcho -eq $True){ write-host `t"LiveOps disabled: Registration bypassed"} write-host `t"Command line would have been: `"TargetFolder.RegisterVM_Task `" $vmx,$Target,FALSE,$TargetResourcePool.name ,$TargetESX.name" If ($StatLog -eq $True){add-content $LogFile `t"LiveOps disabled: Registration bypassed"} } #--[ Move the VM to the proper folder ]-- If ($LiveOps -eq $True){ If ($StatEcho -eq $True){write-host "Moving $Target back into proper folder..."} If ($StatLog -eq $True){add-content $LogFile "Moving $Target back into proper folder..." } move-vm -VM $(get-vm $Target) -Destination $(Get-Folder -Name $TargetVCFolder[1] -Location $(Get-Datacenter $TargetDataCenter)) }else{ If ($StatEcho -eq $True){write-host "LiveOps disabled: Folder Move bypassed"} If ($StatLog -eq $True){add-content $LogFile "LiveOps disabled: Folder Move bypassed"} move-vm -VM $(get-vm $Target) -Destination $(Get-Folder -Name $TargetVCFolder[1] -Location $(Get-Datacenter $TargetDataCenter)) -WhatIf } #--[ Optional VM Power On ]-- if ((get-vm -name $Target).PowerState -eq "PoweredOff"){ If ($LiveOps -eq $True){ If ($StatEcho -eq $True){Write-Host "Powering on $Target..."} If ($StatLog -eq $True){add-content $LogFile "Powering on $Target..."} Start-VM -VM $Target -Confirm:$false -RunAsync }else{ If ($StatEcho -eq $True){write-host `t"LiveOps disabled: Power On bypassed"} If ($StatLog -eq $True){add-content $LogFile `t"LiveOps disabled: Power On bypassed"} Start-VM -VM $Target -whatif } } } If ($StatLog -eq $True){add-content $LogFile "============================================" add-content $LogFile "Completed..."} If ($StatEcho -eq $True){Write-Host "============================================" write-host "Completed..."} $fullpath = $null
PowerShellCorpus/PoshCode/Find Local Group Members_2.ps1
Find Local Group Members_2.ps1
# Author: Hal Rottenberg # Purpose: Find matching members in a local group # Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx # Change these two to suit your needs $ChildGroups = "Domain Admins", $LocalGroup = "Administrators" $error.clear() $MemberNames = @() # uncomment this line to grab list of computers from a file $Servers = Get-Content serverlist.txt # $Servers = $env:computername # for testing on local computer foreach ( $Server in $Servers ) { $MemberNames = @() $Group= [ADSI]"WinNT://$Server/$LocalGroup,group" $Members = @($Group.psbase.Invoke("Members")) $Members | ForEach-Object { $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } $errCount = $error.count $ChildGroups | ForEach-Object { $output = "" | Select-Object Server, Group, InLocalAdmin $output.Server = $Server $output.Group = $_ If ($errCount -gt 0){$output.InLocalAdmin = "Connection Error!"}ELSE{$output.InLocalAdmin = $MemberNames -contains $_} Write-Output $output } $error.clear() }
PowerShellCorpus/PoshCode/Get-CalendarWeek_1.ps1
Get-CalendarWeek_1.ps1
# Get-CalendarWeek by Holger Adam # Simple function to retrieve the calendar week to a given or the current date. function Get-CalendarWeek { param( $Date ) # check date input if ($Date -eq $null) { $Date = Get-Date } # get current culture object $Culture = [System.Globalization.CultureInfo]::CurrentCulture # retrieve calendar week $Culture.Calendar.GetWeekOfYear($Date, $Culture.DateTimeFormat.CalendarWeekRule, $Culture.DateTimeFormat.FirstDayOfWeek) }