full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/ciao.ps1
ciao.ps1
######################################################## # Created by Brian English # Brian.English@charlottefl.com # eddiephoenix@gmail.com # # for Charlotte County Government # No warranty suggested or implied ######################################################## # Purpose: Cycle through all VMs on a Virtualcenter Server # and update the VMTools after Virtualcenter update ######################################################## # Notes: VMware Tools must be installed prior to updating # it. After VMware Tools is updated, the virtual # machine is restarted if needed. See Vi Toolkit # CmdLets Reference: Update-Tools ######################################################## #connect to VirtualCenter server (i.e. virtual-center-1) if ($args[0] -eq $null) {$hostName = Read-Host "What host do you want to connect to?"} else {$hostName = $args[0]} #connect to selected Virtualcenter or host server Connect-VIServer $hostName ######################################################## #get all vms listed in virtualcenter $vms = get-vm ######################################################## #check power state on each vm #if 'On' update tools Foreach ($i in $vms) { #if virtualcenter is virtualized skip it # a system restart would stop this script if ((get-vm -name $i).Name -eq $hostname) {"Skipping " + $hostname} #if primary DC or DNS is virtualized skip it too #elseif ((get-vm -name $i).Name -eq "DNS/DC/DHCP") #{"Skipping DNS/DC/DHCP server name"} else { if ((get-vm -name $i).PowerState -eq "PoweredOn") { $i Get-Date -format "hh:mm:ss" update-tools -guest (get-vmguest -vm (get-vm -name $i)) Get-Date -format "hh:mm:ss" }#if #}#if }#foreach
PowerShellCorpus/PoshCode/Resolve-Aliases _2.7.ps1
Resolve-Aliases _2.7.ps1
#requires -version 2.0 ## ResolveAliases Module v 1.6 ######################################################################################################################## ## Sample Use: ## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1 ## ls *.ps1 | Resolve-Aliases -Inplace ######################################################################################################################## ## Version History ## 1.0 - First Version. "It worked on my sample script" ## 1.1 - Now it parses the $(...) blocks inside strings ## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts) ## 1.3 - I went back to processing the whole script at once (instead of a line at a time) ## Processing a line at a time makes it impossible to handle Here-Strings... ## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it ## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is ## 1.4 - Now resolves parameters too ## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem) ## - Refactored the Resolve-Line filter right out of existence ## - Created a test script for validation, and ## 1.6 - Added resolving parameter ALIASES instead of just short-forms ## 1.7 - Minor tweak to make it work in CTP3 ## ## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path ## * *TODO:* Add an option to put #requires statements at the top for each snapin used ######################################################################################################################## function which { PARAM( [string]$command ) # aliases, functions, cmdlets, scripts, executables, normal files $cmds = @(Get-Command $command -EA "SilentlyContinue") if($cmds.Count -gt 1) { $cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0] } else { $cmd = $cmds[0] } if(!$cmd) { $cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0] } if( $cmd.CommandType -eq "Alias" ) { $cmd = which $cmd.Definition } return $cmd } function Resolve-Aliases { [CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")] Param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")] [string]$Line , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")] [Alias("FullName","PSChildName","PSPath")] [IO.FileInfo]$File , [Parameter(Position=1, ParameterSetName="Files")] [Switch]$InPlace ) BEGIN { Write-Debug $PSCmdlet.ParameterSetName } PROCESS { if($PSCmdlet.ParameterSetName -eq "Files") { if($File -is [System.IO.FileInfo]){ $Line = ((Get-Content $File) -join "`n") } else { throw "We can't resolve a whole folder at once yet" } } $Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null) for($t = $Tokens.Count; $t -ge 0; $t--) { $token = $Tokens[$t] # DEBUG $token | fl * | out-host switch($token.Type) { "Command" { $cmd = which $token.Content Write-Debug "Command $($token.Content) => $($cmd.Name)" #if($cmd.CommandType -eq "Alias") { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name ) #} } "CommandParameter" { Write-Debug "Parameter $($token.Content)" for($c = $t; $c -ge 0; $c--) { if( $Tokens[$c].Type -eq "Command" ) { $cmd = which $Tokens[$c].Content # if($cmd.CommandType -eq "Alias") { # $cmd = @(which $cmd.Definition)[0] # } $short = $token.Content -replace "^-?","^" Write-Debug "Parameter $short" $parameters = $cmd.ParameterSets | Select -expand Parameters $param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique) if($param.Count -eq 1) { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" ) } break } } } } } switch($PSCmdlet.ParameterSetName) { "Text" { $Line } "Files" { switch($File.GetType()) { "System.IO.FileInfo" { if($InPlace) { $Line | Set-Content $File } else { $Line } } default { throw "We can't resolve a whole folder at once yet" } } } default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" } } } }
PowerShellCorpus/PoshCode/Decrypt Psi Password_1.ps1
Decrypt Psi Password_1.ps1
function decrypt-psi ($jid, $pw) { $OFS = ""; $u = 0; for($p=0;$p -lt $pw.Length;$p+=4) { [char]([int]"0x$($pw[$p..$($p+3)])" -bxor [int]$jid[$u++]) } } $accounts = ([xml](cat ~\\psidata\\profiles\\default\\accounts.xml))["accounts"]["accounts"] foreach($account in ($accounts | gm a[0-9]*)) { $a = $accounts.$($account.Name) "$($a.jid.'#text'):$( decrypt-psi $a.jid.'#text' $a.password.'#text' )" }
PowerShellCorpus/PoshCode/Remove Special Char.ps1
Remove Special Char.ps1
gci 'c:\\test\\' -Recurse | % { Rename-Item $_.FullName $($_.Name -replace '[^\\w\\.]','') }
PowerShellCorpus/PoshCode/Export-PSCredential_1.ps1
Export-PSCredential_1.ps1
# Author: Hal Rottenberg <hal@halr9000.com> # Url: http://halr9000.com/article/tag/lib-authentication.ps1 # Purpose: These functions allow one to easily save network credentials to disk in a relatively # secure manner. The resulting on-disk credential file can only [1] be decrypted # by the same user account which performed the encryption. For more details, see # the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as # MSDN pages about Windows Data Protection API. # [1]: So far as I know today. Next week I'm sure a script kiddie will break it. # # Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>] # # If Credential is not specififed, user is prompted by Get-Credential cmdlet. # If not specififed, Path is "./credentials.enc.xml". # Output: FileInfo object referring to saved credentials # # Import-PSCredential [-Path <file to import>] # # If not specififed, Path is "./credentials.enc.xml". # Output: PSCredential object function Export-PSCredential { param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" ) # Test for valid credential object if ( !$Credential -or ( $Credential -isnot [system.Management.Automation.PSCredential] ) ) { Throw "You must specify a credential object to export to disk." } # Create temporary object to be serialized to disk $export = "" | Select-Object Username, EncryptedPassword # Give object a type name which can be identified later $export.PSObject.TypeNames.Insert(0,’ExportedPSCredential’) $export.Username = $Credential.Username # Encrypt SecureString password using Data Protection API # Only the current user account can decrypt this cipher $export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString # Export using the Export-Clixml cmdlet $export | Export-Clixml $Path Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine # Return FileInfo object referring to saved credentials Get-Item $Path } function Import-PSCredential { param ( $Path = "credentials.enc.xml" ) # Import credential file $import = Import-Clixml $Path # Test for valid import if ( $import.PSObject.TypeNames -notcontains 'Deserialized.ExportedPSCredential' ) { Throw "Input is not a valid ExportedPSCredential object, exiting." } $Username = $import.Username # Decrypt the password and store as a SecureString object for safekeeping $SecurePass = $import.EncryptedPassword | ConvertTo-SecureString # Build the new credential object $Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass Write-Output $Credential }
PowerShellCorpus/PoshCode/Test-Prompt_1.ps1
Test-Prompt_1.ps1
$choices = [System.Management.Automation.Host.ChoiceDescription[]]( (New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Choose me!"), (New-Object System.Management.Automation.Host.ChoiceDescription "&No","Pick me!")) $Answer = $host.ui.PromptForChoice('Caption',"Message",$choices,(1)) Write-Output $Answer $fields = new-object "System.Collections.ObjectModel.Collection``1[[System.Management.Automation.Host.FieldDescription]]" $f = New-Object System.Management.Automation.Host.FieldDescription "String Field" $f.HelpMessage = "This is the help for the first field" $f.DefaultValue = "Field1" $f.Label = "&Any Text" $fields.Add($f) $f = New-Object System.Management.Automation.Host.FieldDescription "Secure String" $f.SetparameterType( [System.Security.SecureString] ) $f.HelpMessage = "You will get a password input with **** instead of characters" $f.DefaultValue = "Password" $f.Label = "&Password" $fields.Add($f) $f = New-Object System.Management.Automation.Host.FieldDescription "Numeric Value" $f.SetparameterType( [int] ) $f.DefaultValue = "42" $f.HelpMessage = "You need to type a number, or it will re-prompt" $f.Label = "&Number" $fields.Add($f) $results = $Host.UI.Prompt( "Caption", "Message", $fields ) Write-Output $results
PowerShellCorpus/PoshCode/Pipeline and Parameter.ps1
Pipeline and Parameter.ps1
Function Test-Func { param( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] [string[]]$ComputerName ) Begin { Function Do-Process($p) { "Processing $($p)" } } Process { if($_) { Do-Process $_ } } End { if($ComputerName) { @($ComputerName) | % {Do-Process $_} } } } Test-Func a,b 'a','b' | Test-Func Test-Func x 'x' | Test-Func
PowerShellCorpus/PoshCode/set-FSRMQuotaBasedOnSQL.ps1
set-FSRMQuotaBasedOnSQL.ps1
#0# init $error.clear() cls $ErrorActionPreference= "Stop" # do zmiany na "SilentlyContinue" lub "Continue" po adaptacji #/0# #1# sql conn parameters $dataSource = "Serwer\\SQL01" $database = "nazwaBazyDanych" #$authentication = "Integrated Security=SSPI" # preferowana metoda, ale nie zawsze si&#281; tak da... $authentication = "User Id=sqlLogin;Password=P@sswd1;" $connectionString = "Provider=sqloledb; Data Source=$dataSource; Initial Catalog=$database; $authentication;" $connection = New-Object System.Data.OleDb.OleDbConnection $connectionString $connection.Open() #/1# #2# exec query $qry = "SELECT ItemName,ServerName,QuotaValue FROM Packages WHERE (SI.ItemTypeID = 2)" $commandPrev = New-Object System.Data.OleDb.OleDbCommand $qry,$connection $adapterPrev = New-Object System.Data.OleDb.OleDbDataAdapter $commandPrev $datasetPrev = New-Object System.Data.DataSet [void] $adapterPrev.Fill($dataSetPrev) $arr = $dataSetPrev.Tables[0].Rows foreach ($row in $arr) { $ItemName = $row.ItemName $ServerName = $row.ServerName $QuotaValue = $row.QuotaValue.ToString() $QuotaValueMB = $QuotaValue + "MB" # a tu cel ca&#322;ej operacji - ustawienie quoty na folder na podstawie bazy danych (na wielu serwerach) dirquota quota add /Path:$ItemName /Limit:$QuotaValueMB /Remote:$ServerName /Overwrite /Type:Soft dirquota quota list /Path:$ItemName /Remote:$ServerName } #/2# #3#close sql connection $connection.Close() #/3#
PowerShellCorpus/PoshCode/Invoke-ISPackage.ps1
Invoke-ISPackage.ps1
<# .SYNOPSIS Runs an SSIS package from an SQL package store. .DESCRIPTION Invoke-ISPackage.ps1 script is a wrapper around dtexec.exe to run an SSIS package. .EXAMPLE PowerShell.exe -File "C:\\Scripts\\Invoke-ISPackage.ps1" -PackagePath "SQLPSX\\sqlpsx1" -ServerInstance "Z001\\SQL1" This example connects to SSIS Server and runs the an SSIS package on Z001\\SQL1 .NOTES Version History v1.0 - Chad Miller - 6/14/2012 - Initial release #> param( [Parameter(Position=0, Mandatory=$true)] [string] $PackagePath, [Parameter(Position=1, Mandatory=$true)] [string] $ServerInstance, [Parameter(Position=2, Mandatory=$false)] [ValidateNotNullOrEmpty()] [ValidateScript({Test-Path "$_"})] [string] $CommandFile, [Parameter(Position=3, Mandatory=$false)] [ValidateNotNullOrEmpty()] [string] $Application="Invoke-ISPackage.ps1", [Parameter(Position=4, Mandatory=$false)] [switch] $Use32Bit ) #This must be run as administrator on Windows 2008 and higher! New-EventLog -LogName Application -Source $Application -EA SilentlyContinue $Error.Clear() $ErrorActionPreference = "Stop" $exitCode = @{ 0="The package executed successfully." 1="The package failed." 3="The package was canceled by the user." 4="The utility was unable to locate the requested package. The package could not be found." 5="The utility was unable to load the requested package. The package could not be loaded." 6="The utility encountered an internal error of syntactic or semantic errors in the command line."} $events = @{"ApplicationStartEvent" = "31101"; "ApplicationStopEvent" = "31104"; "DatabaseException" = "31725"; "ConfigurationException" = "31705";"BadDataException" = "31760"} $msg =$null $MaxErrorMsgLen = 3000 ####################### function Write-Message{ Param([string]$Severity,[string]$Category,[string]$Eventid,[string]$ShortMessage=$null,[string]$Context=$null) $msg = @" Severity: $Severity Category: $Category EventID: $Eventid Short Message: $ShortMessage Context: $Context "@ $msg = $msg -replace "'" Write-EventLog -LogName Application -Source $Application -EntryType $Severity -EventId $Eventid -Category $Category -Message $msg } #Write-Message ####################### # MAIN # ####################### $options = @" /Rep E /DTS "$PackagePath" /Conf "c:\\SSISconfig\\$ServerInstance\\SSISconnection.dtsConfig" "@ if ($CommandFile) { $options += " /Com `"$CommandFile`"" } $paths = [Environment]::GetEnvironmentVariable("Path", "Machine") -split ";" if ($Use32Bit) { $dtexec = $paths | where { $_ -like "*Program Files(x86)\\Microsoft SQL Server\\*\\DTS\\Binn\\" } $dtexec += 'dtexec.exe' } if ($dtexec -eq $null) { $dtexec = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\*\\DTS\\Binn\\" } $dtexec += 'dtexec.exe' } write-verbose "$dtexec $options" $Context = "servername = $ServerInstance`npath = $PackagePath" $msg = "ApplicationStartEvent" Write-Message -Severity Information -Category $events.ApplicationStartEvent -Eventid 1 -ShortMessage $msg -Context $Context try { $result = & $dtexec $options $result = $result -join "`n" if ($lastexitcode -eq 0) { $msg = "ApplicationStopEvent" Write-Message -Severity Information -Category $events.ApplicationStopEvent -Eventid 99 -ShortMessage $msg -Context $Context } else { throw $exitcode[$lastexitcode] } } catch { $result = "$_ `n$result" if ($result -and $result.Length -gt $MaxErrorMsgLen) { $result = $result.SubString($result.Length - $MaxErrorMsgLen) } Write-Verbose "DtExecException" Write-Message -Severity Error -Category $events.Get_Item("ConfigurationException") -Eventid 334 -ShortMessage "ConfigurationException: $result" -Context $Context throw "$result `n $("Failed to run PackagePath {0} to ServerInstance {1}" -f $PackagePath,$ServerInstance)" }
PowerShellCorpus/PoshCode/Get-CInfo_2.ps1
Get-CInfo_2.ps1
function Get-CInfo { param($Comp) Function PC-Name{ param ($compname) $ADS = Get-ADComputer -Filter {name -eq $compname} -Properties * | Select-Object -Property name If($ads -eq $null) {$false} ELSE{$True} } $ping = PC-Name $COMP if ($ping -eq $true) { Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } ELSEIF ($ping -eq $false) { do { Write-Host -ForegroundColor yellow "No Match Found, Below Is An AD Search, Try Again (CTRL-C to Exit):" $SEARCH = "*$COMP*" Get-ADComputer -Filter {name -like $SEARCH} | Select-Object -property name,enabled | Format-Table -AutoSize $comp = (read-host "What is the Computer Name? (EX. demersm-l7567)").ToLower() function Ping-Server { Param([string]$srv) $pingresult = Get-WmiObject Win32_PingStatus -Filter "Address='$srv'" if($pingresult.StatusCode -eq 0) {$true} else {$false} } $PING2 = PC-Name $COMP } While ($PING2 -eq $false) } If($ping2 -eq $true){ Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } }
PowerShellCorpus/PoshCode/Powershell $ UIA.ps1
Powershell $ UIA.ps1
$path = "$env:programfiles\\Reference Assemblies\\Microsoft\\Framework\\v3.0" $TypesAssembly = [Reflection.Assembly]::LoadFile("$path\\UIAutomationTypes.dll") $ClientAssembly = [Reflection.Assembly]::LoadFile("$path\\UIAutomationClient.dll") $NS = "System.Windows.Automation" [System.Diagnostics.Process]::Start(¡±notepad¡±) $UiaElement = [System.Windows.Automation.AutomationElement] $Desktop = $UiaElement::RootElement $Condition = New-Object "$NS.PropertyCondition"($UiaElement::NameProperty, "Untitled - Notepad") $Window = $Desktop.FindFirst("Children", $Condition) $Condition = New-Object "$NS.PropertyCondition"($UiaElement::ClassNameProperty, "") $notCondition = New-Object "$NS.NotCondition"($Condition) @@$Control = $Window.FindFirst("Descendants", $Condition) # $Control will be null @@$Control.getruntimeid() # this call will fail @@$Control = $Window.FindFirst("Descendants", $NotCondition) # the first UI Element whose classname is not "" will be found @@$Control.getruntimeid() # this call will succeed
PowerShellCorpus/PoshCode/Set-Extension.ps1
Set-Extension.ps1
function Set-Extension { #.Synopsis # Change the extension on file paths #.Example # ls *.ps1 | Set-Extension bak | ls # # Lists all .bak files that correspond to .ps1 scripts #.Example # ls *.txt | move -dest { Set-Extension log -path $_.PSPath } # # Renames all .txt files by changing their extension to .log #.Example # ls *.txt -Rename # # Renames all .txt files by changing their extension to .log #.Parameter Path # The file path to change the extension on #.Parameter Extension # The new extension to use #.Parameter Rename # Actually rename the file instead of just outputting the altered path param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [Alias("FullName")] [string]$Path , [Parameter(Mandatory=$true,Position=0)] [string]$Extension , [Parameter()] [switch]$Rename , [Parameter()] [switch]$Passthru ) process { if($Rename) { Move-Item -Literal $Path -Destination ([IO.Path]::ChangeExtension($path, $extension)) -Passthru:$Passthru } else { [IO.Path]::ChangeExtension($path, $extension) } } }
PowerShellCorpus/PoshCode/New-DesktopIni.ps1
New-DesktopIni.ps1
$di = [System.IO.FileInfo]"$(split-path $Profile -Parent)\\desktop.ini"\nset-content $di "[.ShellClassInfo]`r`nLocalizedResourceName=1$([char]160)WindowsPowerShell`r`nIconResource=C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe,0`r`n[ViewState]`r`nFolderType=Documents"\n$di.Attributes = $di.Attributes -bor [IO.FileAttributes]"System,Hidden" -bxor [IO.FileAttributes]"Archive"
PowerShellCorpus/PoshCode/_CTP3_ Invoke-ISE.ps1
_CTP3_ Invoke-ISE.ps1
Set-Alias ISE Invoke-ISE function Invoke-ISE () <# .SYNOPSIS start ISE from the PS-commandline .DESCRIPTION start ISE provide files as parameters or per pipe-line .NOTES Author : Bernd Kriszio - http://pauerschell.blogspot.com/ Requires : PowerShell V2 CTP3 and please can someone fix the problem that get-help doesn't use this comment .EXAMPLE Invoke-ISE $foo.ps1 .EXAMPLE Invoke-ISE foo.ps1 foobar.ps1 .EXAMPLE Invoke-ISE 'foo.ps1' 'foobar.ps1' .EXAMPLE get-childitem f*.ps1 | Invoke-ISE .EXAMPLE Invoke-ISE (dir f*.ps1) .EXAMPLE 'foo.ps1' | Invoke-ISE .EXAMPLE Invoke-ISE .LINKS http://tfl09.blogspot.com/2009/01/parameter-attributes-in-powershell-v2.html http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/12/30/windows-powershell-integrated-scripting-environment-ise.aspx #> { param ( [Parameter(Position = 0, Mandatory=$false, ValueFromPipeline=$True, ValueFromRemainingArguments = $true)] [string[]]$file ) begin { $path="$pshome\\powershell_ise.exe" if ($file -eq $null){ & $path } } PROCESS { foreach($f in $file){ # note the comment of Mark Schill # & $path (resolve-path $f) # http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/12/30/windows-powershell-integrated-scripting-environment-ise.aspx#comments & $path ( ([system.IO.FileInfo]$f).FullName) } } }
PowerShellCorpus/PoshCode/74d37072-bf65-4930-9299-29a0ec36260e.ps1
74d37072-bf65-4930-9299-29a0ec36260e.ps1
Function Get-DriveInfo([string]$computer = "localhost") { PROCESS{ $LogicalDrive = Get-WmiObject –computername $computer Win32_LogicalDisk -filter "DriveType=3" $PhysicalDrive = Get-WmiObject -class "Win32_DiskDrive" -namespace "root\\CIMV2" -computername $computer $objResult = @() foreach ($item in $LogicalDrive) { $Logical = New-Object System.Object $logical | Add-Member -MemberType NoteProperty -Name ServerName -value $computer $Logical | Add-Member -MemberType NoteProperty -Name LogicalDeviceID -value $item.deviceid $Logical | Add-Member -MemberType NoteProperty -Name LogicalDiskSizeGB -value ($item.size/1GB).tostring("0.00") $Logical | Add-Member -MemberType NoteProperty -Name LogicalFreeSpaceGB -value ($item.freeSpace/1GB).tostring("0.00") $Logical | Add-Member -MemberType NoteProperty -Name LogicalUsedSpaceGB -value (($item.size/1GB)-($item.freeSpace/1GB)).tostring("0.00") $objResult += $Logical } foreach ($item in $PhysicalDrive ) { $physical = New-Object System.Object $physical | Add-Member -MemberType NoteProperty -Name ServerName -value $computer $physical | Add-Member -MemberType NoteProperty -Name PhysicalCaption -value $item.Caption $physical | Add-Member -MemberType NoteProperty -Name PhysicalSizeGB -value ($item.size/1GB).tostring("0.00") $physical | Add-Member -MemberType NoteProperty -Name Manufacturer -value $item.Manufacturer $objResult += $physical } Write-Output $objResult } }
PowerShellCorpus/PoshCode/Out-Default URL Launcher.ps1
Out-Default URL Launcher.ps1
# Wrapper for Out-Default that saves the last object written # and handles missing commands if the command is a directory # or an URL # function Out-Default ` { [CmdletBinding(ConfirmImpact="Medium")] param( [Parameter(ValueFromPipeline=$true)] ` [System.Management.Automation.PSObject] $InputObject ) begin { $wrappedCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet( "Out-Default") $sb = { & $wrappedCmdlet @PSBoundParameters } $__sp = $sb.GetSteppablePipeline() $__sp.Begin($pscmdlet) } process { $do_process = $true if ($_ -is [System.Management.Automation.ErrorRecord]) { if ($_.Exception -is [System.Management.Automation.CommandNotFoundException]) { $__command = $_.Exception.CommandName if (test-path -path $__command -pathtype container) { set-location $__command $do_process = $false } elseif ($__command -match '^http://|\\.(com|org|net|edu)$') { if ($matches[0] -ne "http://") { $__command = "HTTP://" + $__command } [diagnostics.process]::Start($__command) $do_process = $false } } } if ($do_process) { $global:LAST = $_; $__sp.Process($_) } } end { $__sp.End() } }
PowerShellCorpus/PoshCode/Convert-BounceToX_11.ps1
Convert-BounceToX_11.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/Send-Growl _1.0.ps1
Send-Growl _1.0.ps1
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0) ## Initially it only supports a very simple notice, and I haven't gotten callbacks working yet ## Coming soon: ## * Send notices to other PCs directly ## * Wrap the registration of new messages ## * Figure out the stupid ## Change these to whatever you like, at least the first one, since it should point at a real ico file $defaultIcon = "$PSScriptRoot\\PowerGrowl.ico" $appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Script:PowerGrowler)) { $script:GrowlApp = New-Object "Growl.Connector.Application" $appName $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::AES [Growl.Connector.NotificationType[]]$global:PowerGrowlerNotices = @("Default") ## You should change this $global:PowerGrowlerNotices[0].Icon = $defaultIcon } ## I was going to store these ON the PowerGrowler object, but ... ## I wanted to make the notices editable, without making it editable ## So instead, I add them to it only after you register them.... # Add-Member -InputObject $script:PowerGrowler -MemberType NoteProperty -Name Notices -Value $PowerGrowlerNotices ## Should only (have to) do this once. $script:PowerGrowler.Register($script:GrowlApp, $global:PowerGrowlerNotices ) function Send-Growl { #.Synopsis # Send a growl notice #.Description # Send a growl notice with the scpecified values #.Parameter Caption # The short caption to display #.Parameter Message # The message to send (most displays will resize to accomodate) #.Parameter NoticeType # The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur. # For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities. #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Send-Growl "Greetings" "Hello World!" # # The Hello World of Growl. #.Example # Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png # # Displays a message with a couple of movie quotes and a mail icon. # PARAM ( # [Parameter(Mandatory=$true, Position=0)] [string]$Caption=$(Read-Host "A SHORT caption") , # [Parameter(Mandatory=$true, Position=1)] [string]$Message=$(Read-Host "The detailed message") #, [string]$CallbackData #, [string]$CallbackType , # [Parameter(Mandatory=$false)][Alias("Type")] [string]$NoticeType=$global:PowerGrowlerNotices[0].Name , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } if( $CallbackData -and $CallbackType ) { $context = new-object Growl.Connector.CallbackContext $context.Data = $CallbackData $context.Type = $CallbackType $script:PowerGrowler.Notify($notice, $context) } else { $script:PowerGrowler.Notify($notice) } } Export-ModuleMember -Function Send-Growl
PowerShellCorpus/PoshCode/TabExpansion for V2CTP3.ps1
TabExpansion for V2CTP3.ps1
## Tab-Completion ################# ## For V2CTP3. ## All or some features 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. ## 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 -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 ## 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 -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> ### 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 { 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 '.') { $params = @{view = 'extended','adapted','base'} } else { $params = @{static=$true} } 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 } } if ( $_keys -ne $null ) { $_members = (Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat}) } else { $_members = (Get-Member @params -InputObject $_val $_pat) } foreach ($_m in $_members | 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 $global:_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] $_pat = $matches[4] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] 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] + '*' $_command = [regex]::Split($line, '[|;=]')[-1] if ($_command -match '\\{([^\\{\\}]*)$') { $_command = $matches[1] } if ($_command -match '\\(([^()]*)$') { $_command = $matches[1] } $_command = $_command.Trim().Split()[0] $_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command)[0] while ($_command.CommandType -eq 'alias') { $_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command.Definition)[0] } if ( $_command -ne $null ) { foreach ($_n in $_command.Parameters.Keys | sort) { if ($_n -like $_pat) { '-' + $_n } } } else { "-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+))\\((.*)$' ) { $_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 | gm -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 " " ) { $_cmdlet = [regex]::Split($line, '[|;=]')[-1] if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_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\\.])*)$' ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] 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 ( "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] if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_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 ) { $_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; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } # parse the script... $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null) if ($_tokens) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Command') { $_cmd = $_lastToken.Content # don't look for paths... if ($_cmd.IndexOfAny('/\\') -eq -1) { # handle parsing errors - the last token string should be the last # string in the line... if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) { $_pat = $_cmd + '*' $_base = $lastword.substring(0, $lastword.length-$_cmd.length) "begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (", "end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ", "param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" ` -like $_pat | % {'{0}{1}' -f $_base,$_ } $ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) | Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ } } } } } } } } }
PowerShellCorpus/PoshCode/Get-HostsFile_1.ps1
Get-HostsFile_1.ps1
Function Get-HostsFile { <# .SYNOPSIS Retrieves the contents of a hosts file on a specified system .DESCRIPTION Retrieves the contents of a hosts file on a specified system .PARAMETER Computer Computer name to view host file from .NOTES Name: Get-HostsFile Author: Boe Prox DateCreated: 15Mar2011 .LINK http://boeprox.wordpress.com .EXAMPLE Get-HostsFile "server1" Description ----------- Retrieves the contents of the hosts file on 'server1' #> [cmdletbinding( DefaultParameterSetName = 'Default', ConfirmImpact = 'low' )] Param( [Parameter( ValueFromPipeline = $True)] [string[]]$Computer ) Begin { $psBoundParameters.GetEnumerator() | % { Write-Verbose "Parameter: $_" } If (!$PSBoundParameters['computer']) { Write-Verbose "No computer name given, using local computername" [string[]]$computer = $Env:Computername } $report = @() } Process { Write-Verbose "Starting process of computers" ForEach ($c in $computer) { Write-Verbose "Testing connection of $c" If (Test-Connection -ComputerName $c -Quiet -Count 1) { Write-Verbose "Validating path to hosts file" If (Test-Path "\\\\$c\\C$\\Windows\\system32\\drivers\\etc\\hosts") { Switch -regex -file ("\\\\$c\\c$\\Windows\\system32\\drivers\\etc\\hosts") { "^\\d\\w+" { Write-Verbose "Adding IPV4 information to collection" $temp = "" | Select Computer, IPV4, IPV6, Hostname, Notes $new = $_.Split("") | ? {$_ -ne ""} $temp.Computer = $c $temp.IPV4 = $new[0] $temp.HostName = $new[1] If ($new[2] -eq $Null) { $temp.Notes = $Null } Else { $temp.Notes = $new[2] } $report += $temp } Default { If (!("\\s+" -match $_ -OR $_.StartsWith("#"))) { Write-Verbose "Adding IPV6 information to collection" $temp = "" | Select Computer, IPV4, IPV6, Hostname, Notes $new = $_.Split("") | ? {$_ -ne ""} $temp.Computer = $c $temp.IPV6 = $new[0] $temp.HostName = $new[1] If ($new[2] -eq $Null) { $temp.Notes = $Null } Else { $temp.Notes = $new[2] } $report += $temp } } } }#EndIF ElseIf (Test-Path "\\\\$c\\C$\\WinNT\\system32\\drivers\\etc\\hosts") { Switch -regex -file ("\\\\$c\\c$\\WinNT\\system32\\drivers\\etc\\hosts") { "^#\\w+" { } "^\\d\\w+" { Write-Verbose "Adding IPV4 information to collection" $temp = "" | Select Computer, IPV4,IPV6, Hostname, Notes $new = $_.Split("") | ? {$_ -ne ""} $temp.Computer = $c $temp.IPV4 = $new[0] $temp.HostName = $new[1] If ($new[2] -eq $Null) { $temp.Notes = $Null } Else { $temp.Notes = $new[2] } $report += $temp } Default { If (!("\\s+" -match $_ -OR $_.StartsWith("#"))) { Write-Verbose "Adding IPV6 information to collection" $temp = "" | Select Computer, IPV4, IPV6, Hostname, Notes $new = $_.Split("") | ? {$_ -ne ""} $temp.Computer = $c $temp.IPV6 = $new[0] $temp.HostName = $new[1] If ($new[2] -eq $Null) { $temp.Notes = $Null } Else { $temp.Notes = $new[2] } $report += $temp } } } }#End ElseIf Else { Write-Verbose "No host file found" $temp = "" | Select Computer, IPV4, IPV6, Hostname, Notes $temp.Computer = $c $temp.IPV4 = "NA" $temp.IPV6 = "NA" $temp.Hostname = "NA" $temp.Notes = "Unable to locate host file" $report += $temp }#End Else } Else { Write-Verbose "No computer found" $temp = "" | Select Computer, IPV4, IPV6, Hostname, Notes $temp.Computer = $c $temp.IPV4 = "NA" $temp.IPV6 = "NA" $temp.Hostname = "NA" $temp.Notes = "Unable to locate Computer" $report += $temp } } } End { Write-Output $report } }
PowerShellCorpus/PoshCode/Get Stock Quotes.ps1
Get Stock Quotes.ps1
function Get-StockQuote { param($symbols) process { $s = new-webserviceproxy -uri http://www.webservicex.net/stockquote.asmx foreach ($symbol in $symbols) { $result = [xml]$s.GetQuote($symbol) $result.StockQuotes.Stock } } } # Example: # Get-StockQuote VMW, EMC | select Symbol, Last
PowerShellCorpus/PoshCode/sharpsvn, btw PS sucks.ps1
sharpsvn, btw PS sucks.ps1
[string]$rootDir = "C:\\Build\\" [string]$buildDir = "C:\\Build\\build_dir\\" [string]$outputDir = "C:\\Build\\output_dir\\" [string]$svnDir = "C:\\Build\\build_dir\\vacuum" [string]$svnUrl = "http://vacuum-im.googlecode.com/svn/trunk/" $currentScriptDirectory = Get-Location [System.IO.Directory]::SetCurrentDirectory($currentScriptDirectory) [Reflection.Assembly]::LoadFile(($currentScriptDirectory.Path + ".\\SharpSvn-x64\\SharpSvn.dll")) $svnClient = New-Object SharpSvn.SvnClient $repoUri = New-Object SharpSvn.SvnUriTarget($svnUrl) Write-Host "Getting source code from subversion repository" $repoUri -ForegroundColor Green $svnClient.CheckOut($repoUri, $svnDir) $svnClient.GetInfo($SvnDir, ([ref]$svnInfo)) $rev = $svnInfo.Revision Write-Host $rev
PowerShellCorpus/PoshCode/Get-Weather 2.1.ps1
Get-Weather 2.1.ps1
#require -version 2.0 #require -shellid PoshConsole ################################################################################################### ## Get-Weather ## Parse and display the current weather and forecast from yahoo RSS ## Note that you _could_ modify this a bit to return "current condition" and "forecast" objects ## but for now, it just prints them out in a relatively nice format ################################################################################################### ## Version History: ## 2.1 - Updated for Out-WPF 2.0, can show -Popup graphics even in PowerShell.exe (with Out-WPF) ## 2.0 - Updated for Out-WPF and PoshConsole, now shows inline graphics in PoshConsole, ## 1.1 - Added TempColor function ## 1.0 - My initial cleanup of a script from ## http`://fortheloveofcode.wordpress.com/2008/04/28/powershell-webservice-client/ ######### ## ToDo: Color code the "text": Showers/Rain/Snow/... ## ToDo: Pull out extreme weather *Warnings* ## ToDo: Parse wind and show the wind-chill when temp is cold ################################################################################################### # function get-weather { param($zip=14586,[switch]$celcius,[switch]$Popup) $url = "http`://weather.yahooapis.com/forecastrss?p={0}{1}" -f $zip, $(if($celcius){"&u=c"}) $channel = ([xml](New-Object Net.WebClient).DownloadString($url)).rss.channel function TempColor ($temp) { if($celcius) { if( $temp -lt 0 ) { "blue" } elseif( $temp -le 10 ) { "cyan" } elseif( $temp -le 21 ) { "blue" } elseif( $temp -lt 27 ) { "green" } else { "red" } } else { if( $temp -lt 5 ) { "blue" } elseif( $temp -le 50 ) { "cyan" } elseif( $temp -le 70 ) { "blue" } elseif( $temp -lt 80 ) { "green" } else { "red" } } } if($channel) { if( ($Host.PrivateData.GetType().Name -eq "PoshOptions") -OR ( $Popup -AND (Get-Command Out-WPF -Type Cmdlet -EA SilentlyContinue))) { # alternate images: http`://l.yimg.com/us.yimg.com/i/us/we/52/ $template = @" <StackPanel xmlns="http`://schemas.microsoft.com/winfx/2006/xaml/presentation" > <TextBlock FontFamily="Constantia" FontSize="12pt">{0}, {1} {2}</TextBlock> <StackPanel Orientation="Horizontal"> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{3}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{4}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"><Run FontWeight="700" Text="Now: " /><Run Foreground="{5}"> {6}{7}</Run></TextBlock> </StackPanel> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{8}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{9}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"> <Run FontWeight="700">{10}</Run><LineBreak/> <Run Foreground="{11}">{12}{7}</Run> - <Run Foreground="{13}">{14}{7}</Run></TextBlock> </StackPanel> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{15}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{16}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"> <Run FontWeight="700">{17}</Run><LineBreak/> <Run Foreground="{18}">{19}{7}</Run> - <Run Foreground="{20}">{21}{7}</Run></TextBlock> </StackPanel> </StackPanel> </StackPanel> "@ $template = ($template -f $channel.location.city, $channel.location.region, $channel.lastBuildDate, $channel.item.condition.text, $channel.item.condition.code, (TempColor $channel.item.condition.temp), $channel.item.condition.temp, $channel.units.temperature, $channel.item.forecast[0].text, $channel.item.forecast[0].code, $channel.item.forecast[0].day, (TempColor $channel.item.forecast[0].low), $channel.item.forecast[0].low, (TempColor $channel.item.forecast[0].high), $channel.item.forecast[0].high, $channel.item.forecast[1].text, $channel.item.forecast[1].code, $channel.item.forecast[1].day, (TempColor $channel.item.forecast[1].low), $channel.item.forecast[1].low, (TempColor $channel.item.forecast[1].high), $channel.item.forecast[1].high) $template | out-clipboard ## Work around defect in Out-WPF that hides -POpup when -Popup is implied. Silly of me. if($Host.PrivateData.GetType().Name -eq "PoshOptions") { Out-WPF -SourceTemplate $template -Popup:$Popup } else { Out-WPF -SourceTemplate $template } } else { # "ConsoleColorProxy" $current = $channel.item.condition Write-Host Write-Host ("Location: {0}" -f $channel.location.city) Write-Host ("Last Update: {0}" -f $channel.lastBuildDate) Write-Host ("Weather: {0}" -f $current.text)-NoNewline Write-Host (" {0}閃1}" -f $current.temp, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $current.temp) Write-Host Write-Host "Forecasts" Write-Host "---------" foreach ($f in $channel.item.forecast) { Write-Host ("`t{0}, {1}: {2}" -f $f.day, $f.date, $f.text) -NoNewline Write-Host (" {0}-{1}閃2}" -f $f.low, $f.high, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $f.High) } Write-Host } } #}
PowerShellCorpus/PoshCode/Get-LocalGroupMember.ps1
Get-LocalGroupMember.ps1
function Get-LocalGroupMember { param( # The name of the local group to retrieve members of [Parameter(Position=0,Mandatory=$true)] [String]$GroupName = "administrators", # A filter for the user name(s) [Parameter(Position=1)] [String]$UserName = "*", # The computer to query (defaults to the local machine) [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("CN")] [String[]]$ComputerName = ${Env:ComputerName}, # If set, returns only local computer accounts [Switch]$LocalAccountsOnly, # If set, returns only domain accounts [Switch]$DomainAccountsOnly ) process { foreach($cName in $ComputerName) { $Group = [System.DirectoryServices.DirectoryEntry][ADSI]"WinNT://$cName/$GroupName,group" if(!$Group.Path) { Write-Error "Can't contact '$cName'" continue } $Group.Members() | ForEach-Object { [System.DirectoryServices.DirectoryEntry]$_ | ## Overwrite or Create an NTAccountName property Add-Member ScriptProperty NTAccountName {$this.Path.Replace("WinNT://","").Replace("/","\\")} -force -passthru | ## Create a distinguishedName, because that displays by default, but is empty Add-Member AliasProperty distinguishedName NTAccountName -force -passthru | ## Add a PSComputerName Add-Member NoteProperty PSComputerName $cName -force -passthru | ## Add IsLocalAccount Add-Member ScriptProperty IsLocalAccount {$this.Path -match "/$($this.PSComputerName)/"} -force -passthru } | Where-Object { ($_.Name -like $UserName) -And (!$LocalAccountsOnly -or ($_.Path -match "/${ComputerName}/")) -And (!$DomainAccountsOnly -or ($_.Path -notmatch "/${ComputerName}/") ) } } } <# .Synopsis Lists the members of the specified local group .Description List all members of local Groups from a specified computer (eg: administrators, power users, backup operators, etc.) .Example Get-LocalGroupMember administrators -LocalAccount Retrieves all the local computer accounts that are members of the administrators group on the local machine .Example Get-LocalGroupMember "Power Users" Retrieves all the accounts that are members of the Power Users group .Example Get-LocalGroupMember administrators Admin* Retrieves all the administrators who's name starts with "admin" .Example Get-LocalGroupMember administrators -ComputerName Server1, Server2 | ft PSComputerName, Name, IsLocalAccount Retrieves administrators from several computers and displays specific information about them .Notes Copyright (c) 2010 Joel Bennett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************** NOTE: YOU MAY *ALSO* DISTRIBUTE THIS FILE UNDER ANY OF THE FOLLOWING... PERMISSIVE LICENSES: BSD: http://www.opensource.org/licenses/bsd-license.php MIT: http://www.opensource.org/licenses/mit-license.html Ms-PL: http://www.opensource.org/licenses/ms-pl.html RECIPROCAL LICENSES: Ms-RL: http://www.opensource.org/licenses/ms-rl.html GPL 2: http://www.gnu.org/copyleft/gpl.html ***************************************************************************** LASTLY: THIS IS NOT LICENSED UNDER GPL v3 (although the above are compatible) #> }
PowerShellCorpus/PoshCode/Get-GoogleSpreadsheets.ps1
Get-GoogleSpreadsheets.ps1
#requires -version 2 Function Get-GoogleSpreadSheets { param( $userName = $(throw 'Please specify a user name'), $password = $(throw 'Please specify a password') ) Add-Type -Path "C:\\Program Files\\Google\\Google Data API SDK\\Redist\\Google.GData.Client.dll" Add-Type -Path "C:\\Program Files\\Google\\Google Data API SDK\\Redist\\Google.GData.Extensions.dll" Add-Type -Path "C:\\Program Files\\Google\\Google Data API SDK\\Redist\\Google.GData.Spreadsheets.dll" $service = New-Object Google.GData.Spreadsheets.SpreadsheetsService("TestGoogleDocs") $service.setUserCredentials($userName, $password) $query = New-Object Google.GData.Spreadsheets.SpreadsheetQuery $feed = $service.Query($query) $feed.Entries | foreach { $_.Title.Text $_.Links | ? {$_.rel -eq "http://schemas.google.com/spreadsheets/2006#worksheetsfeed"} | % { $query = New-Object Google.GData.Spreadsheets.WorksheetQuery($_.Href) $feed = $service.Query($query) $feed.Entries | % { $_.Title.Text $_.Links | ? { $_.rel -eq "http://schemas.google.com/spreadsheets/2006#listfeed"} | % { $listQuery = New-Object Google.GData.Spreadsheets.ListQuery($_.Href) $feed = $service.Query($listQuery) "Worksheet has $($feed.Entries.Count) rows:" $feed.Entries | % { $_.Elements | % { Write-Host -NoNewline "$($_.value)`t" } Write-Host } } } } } }
PowerShellCorpus/PoshCode/New-ODataServiceProxy_2.ps1
New-ODataServiceProxy_2.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 #.Example # function Get-Films { # param($Name) # $proxy = New-ODataServiceProxy http://odata.netflix.com/Catalog/ # if($Name -match "\\*") { # $sName = $Name -replace "\\*" # # Note the substring PLUS a Where -like filter to pull off wildcard matching which isn't supported by NetFlix # $Global:Films = $proxy.Titles.AddQueryOption('$filter',"substringof('$sName',Name)") | Where { $_.Name -like $Name } # } else { # $Global:Films = $proxy.Titles.AddQueryOption('$filter',"'$Name' eq Name") # } # $Films | Format-List Name, ReleaseYear, AverageRating, Url, Synopsis # Write-Host "NOTE: This data is cached in `$Films" -Fore Yellow # } # # C:\\PS>Get-Films Salt # #.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 - Simple Caching http://poshcode.org/2040 # - Added a type cache to make it easier to find proxies you've already compiled (because we can't recompile them) # v1.2 - 2010 Aug 03 - Examples # - Added additional examples # v1.3 - 2010 Aug 03 - This Version # - Removed the -Language parameter from Add-Type when on .Net4 (setting it explicitly results in downgrading to 3, and having multiple assembly references!?) 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 } default { throw "The script is out of date, please fix it and upload a new one to PoshCode!" } } ## 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 switch($PSVersionTable.ClrVersion.Major) { 4 { $Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Core" -Passthru } 2 { $Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" -Passthru -Language CSharpVersion3 } default { throw "The script is out of date, please fix it and upload a new one to PoshCode!" } } if(!$Types) { return } $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 } }
PowerShellCorpus/PoshCode/Convert-BounceToX_10.ps1
Convert-BounceToX_10.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/New-FileShare.ps1
New-FileShare.ps1
Function New-FileShare { #this function returns $True is the share is successfully created Param([string]$computername=$env:computername, [string]$path=$(Throw "You must enter a complete path relative to the remote computer."), [string]$share=$(Throw "You must enter the name of the new share."), [string]$comment, [int]$connections ) $FILE_SHARE = 0 if (! $connections) { #if no connection number specifed set to $Null so #share will be created with maximum number of connections [void]$connections = $NULL } #uncomment this next line for debugging # Write-Host ("Creating share {0} for {1} on {2} ({3})" -f $share,$path,$computername,$comment) -fore Green [wmiclass]$wmishare="\\\\$computername\\root\\cimv2:win32_share" $return=$wmishare.Create($path,$share,$FILE_SHARE,$connections,$comment) Switch ($return.returnvalue) { 0 {$rvalue = "Success"} 2 {$rvalue = "Access Denied"} 8 {$rvalue = "Unknown Failure"} 9 {$rvalue = "Invalid Name"} 10 {$rvalue = "Invalid Level"} 21 {$rvalue = "Invalid Parameter"} 22 {$rvalue = "Duplicate Share"} 23 {$rvalue = "Redirected Path"} 24 {$rvalue = "Unknown Device or Directory"} 25 {$rvalue = "Net Name Not Found"} } if ($return.returnvalue -ne 0) { Write-Warning ("Failed to create share {0} for {1} on {2}. Error: {3}" -f $share,$path,$computername,$rvalue) return $False } else { return $True } }
PowerShellCorpus/PoshCode/Xml Module 4.5.ps1
Xml Module 4.5.ps1
#requires -version 2.0 # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492 # 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. # IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did. # Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible # with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node # Version History: # Select-Xml 2.0 This was the first script version I wrote. # it didn't function identically to the built-in Select-Xml with regards to parameter parsing # Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement # BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node # Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed* # Version 3.0 Added New-XDocument and associated generation functions for my XML DSL # Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released # Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument # Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack. # Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags. # Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml) # Version 4.3 Added a Path parameter set to Format-XML so you can specify xml files for prety printing # Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument) # Work around possible variable slipping on null values by: # 1) allowing -param:$value syntax (which doesn't fail when $value is null) # 2) testing for -name syntax on the value and using it as an attribute instead $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } filter Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Path # The path to an xml document (on disc or any other content provider). #.Parameter Indent # The indent level (defaults to 2 spaces) #.Example # [xml]$xml = get-content Data.xml # C:\\PS>Format-Xml $xml #.Example # get-content Data.xml | Format-Xml #.Example # Format-Xml C:\\PS\\Data.xml #.Example # ls *.xml | Format-Xml # Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")] [xml]$Xml , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")] [Alias("PsPath")] [string]$Path , [Parameter(Mandatory=$false)] $Indent=2 ) ## Load from file, if necessary if($Path) { [xml]$xml = Get-Content $Path } $StringWriter = New-Object System.IO.StringWriter $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter $xmlWriter.Formatting = "indented" $xmlWriter.Indentation = $Indent $xml.WriteContentTo($XmlWriter) $XmlWriter.Flush() $StringWriter.Flush() Write-Output $StringWriter.ToString() } Set-Alias fxml Format-Xml -EA 0 function Select-Xml { #.Synopsis # 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. #.Description # 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. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also 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") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.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 Xsl # Specifies an Xml StyleSheet to transform with... [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("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias cvxml Convert-Xml -EA 0 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(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("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.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> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace -EA 0 function New-XDocument { #.Synopsis # Creates a new XDocument (the new xml document type) #.Description # This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML # It creates a new XDocument, and takes scritpblock(s) to define it's contents #.Parameter root # The root node name #.Parameter version # Optional: the XML version. Defaults to 1.0 #.Parameter encoding # Optional: the Encoding. Defaults to UTF-8 #.Parameter standalone # Optional: whether to specify standalone in the xml declaration. Defaults to "yes" #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) # #.Example # [string]$xml = New-XDocument rss -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # item { # title {"The First Item"} # link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # description {"Ema Lazarus' Poem"} # pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"} # } # } # } # # C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # C:\\PS>$xml.ToString() # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss version="2.0"> # <channel> # <title>Test RSS Feed</title> # <link>http ://HuddledMasses.org</link> # <description>An RSS Feed generated simply to demonstrate my XML DSL</description> # <item> # <title>The First Item</title> # <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link> # <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid> # <description>Ema Lazarus' Poem</description> # <pubDate>2003-10-31T00:00:00Z</pubDate> # </item> # </channel> # </rss> # # # Description # ----------- # This example shows the creation of a complete RSS feed with a single item in it. # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output. # # #.Example # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc { # title {"Test First Entry"} # link {"http`://HuddledMasses.org"} # updated {(Get-Date -f u) -replace " ","T"} # author { # name {"Joel Bennett"} # uri {"http`://HuddledMasses.org"} # } # id {"http`://huddledmasses.org/" } # # entry { # title {"Test First Entry"} # link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" } # id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" } # updated {(Get-Date 10/31/2003 -f u) -replace " ","T"} # summary {"Ema Lazarus' Poem"} # link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution" # dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" } # category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses" # } # } | % { $_.Declaration.ToString(); $_.ToString() } # # <?xml version="1.0" encoding="UTF-16" standalone="yes"?> # <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom"> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org</link> # <updated>2009-07-29T17:25:49Z</updated> # <author> # <name>Joel Bennett</name> # <uri>http ://HuddledMasses.org</uri> # </author> # <id>http ://huddledmasses.org/</id> # <entry> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link> # <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id> # <updated>2003-10-31T00:00:00Z</updated> # <summary>Ema Lazarus' Poem</summary> # <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" /> # <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights> # <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" /> # </entry> # </feed> # # # Description # ----------- # This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString(). # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.# # Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$root , [Parameter(Mandatory = $false)] [string]$Version = "1.0" , [Parameter(Mandatory = $false)] [string]$Encoding = "UTF-8" , [Parameter(Mandatory = $false)] [string]$Standalone = "yes" , [AllowNull()][AllowEmptyString()][AllowEmptyCollection()] [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) BEGIN { $script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]' if($root.NamespaceName) { $script:NameSpaceHash.Add("", $root.Namespace) } } PROCESS { New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),( New-Object XElement $( $root while($args) { $attrib, $value, $args = $args if($attrib -is [ScriptBlock]) { # Write-Verbose "Preparsed DSL: $attrib" $attrib = ConvertFrom-XmlDsl $attrib Write-Verbose "Reparsed DSL: $attrib" &$attrib } elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { $value = ConvertFrom-XmlDsl $value &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value $script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value) } else { New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value } } )) } } Set-Alias xml New-XDocument -EA 0 Set-Alias New-Xml New-XDocument -EA 0 function New-XAttribute { #.Synopsys # Creates a new XAttribute (an xml attribute on an XElement for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter name # The attribute name #.Parameter value # The attribute value Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value) New-Object XAttribute $name, $value } Set-Alias xa New-XAttribute -EA 0 Set-Alias New-XmlAttribute New-XAttribute -EA 0 function New-XElement { #.Synopsys # Creates a new XElement (an xml tag for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter tag # The name of the xml tag #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$tag , [AllowNull()][AllowEmptyString()][AllowEmptyCollection()] [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) # BEGIN { # if([string]::IsNullOrEmpty( $tag.NamespaceName )) { # $tag = $($script:NameSpaceStack.Peek()) + $tag # if( $script:NameSpaceStack.Count -gt 0 ) { # $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() ) # } else { # $script:NameSpaceStack.Push( $null ) # } # } else { # $script:NameSpaceStack.Push( $tag.Namespace ) # } # } PROCESS { New-Object XElement $( $tag while($args) { $attrib, $value, $args = $args if($attrib -is [ScriptBlock]) { # then it's content &$attrib } elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value $script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value) } elseif($value -match "-(?!\\d)\\w") { $args = @($value)+@($args) } elseif($value -ne $null) { New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value } } ) } # END { # $null = $script:NameSpaceStack.Pop() # } } Set-Alias xe New-XElement Set-Alias New-XmlElement New-XElement function ConvertFrom-XmlDsl { Param([ScriptBlock]$script) $parserrors = $null $global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) } [Array]::Reverse( $duds ) [string[]]$ScriptText = "$script" -split "`n" ForEach($token in $duds ) { # replace : notation with namespace notation if( $token.Content.Contains(":") ) { $key, $localname = $token.Content -split ":" $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" ) } else { $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" ) } # insert 'xe' before everything (unless it's a valid command) $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " ) } Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") )) } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUmrZlx69zCgoayALV1qJAbLV6 # fAiggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # 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 # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBTjyXflYZKj # by4lmx0Jd4HX0SJm5zANBgkqhkiG9w0BAQEFAASCAQAREDiyhjKl4JSCX61rAtoU # oJ7Ly1O1dKFdR5+bt0ghet9uK9qzqAl9+4fxb4RC/XqncXYBumtaSwHcjhyn5G68 # HycOhdY3g+4euz6xo/bPfBFVSz3cA0A0oPu5S2cat+jftnWMbk3Y+jZsc7g9SbIZ # 0MGAf808lqkZuTdwG/dH8JdSCk3Yw11pjss8zz2AXHg5FFH24ZKR3zLpnSSHX0Ln # XMVRrktKWHF/BWl4PDOK06u4ZZgw3v1X0vifDMVy89XRwN1Oc6j22AuX/ob9Zkih # DzapWeedZIOscR0tyFR6DOrD6gj8ytsp/Iy1T8taP99GZPHiEnjsc479LXeyarVt # SIG # End signature block
PowerShellCorpus/PoshCode/Set-EnvironmentVariable.ps1
Set-EnvironmentVariable.ps1
#requires -version 2 function Set-EnvironmentVariable { param ( [String] [Parameter( Position = 0, Mandatory = $true )] $Name, [String] [Parameter( Position = 1, Mandatory = $true )] $Value, [EnvironmentVariableTarget] [Parameter( Position = 2 )] $Target = [EnvironmentVariableTarget]::Process, [switch] $Passthru ) [environment]::SetEnvironmentVariable( $Name, $Value, $Target ) if ( $Passthru ) { $result = [environment]::GetEnvironmentVariable( $Name, $Target ) Write-Output @{ $Name = $Result } } }
PowerShellCorpus/PoshCode/GPRS Online log_9.ps1
GPRS Online log_9.ps1
<# .SYNOPSIS Get-GprsTime (V4.0 Update for Windows 7 and allow time correction) (V4.4 'Interval' now incorporate previous 'FormatSpan' function) (V4.6 'Adjust' pattern will now reject times like '1:300:50') Check the total connect time of any GPRS SIM devices from a specified date. Use 'Get-Help .\\Get-GprsTime -full' to view Help for this script. .DESCRIPTION Display all the GPRS modem Event Log entries. While applications issued by the mobile phone manufacturers will invariably monitor only their own usage, this will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc. Use the -Verbose switch for some extra information if desired. A default value can be set with the -Monthly switch but can be temporarily overridden with any -Start value and deleted by entering an invalid date. Now uses .NET Parse to use any culture date input. Switches -M and -S cannot be used together. A Balloon prompt will be issued in the Notification area for the 5 days before the nominal month end. NOTE: this can effectively be suppressed by using a value higher than the SIM card term, ie something like -Account 90 for a 30 day card which will override the default setting. Define a function in $profile to set any permanent switches, for example to remove 1hour 15 minutes from the total each time. function GPRS { Invoke-Expression ".\\Get-GprsTime -Adjust 1:15:00- $args" } .EXAMPLE .\\Get-GprsTime.ps1 -Monthly 4/8/2011 This will set the default search date to start from 4/8/2011 and is used to reset the start date each month for the average 30/31 day SIM card. .EXAMPLE .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose Search from 12/07/2011 and also show (Verbose) details for each session. The Account switch will override any balloon prompt near the SIM expiry date. .EXAMPLE .\\Get-GprsTime.ps1 5/9/2011 -v Search one day only and show session details. .EXAMPLE .\\Get-GprsTime.ps1 -Today Show all sessions for today. This always defaults to verbose output. .EXAMPLE .\\Get-GprsTime.ps1 -Debug This shows the first available Event Log record & confirms switch settings. (Note that it will probably not be the first 'RemoteAccess' or 'RasClient' record). .EXAMPLE .\\Get-GprsTime -Adjust 1:20:00 .\\Get-GprsTime -Hours 1:20:00 If the same SIM card is used on another computer then such times will have to be added here manually (this should be put in a function in $profile so that it will automatically be included - see example above). To remove an amount of time, just put a '-' sign after the desired figure. The alias 'Hours' may be used to distinguish from the 'Account' parameter. .NOTES A shorter total time than that actually used will result if the Event Log does not contain earlier dates; just increase the log size in such a case. The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a (binary compiled) Module version of this procedure is included in the file Gprs3xxx.zip download there; the execution time of the module being about 10 times faster than this script. Use '(measure-Command {.\\Get-GprsTime}).TotalSeconds' to confirm the times. For the Event Log to record connect & disconnect events, the modem software should be set to RAS rather than NDIS if possible. #> Param ([String] $start, [alias("HOURS")][string] $adjust, [String] $monthly, [Int] $account = 0, [Switch] $today, [Switch] $verbose, [Switch] $debug) Trap [System.Management.Automation.MethodInvocationException] { [Int]$line = $error[0].InvocationInfo.ScriptLineNumber [System.Media.SystemSounds]::Hand.Play() if ($line -eq 213) { Write-Warning "[$name] Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } else { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" } exit 1 } #Establish the Operating System...We only need to confirm XP here. #The result will be written to the 'out' variable '$osv'. function Get-OSVersion($computer,[ref]$osv) { $os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer Switch -regex ($os.Version) { '^5\\.1\\.(\\d{1,4})$' { $osv.value = "xp" } #Find XP & variants. default { $osv.value = "unknown" } } } $osv = $null Get-OSVersion -computer 'localhost' -osv ([ref]$osv) if ($osv -eq 'xp') { $logname = 'System' $connEvent = 20158 $discEvent = 20159 $source = 'RemoteAccess' } else { #Treat As Vista or Windows 7. $logname = 'Application' $connEvent = 20225 $discEvent = 20226 $source = 'RasClient' } $entryType = 'Information' $logEntry = $null $source = 'Undetermined' $oldest = Get-eventlog -LogName $logname | #Get the earliest Log record. Sort-Object TimeGenerated | Select-Object -first 1 if ($oldest.TimeGenerated) { $logEntry = "$logname Event records available from - $($oldest.TimeGenerated.ToLongDateString())" } $name = $myInvocation.MyCommand $newLine = "[$name] The switches -Start and -Monthly can only be used separately." if ($debug) { $DebugPreference = 'Continue' } if ($start -and $monthly) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$newLine" exit 1 } $SCRIPT:form = $null #In certain cases Culture & UICulture can be different and have been known to # return conflicting results regarding '-is [DateTime]' queries, etc. if ($Host.CurrentCulture -eq $Host.CurrentUICulture) { $SCRIPT:form = '-Use format mm/dd/year' [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day. if ($culture -eq 6) { $SCRIPT:form = '-Use format dd/mm/year' } } if ($SCRIPT:form) { $debugForm = $SCRIPT:form.Replace('Use format','') Write-Debug "Current local system Date format is $debugForm" } $ErrorActionPreference = 'SilentlyContinue' $VerbosePreference = 'SilentlyContinue' $conn = $disc = $default = $print = $null $timeNow = [DateTime]::Now $total = $timeNow - $timeNow #Set initial value to 00:00:00. $insert = "since" if ($verbose) { $VerbosePreference = 'Continue' } function CreditMsg ($value, $value2) { $value = [Math]::Abs($value) $prefix = "CURRENT" [DateTime] $creditDT = $value2 $creditDT = $creditDT.AddDays($value) #Add the -Account days. $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format. #If we use '$number = $creditDT - (Get-Date)' instead of the line below we #can sometimes get a value of 1 returned instead 2, hence the above lines. $number = $creditDT - [DateTime] $thisDay [String] $credit = $creditDT $credit = $credit.Replace('00:00:00','') #Remove any trailing time. $credit = "{0:d}" -f [DateTime]$credit Switch($number.Days) { 1 {$prefix = "($value days) will expire tomorrow"; break} 0 {$prefix = "($value days) will expire today"; break} -1 {$prefix = "($value days) expired yesterday"; break} {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break} {($_ -le 5)} {$prefix = "($value days) will expire on $credit"} default {$prefix = "CURRENT"} #Only come here if over 5 days. } return $prefix } function Interval ([String] $value) { #Convert returns of '1.11:00:00'. Switch -regex ($value) { '^00?:00?:\\d+(.*)$' {$suffix = "seconds"; break} '^00?:\\d+:\\d+(.*)$' {$suffix = "minutes"; break} '^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break} '^(\\d+)\\.(\\d+)(\\D.*)$' {$suffix = " hours" $pDays = $matches[1] $pHours = $matches[2] [string]$pRest = $matches[3] [string]$tHours = (([int]$pDays) * 24)+[int]$pHours $value = $tHours + $pRest; break} default {$suffix = " hours"} #Should never come here! } return "$value $suffix" } function CheckSetting ($value) { if ($value) { #Correct for local culture. $print = $default.ToShortDateString() } else { $print = "(Value not set)" } return $print } #The Script effectively starts here............................................. $getGprs = [Environment]::GetEnvironmentVariable("GPRS","User") #First check for GPRS variable and change from US date format to current locale. if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid. $default = "{0:d}" -f [datetime]$getGprs $default = [DateTime]::Parse($default) $checkParts = "{0:yyyy},{0:%M}" -f $default $times = $checkParts.Split(',') $dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31. if($account -eq 0) { $account = $dayCount $summary = "$($dayCount.ToString()) days" } else { $summary = "$($account.Tostring()) days" } $text = CreditMsg $account $getGprs #Check if within 5 days of expiry date. if ($text -ne "CURRENT") { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipTitle = "GPRS online account" $objNotifyIcon.BalloonTipText = "Credit $text" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) } } else { $summary = "(Days not set)" if ((!$today) -and (!$monthly) -and (!$start)) { [System.Media.SystemSounds]::Hand.Play() Write-Warning("Monthly date is either invalid or not set.") exit 1 } } if ($start) { $start = [DateTime]::Parse($start) #Trigger TRAP if invalid! [DateTime]$limit = $start $convert = "{0:D}" -f $limit $print = CheckSetting $default } if ($monthly) { $start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid! Write-Output "Setting GPRS (monthly) environment variable to: $monthly" $gprs = [String]$start.Replace('00:00:00','') [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User") [DateTime] $limit = $start #Change to required US date format. $convert = "{0:D}" -f $limit $print = $limit.ToShortDateString() $summary = "(Days undetermined)" #Will show next time around. } if ($today) { $verBosePreference = 'Continue' #Show VERBOSE by default. [DateTime] $limit = (Get-Date) $convert = "{0:D}" -f $limit $limit = $limit.Date #Override any start date if using -Today input. $insert = "for today" $print = CheckSetting $default } if ((!$today) -and (!$monthly) -and (!$start)) { if ($default) { $monthly = $default [DateTime] $limit = $monthly $convert = "{0:D}" -f $limit $print = CheckSetting $default } } $adjustment = $null #Otherwise 'Set-Strictmode -Version latest' will catch. if ($adjust) { $pattern = '^(\\d{1,3}):([0-5]?[0-9]):([0-5]?[0-9])-?$' if ($adjust -notmatch $pattern ) { Write-Warning "Invalid input ($adjust) - use <hours>:<minutes>:<seconds>" -WarningAction Continue return } #Now create the 'adjustment' to add later. $adjustment = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] $outString = $adjust.Replace('-','') $outString = interval $outString } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" if ($logEntry) { Write-Debug "$logEntry" } $lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)} if ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the $logname Event Log." } else { Write-Output "(There are no events indicated in the $logname Event Log)" exit 2 #No need to go any further. } $lines | ForEach-Object { try { $source = $_.Source } catch { return } if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = interval $diff Write-Verbose "Disconnect at $convDisc. Online - $period" Write-Verbose " Connect at $convConn." } } #End ForEach Write-Verbose "Using local event source - $logname Event Log [$source]" $period = interval $total if ($adjustment -and ($total -match $pattern)) { $outDate = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] if (!$adjust.EndsWith('-')) { $period = $outDate + $adjustment #The '-adjust' value added at start. $temp = [String]$period #Extract any 1.0:00:00 values if + 24 hours. Write-Debug "Processing (Timespan) string: $temp" $show = (interval $temp).Replace(' ',' ') Write-Output "Total online usage $insert $convert is $show" Write-Output "(including $($outString.Replace(' ',' ')) adjustment time)" } else { if ($outDate.TotalSeconds -gt $adjustment.TotalSeconds) { $period = $outDate - $adjustment $temp = [String]$period Write-Debug "Processing (Timespan) string: $temp" $show = (interval $temp).Replace(' ',' ') Write-Output "Total online usage $insert $convert is $show" Write-Output "(excluding $($outString.Replace(' ',' ')) adjustment time)" } else { $adjust = $adjust.Replace('-','') Write-Output "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))." Write-Warning "Total usage exceeded ($adjust) - no adjustment performed" } } } else { Write-OutPut "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))." } Write-Output ""
PowerShellCorpus/PoshCode/Get-Parameter_14.ps1
Get-Parameter_14.ps1
#Requires -version 2.0 ##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]$ShowCommon , [switch]$Full , [switch]$Passthru ) 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 param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$ShowCommon , [switch]$Full , [switch]$Passthru ) if($Passthru) { $PSBoundParameters.Remove("Passthru") Get-ParameterRaw @PSBoundParameters } elseif(!$Full) { $props = "Name", "Type", "ParameterSet", "Mandatory", "Provider" Get-ParameterRaw @PSBoundParameters | Format-Table $props -GroupBy @{n="Command";e={"{0}`n Set: {1}" -f $_.Command,$_.ParameterSet}} } else { $props = "Name", "Aliases", "Type", "ParameterSet", "Mandatory", "Provider", "Pipeline", "PipelineByName", "Position" Get-ParameterRaw @PSBoundParameters | Format-Table $props -GroupBy @{n="Command";e={"{0}`n Set: {1}" -f $_.Command,$_.ParameterSet}} } } ## This is Hal's original script (modified a lot) Function global:Get-ParameterRaw { param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$ShowCommon , [switch]$Full ) BEGIN { $PropertySet = @( "Name", "Aliases", @{n="Type";e={$_.ParameterType.Name}}, "ParameterSet", @{n="Command";e={"{0}/{1}" -f $(if($command.ModuleName){$command.ModuleName}else{$Command.CommandType.ToString()+":"}),$command.Name}}, @{n="Mandatory";e={$_.IsMandatory}}, @{n="Provider";e={$_.DynamicProvider}}, @{n="Pipeline";e={$_.ValueFromPipeline}}, @{n="PipelineByName";e={$_.ValueFromPipelineByPropertyName}}, "Position" ) if(!$Full) { $PropertySet = $PropertySet[0,2,3,4,5,6] } 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") $MoreParameters = Get-Command $command -Args $drive | Select -Expand Parameters $Dynamic = $MoreParameters | Select -Expand Values | Where { $_.IsDynamic } foreach($k in $Parameters.Keys){ $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 } } } } #Write-Output $Parameters foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){ foreach($parameter in $Parameters.Keys) { if(!$ShowCommon -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue } # Write-Verbose "Parameter: $Parameter" 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 } if($Full -and $output.Position -lt 0) {$output.Position = $null} $setName = $(if($paramset -eq "__AllParameterSets") { "Default" } else { $paramset }) Write-Verbose "ParameterSet: $setName" $output = $output | Add-Member NoteProperty ParameterSet -value "$setName" -Passthru Write-Output $Output | Select-Object $PropertySet } } } } } } } # 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/Update AD Security Group.ps1
Update AD Security Group.ps1
#Active Directory Group Name To Be Edited #Load Active Directory Module if(@(get-module | where-object {$_.Name -eq "ActiveDirectory"} ).count -eq 0) {import-module ActiveDirectory} ###Functions function Get-FSMORoles { Param ( $Domain ) $DomainDN = $Domain.defaultNamingContext $FSMO = @{} # PDC Emulator $PDC = [adsi]("LDAP://"+ $DomainDN) $FSMO = $FSMO + @{"PDC" = $PDC.fsmoroleowner} return $FSMO } $Role = (Get-FSMORoles ([adsi]("LDAP://RootDSE"))) $PDC = $Role.PDC.ToString().split(",")[1] $PDC = $PDC.ToString().split("=")[1] #Active Directory Group Name $group="Test" #Search Active Directory for Users with Department X (Searches "PDC") $Users = Get-ADUser -Server $PDC -Filter {(department -eq "test") -and (objectclass -eq "user")} #Check to make sure Active Directory group exists $checkGroup=Get-ADGroup -Server $PDC -Filter {(name -eq $group)} if($checkGroup -eq $null) {echo "Group Doesn't Exist"; exit} #Get Members of the $group including child groups $groupmembers = Get-ADGroupMember "$group" -recursive -Server $PDC #Prep new array $gmembers = @() #Muck with groupmembers arrary data Foreach ($member in $groupmembers) { $gmembers += $member.SamAccountName } #Check to see if User is already a member of the group Foreach ($User in $Users) { If ($gmembers -notcontains $User.SamAccountName){Add-ADGroupMember -Server $PDC $group $User.SamAccountName } }
PowerShellCorpus/PoshCode/Get Exchange2003 Servers.ps1
Get Exchange2003 Servers.ps1
[Array]$ExchSrvs = @("") [String]$StrFilter = "(objectCategory=msExchExchangeServer)" $objRootDSE = [ADSI]"LDAP://RootDSE" [String]$strContainer = $objRootDSE.configurationNamingContext $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = New-object System.DirectoryServices.DirectoryEntry("LDAP://$strContainer") $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = "Subtree" $colResults = $objSearcher.FindAll() ForEach($objResult in $colResults) { [String]$Server = $objResult.Properties.name $ExchSrvs += $Server } $ExchSrvs.Count
PowerShellCorpus/PoshCode/ConvertTo-GoogleChartNum.ps1
ConvertTo-GoogleChartNum.ps1
## Google Chart API extended value encoding function ######################################################################### #function ConvertTo-GoogleChartNum{ BEGIN { ## Google's odydecody is a 64 character array $ody = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","-","." ## The actual filter function filter encode { # we have a hard-coded "overflow" value if($_ -ge ($ody.Count * $ody.Count) ) { return "__" } $y = -1 # $y is a ref variable, so it has to be defined $x = [Math]::DivRem( $_, $ody.Count, [ref]$y ) return "$($ody[$x])$($ody[$y])" } ## Handle numbers as parameters [int[]]$nums = $args | % { [int]$_ } } ## Or handle numbers from the pipeline. We don't care :-) PROCESS { if($_ -ne $null) { $nums += $_ } } #} END { $diff = ($nums | sort | select -last 1) / ($ody.Count * $ody.Count -1) $nums | %{$_/$diff} | encode }
PowerShellCorpus/PoshCode/Run-Defrag_1.ps1
Run-Defrag_1.ps1
# Run-Defrag # Defragments the targeted hard drives. # # Args: # $server: A target Server 2003 or 2008 system # $drive: An optional drive letter. If this is blank then all # drives are defragmented # $force: If this switch is set then a defrag will be forced # even if the drive is low on space # # Returns: # The result description for each drive. function Run-Defrag { param([string]$server, [string]$drive, [switch]$force) [string]$query = 'Select * from Win32_Volume where DriveType = 3' if ($drive) { $query += " And DriveLetter LIKE '$drive%'" } $volumes = Get-WmiObject -Query $query -ComputerName $server foreach ($volume in $volumes) { Write-Host "Defragmenting $($volume.DriveLetter)..." -noNewLine $result = $volume.Defrag($force) switch ($result) { 0 {Write-Host 'Success'} 1 {Write-Host 'Access Denied'} 2 {Write-Host 'Not Supported'} 3 {Write-Host 'Volume Dirty Bit Set'} 4 {Write-Host 'Not Enough Free Space'} 5 {Write-Host 'Corrupt MFT Detected'} 6 {Write-Host 'Call Cancelled'} 7 {Write-Host 'Cancellation Request Requested Too Late'} 8 {Write-Host 'Defrag In Progress'} 9 {Write-Host 'Defrag Engine Unavailable'} 10 {Write-Host 'Defrag Engine Error'} 11 {Write-Host 'Unknown Error'} } } }
PowerShellCorpus/PoshCode/PS+ImgBurn burn all ISOs.ps1
PS+ImgBurn burn all ISOs.ps1
function burn() { #get the files and ship them to burn-file dir -recurse -include *.iso -path c:\\,d:\\,e:\\ | foreach { burn-file $_.FullName } } function burn-file($filename) { #call img burn with the nessessary arguments . "c:\\Program Files\\ImgBurn\\ImgBurn.exe" /mode ISOWRITE /WAITFORMEDIA /start /close /DELETEIMAGE /EJECT /SRC $filename #Wait for IMGBURN to finish (right now you can only have one open at a time) while ( (get-process | where{$_.ProcessName -eq "ImgBurn"}) -ne $null) { #sleep for a bit to let the processor work on burning Start-Sleep –s 10 #tell the user what file you are still working on "waiting for $filename to complete" } } #call the burn function burn
PowerShellCorpus/PoshCode/Boots & Background Jobs.ps1
Boots & Background Jobs.ps1
Import-Module PowerBoots # This simulates a download function, say Jaykul's Get-Webfile # You can output current progress for a large file, or if it's an array of links then out put the current (index/length)% # You will need to run the function as a background thread in order for it to not interfere with the UI thread (freezes UI) when called from event handler. Function Start-FakeDownload { $global:job = Start-Job { foreach ($i in $(1..50)){ sleep 0.7 ($i/50)*100 } } } # GUI using boots. Registers controls as global variables. $global:Window = Boots -Width 250 -Async -Passthru -Title "Progress Meter" { StackPanel { ProgressBar -Height 25 -Name "Progress" | tee -var global:progress Button "Download" -Name "Download" | tee -var global:download Textblock | Tee -var global:status } } # Add event handler for the Download button. # Runs Background job and updates Ui $download.Add_Click({ # Prevents download from being pressed while running ... causes overload with $timer. $download.IsEnabled = $false $download.Content = "Downloading..." # Get background job out and updates controls with value $updateblock = { # Notice the -Keep usage. Job result/output clears everytime you Receive-Job. # -Keep allows us to get the result from the background job multiple times and also serves as a marker to figure out when the job completes if($($job.State -eq "Running") -or $($($job.State -eq "Completed") -and $($(Receive-Job $job -Keep)[-1] -eq 100))){ Invoke-BootsWindow $Window { $progress.Value = $(Receive-Job $job -Keep)[-1] $status.Text = "$($(Receive-Job $job)[-1])`% done" } } if($($job.State -eq "Completed") -and $($(Receive-Job $job) -eq $null)){ Invoke-BootsWindow $Window { $status.Text = "Download Complete" } $timer.Stop() $download.Content = "Download" $download.IsEnabled = $true } } $timer = new-object System.Windows.Threading.DispatcherTimer $timer.Interval = [TimeSpan]"0:0:3" $timer.Add_Tick( $updateBlock ) Start-FakeDownload $timer.start() })
PowerShellCorpus/PoshCode/Write-Log_2.ps1
Write-Log_2.ps1
function Write-Log { #region Parameters [cmdletbinding()] Param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $Message, [Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)] [string] $Level = “Info”, [Parameter()] [Switch] $NoConsoleOut, [Parameter()] [String] $ConsoleForeground = 'White', [Parameter()] [ValidateRange(1,30)] [Int16] $Indent = 0, [Parameter()] [IO.FileInfo] $Path = ”$env:temp\\PowerShellLog.txt”, [Parameter()] [Switch] $Clobber, [Parameter()] [String] $EventLogName, [Parameter()] [String] $EventSource, [Parameter()] [Int32] $EventID = 1 ) #endregion Begin {} Process { try { $msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message if ($NoConsoleOut -eq $false) { switch ($Level) { 'Error' { Write-Error $Message } 'Warn' { Write-Warning $Message } 'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground} } } if ($Clobber) { $msg | Out-File -FilePath $Path -Force } else { $msg | Out-File -FilePath $Path -Append } if ($EventLogName) { if (-not $EventSource) { $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name } if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) } $log = New-Object System.Diagnostics.EventLog $log.set_log($EventLogName) $log.set_source($EventSource) switch ($Level) { “Error” { $log.WriteEntry($Message, 'Error', $EventID) } “Warn” { $log.WriteEntry($Message, 'Warning', $EventID) } “Info” { $log.WriteEntry($Message, 'Information', $EventID) } } } } catch { throw “Failed to create log entry in: ‘$Path’. The error was: ‘$_’.” } } End {} <# .SYNOPSIS Writes logging information to screen and log file simultaneously. .DESCRIPTION Writes logging information to screen and log file simultaneously. Supports multiple log levels. .PARAMETER Message The message to be logged. .PARAMETER Level The type of message to be logged. .PARAMETER NoConsoleOut Specifies to not display the message to the console. .PARAMETER ConsoleForeground Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified. .PARAMETER Indent The number of spaces to indent the line in the log file. .PARAMETER Path The log file path. .PARAMETER Clobber Existing log file is deleted when this is specified. .PARAMETER EventLogName The name of the system event log, e.g. 'Application'. .PARAMETER EventSource The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER EventID The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .EXAMPLE PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application' .EXAMPLE PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script" .INPUTS System.String .OUTPUTS No output. .NOTES Revision History: 2011-03-10 : Andy Arismendi - Created. #> }
PowerShellCorpus/PoshCode/playlist.com music cache.ps1
playlist.com music cache.ps1
#put the playlist.com playlist number into $pl $pl = 14870805259; ([xml](new-object system.net.webclient).downloadstring("http://pl.playlist.com/pl.php?playlist=$([int]($pl/256))")).playlist.tracklist.track | % {try { $a= $_.tracktitle;$a;(new-object system.net.webclient).downloadfile($_.originallocation,"c:\\musiccache\\$a.mp3") } catch { } }
PowerShellCorpus/PoshCode/Get-Sysinternals.ps1
Get-Sysinternals.ps1
function Get-SysInternals { param ( $sysIntDir=(join-path $env:systemroot "\\Sysinternals\\") ) if(!(Test-Path -Path $sysIntDir -PathType Container)) { $null = New-Item -Type Directory -Path $sysIntDir -Force } $log = join-path $sysIntDir "changes.log" Add-Content -force $log -value "`n`n[$(get-date)]SysInternals sync has been started" net use \\\\live.sysinternals.com\\tools /persistent:no New-PSDrive -Name SYS -PSProvider filesystem -Root \\\\live.sysinternals.com\\tools dir Sys: -recurse | foreach { $fileName = $_.name $localFile = join-path $sysIntDir $_.name $exist = test-path $localFile $msgNew = "new utility found: $fileName , downloading..." $msgUpdate = "file : $fileName is newer, updating..." $msgNoChange = "nothing changed for: $fileName" if($exist){ if($_.lastWriteTime -gt (Get-Item $localFile).lastWriteTime) { Copy-Item $_.fullname $sysIntDir -force Write-Host $msgUpdate -fore yellow Add-Content -force $log -value $msgUpdate } else { Add-Content $log -force -value $msgNoChange Write-Host $msgNoChange } } else { if($_.extension -eq ".exe") { Write-Host $msgNew -fore green Add-Content -force $log -value $msgNew } Copy-Item $_.fullname $sysIntDir -force } } Update-Path "Sysinternals" $sysIntDir "" net use \\\\live.sysinternals.com\\tools\\ /delete } function Update-Path ( [string] $Product, [string] $productPath, [string] $Property) { # Get our existing path as an array $pathArray = @() foreach ($pathItem in [Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';')) { # Remove trailing \\ if any $pathItem = $pathItem.TrimEnd(('\\')); $pathItem = $pathItem.Replace('"',""); #$pathItem =('"{0}"' -f $pathItem) if ($pathArray -contains $pathItem) { "Removing duplicate item: " + $pathItem; } else { "Keeping item: " + $pathItem; $pathArray += $pathItem } } # Append new paths. "test path "+$productPath #TODO: encapsulate to a function if (Test-Path $productPath) { if ([string]::IsNullOrEmpty($Property)) { [string] $path = $productPath } else { [string] $path = (Get-ItemProperty $produuctPath).($Property) } #$path if (-not [string]::IsNullOrEmpty($path)) { $Product + " found" $path = $path.TrimEnd(('\\')); $path = $path.Replace('"',""); #$path =('"{0}"' -f $path) if ($pathArray -notcontains $path ) { " Appending " + $path + " to path" $pathArray += $path } else { " " + $path + " already in path" } } } else { $product + " not found" } [Array]::Sort([array]$pathArray) #$pathArray "" "Old Path: " ([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list "" "" [string] $newPath = [string]::Join(';', $pathArray); # This is where the breakage happens [Environment]::SetEnvironmentVariable('Path', $newPath, 'Machine'); "New Path: " ([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list } $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent() $prp=new-object System.Security.Principal.WindowsPrincipal($wid) $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator $IsAdmin=$prp.IsInRole($adm) if($IsAdmin) { if ($args.Length -eq 0) { Get-Sysinternals } else { Get-Sysinternals $args[0] } #Get-Sysinternals "c:\\sys\\" } else { Write-Warning "This script requires running as an elevated administrator." }
PowerShellCorpus/PoshCode/Out-SqlLdrCtlFile.ps1
Out-SqlLdrCtlFile.ps1
param($fileName) Add-Type -Path "C:\\Oracle\\Oracle.ManagedDataAccess.dll" #Change these values $userID = "yourOracleUserID" $password ="yourOraclePassword" $dataSource ="yourOracleDB" #Assumes Table name is same as file name without extension #and ctl file will output to same directory with ctl extension get-item $fileName | %{$baseName = $_.BaseName; $directory = $_.Directory} $table = $baseName.ToUpper() $ctlFile = "{0}\\{1}.ctl" -f $directory,$baseName ####################### function Get-CtlFile { param($fileName,$table, $cols) $ctlFile = @" load data infile '$fileName' "str '<EOFD><EORD>'" into table $table fields terminated by '<EOFD>' trailing nullcols ( $cols ) "@ Write-Output $ctlFile } #Get-CtlFile ####################### function Get-Query { param($table) $query = @" SELECT CASE WHEN DATA_TYPE = 'DATE' THEN COLUMN_NAME || ' DATE "MM/DD/YYYY HH24:MI:SS"' WHEN DATA_TYPE = 'CLOB' THEN COLUMN_NAME || ' CHAR(8000)' ELSE COLUMN_NAME END AS COLUMN_NAME FROM user_tab_columns WHERE TABLE_NAME = '$table' ORDER BY column_id "@ Write-Output $query } #Get-Query ####################### $con = New-Object Oracle.ManagedDataAccess.Client.OracleConnection("User Id=$userID;Password=$password;Data Source=$dataSource") $con.open() $query = Get-Query $table $cmd=new-object Oracle.ManagedDataAccess.Client.OracleCommand($query,$con) #$cols = $cmd.ExecuteScalar() $ds=New-Object system.Data.DataSet $da=New-Object Oracle.ManagedDataAccess.Client.OracleDataAdapter($cmd) [void]$da.fill($ds) $cols = $ds.Tables | %{$_.COLUMN_NAME} $cols = $cols -join "," $con.Close() if ($cols) { Get-CtlFile $fileName $table $cols | out-file -filepath $ctlFile -encoding ASCII } #1. Call Script for all .dat files in directory #get-item C:\\users\\u00\\Desktop\\APEX\\out\\db\\*.dat | %{.\\Out-SqlldrCtlFile.ps1 $_.FullName} #2. Gen up sqlldr commands to execute #get-item *.ctl | % { "sqlldr userID/password control=$($_.FullName)"} | ogv
PowerShellCorpus/PoshCode/PSTUtility.psm1.ps1
PSTUtility.psm1.ps1
#============================================================================= # # PST Utilities - For Discovery, Import, Removal # # Dan Thompson # dethompson71 at live dot com # # This collection of tools for importing PSTs has been pieced together # over many months of trial and error. # # Goal is to get PST files off the user's home share and into an archive mailbox. # # Throughout these scripts, what Microsoft calls a "Personal Archive" and # "Archive Mailbox," we call an "Online PST" or "Online Archive PST." # All these terms are the same thing. # # We used the name "Online PST" due to the user's fear of the word "Archive" # # They thought we were pushing their mail down some hole and they would # never see it again. "Online PST" is more friendly and helps them understand # the overall goal. Once we started importing PSTs for users, others saw the # increased quota, as well as seeing the mail in OWA, and many requests # started pouring in. # # All part of our evil plan to erradicate PST files. ;) # # The reason we created these scripts and made particular choices are detailed here: # http://powershellatwork.blogspot.com/2012/01/enterprise-wide-pst-import-beginnings.html # # Yes, we know about the tool PST Capture, but it just wasn't going to work for us. # # requires Quest Powershell Commands for Active Directory # (Active Roles Management Shell) # http://www.quest.com/powershell/activeroles-server.aspx # # I don't claim any of this to be perfect or work for every person out of the # box. You will certainly have to modify some settings to begin using this set # of tools in your environment. # # I hope someone can use this as a starting point if they are in a # similar situation. # # I also suggest you at least try PST Capture first. It did not work for me for # varous reasons. Your mileage may vary. # # #============================================================================= #============================================================================= # File Locations: PSTImportJobQueue; ReportJobQueue; PSTFileLogQueue #============================================================================= #====> TO DO -- add your servername and drive location $Script:PSTServer = '<ServerBIOSName>' # example 'Ex01' $Script:PSTDrive = '<drive>' # admin share example: 'd$' $Script:PSTShareDir = '\\\\' + $Script:PSTServer + '\\PSTImports' #Exchange servers must have rights to this share $Script:PSTUNCDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\pstimports' #UNC path to same share $Script:CASConnectLogDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\CASConnectLogs' # where 'Connect' logs are kept $Script:ReportsUNCDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\Current' #UNC path to report results $Script:PSTQueueFile = $Script:PSTShareDir + '\\PSTImportJobQueue.csv' $Script:PSTCompeletDir = $Script:PSTShareDir + '\\^Completed' # so it always shows at the top $Script:PSTCompleteFile = $Script:PSTShareDir + '\\PSTImportCompleteQueue.csv' # Completed PST Import Jobs $Script:NotifiedFile = $Script:PSTShareDir + '\\PSTImportJobNotified.txt' # Users who have been notified $Script:ArchReportFile = $Script:PSTUNCDir + '\\ArchiveReport.csv' # The daily archive report (also a webpage) $Script:ArchPSTFile = $Script:PSTUNCDir + '\\ArchivePSTHistory.csv' # history of PSTs owned by Archive Mailbox users $Script:MoveFileLog = $Script:PSTUNCDir + '\\MovePSTFIles-' + $Script:T + '.log' # the Move log created when run $Script:AllPSTFileLog = $Script:PSTUNCDir + '\\AllPSTHistory.csv' # the history of ALL PST files discovered # always shows at the bottom of directory listings $Script:ImportQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportJobQueue' + "-" + $Script:TE + ".csv" # backup of ImportQueue $Script:CompleteQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportCompleteQueue' + "-" + $Script:TE + ".csv" #backup of Completed Jobs $Script:ArchReportFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchiveReport-' + $Script:TE + '.csv' #back up of a report that is generated daily? $Script:ArchPSTFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchivePSTHistory-' + $Script:TE + '.csv' # back up of ArchiveMailboxOwners PSTs $Script:AllPSTFileLogBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\AllPSTHistory-' + $Script:TE + '.csv' # backup of history of ALL psts discovered #============================================================================= # Variables #============================================================================= # This site name is used to determine what tool is used to copy files. # Copy-item is used for local PST files; BITS is used for distant files. $Script:LocalADSite = 'HQ' $Script:PSTUtilityVersion = "14.1.20121015" $Script:MinRunJobs = 9 # minimum jobs running before we start more - 0 means no jobs can be running $Script:MaxRunJobs = 19 # how many job can run at once $Script:FreeSpaceLimit = 199471 # set in MB, the lowest you want free space to go on the Import Share $Script:T = Get-Date -Format yyyyMMdd # today $Script:TE = Get-Date -Format yyyyMMddhhmmss # today extended $Script:SMTPServer = "smtpserver.domain.com" # where to send $Script:AdminEmail = "admin1@domain.com, admin2@domain.com" # gets notified, sent daily summary report email $Script:BossEmail = "boss@domain.com" # send daily report on Wednesday only (Weekly Summary Report) $Script:FromEmail = "EmailTeam@domain.com" # from address of reports to porcessed users $Script:FromReportEmail = "PSTReports@domain.com" # from Address of manager's summary reports #============================================================================= # these are all the people that have applications which generate and process .PST files # but are Java configuration files. Not Mail. Ignore anything not in an "Outlook" directory # --> Add DisplayName of user... $Script:SpecialPeople = @("<DisplayName1>","<Displayname2>") #============================================================================= # These users will be ignored and not 'messed with' # There will be some ;) $Script:IgnoreUsers = @("<DisplayName1>","<DisplayName2>") #============================================================================= # Job Objects: PSTJob; ReportJob; PSTFileLog #============================================================================= Function New-PSTFileLogObject(){ <# .SYNOPSIS Return a new object to track a PST file. .DESCRIPTION Return a new object to track a PST file. This is created for each new PST discovered for any user #> $PSTObj = New-Object PSObject $PSTObj | Add-Member -type NoteProperty -name UNCFullPathName -value (0) $PSTObj | Add-Member -type NoteProperty -name LastWriteTime -value ("") $PSTObj | Add-Member -type NoteProperty -name Size -value (0) $PSTObj | Add-Member -type NoteProperty -name IgnoreFile -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name DateRemoved -value ("") $PSTObj | Add-Member -type NoteProperty -name BackupFolksNotified -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name AgeInDays -value (0) $PSTObj } Function Get-ArchPSTIndex ($PST=$null) { <# .SYNOPSIS Creates or finds an index number for PST name. .DESCRIPTION Creates or finds an index number for PST name. Uses the full UNC path for index building #> $Return = $null` If ($Script:PSTIndex.ContainsKey($PST.VersionInfo.FileName)) { # return the Index number $Return = $PSTIndex.Item($PST.VersionInfo.FileName) } Else { # not found so this is a never before see file # create the entry for the file $PSTLog = New-ArchPSTFileLogObject $PSTLog.UNCFullPathName = $PST.VersionInfo.FileName $Script:ArchPSTQueue += $PSTLog # create the index and add it to $Script:PSTIndex.Add($PSTLog.UNCFullPathName,$Script:ArchPSTQueue.Count) $Return = $Script:ArchPSTQueue.Count } $Return } Function New-ArchPSTFileLogObject(){ <# .SYNOPSIS Return a new object to track PST file. .DESCRIPTION Return a new object to track a PST file. This is created for each new PST discovered for any users with an Archive Mailbox #> $PSTObj = New-Object PSObject $PSTObj | Add-Member -type NoteProperty -name UNCFullPathName -value (0) $PSTObj | Add-Member -type NoteProperty -name LastWriteTime -value ("") $PSTObj | Add-Member -type NoteProperty -name Size -value (0) $PSTObj | Add-Member -type NoteProperty -name IgnoreFile -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name DateChecked -value ("") $PSTObj | Add-Member -type NoteProperty -name BackupFolksNotified -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name AgeInDays -value (0) $PSTObj | Add-Member -type NoteProperty -name AcctName -value ("") $PSTObj | Add-Member -type NoteProperty -name Dept -value ("") $PSTObj | Add-Member -type NoteProperty -name Server -value ("") $PSTObj | Add-Member -type NoteProperty -name DateDiscovered -value (Get-date) $PSTObj | Add-Member -type NoteProperty -name DateCreated -value ("") $PSTObj } Function Get-PSTFileIndex ($PST=$null) { <# .SYNOPSIS Creates or finds an index number for PST name. .DESCRIPTION Creates or finds an index number for PST name. Uses the full UNC path for index building #> $Return = $null` Write-Host "Enter [Get-PSTFileIndex]: $(($PST).VersionInfo.FileName) Count: $(($Script:AllPSTQueue).Count)" If ($Script:PSTIndex.ContainsKey($PST.VersionInfo.FileName)) { # return the Index number $Return = $Script:PSTIndex.Item($PST.VersionInfo.FileName) Write-Host "Found [Get-PSTFileIndex]: $($Return)" } Else { # not found so this is a never before seen file # create the entry for the file $PSTLog = New-PSTFileLogObject $PSTLog.UNCFullPathName = $PST.VersionInfo.FileName Write-Host "Fullname $(($PSTLog).UNCFullPathName)" Write-Host "Before: " $PSTLog $Script:AllPSTQueue += $PSTLog Write-host "After: " $Script:AllPSTQueue[-1] # create the index and add it to #$Script:PSTIndex.Add($_.UNCFullPathName,$i) $Script:PSTIndex.Add($PSTLog.UNCFullPathName,($Script:AllPSTQueue).Count-1) Write-Host "Added? : " $Script:PSTIndex.Get_item($PSTLog.UNCFullPathName) $Return = ($Script:AllPSTQueue).Count -1 Write-host "Try to reindex in: " $Script:AllPSTQueue[($Return)] Write-Host "Add [Get-PSTFileIndex]: $($Return)" } Write-Host "Leave [Get-PSTFileIndex]" $Return } Function New-PSTJobObject() { <# .SYNOPSIS Object for storing information about a PST Import Job. .DESCRIPTION Object for storing information about a PST Import Job. A user many have many Jobs, one for each PST file being imported. #> $PSTJob = New-Object PSObject # User Related $PSTJob | Add-Member -type NoteProperty -name JobName -value ("") # <userobj>-<filename> $PSTJob | Add-Member -type NoteProperty -name JobStatus -value ("") # <> $PSTJob | Add-Member -type NoteProperty -name UserMBX -value ("") # DisplayName $PSTJob | Add-Member -type NoteProperty -name UserEmail -value ("") # PrimarySMTPAddress $PSTJob | Add-Member -type NoteProperty -name UserObj -value ("") # NTAccopuntName $PSTJob | Add-Member -type NoteProperty -name HomeDir -value ("") # from QADuser $PSTJob | Add-Member -type NoteProperty -name ClientVer -value ("") # from CAS logs if found $PSTJob | Add-Member -type NoteProperty -name ClientVerOK -value ("") # True/False # User PC Related $PSTJob | Add-Member -type NoteProperty -name IP -value ("") # ComputerName, IP, or None (order of preference) $PSTJob | Add-Member -type NoteProperty -name OSname -value ("") # X, 7, or none # PST File Related $PSTJob | Add-Member -type NoteProperty -name ProcessFile -value ($True) # for potentially turning off one PST in a group $PSTJob | Add-Member -type NoteProperty -name OrgFileName -value ("") # should be file name only $PSTJob | Add-Member -type NoteProperty -name OrgUNCName -value ("") # UNC file name Original location $PSTJob | Add-Member -type NoteProperty -name TargetDir -value ("") # target directory for creation $PSTJob | Add-Member -type NoteProperty -name TargetUNCName -value ("") # UNC file name Target location $PSTJob | Add-Member -type NoteProperty -name FileSize -value (0) # file size in MB $PSTJob | Add-Member -type NoteProperty -name FileLastWrite -value ("") # last write time of file # Migration Related $PSTJob | Add-Member -type NoteProperty -name TargetDB -value ("") # target archive mailbox location $PSTJob | Add-Member -type NoteProperty -name MRServer -value ("") # which MRS server to use - depends on AD site $PSTJob | Add-Member -type NoteProperty -name LastNumBI -value (0) # from results, how many bad items did we encounter? $PSTJob | Add-Member -type NoteProperty -name UseTargetRootFolder -value ($true) # True/False $PSTJob | Add-Member -type NoteProperty -name TargetRootFolder -value ("") # True/False $PSTJob | Add-Member -type NoteProperty -name JobCreationTime -value ($null) # Update Related $PSTJob | Add-Member -type NoteProperty -name LastCheckTime -value ($null) # last time this entry processed $PSTJob | Add-Member -type NoteProperty -name InProgressTime -value ($null) # from results $PSTJob | Add-Member -type NoteProperty -name OverAllTime -value ($null) # from results $PSTJob | Add-Member -type NoteProperty -name ExpandedErrs -value ($null) # any encountered errors $PSTJob | Add-Member -type NoteProperty -name RegPSTGrow -value ($false) # has been added to group for GPO to PSTDisableGrow?- my signal this user is complete - check membership $PSTJob | Add-Member -type NoteProperty -name SkipReason -value ("") # when a file is skipped, Size, Age, or Failed $PSTJob } Function New-PSTReportObj (){ <# .SYNOPSIS PST Report Object for tracking the progress of PST migration. .DESCRIPTION PST Report Object for tracking the progress of users with an Archive Mailbox and their progress at removing PST files from their home drives. #> $ReportObj = New-Object PSObject # OverallUser Info $ReportObj | Add-Member -type NoteProperty -name DisplayName -value ("") # PST Information $ReportObj | Add-Member -type NoteProperty -name InUsePST -value (0) $ReportObj | Add-Member -type NoteProperty -name HDrvPST -value (0) $ReportObj | Add-Member -type NoteProperty -name HDrvSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ImpPST -value (0) $ReportObj | Add-Member -type NoteProperty -name ImpSize -value (0) $ReportObj | Add-Member -type NoteProperty -name TotalSize -value (0) $ReportObj | Add-Member -type NoteProperty -name SkippedPST -value (0) $ReportObj | Add-Member -type NoteProperty -name DaysSinceImport -value (0) $ReportObj | Add-Member -type NoteProperty -name GPO -value ("") $ReportObj | Add-Member -type NoteProperty -name '-' -value ("") # General MBX INfo $ReportObj | Add-Member -type NoteProperty -name MBXDB -value ("") $ReportObj | Add-Member -type NoteProperty -name ArchDB -value ("") $ReportObj | Add-Member -type NoteProperty -name MBXSize -value (0) $ReportObj | Add-Member -type NoteProperty -name MBXQuota -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchQuota -value (0) $ReportObj | Add-Member -type NoteProperty -name InitArchSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchGrowth -value (0) $ReportObj | Add-Member -type NoteProperty -name DateCreated -value ((Get-Date)) $ReportObj } Function Reset-PSTBackupFileNames () { <# .SYNOPSIS Reset Backup file names to current time .DESCRIPTION Reset them all so that you'll be guaranteed to have the correct name each time #> $Script:TE = Get-Date -Format yyyyMMddhhmmss # today extended $Script:ImportQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportJobQueue' + "-" + $Script:TE + ".csv" $Script:CompleteQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportCompleteQueue' + "-" + $Script:TE + ".csv" $Script:ArchReportFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchiveReport-' + $Script:TE + '.csv' $Script:ArchPSTFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchivePSTHistory-' + $Script:TE + '.csv' $Script:AllPSTFileLogBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\AllPSTHistory-' + $Script:TE + '.csv' } #============================================================================= # Helper Functions #============================================================================= Function CC () { <# .SYNOPSIS a utility to return the count of members in a collection .DESCRIPTION a utility to return the count of members in a collection 0, 1, or many ... #> Param ( $Col ) if ($Col) { if ($Col.Count -eq $null) { $Cnt = 1 } Else { $Cnt = $Col.Count } } Else { $Cnt = 0 } $Cnt } Function isMemberOf() { <# .SYNOPSIS A utility to check if a mailbox is a member of a group. .DESCRIPTION A utility to check if a mailbox is a member of a group. #> Param ( [string] $groupName, [string] $MemberName # displayname ) $m = Get-QADGroupMember $groupName -SizeLimit 0 | where { $_.Displayname -eq $memberName } if($m) {$true} else {$false} } Function WhoAmI () { <# .SYNOPSIS sometimes you want to know who is running this job ;) .DESCRIPTION ometimes you want to know who is running this job ;) #> ([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name } Function Get-ISODayOfWeek { <# .SYNOPSIS Get the correct (according to ISO 8601) day of the week .DESCRIPTION For any given date you get the day of the week, according to ISO8610 .PARAMETER Date The date you want to analyze. Accepts dates on the pipeline #> Param([DateTime]$date=$(Get-Date)) Process { if($_){$date=$_} @(7,1,2,3,4,5,6)[$date.DayOfWeek] } } Function Get-FreeDiskSpace($drive,$computer) { <# .SYNOPSIS Utility to discover the free space of a drive .DESCRIPTION Utility to discover the free space of a drive Used to decide if there is enough space to copy a PST file to either the Temp processing area, or to the local PC for backup. #> $driveData = Get-WmiObject -class win32_LogicalDisk -computername $computer -filter "Name = '$drive'" #"$computer free disk space on drive $drive" "{0:n2}" -f ($driveData.FreeSpace/1MB) } Function ConvertTo-ComputerName() { <# .SYNOPSIS Resolve the IP to a computer name .DESCRIPTION CAS logs record IP address for a user, but those can change over time resolve the IP to a computer name to save in the PST Job Queue - try to look up in DNS - 90% of time this will be an IP #> Param ( $FindName ) $Return = $null $ErrorActionPreference = "SilentlyContinue" $c = [System.Net.Dns]::GetHostbyAddress($FindName).HostName $ErrorActionPreference = "Continue" if ($c) { $Return = ($c.Split(".")[0]).ToUpper() } Else { $Return = $FindName } $Return } Function ConvertTo-IP () { <# .SYNOPSIS Lookup IP using the ComputerName .DESCRIPTION CAS logs record IP address for a user, but those can change over time resolve the IP to a computer name to save in the PST Job Queue #> Param ($FindName) $Return = $null $ErrorActionPreference = "SilentlyContinue" $c = [System.Net.Dns]::GetHostEntry($FindName).Addresslist[0].ToString() $ErrorActionPreference = "Continue" if ($c) { $Return = ($c.Split(".")[0]).ToUpper() } Else { $Return = $FindName } $Return } Function Clean-OnlinePSTGPO(){ <# .SYNOPSIS Clear up GPO group and make sure it has only the correct members .DESCRIPTION Clear up GPO group and make sure it has only the correct members .Notes In our world, there are 2 types of PST file users: Controled and Non-Controlled Controled Users: New users created after a certain date (1FEB2012) and Users migrated to Online PSTs Non-Controlled Users: Those users created befor 1FEB2012 and not having been migrated. Eventually the Non-Controlled user will disappear. At least, we can hope. #> $GPO = get-group 'GPO-ReadOnlyPST' | select -ExpandProperty Members $GPO | %{ Write-Host "Working " $_.ToString() $Dumpable = $false $Reason = "None" $MBX = get-mailbox $_.ToString() # Does User even have a mailbox? if(! (($MBX).DataBase.Name)) { $Dumpable = $true $Reason = "NoMailbox" } Elseif (!(($MBX).ArchiveDataBase.Name)) { #Has Mailbox but No Archive if ((get-date '2/1/2012') -gt (get-date ($MBX).WhenMailboxCreated)){ $Dumpable = $true $Reason = "No archive and 2/1/2012 is greater than " + $(($MBX).WhenMailboxCreated) } } if ($Dumpable){ #remove them from the group (GPO). Write-Host "Removing: " ($MBX).Displayname " - " $Reason Remove-QADGroupMember -Identity 'GPO-ReadONlyPST' -Member $_.ToString() } } # "{0,30}`t{1,10}`t{2,25}" -f (($MBX).DataBase.Name), (($MBX).ArchiveDataBase.Name),((get-date '2/1/2012') -gt ($MBX).WhenMailboxCreated)} } #============================================================================= # User Obj Functions - Done #============================================================================= Function Add-ToGPO ($User = $null) { <# .SYNOPSIS Add user to a group that defines scope of GPO to Disallow PST Growth .DESCRIPTION In our organization our GPO that disallows PST growth is governed by a group during the transition, later we can apply that setting worldwide. For users to be comfortable, they need to Read their old PST files They can then check our work for themselves. #WarmAndFuzzyFactor These skipped users are legal discovery people that need to continue to create PSTs as they gather info for Lawyer types. #> if ($User) { if (-not ($Script:IgnoreUser -contains (get-mailbox $User).SamAccountName)) { Add-QADGroupMember -Identity 'gpo-ReadonlyPST' -Member (get-mailbox $User).SamAccountName } } } Function Adjust-Quota ($User = $null) { <# .SYNOPSIS Make sure people are not hit by a quota during their transition. .DESCRIPTION Make sure people are not hit by a quota during their transition Set new quota to 500MB -- unless theie quota is already huge #> if ($User) { $MBX = get-mailbox $User # what is current quota $UsingDBQuotas = $MBX.UseDatabaseQuotaDefaults if ($UsingDBQuotas -eq $True){ $Database = Get-MailboxDatabase -Identity $MBX.Database $ProhibitSendQuota = $Database.ProhibitSendQuota.value.ToMB() -as [Int] $IssueWarningQuota = $Database.IssueWarningQuota.value.ToMB() -as [Int] } Else { $ProhibitSendQuota = $MBX.ProhibitSendQuota.value.ToMB() -as [Int] $IssueWarningQuota = $MBX.IssueWarningQuota.value.ToMB() -as [Int] } $NewProhibitSendQuota = 500 -as [int] $NewIssueWarningQuota = 450 -as [int] # this has bit me b4, so changed it to "-as [int]" above for better results if($NewIssueWarningQuota -gt $IssueWarningQuota) { Set-Mailbox -Identity $MBX -UseDatabaseQuotaDefaults:$False -ProhibitSendQuota 500MB -IssueWarningQuota 450MB -ProhibitSendReceiveQuota "Unlimited" } } } Function Get-ClientAccessUserLog () { <# .SYNOPSIS Discover a user's Client and IP information. .DESCRIPTION Discover a user's client and IP information. Script uses this function too. There is also nightly process that runs which gets all the "connect" log entries for OUTLOOK.EXE. It's run overnight. Initially we were looking at all the logs and that was very teadious. Now we search an already created subset. It's best to pass in the LegacyExchangeDN and SAMAccountName from the mailbox object from testing it seems to get better results right now using both There is no way of knowing where this user logged in so we must search all CAS servers until we find a "connect" entry and pass the full line back Also users can log in from many PCs -- we only want the most used so look thru the full day and get all info you can, then group by IP and take the one with the most connects. alas, sometimes you won't find anything ... #> param ( $DisplayName = $null, $SamName = $null, $LegacyName = $null, $IP = $null, $SearchDays = 14, [switch]$Quiet ) #----------------------------------------------------------------- $Results = @() If($DisplayName) { #ignore all the other cmdline entries and use this to grab those $MB = Get-SingleMailboxObject $DisplayName $LegacyName = $MB.LegacyExchangeDN $SamName = $MB.SamAccountName } Elseif ($IP) { $LegacyName = $IP } $Days = -1 Do { $Y = Get-Date $((get-date).adddays($Days)) -Format yyyyMMdd if (!($Quiet)) {Write-Host "Searching "$Y} if(Test-path ($Script:CASConnectLogDir + "\\olConnect-"+$Y+"*")) { $tmpResults = gc (gci ($Script:CASConnectLogDir + "\\olConnect-"+$Y+"*")) | ?{($_ -match ($LegacyName + ",")) -and ($_ -match ",,Outlook") -and ($_ -match "Connect,")} #Write-Verbose "Found: [$($tmpResults.count)]" if($tmpResults) { $tmpResults | %{$Results += $_} } } $Days-- } While (!($Results) -And ($Days -gt ($SearchDays * (-1)))) if ($Results) { #split the line(s) found into Name, Version, and IP, and mode $c = $Results | %{"{0};{1};{2};{3}" -f $_.Split(",")[3],$_.Split(",")[6],$_.Split(",")[8],$_.Split(",")[7]} # this will sort the ips to the most common one, ie: users logs into 6 machines, # but 1 was 12 times and all the others was 1 each, we get the 12 times $d = $c | %{if($_.split(";")[2]){$_.Split(";")[2]}} | group -NoElement | sort -Descending if($d){ #Just give me the entries with my most common IP $e = $c | ?{$_ -match $d.Values} } #return what you found... if ($e.count) { # Returning 1st entry in array with ips $e[0] } Elseif ($e) { # Returning only entry with ip $e } Else { if ($c.count) { # Returning 1st entry in array with no IP $c[0] } Else { # Returning only entry with no IP $c } } } } Function Get-MRServer ($MBX = $null) { <# .SYNOPSIS Pick an MRSServer in the same AD Site as the destination MBX Database. .DESCRIPTION If you are using deticated CAS servers to import the PST files use this function to pick the correct one. Pick the wrong MRServer and the Import will never start - here I pick the an MR Server in the Same AD Site using the CAS as a guide we have dediticated "pst import" CAS servers. We are chosing the One CAS server we have designated to heap many request upon so we don't effect user's normal performance on production CAS servers. .NOTES We have since moved all our live copies of each Archive Mailboxdatabase to the same AD site. It is also possible to skip this step, and let exchange pick a cas server. Depends on how much you are moving and how you feel that will effect your users See "Import-PSTFromShare" #> #--------------------------------------------------------------------- $Return = $null # If ($MBX) { # if (((get-mailboxdatabase $mbx.database.Name).RpcClientAccessServer) -match "^ad01") { # $Return = "cas02.domain.com" # } Else { # $Return = "cas04.domain.com" # } # } # ====> TO DO ==== # you will need to replace this with your cas server # or adjust the code above to pick the correct one $Return = "cas02.domain.com" $Return } Function Get-OutlookEXEVersion () { <# .SYNOPSIS Discover the version of Outlook on a PC .DESCRIPTION Discover the version of Outlook on a PC There are many version and many people do not have a compatible version with Exchange 2010 Archive Mailbox #> param( $ComputerName = $null ) $OL = $Null if($ComputerName) { if (Test-Connection -ComputerName $ComputerName -Quiet -Count 1) { Write-Verbose "Trying $ComputerName" If ( Test-path ('\\\\' + $ComputerName + '\\C$\\Program Files (x86)\\Microsoft Office\\Office14\\outlook.exe')) {# office 2010 (32b) on 64bit Write-Verbose "Office 2010 on 64bit" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files (x86)\\Microsoft Office\\Office14\\outlook.exe') } ElseIf (Test-path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office14\\outlook.exe')) { # office 2010 on 32bit Write-Verbose "Office 2010" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office14\\outlook.exe') } ElseIf (Test-path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office12\\outlook.exe')) { # office 2007 Write-Verbose "Office 2007" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office12\\outlook.exe') } Else { #check to see if this is (oh my god!) a 2003 client if (Test-Path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\OFFICE11\\outlook.exe')) { Write-Verbose "Office 2003" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\OFFICE11\\outlook.exe') } Else { Write-Verbose "Can't determine Outlook version [$ComputerName]" } } } Else { Write-Warning "[$ComputerName] is not responding" } } Else { Write-Verbose "missing computername [$ComputerName]" } $OL.VersionInfo.ProductVersion } Function Get-SingleMailboxObject($Name = $null) { <# .SYNOPSIS Return a single mailbox .DESCRIPTION Since we are importing mail and humans can be error prone, make absolutely sure we only get one hit on the requested mailbox #> #----------------------------------------------------------------- $ReturnMBX = $null if ($Name) { $MBX = get-mailbox $Name -EA 0 if (!($MBX.Count)) { # is it less than two? if ($MBX) { # is it more than zero $ReturnMBX = $MBX # Return the one } } } $ReturnMBX } Function New-OnlineArchiveByJob($JobObj = $null) { <# .SYNOPSIS Based on Job information, give user Online PST feature. .DESCRIPTION If this job's user is not enabled for online archive then create one in the smallest database. The smallest DB was determined during the "add-PSTImportQueue" ($JobObj.TargetDB) #> $Return = $false if ($JobObj) { $MBXObj = Get-SingleMailboxObject $JobObj.UserEmail #Write-Verbose "User DisplayName : $($mbxObj).Displayname) Derived from $($JobObj.UserEmail)" # this will either fail, create, or do nothing ;) Enable-Mailbox -Archive -Identity $mbxObj -ArchiveDatabase ($JobObj.TargetDB) -ArchiveName $('Online PST - ' + ($mbxObj).Displayname) -ea 0 # just a buffer sleep -Seconds 5 # Adjust Quota so this user is not prohibited during migration Adjust-Quota $MBXObj # reload to capture changes $MBXObj = Get-SingleMailboxObject $JobObj.UserEmail If ($MBXObj.ArchiveDatabase) { $Return = $true #Write-Verbose "User has Archve!" } Else { $Return = $false #Write-Verbose "User has NO Archve!" } } $Return } Function Test-OutlookClientVersion ($V = $null) { <# .SYNOPSIS Test Oulook.exe version .DESCRIPTION older outlook clients can't see the "Online Archive" so flag those users who need an upgrade 12.0.6550.5000 is the minimum level - buggy 12.0.6607.xxxx is Office 2007 SP3 -- preferred level there are search bugs in earlier versions 14.0.6109.5005 is outlook 14 patched to Nov 8, 2011 14.0.6117.5xxx is patched thru April 2012 -- preferred #> $VOK = $False if($V) { if ($V.Split(".")[0] -eq 14) { # Outlook 2010 (32bit) 14.0.4760.1000 if ($V.Split(".")[2] -ge 4760) {$VOK = $true} } Elseif ($V.Split(".")[0] -eq 12) { # Outlook 2007 (32bit) 12.0.6550.5000 (or above) if ($V.Split(".")[2] -ge 6550) {$VOK = $true} } } $VOK } #============================================================================= # PST File Functions #============================================================================= Function Copy-PSTtoImportShare($Path=$Null, $Dest=$null){ <# .SYNOPSIS copy the pst to our share folder .DESCRIPTION Copy the pst to our share folder using Copy-item in the same local AD site works fine. Using BITS when copying over WAN lines #> $Result = "Fail" # Copied or Error(s) #Write-Verbose "Copy From: $Path To: $Dest" if($Path -and $Dest ) { $NewFile = Copy-Item -Path $Path -Destination $Dest -PassThru if ($NewFile){ $Result = "Copied" } Else { # return the last error $Result = $error[0].Exception Write-Verbose "Copy ResultFrom: $($error[0].Exception)" } } $Result } Function Copy-PSTusingBITS ($JobObj = $null) { <# .SYNOPSIS copy the pst to our share folder .DESCRIPTION Copy the pst to our share folder using Copy-item in the same local AD site works fine. Using BITS when copying over WAN lines #> $Result = $false if ($JobObj) { $params = @{ Source = ($Jobobj.OrgUNCName) Destination = ($Jobobj.TargetUNCName) Description = ("Online PST BITS Copy") DisplayName = ($JobObj.JobName) Asynchronous = $true Priority = "Normal" } $Result = Start-BitsTransfer @params } $Result = $null sleep 2 $Result = Get-BitsTransfer | Where-Object { $_.DisplayName -eq ($ThisJob.JobName) } $Result } Function Get-PSTFileList() { <# .SYNOPSIS Discover PST Files in folders .DESCRIPTION Discover PST Files in folders .NOTES - Some AD objects do not have a home directory - Allowed for some results of *.pst being directories #> param( $Homedir = $null, $PCIP = $null, $SearchPC = $false, $OS = $null, $UN = $null, $SourceDir=$null ) $HDFiles = $null $PCFIles = $null #Write-Verbose "Get-PSTFileList $HomeDir $PCIP $SearchPC $OS $UN" # assuming SourceDir is a specific target dir if(!($SearchPC) -and $SourceDir) { Write-host "`t-> Override HomeDir: $HomeDir to $SourceDir" $Homedir = $SourceDir } If ($Homedir){ if(Test-Path $HomeDir) { Write-Verbose "`t`t-> Searching $HomeDir" # ensure this is an array even if we have only one entry [array]$HDFiles = gci -path $HomeDir -Filter '*.pst' -Recurse -Force -EA 0 | ?{$_.PSIsContainer -eq $false} } } if($SearchPC -and $PCIP) { if(Test-Connection $PCIP -Count 1 -Quiet) { $PCDir = $null if($SourceDir) { $PCDir = $SourceDir } Else { if($OS -match "7") { Write-Verbose "`t`t-> Searching Windows7 PC $UN" $PCDir = $("\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook") } Elseif ($OS -match "XP") { Write-Verbose "`t`t-> Searching WindowsXP PC $UN" $PCDir = $("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN) } Else { #we don't know OS, so test them and see which flies Write-Verbose "`t`t-> OS not known, testing for OS :" if(Test-Path ("\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook")) { Write-Verbose "`t`t-> Try Windows7" $PCDir = "\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook" } Elseif (Test-Path ("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN)){ Write-Verbose "`t`t-> Try WindowsXP" $PCDir = $("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN) } Else { Write-Verbose "`t`t-> OS Unknown" $PCDir = $("\\\\" + $PCIP + "\\c$") } } } #if have a legit dir or just the whole c drive ... Write-Verbose "`t`t-> Searching $PCDir" If(Test-Path $PCDir) { [array]$PCFIles = gci -path ($PCDir) -Filter '*.pst' -Recurse -Force -EA 0 | ?{$_.PSIsContainer -eq $false} } } Else { Write-Output ("`t-> $PCIP is not responding.") } } if($HDFiles -and $PCFIles){ $Files = $HDFiles + $PCFIles } Elseif ($HDFiles -and (-not $PCFIles)){ $Files = $HDFiles } Elseif ((-not $HDFiles) -and $PCFIles){ $Files = $PCFIles } Else { $Files = $null } $Files } Function Import-PSTFromShare($JobObj){ <# .SYNOPSIS import into the Archive mailbox .DESCRIPTION import into the Archive mailbox .NOTES We found that 99% of the people wanted to keep their data separate after the import, just like it was in their PST files, so UseTargetRootFolder was defaulted to true in the NEw-PSTJobObject function We check here for false. #> $Return = "Failed" $Error.Clear | Out-Null $MBXName = $JobObj.UserObj $User = $JobObj.UserObj.Split("\\")[1] $File = $JobObj.TargetUNCName $JobName = $JobObj.JobName $CAS = $JobObj.MRServer if ($JobObj.TargetRootFolder) { $Folder = $JobObj.TargetRootFolder } Else { $Folder = $JobObj.OrgFileName } Write-Debug "$MBXName -Name $JobName -Batchname $USER -MRSServer $CAS -TargetDB $JobObj.TargetDB" # import the pst #======= TO DO ============ # remove the -MRSServer $CAS - if you want Exchange to choose the CAS server every time. if($JobObj.UseTargetRootFolder -eq "TRUE") { $PSTQueued = New-MailboxImportRequest -Name $JobName -BatchName $USER -Mailbox "$MBXName" -FilePath "$File" -IsArchive -MRSServer $CAS -BadItemLimit 9999 -AcceptLargeDataLoss -Confirm:$false -targetrootfolder $Folder } Else { $PSTQueued = New-MailboxImportRequest -Name $JobName -BatchName $USER -Mailbox "$MBXName" -FilePath "$File" -IsArchive -MRSServer $CAS -BadItemLimit 9999 -AcceptLargeDataLoss -Confirm:$false } If($PSTQueued) { $Return = $PSTQueued.Status } Else { $Return = $Error[0].ToString() } sleep -Seconds 5 $Return } Function Move-PSTToLocal ($IP=$null, $PSTFiles=$null, $SamAcct=$null, $IgnoreAge=$False) { <# .SYNOPSIS clear PST files off the Home shares .DESCRIPTION The botton line of this project is to clear PST files off the Home shares If the PST file has been imported the file itself has become a backup and as such is safe to put on the local PC of the user. .NOTES Move PSTs If this is a windows 7 box and has 2010 this might be the place to put them \\\\172.18.20.1\\c$\\Users\\<user>\\Documents\\Outlook Files but this is good for XP \\\\172.18.20.1\\c$\\D9ocuments and Settings\\<user>\\My Docuemtns\\Outlok Files If this user is in a far away place, then do NOT push the data back to the PC #> Write-Host "Starting = Who:($SamAcct), Count:($(($PSTFiles).Count)), Computer:($IP)" $HQUser = $true $Region = (get-mailbox $SamAcct).CustomAttribute2 If (($Region -eq "Asia") -or ($Region -eq "Europe")) {$HQUser = $false} if ($IP -eq "None") {$IP = $null} if($IP -and $PSTFIles -and $SamAcct -and $HQUser) { #make sure we can ping the PC Write-Host $("$SamAcct; Starting Move-PSTFiles $(get-date)") $("$SamAcct; Starting Move-PSTFiles $(get-date)") >> $Script:MoveFileLog if (Test-Connection -ComputerName $IP -Quiet){ Write-Host $("$SamAcct; Connect to $IP passed") $("$SamAcct; Connect to $IP passed") >> $Script:MoveFileLog # both return MB $AvailableSpace = [int](get-freediskspace 'c:' $IP)/2 $PSTFiles = $PSTFiles | Sort Length $PSTSize = (($PSTFIles | Measure-Object Length -sum).Sum)/(1024*1024) $OldPSTSize = ((($PSTFIles | ?{$_.LastWriteTime -le (get-date ((get-date).adddays(-90))) } | Measure-Object Length -sum).Sum)/(1024*1024)) $Continue = $false if (Test-Path $('\\\\' + $IP + '\\c$\\users\\' + $SamAcct)) { # Put them in this dir structure, create or use Outlook Files dir $LocalBU = $('\\\\' + $IP + '\\c$\\users\\' + $SamAcct+ '\\Documents\\Outlook Files') if (!(Test-Path $LocalBU)){ mkdir $LocalBU } $Continue = $true Write-Host $("$SamAcct; Connect to $IP passed") $("$SamAcct; LocalBU is $LocalBU") >> $Script:MoveFileLog } Elseif (Test-Path $('\\\\' + $IP + '\\c$\\documents and settings\\' + $SamAcct)) { # Put them in this dir structure, create or use Outlook Files dir $LocalBU = $('\\\\' + $IP + '\\c$\\documents and settings\\' + $SamAcct + '\\Outlook Files') if (!(Test-Path $LocalBU)){ mkdir $LocalBU } $Continue = $true Write-Host $("$SamAcct; LocalBU is $LocalBU") $("$SamAcct; LocalBU is $LocalBU") >> $Script:MoveFileLog } Else { # crap! i give up... #I hope i have the right IP -- log it Write-Host "Can not find a secure directory for $SamAcct" $Continue = $false $("$SamAcct; LocalBU is Can not find a secure directory; Fail") >> $Script:MoveFileLog } if ($Continue) { # move the files $FileNames = @() $PSTFiles | %{ $ThisPST = $_ $FN = $ThisPST.Name $PSTBackups = $LocalBU $FileAge = (((get-date) - ($ThisPST.LastWriteTime)).Days) Write-Host "Working: $FN" Write-Host "(($AvailableSpace) -gt ($PSTSize))" Write-Host "IgnoreAge is $IgnoreAge" if($AvailableSpace -gt $PSTSize) { # there is enough space on the drive to hanlde all the PSTs If($IgnoreAge) { # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { #don't move if younger than 30 days If ($ThisPST.LastWriteTime -le (get-date ((get-date).adddays(-30)))){ #meaning it's older, so move it # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct;Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { # file is too young $("$SamAcct; Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" } } } Else { # there is NOT enough space on the drive to handle all the PSTs # Psts are sorted by smallest to largest so do what you can $AvailableSpace = [int](get-freediskspace 'c:' $IP)/2 $PSTSize = (($ThisPST | Measure-Object Length -sum).Sum)/(1024*1024) If($AvailableSpace -gt $PSTSize) { Write-Host "(($AvailableSpace) -gt ($PSTSize))" If($IgnoreAge) { # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { #don't move if younger than 90 days If ($ThisPST.LastWriteTime -le (get-date ((get-date).adddays(-30)))){ #meaning it's older, so move it # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { # file is too young $("$SamAcct; Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog } } } Else { $("$SamAcct; Age [$($FileAge)] Skipping due to AvailableSpace $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog } } $FileNames += $FN } } Else { Write-Host "No Files Moved." $("$SamAcct; No Files Moved.") >> $Script:MoveFileLog } } Else { Write-Host "Computer [$IP] seems dead" $("$SamAcct; Computer [$IP] seems dead.") >> $Script:MoveFileLog } } Else { if (!($PSTFiles)) { Write-Host "No PST Files found." $("$SamAcct; No PST Files found.") >> $Script:MoveFileLog } Else { Write-Host "Bad Parameters or Not CONUS User." $("$SamAcct; Bad Parameters or Not CONUS User.") >> $Script:MoveFileLog } } } #============================================================================= # PST Queue Functions #============================================================================= Function Format-JobStatus($JobObj) { <# .SYNOPSIS Query the queue for info on a particular user. .DESCRIPTION Query the queue for info on a particular user. Count the number of jobs in each status category, incoming JobObj is a collection. #> # # # # $JobsCount = 0 $StatusNew = 0 $StatusCopied = 0 $StatusBITS = 0 $StatusInQueue = 0 $StatusImported = 0 $StatusCleanedup = 0 $StatusNotified = 0 $LastError = $null $JobSize = 0 $StatusSkipped = 0 $JobObj | %{ $ClientOK = $_.ClientVerOK $UName = $_.UserMBX $TargetDB = $_.TargetDB $a = [int]($_.FileSize) $JobSize += $a $skip=$false if(($_.ProcessFile -eq "FALSE")){$Skip=$true} Switch ($_.JobStatus) { New { if(($Skip)){$StatusSkipped++} Else {$StatusNew++} } NewBits { if(($Skip)){$StatusSkipped++} Else {$StatusNew++} } Copied {$StatusCopied++} InBits {$StatusBITS++} InQueue {$StatusInQueue++} Imported {$StatusImported++} CleanedUp {$StatusCleanedup++} Notified {$StatusNotified++} } $JobsCount++ } $StatusEntry = New-Object PSObject $StatusEntry | Add-Member -type NoteProperty -name Name -value ($UName) $StatusEntry | Add-Member -type NoteProperty -name Client -value ($ClientOK) $StatusEntry | Add-Member -type NoteProperty -name Size -value ($JobSize) $StatusEntry | Add-Member -type NoteProperty -name Jobs -value ($JobsCount) $StatusEntry | Add-Member -type NoteProperty -name New -value ($StatusNew) $StatusEntry | Add-Member -type NoteProperty -name Skip -value ($StatusSkipped) $StatusEntry | Add-Member -type NoteProperty -name BITS -value ($StatusBITS) $StatusEntry | Add-Member -type NoteProperty -name Copied -value ($StatusCopied) $StatusEntry | Add-Member -type NoteProperty -name InQue -value ($StatusInQueue) $StatusEntry | Add-Member -type NoteProperty -name Imptd -value ($StatusImported) $StatusEntry | Add-Member -type NoteProperty -name ClndUp -value ($StatusCleanedup) $StatusEntry | Add-Member -type NoteProperty -name Notifd -value ($StatusNotified) $StatusEntry | Add-Member -type NoteProperty -name Target -value ($TargetDB) #$StatusEntry | Add-Member -type NoteProperty -name Errors -value ($LastError) $StatusEntry } Function Get-ArchDB() { <# .SYNOPSIS Find the smallest Archive mailbox database .DESCRIPTION Find the smallest Archive mailbox database, not necesarily the smallest now, but even after all the current jobs are processed #> #get current sizes - include or exclude certain DBs $ArchSize = @{} # get all database that Start with "arch", 3 digits, and end with character "b-z" like "Arch101B" for example # excluding arch102* for now, no more users there... (get-mailboxdatabase |?{$_.name -match 'arch\\d{3}[acdef]' -and $_.name -notmatch 'arch102'} | Get-MailboxDatabase -Status) | %{$ArchSize.Add($_.Name, $_.DatabaseSize.ToMB())} # need to account for pending items... if($OldJobQueue) { $OldJobQueue | %{ $tmp = $ArchSize.item($_.TargetDB) $Tmp += [int]$_.FileSize $ArchSize.remove($_.TargetDB) $ArchSize.add($_.TargetDB, $tmp) } } # return the smallest one ($ArchSize.GetEnumerator() | sort Value)[0].Name } Function Lock-PSTIQ() { <# .SYNOPSIS Signal the queue file is in use by creating a file. .DESCRIPTION Signal the queue file is in use by creating a file. #> if(!(Test-PSTIQLock)) {$a = New-Item $($Script:PSTUNCDir + '\\PSTImportQueue.Lock') -itemtype "file"} } Function New-TargetPSTDirectory($MBX = $null) { <# .SYNOPSIS Create a directory to hold the PST file while they are importing. .DESCRIPTION Create a directory to hold the PST file while they are importing. These psts are deleted at the end, but reports for each PST file are left in the directory. #> $Return = "Error" If ($MBX) { $dir = $Script:PSTShareDir + "\\" + $MBX.samaccountname if(!(Test-Path $dir)) { $newdir = ni -ItemType Directory -Path $dir } Else { $Return = $dir } } #Test new dir and make sure it's there If($newdir) { $Return = (resolve-path $newdir).ProviderPath } $Return } Function Test-PSTIQLock () { <# .SYNOPSIS Test to see if PST Import Queue is in use. .DESCRIPTION Test to see if PST Import Queue is in use. #> Test-Path $($Script:PSTUNCDir + '\\PSTImportQueue.Lock') } Function Unlock-PSTIQ() { <# .SYNOPSIS Remove the lock when the PST Import Queue is no longer in use. .DESCRIPTION Remove the lock when the PST Import Queue is no longer in use. #> if(Test-PSTIQLock) {Remove-Item $($Script:PSTUNCDir + '\\PSTImportQueue.Lock')} } #============================================================================= # Send Notification Functions #============================================================================= Function Send-NotificationInitialReport($JobObj) { <# .SYNOPSIS Send the User a notification of PST files found and the work to be done. .DESCRIPTION Send the User a notification of PST files found and the work to be done. Incoming JobObj will give us the information we needed to the report. #> $AllProcessFiles = $JobObj | ?{$_.ProcessFile -eq $true} $AllSkippedJobs = $JobObj | ?{$_.ProcessFile -ne $true} $JobObj | %{$User = $_.UserMBX; $CLOK = $_.ClientVerOK } Write-Host $User Write-Host $CLOK $Subject = "Requested PST Import: Initial Report for " + $User $From = "EmailTeam@domain.com" $Body = "Note: This process will not delete or alter your original PSTs in any way.`n" if ($JobObj.ClientVer -match "^14.") { $Body = $Body + "Your offline PST files will be copied into your new " + '"Archive - ' + $JogObj.UserEmail + '"' + " folder in Outlook.`n" } Else { $Body = $Body + "Your offline PST files will be copied into your new " + '"Online PST"' + " folder in Outlook.`n" } $Body = $Body + "`n" $Body = $Body + "The copy may take a few nights to complete. The process will start tonight about 7PM (1900). `n" $Body = $Body + "`t- Do not add any messages to your PSTs during this process.`n" $Body = $Body + "`t- Please shut down Outlook before leaving each night.`n" $Body = $Body + "`t- You do not need to turn off your PC.`n" $Body = $Body + "`n" $Body = $Body + "You will be notified when the copies are complete.`n" $Body = $Body + "`n" # you may want to comment this out, or create one of your own #$Body = $Body + "Click below to read the FAQ about Online PSTs." #$Body = $Body + "`n" #$Body = $Body + '"' + 'http://<link to self help doc on sharepoint> #$Body = $Body + "`n" $Body = $Body + "Once you see your new Online PST, use it as you would any PST.`n" $Body = $Body + "`n" $Body = $Body + "The procedure for finding your PST files has finished and found " + $JobObj.Count + " files. The ones scheduled for import, are:`n`n" #location of How to remove password on PST #"`n(http://office.microsoft.com/en-us/outlook-help/remove-a-password-from-a-personal-folders-file-pst-HA001151725.aspx)" if ($AllProcessFiles) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,-25}`t{2}`t`t{3}`n" -f ("Num"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllProcessFiles | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $tmp = $null $tmp = "{0,3}`t{1,-25}`t({2,7} M)`t{3}`n" -f ($Num),($temp1),($tempS), ($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None)" } $Body = $Body + "`n`nSkipped Files: `n" if($AllSkippedJobs) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-25}`t{3}`t`t{4}`n" -f ("Num"),("Reason"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllSkippedJobs | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $skip = $_.SkipReason $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-25}`t({3,7} M)`t{4}`n" -f ($Num),($skip),($temp1),($tempS),($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None)" } $Body = $Body + "`n`n" $Body = $Body + "Files are skipped due to either size (empty file) or not opened by Outlook in the last 2 years.`n" $Body = $Body + "Files also can be skipped if they look like Backups (BU) or Sharepoint Lists (SP).`n" $Body = $Body + "(Skipping files is just a suggestion. You can opt to include them.)`n" if($JobObj.Count){ $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj)[0].ClientVerOK) + " " + (($JobObj)[0].ClientVer) + "]["+(($JobObj)[0].IP)+"]["+(($JobObj)[0].OSName)+"]" } Else { $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj).ClientVerOK) + " " + (($JobObj).ClientVer) + "]["+(($JobObj).IP)+"]["+(($JobObj).OSName)+"]" } If ($NoNotify) { Send-MailMessage -Body $body -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -To $Script:AdminEmail } Else { Send-MailMessage -Body $body -To $To -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -cc $Script:AdminEmail #Send-MailMessage -Body $body -To $JobObj.UserEmail -From $From -SmtpServer $Script:SMTPServer -Subject $Subject } } Function Send-NotificationFinalReport($JobObj) { <# .SYNOPSIS Send User the Final report detailing the work done. .DESCRIPTION Send User the Final report detailing the work done. #> $AllProcessFiles = $JobObj | ?{$_.ProcessFile -eq "TRUE"} $AllSkippedJobs = $JobObj | ?{$_.ProcessFile -eq "FALSE"} if($JobObj.Count) { $Subject = "Requested PST Import: Final Results for: " + $JobObj[0].UserMBX $ClientVer = $JobObj[0].ClientVer $Email = $($JobObj[0].UserEmail.ToString()) } Else { $Subject = "Requested PST Import: Final Results for: " + $JobObj.UserMBX $ClientVer = $JobObj.ClientVer $Email = $($JobObj.UserEmail.ToString()) } $From = "EmailTeam@domain.com" $Body = "The process for copying your PST files has finished. Please take a few moments to complete the final steps:`n" $Body = $Body + "`n" if ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Body = $Body + "`t1. Review messages in the " + '"Archive - ' + $Email + '"' + " folder in Outlook and confirm all have been copied correctly.`n" } Else { $Body = $Body + "`t1. Review messages in the " + '"Online PST"' + " folder in Outlook and confirm all have been copied correctly.`n" } #$Body = $Body + "`t1. Review messages in the " + '"Online PST - <yourname>" or "Archive - <yourname>"' + " folder in Outlook and confirm all have been copied correctly.`n" $Body = $Body + "`t2. Disconnect the old PSTs from Outlook. (right click the name and choose: Close <pstname>)`n" $Body = $Body + "`t3. Restart Outlook - to release the lock on the file.`n" $Body = $Body + "`t4. Move the old PST files from your Home Drive (H:\\) to a local drive. This will improve your Outlook performance!`n" $Body = $Body + "`t (For example, create a directory in " + '"My Documents"' + " called " + '"Outlook Files"' + " and move the files listed below from your H:\\ to the new Outlook Files directory.)`n" if ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Body = $Body + "`t5. Begin storing messages in your " + '"Archive - ' + $Email + '"' + " folder instead of your old PSTs.`n" } Else { $Body = $Body + "`t5. Begin storing messages in your " + '"Online PST"' + " folder instead of your old PSTs.`n" } #$Body = $Body + "`n`tFor detailed instructions, click this link:`n" #$Body = $Body + "`n`t" + '"http://<sharepointsite>/Self-Help/Standard Application Issues/How do I Disconnect My Personal Folders.pdf"' + "`n" #$Body = $Body + "`n" $Body = $Body + "`tNote: Remember you can read your old PSTs at any time. In a few days you will not be able to add any new emails to these old PST files.`n" $Body = $Body + "`t You are now using the Online PST instead.`n" $Body = $Body + "`n" $Body = $Body + "`nThe files which can be moved off your home drive:`n" $Body = $Body + "`n" $Body = $Body + "`nIf you need assistance or have any questions, simply reply-all to this email.`n" $Body = $Body + "`n" $Body = $Body + "Imported Files:`n" $NUm = 0 $tmp = "{0,3}`t{1,-40}`t{2,-35}`t{3}`t{4}`n" -f ("Num"),("FileName"),("Target Folder"),("Size"),("Directory") $Body = $Body + $tmp $AllProcessFiles | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $tempT = $_.TargetRootFolder $tmp = $null $tmp = "{0,3}`t{1,-40}`t{2,-35}`t({3,7} M)`t{4}`n" -f ($Num),($temp1),($tempT),($tempS),($temp) $Body = $Body + $tmp } $Body = $Body + "`n`nSkipped Files:`n" if($AllSkippedJobs) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-40}`t{3}`t`t{4}`n" -f ("Num"),("Reason"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllSkippedJobs | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $skip = $_.SkipReason $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-40}`t({3,7} M)`t{4}`n" -f ($Num),($skip),($temp1),($tempS),($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None) " } #$Body = $Body + "`n`nIf you have any questions, reply to this email." $Body = $Body + "`n" $Body = $Body + "`Thank You -- The Email Group" $Body = $Body + "`n" if($JobObj.Count){ $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj)[0].ClientVerOK) + " " + (($JobObj)[0].ClientVer) + "]["+(($JobObj)[0].IP)+"]["+(($JobObj)[0].OSName)+"]" } Else { $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj).ClientVerOK) + " " + (($JobObj).ClientVer) + "]["+(($JobObj).IP)+"]["+(($JobObj).OSName)+"]" } Send-MailMessage -Body $body -To $To -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -Cc $Script:AdminEmail } Function Send-NotificationPSTRemoval() { <# .SYNOPSIS Send user a report showing the files that are still 'connected' to Outlook .DESCRIPTION Send user a report showing the files that are still 'connected' to Outlook Connected means the LastWriteTime was within the last 24 hours. User gets this email every 14 days as a reminder to disconnect their Old PST files and optionaly remove those PST files from Home Share. #> #------------------------------------------------------------------------ Param( $ArchObj, [array]$PSTFilesInUse, [array]$PSTFilesALL, [array]$PSTFilesMovable ) $Subject = "Online PST -- Possible Outlook Issue : " + $ArchObj.DisplayName + " (" + $ArchObj.DaysSinceImport + ")" $From = "EmailTeam@domain.com" $To = $((get-mailbox $ArchObj.DisplayName).PrimarySMTPAddress.ToString()) $CC = $Script:AdminEmail [int]$InUse = cc $PSTFilesInUse; Write-Verbose "[SendNotification] Inuse - $InUse" [int]$AllPSTs = cc $PSTFilesALL; Write-Verbose "[SendNotification] AllPST - $AllPSTs" [int]$Movable = cc $PSTFilesMovable; Write-Verbose "[SendNotification] AllPST - $AllPSTs" #grab this user's latest client version $Vers = (import-csv $Script:PSTCompleteFile | ?{$_.UserMBX -match ($ArchObj.DisplayName)} | sort LastCheckTime -Descending) If ($Vers.Count) { $ClientVer = $Vers[0].ClientVer } Else { If ($Vers){ $ClientVer = $Vers.ClientVer } Else { $ClientVer = "Ignore" } } Write-Verbose "[SendNotification] $(($ArchObj).DisplayName) : Client Ver is $($ClientVer)" If ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Archive =
PowerShellCorpus/PoshCode/Audit NTFS on Shares_1.ps1
Audit NTFS on Shares_1.ps1
$Excel = New-Object -Com Excel.Application $Excel.visible = $True $Excel = $Excel.Workbooks.Add() $wSheet = $Excel.Worksheets.Item(1) $wSheet.Cells.item(1,1) = "Folder Path:" $wSheet.Cells.Item(1,2) = "Users/Groups:" $wSheet.Cells.Item(1,3) = "Permissions:" $wSheet.Cells.Item(1,4) = "Permissions Inherited:" $WorkBook = $wSheet.UsedRange $WorkBook.Interior.ColorIndex = 8 $WorkBook.Font.ColorIndex = 11 $WorkBook.Font.Bold = $True ####Change the path to the folder or share you want NTFS perms on#### $dirToAudit = Get-ChildItem -Path "c:\\inetpub" -recurse | Where {$_.psIsContainer -eq $true} $intRow = 1 foreach ($dir in $dirToAudit) { $colACL = Get-Acl -Path $dir.FullName foreach ($acl in $colACL) { $intRow++ $wSheet.Cells.Item($intRow,1) = $dir.FullName foreach ($accessRight in $acl.Access) { $wSheet.Cells.Item($intRow,2) = "$($AccessRight.IdentityReference)" $wSheet.Cells.Item($intRow,3) = "$($AccessRight.FileSystemRights)" $wSheet.Cells.Item($intRow,4) = $acl.AreAccessRulesProtected $intRow++ } } } $WorkBook.EntireColumn.AutoFit()
PowerShellCorpus/PoshCode/Invoke-WMSettingsChange.ps1
Invoke-WMSettingsChange.ps1
#requires -version 2 if (-not ("win32.nativemethods" -as [type])) { # import sendmessagetimeout from win32 add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @" [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult); "@ } $HWND_BROADCAST = [intptr]0xffff; $WM_SETTINGCHANGE = 0x1a; $result = [uintptr]::zero # notify all windows of environment block change [win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [uintptr]::Zero, "Environment", 2, 5000, [ref]$result);
PowerShellCorpus/PoshCode/Get-Credential 2.1.ps1
Get-Credential 2.1.ps1
## Get-Credential ## An improvement over the default cmdlet which has no options ... ################################################################################################### ## History ## v 2.1 Fix the comment help and parameter names to agree with each other (whoops) ## v 2.0 Rewrite for v2 to replace the default Get-Credential ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit ## v 1.1 Add -Console switch and set registry values accordingly (ouch) ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet ################################################################################################### function Get-Credential { ## .Synopsis ## Gets a credential object based on a user name and password. ## .Description ## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations. ## ## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically. ## ## .Parameter UserName ## A default user name for the credential prompt, or a pre-existing credential (would skip all prompting) ## .Parameter Title ## Allows you to override the default window title of the credential dialog/prompt ## ## You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it. ## .Parameter Message ## Allows you to override the text displayed inside the credential dialog/prompt. ## ## You can use this for things like presenting an explanation of what you need the credentials for. ## .Parameter Domain ## Specifies the default domain to use if the user doesn't provide one (by default, this is null) ## .Parameter GenericCredentials ## The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\". ## .Parameter Inline ## Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE) ## [CmdletBinding(DefaultParameterSetName="Better")] PARAM( [Parameter(Position=1,Mandatory=$false)] [Alias("Credential")] [PSObject]$UserName=$null, [Parameter(Position=2,Mandatory=$false)] [string]$Title=$null, [Parameter(Position=3,Mandatory=$false)] [string]$Message=$null, [Parameter(Position=4,Mandatory=$false)] [string]$Domain=$null, [Parameter(Mandatory=$false)] [switch]$GenericCredentials, [Parameter(Mandatory=$false)] [switch]$Inline ) PROCESS { if( $UserName -is [System.Management.Automation.PSCredential]) { return $UserName } elseif($UserName -ne $null) { $UserName = $UserName.ToString() } if($Inline) { if($Title) { Write-Host $Title } if($Message) { Write-Host $Message } if($Domain) { if($UserName -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } if(!$UserName) { $UserName = Read-Host "User" if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } return New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString) } if($GenericCredentials) { $Credential = "Generic" } else { $Credential = "Domain" } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. ## BugBug? PowerShell.exe disregards the last parameter $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Credential,"Default") } }
PowerShellCorpus/PoshCode/Bulk Storage vMotion .ps1
Bulk Storage vMotion .ps1
#======================================================================== # Created on: 5/31/2012 4:31 PM # Created by: Clint Jones # Organization: Virtually Genius! # Filename: StorageVMotion-BulkVMs #======================================================================== #Import Plugins and Connect to vCenter Add-PSSnapin VMware.VimAutomation.Core $creds = Get-Credential $viserver = Read-Host "vCenter Server:" Connect-VIServer -Server $viserver -Credential $creds #Load information from the selected cluster $cluster = Read-Host "What cluster do you want to migrate:" $destdata1 = Read-Host "Destination datastore #1:" $destdata2 = Read-Host "Destination datastore #2:" $vms = Get-Cluster -Name $cluster | Get-VM #Stoage vMotion each VM in selected cluster in a staged fashion foreach($vm in $vms) { #Ensure that the storage is balanced as it was before the transfer $currentdata = Get-VM -Name $vm.Name | Get-Datastore $currentdata = $currentdata.Name if ($currentdata.EndsWith("a") -eq "True") {$destdata = $destdata1} else {$destdata = $destdata2} #Storage vMotion to the datastore of choice and wait to start next transfer $task = Get-VM -Name $vm.Name | Move-VM -Datastore (Get-Datastore -Name $destdata) Wait-Task -Task $task }
PowerShellCorpus/PoshCode/e7cd2cb0-d32a-4631-a081-302f0685887c.ps1
e7cd2cb0-d32a-4631-a081-302f0685887c.ps1
$Mailboxes = Get-CASMailbox -Filter {HasActivesyncDevicePartnership -eq $true} $EASMailboxes = $Mailboxes | Select-Object PrimarySmtpAddress,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}} $EASMailboxes | foreach {Set-CASMailbox $_.PrimarySmtpAddress -ActiveSyncAllowedDeviceIDs $_.DeviceID}
PowerShellCorpus/PoshCode/ConvertFrom-Hashtable 2.ps1
ConvertFrom-Hashtable 2.ps1
#function ConvertFrom-Hashtable { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] [HashTable]$hashtable , [switch]$Combine , [switch]$Recurse ) BEGIN { $output = @() } PROCESS { if($recurse) { $keys = $hashtable.Keys | ForEach-Object { $_ } Write-Verbose "Recursing $($Keys.Count) keys" foreach($key in $keys) { if($hashtable.$key -is [HashTable]) { $hashtable.$key = ConvertFrom-Hashtable $hashtable.$key -Recurse # -Combine:$combine } } } if($combine) { $output += @(New-Object PSObject -Property $hashtable) Write-Verbose "Combining Output = $($Output.Count) so far" } else { New-Object PSObject -Property $hashtable } } END { if($combine -and $output.Count -gt 1) { Write-Verbose "Combining $($Output.Count) cached outputs" $output | Join-Object } else { $output } } #}
PowerShellCorpus/PoshCode/CommandTranscript_1.ps1
CommandTranscript_1.ps1
if(!$global:CommandTranscriptPrompt) { ## Record the original prompt so we can put it back if they change their minds... $global:CommandTranscriptPrompt = ${Function:Prompt} } function Test-CommandTranscript { #.Synopsis # Tests whether or not a current command transcript is in place. return $global:CommandTranscriptPrompt -ne ${Function:Prompt} } function Get-CommandTranscript { #.Synopsis # Returns the current (or most recent) transcript log #.Example # notepad $(Get-CommandTranscript) [CmdletBinding()] param() end { if(!(Test-CommandTranscript)) { Write-Warning "Not currently logging transcript. Output is last transcript if any." } if($global:CommandTranscriptPath -and (Test-Path $global:CommandTranscriptPath)) { Get-Item -LiteralPath $global:CommandTranscriptPath } } } function Start-CommandTranscript { #.Synopsis # Start a transcript recording the commands you enter, and optionally, the success and duration of them #.Description # Each time your prompt is displayed, the previous command is logged to the transcript. # If you specify plain (or ps1) output, the result is basically a PowerShell script containing the commands you enter. # If you specify Full (or csv) output, the result is a csv file with start and end times, success, etc. # If you specify Annotated (the default) the duration and success of the command are appended as a comment #.Parameter Output # What output format you prefer # # If you specify plain (or ps1) output, the result is basically a PowerShell script containing the commands you enter. # If you specify Full (or csv) output, the result is a csv file with start and end times, success, etc. # If you specify Annotated (the default) the duration and success of the command are appended as a comment #.Parameter Append # Whether to overwrite the file or append to it. #.Parameter Path # The path to the file to log to #.Example # Start-CommandTranscript "$(Split-Path $Profile)\\Session-$(Get-Date -f 'yyyy-mm-dd').ps1" -Output Plain # # Description # ----------- # Logs commands as a script to the profile directory with and output file something like: Session-2010-07-04.ps1 #.Example # Start-CommandTranscript "~\\Documents\\Logs\\Session $(Get-Date -f 'yyyy-mm-dd').csv" -Output Full # # Description # ----------- # Logs commands in CSV format to the specified file. Note that you must have a Documents\\Logs folder in your $home directory. [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("PSPath","Name")] [string]$Path = "CommandTranscript" , [Parameter(Position=1,Mandatory=$false)] [ValidateSet("Annotated","Plain","Ps1","Csv","Full")] [string]$Output = "Annotated" , [switch]$Append ) begin { if(Test-CommandTranscript) { Write-Warning "Already writing a command transcript to $global:CommandTranscriptPath" return } } end { switch -regex ($Output) { "Csv|Full" { $extension = $Output = "csv" } "Plain|Ps1" { $extension = $Output = "ps1" } "Annotated" { $extension = "ps1" } } $global:CommandTranscriptOutput = $Output if( test-path $path -PathType Container ) { $path = Join-Path $path "CommandTranscript.$extension" } # else ## You can uncomment this block to FORCE the csv/ps1 extension. # { # $path = [System.Io.Path]::ChangeExtension($path,$extension) # } $global:CommandTranscriptPath = $path $Start = "# Command Transcript Started $(Get-Date)" if(!$Append) { switch($CommandTranscriptOutput) { "Csv" { $Type, $Header, $Value = Get-History -count 1 | Add-Member -MemberType NoteProperty -Name Success -Value $? -Passthru | ConvertTo-CSV Set-Content -LiteralPath $global:CommandTranscriptPath -Value $Type, $Start, $Header } default { Set-Content -LiteralPath $global:CommandTranscriptPath -Value "$Start`n`n" } } } else { Add-Content -LiteralPath $global:CommandTranscriptPath -Value "`n`n$Start`n`n" } $global:CommandTranscriptPath = Resolve-Path $global:CommandTranscriptPath ## Insert our transcript prompt Function Global:Prompt { $last = Get-History -count 1 | Add-Member -MemberType NoteProperty -Name Success -Value $? -Passthru switch($CommandTranscriptOutput) { "ps1" { $Value = $last.CommandLine.Trim() } "csv" { $null, $Value = ConvertTo-CSV -Input $last -NoTypeInformation } "annotated" { $Value = "{0,-75} ## Success: {1}, Execution Time: {2} " -f $last.CommandLine.Trim(), $last.Success, ($last.EndExecutionTime - $last.StartExecutionTime) } } Add-Content -LiteralPath $global:CommandTranscriptPath -Value $Value return &$global:CommandTranscriptPrompt @args } Write-Host $Start -Foreground Yellow -Background Black Write-Verbose "Logging commands to $global:CommandTranscriptPath" -Foreground Yellow -Background Black } } function Stop-CommandTranscript { #.Synopsis # End a transcript session #.Description # Terminates transcription and writes out the file item where logging occurred. [CmdletBinding()] param() end { $End = "# Command Transcript Ended $(Get-Date)" Add-Content -LiteralPath $global:CommandTranscriptPath -Value "`n`n$End" ${Function:Prompt} = $Global:CommandTranscriptPrompt Write-Host $End -Foreground Yellow -Background Black Write-Verbose "Transcript is at $global:CommandTranscriptPath" -Foreground Yellow -Background Black Get-Item $global:CommandTranscriptPath } } # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU28988stUHQ9qmYVmls26N6Tp # IJ6gggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj # dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY # BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh # dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId # KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P # n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl # 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC # mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD # /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX # +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L # PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC # B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC # AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC # ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg # M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0 # LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv # bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G # CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee # zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4 # rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7 # bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb # 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA # T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow # gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl # IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY # aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0 # LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC # NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU7R1RKYL8 # G6ZOoMc+zfYPeTZ7oUwwDQYJKoZIhvcNAQEBBQAEggEAUYpkSwGPW04zwgWbohTE # UPntUJ3r3Ydmzwdy+yIMheMJyXMG6OO/exDUYURQIWH28prHrwxuxG8c/7zrP1po # +CaMZbScHjWc8Tw18Auk1YB5ctkjuFyXv5K6Klk2PYsXdoMuXxpIcO1+G33tZC9g # mlK67aBfSQlljBHTbjntV/cG+G0Tv8qJg5/SBmXK7Gk0GGlf4nAD/IpnPzWG5wME # tjjTRu2BGCXL1TRsOdR/VhMIwzy021jDMnXhweeuB5PyXPkBeXx2w/3B9s+a5iTz # jj1L8PDXkT0OYVv9lYLIVI4JVzb18Id6RnTNLYAxWzO+KmiarFaSemhaAs7ZiU3r # Gw== # SIG # End signature block
PowerShellCorpus/PoshCode/Test-Transcribing_1.ps1
Test-Transcribing_1.ps1
#requires -version 2.0 function Test-Transcribing { $externalHost = $host.gettype().getproperty("ExternalHost", [reflection.bindingflags]"NonPublic,Instance").getvalue($host, @()) try { $externalHost.gettype().getproperty("IsTranscribing", [reflection.bindingflags]"NonPublic,Instance").getvalue($externalHost, @()) } catch { write-warning "This host does not support transcription." } }
PowerShellCorpus/PoshCode/Async Sockets.ps1
Async Sockets.ps1
if (-not ("CallbackEventBridge" -as [type])) { Add-Type @" using System; public sealed class CallbackEventBridge { public event AsyncCallback CallbackComplete = delegate { }; private CallbackEventBridge() {} private void CallbackInternal(IAsyncResult result) { CallbackComplete(result); } public AsyncCallback Callback { get { return new AsyncCallback(CallbackInternal); } } public static CallbackEventBridge Create() { return new CallbackEventBridge(); } } "@ } function Open-Socket { #.Synopsis # Open an Internet Socket #.Parameter Server # The name of the server to connect to #.Parameter Port # The port to connect to on the remote server #.Parameter SocketType # The type of socket to open. # Valid values include Stream, Dgram, Raw, Seqpacket, etc. # # Default value Stream #.Parameter ProtocolType # The protocol to use over the socket. # Valid values include Tcp, Udp, Icmp, Ipx, etc. # # Default value Tcp #.Example # $socket = Open-Socket google.com 80 param( [Parameter(Mandatory=$true, Position=0)] [Alias("Host")] [string]$Server , [Parameter(Mandatory=$true, Position=1)] [int]$Port , [Parameter()] [System.Net.Sockets.SocketType]$SocketType = "Stream" , [Parameter()] [System.Net.Sockets.ProtocolType]$ProtocolType = "Tcp" ) end { $socket = new-object System.Net.Sockets.Socket "InterNetwork", $SocketType, $Protocol $socket.Connect($Server, $Port) Write-Output $socket } } function Expect-String { #.Synopsis # Read data from an open socket asynchronously (using BeginRead/EndRead). #.Description # Reads data from an open socket in an async manner, allowing the script to continue and even to cancel reading. # Provides an advanced system for reading up to an expected string with buffering and regex matching. #.Parameter Socket # The socket to read from #.Parameter Expect # One or more patterns to match on (regex syntax supported) # Note: a null value will match all remaining output from the socket #.Parameter SendFirst # Text to send through the socket before reading. For example, a telnet command or http GET request. #.Parameter BufferLength # The size buffer to use when reading from the socket # # Default value 100 #.Parameter OutputBuffer # A List[String] for the output. Defaults to an empty collection, but you can pass in an existing collection to append to. # This is primarily for use when piping the output of Expect-String back to Expect-String to build up multiple results. #.Parameter Wait # The number of seconds to wait for the socket reads to finish. #.Notes # Expect-String doesn't close the socket, in case you need to call Expect-String on it again #.Example # $socket = Open-Socket www.xerox.com 80 # C:\\PS>$State = Expect-String -Socket $socket -Send "GET / HTTP/1.1`r`nHost: www.xerox.com`r`n`r`n" -Wait 30 -Expect ".*(?=<)",".*(?=<body>)","</body>",$null # C:\\PS>$socket.Close() # C:\\PS>Write-Host "Headers:" $State.Output[0] # C:\\PS>Write-Host "Body:" $State.Output[2] # # Description # ----------- # This calls Expect-String with four expectations, which means there will be four items in $State.Output if they all match. The 3rd item (index 2) will show the entire body of the Xerox homepage. Notice that the first two are using regular expression positive lookaheads (the parenthesis and ?= enclosing some text) to match up to but not including the tags. The four expectations specified result in the http headers, the html up to (but not including) the body tag, the whole body, and anything else that comes after the body (</html>) being in Output, because putting $null as the last expectation copies all remaining data until the end of the stream. We then close the socket. # # NOTE: Using -Wait causes Expect-String not to return until either all expectations are met, we reach the end of the data, or we timeout. Otherwise, Expect-String returns immediately, but you have to manually check $State.Complete # #.Example # $State = Open-Socket localhost 80 | # Expect-String -Send "GET /xsm57/ui/home.aspx HTTP/1.1`r`nHost: localhost`r`n`r`n" # while(!$State.Complete) { write-host $State.Output.Length "characters so far." } # # Description # ----------- # Without the -Wait parameter, this will return instantly, but the data may not have started arriving yet. Note that on a fast server, once the data starts arriving, it arrives so fast that the Write-Host line may never write anything but zeros, and since we're not -Expecting anything, it should just return everything as a single string in $State.Output param( [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [System.Net.Sockets.Socket]$Socket , [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [String[]]$Expect = @() , [String]$SendFirst , [Parameter(ValueFromPipelineByPropertyName=$true)] [Int]$BufferLength = 100 , [Parameter(ValueFromPipelineByPropertyName=$true)] [Alias("Output")] [System.Collections.Generic.List[String]]$OutputBuffer = $(New-Object System.Collections.Generic.List[String]) , [double]$Wait ) begin { if($SendFirst) { $Socket.Send(([char[]]$SendFirst)) | Out-Null } $Expecting = $Expect -as [bool] New-Object PSObject @{ Bridge = [CallbackEventBridge]::create() Buffer = New-Object System.Byte[] $BufferLength BufferLength = $BufferLength Received = New-Object System.Text.StringBuilder Output = $OutputBuffer Socket = $Socket Complete = $false Expecting = $Expect } | Tee-Object -Variable State } process { Trap [System.ObjectDisposedException] { Write-Warning "The socket was forcibly closed" } Register-ObjectEvent -input $State.Bridge -EventName CallbackComplete -action { param($AsyncResult) Trap [System.ObjectDisposedException] { Write-Warning "The socket was forcibly closed" $as.Complete = "ERROR: The socket was forcibly closed" } $as = $AsyncResult.AsyncState $read = $as.Socket.EndReceive( $AsyncResult ) Write-Verbose "Reading $read" if($read -gt 0) { $as.Received.Append( ([System.Text.Encoding]::ASCII.GetString($as.Buffer, 0, $read)) ) | Out-Null } ## This is the "Expect" logic which aborts reading when we get what we wanted ... if(($as.Expecting.Count -gt $as.Output.Count) -and $as.Received.Length -gt $as.Expecting[$as.Output.Count].Length -and $as.Expecting[$as.Output.Count]) { $Expecting = $as.Expecting[$as.Output.Count] Write-Verbose "Expecting $Expecting" # Speeds up matching if the results are large $StartIndex = [Math]::Max(($as.Received.Length - [Math]::Max(($as.BufferLength * 2), $Expecting.Length)), 0) $Length = $as.Received.Length - $StartIndex $match = [regex]::Match( $as.Received.ToString( $StartIndex, $Length ), $Expecting ) if( $match.Success ) { $match | Out-String | Write-Verbose $matchEnd = $StartIndex + $match.Index + $match.Length $as.Output += $as.Received.ToString(0, $matchEnd) $as.Received = New-Object System.Text.StringBuilder $as.Received.ToString($matchEnd, $as.Received.Length - $matchEnd) ## If there's nothing left to expect, then ... don't if($as.Expecting.Count -eq $as.Output.Count) { $as.Complete = "Success: All matches found" $read = 0 # Finish reading for now ... } } } ## It is more correct to keep trying until we get 0 bytes, but some servers never respond when they have 0 to send. # if($read -gt 0) { if($read -eq $as.BufferLength) { # Keep reading ... $as.Socket.BeginReceive( $as.Buffer, 0, $as.BufferLength, "None", $as.Bridge.Callback, $as ) | Out-Null } else { # If we weren't "expecting" or if the last expectation is null (or empty) # put everything we've received into the output buffer if($as.Expecting.Count -eq 0 -or $as.Expecting[-1].Length -eq 0) { $as.Output += $as.Received.ToString() $as.Received = New-Object System.Text.StringBuilder } $as.Complete = $true } } | Out-Null Write-Verbose "Begin Receiving" $State.Socket.BeginReceive( $State.Buffer, 0, $State.BufferLength, "None", $State.Bridge.Callback, $State ) | Out-Null # | Select * -Expand AsyncState | Format-List | Out-String | Write-Verbose } end { if($Wait) { while($Wait -gt 0 -and !$State.Complete) { Sleep -milli 500 $Wait -= 0.5 Write-Progress "Waiting to Receive" "Still Expecting Output $Expect" -SecondsRemaining $Wait } } } }
PowerShellCorpus/PoshCode/Export-SPListToSQL.ps1
Export-SPListToSQL.ps1
#Change these settings as needed #MS Access 2007 Data Components required $connString = 'Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes; DATABASE=http://sharepoint.acme.com/;LIST={96801432-2d03-42b8-82b0-ac96ca9fea8a};' #See http://chadwickmiller.spaces.live.com/blog/cns!EA42395138308430!275.entry for instructions on obtaining list GUID $qry = 'Select Title,Notes,CreateDate, Modified, Created from list' #Create a table in destination database with the with referenced columns and table name. $sqlserver = 'Z002\\SQL2K8' $dbname = 'SQLPSX' $tblname = 'splist_fill' ####################### function Get-SPList { param($connString, $qry='select * from list') $spConn = new-object System.Data.OleDb.OleDbConnection($connString) $spConn.open() $cmd = new-object System.Data.OleDb.OleDbCommand($qry,$spConn) $da = new-object System.Data.OleDb.OleDbDataAdapter($cmd) $dt = new-object System.Data.dataTable $da.fill($dt) > $null $dt } #Get-SPList ####################### function Write-DataTableToDatabase { param($destServer,$destDb,$destTbl) process { $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString $bulkCopy.DestinationTableName = "$destTbl" $bulkCopy.WriteToServer($_) } }# Write-DataTableToDatabase ####################### Get-SPList $connString $qry | Write-DataTableToDatabase $sqlserver $dbname $tblname
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_8.ps1
Send-HTMLFormattedEmail_8.ps1
#------------------------------------------------- # Send-HTMLFormattedEmail #------------------------------------------------- # Usage: Used to send an HTML Formatted Email that is based on an XSLT template. #------------------------------------------------- function Send-HTMLFormattedEmail{ param ( [string] $To, [string] $ToDisName, [string] $BCC, [string] $From, [string] $FromDisName, [string] $Subject, [string] $Content, [string] $Relay, [string] $XSLPath) try { # Load XSL Argument List $XSLArg = New-Object System.Xml.Xsl.XsltArgumentList $XSLArg.Clear() $XSLArg.AddParam("To", $Null, $ToDisName) $XSLArg.AddParam("Content", $Null, $Content) # Load Documents $BaseXMLDoc = New-Object System.Xml.XmlDocument $BaseXMLDoc.LoadXml("<root/>") $XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform $XSLTrans.Load($XSLPath) #Perform XSL Transform $FinalXMLDoc = New-Object System.Xml.XmlDocument $MemStream = New-Object System.IO.MemoryStream $XMLWriter = [System.Xml.XmlWriter]::Create($MemStream) $XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter) $XMLWriter.Flush() $MemStream.Position = 0 # Load the results $FinalXMLDoc.Load($MemStream) $Body = $FinalXMLDoc.Get_OuterXML() # Create from, To, BCC and the message strucures $MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName $MessTo = New-Object System.Net.Mail.Mailaddress $To $MessBCC = New-Object System.Net.Mail.Mailaddress $BCC $Message = New-Object System.Net.Mail.MailMessage $MessFrom, $MessTo # Populate message $Message.Subject = $Subject $Message.Body = $Body $Message.IsBodyHTML = $True # Add BCC $Message.BCC.Add($MessBCC) # Create SMTP Client $Client = New-Object System.Net.Mail.SmtpClient $Relay # Send The Message $Client.Send($Message) } catch { return $Error[0] } } ### XSLT Template Example <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output media-type="xml" omit-xml-declaration="yes" /> <xsl:param name="To"/> <xsl:param name="Content"/> <xsl:template match="/"> <html> <head> <title>My First Formatted Email</title> </head> <body> <div width="400px"> <p>Dear <xsl:value-of select="$To" />,</p> <p></p> <p><xsl:value-of select="$Content" /></p> <p></p> <p><strong>Please do not respond to this email!</strong><br /> An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p> <p></p> <Address> Many thanks from your:<br /> Really Cool IT Team<br /> </Address> </div> </body> </html> </xsl:template> </xsl:stylesheet>
PowerShellCorpus/PoshCode/Atlassian Jira Interface.ps1
Atlassian Jira Interface.ps1
# jirafunctions.ps1 # # Note: Some functions are incomplete/untested. Be sure to TEST before placing in production!! # # Dot-source this script to connect to jira and initialize the functions. # Ex: PS C:\\scripts\\jira> . .\\jirafunctions.ps1 # Ex: PS C:\\scripts\\jira> get-JiraReport # # Connects to Jira and initializes several functions that can be # used to interface with Jira. # # Author: Robbie Foust (rfoust@duke.edu) # Last Modified: December 26, 2008 # # connect-webservice script written by Lee Holmes (http://www.leeholmes.com/guide) # and slightly modified by Robbie Foust. # $global:jiraURL = "https://server.yourdomain.com/jira/rpc/soap/jirasoapservice-v2?wsdl" function global:connect-jira ($wsdlLocation) { ############################################################################## ## ## Connect-WebService.ps1 ## ## From Windows PowerShell, The Definitive Guide (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) ## ## Connect to a given web service, and create a type that allows you to ## interact with that web service. ## ## Example: ## ## $wsdl = "http://terraserver.microsoft.com/TerraService2.asmx?WSDL" ## $terraServer = Connect-WebService $wsdl ## $place = New-Object Place ## $place.City = "Redmond" ## $place.State = "WA" ## $place.Country = "USA" ## $facts = $terraserver.GetPlaceFacts($place) ## $facts.Center ############################################################################## # param( # [string] $wsdlLocation = $(throw "Please specify a WSDL location"), # [string] $namespace, # [Switch] $requiresAuthentication) ## Create the web service cache, if it doesn't already exist if(-not (Test-Path Variable:\\Lee.Holmes.WebServiceCache)) { ${GLOBAL:Lee.Holmes.WebServiceCache} = @{} } ## Check if there was an instance from a previous connection to ## this web service. If so, return that instead. $oldInstance = ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation] if($oldInstance) { $oldInstance return } ## Load the required Web Services DLL [void] [Reflection.Assembly]::LoadWithPartialName("System.Web.Services") ## Download the WSDL for the service, and create a service description from ## it. $wc = new-object System.Net.WebClient if($requiresAuthentication) { $wc.UseDefaultCredentials = $true } $wsdlStream = $wc.OpenRead($wsdlLocation) ## Ensure that we were able to fetch the WSDL if(-not (Test-Path Variable:\\wsdlStream)) { return } $serviceDescription = [Web.Services.Description.ServiceDescription]::Read($wsdlStream) $wsdlStream.Close() ## Ensure that we were able to read the WSDL into a service description if(-not (Test-Path Variable:\\serviceDescription)) { return } ## Import the web service into a CodeDom $serviceNamespace = New-Object System.CodeDom.CodeNamespace if($namespace) { $serviceNamespace.Name = $namespace } $codeCompileUnit = New-Object System.CodeDom.CodeCompileUnit $serviceDescriptionImporter = New-Object Web.Services.Description.ServiceDescriptionImporter $serviceDescriptionImporter.AddServiceDescription( $serviceDescription, $null, $null) [void] $codeCompileUnit.Namespaces.Add($serviceNamespace) [void] $serviceDescriptionImporter.Import( $serviceNamespace, $codeCompileUnit) ## Generate the code from that CodeDom into a string $generatedCode = New-Object Text.StringBuilder $stringWriter = New-Object IO.StringWriter $generatedCode $provider = New-Object Microsoft.CSharp.CSharpCodeProvider $provider.GenerateCodeFromCompileUnit($codeCompileUnit, $stringWriter, $null) ## Compile the source code. $references = @("System.dll", "System.Web.Services.dll", "System.Xml.dll") $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters $compilerParameters.ReferencedAssemblies.AddRange($references) $compilerParameters.GenerateInMemory = $true $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $generatedCode) ## Write any errors if generated. if($compilerResults.Errors.Count -gt 0) { $errorLines = "" foreach($error in $compilerResults.Errors) { $errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText } Write-Error $errorLines return } ## There were no errors. Create the webservice object and return it. else { ## Get the assembly that we just compiled $assembly = $compilerResults.CompiledAssembly ## Find the type that had the WebServiceBindingAttribute. ## There may be other "helper types" in this file, but they will ## not have this attribute $type = $assembly.GetTypes() | Where-Object { $_.GetCustomAttributes( [System.Web.Services.WebServiceBindingAttribute], $false) } if(-not $type) { Write-Error "Could not generate web service proxy." return } ## Create an instance of the type, store it in the cache, ## and return it to the user. $instance = $assembly.CreateInstance($type) ## Many services that support authentication also require it on the ## resulting objects if($requiresAuthentication) { if(@($instance.PsObject.Properties | where { $_.Name -eq "UseDefaultCredentials" }).Count -eq 1) { $instance.UseDefaultCredentials = $true } } ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation] = $instance $instance } } function global:get-JiraServerInfo { $jira.GetServerInfo($jiraAuthID) } function global:get-JiraIssueType { $jira.GetIssueTypes($jiraAuthID) } function global:get-JiraSubtaskIssueType { $jira.GetSubtaskIssueTypes($jiraAuthID) } function global:get-JiraStatus { $jira.GetStatuses($jiraAuthID) } function global:get-JiraPriority { $jira.GetPriorities($jiraAuthID) } function global:get-JiraResolution { $jira.GetResolutions($jiraAuthID) } function global:get-JiraReport { $jira.GetSavedFilters($jiraAuthID) } function global:get-JiraProject { $jira.GetProjects($jiraAuthID) } function global:get-JiraComment ($issueKey) { $jira.GetComments($jiraAuthID,$issueKey) } function global:new-JiraComment ($issueKey, $comment) { $jiraComment = new-object RemoteComment $jiraComment.body = $comment $jira.AddComment($jiraAuthID, $issueKey, $jiraComment) } function global:export-JiraReport ($reportNumber) { $jira.GetIssuesFromFilter($jiraAuthID, $reportNumber) } # needs work function global:update-JiraIssue ([string]$issueKey) { $jira.UpdateIssue($jiraAuthID,$issueKey,$placeholder) } # needs work function global:set-JiraIssueStatus ($issueKey,$actionID,$placeholder) { $jira.ProgressWorkflowAction($jiraAuthID,$issueKey,$actionID,$placeholder) } function global:get-JiraIssue ($issueKey) { $jira.GetIssue($jiraAuthID, $issueKey) } function global:new-JiraIssue ($project, $type, $summary, $description) { $jiraIssue = new-object RemoteIssue $jiraIssue.project = $project $jiraIssue.type = $type $jiraIssue.summary = $summary $jiraIssue.description = $description $newIssue = $jira.CreateIssue($jiraAuthID, $jiraIssue) $newIssue } function global:disconnect-jira { $jira.logout($jiraAuthID) } $global:jira = connect-jira $jiraURL if (!$credential) { $global:credential = get-credential } $BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($credential.Password) $global:jiraAuthID = $jira.login($credential.UserName.TrimStart("\\"),[System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR)) [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR);
PowerShellCorpus/PoshCode/Compile-Help_2.ps1
Compile-Help_2.ps1
# Compile-Help.ps1 # by Jeff Hillman # # this script uses the text and XML PowerShell help files to generate HTML help # for all PowerShell Cmdlets, PSProviders, and "about" topics. the help topics # are compiled into a .chm file using HTML Help Workshop. # # Minor tweak by John Robbins to work on x64 when looking for HHC.EXE. param( [string] $outDirectory = ".\\PSHelp", [switch] $GroupByPSSnapIn ) function Html-Encode( [string] $value ) { # System.Web.HttpUtility.HtmlEncode() doesn't quite get everything, and # I don't want to load the System.Web assembly just for this. I'm sure # I missed something here, but these are the characters I saw that needed # to be encoded most often $value = $value -replace "&(?![\\w#]+;)", "&amp;" $value = $value -replace "<(?!!--)", "&lt;" $value = $value -replace "(?<!--)>", "&gt;" $value = $value -replace "’", "&#39;" $value = $value -replace '["“”]', "&quot;" $value = $value -replace "\\n", "<br />" $value } function Capitalize-Words( [string] $value ) { $capitalizedString = "" # convert the string to lower case and split it into individual words. for each one, # capitalize the first character, and append it to the converted string [regex]::Split( $value.ToLower(), "\\s" ) | ForEach-Object { $capitalizedString += ( [string]$_.Chars( 0 ) ).ToUpper() + $_.SubString( 1 ) + " " } $capitalizedString.Trim() } function Get-ParagraphedHtml( [string] $xmlText ) { $value = "" if ( $xmlText -match "<(\\w+:)?para" ) { $value = "" $options = [System.Text.RegularExpressions.RegexOptions]::Singleline foreach ( $match in [regex]::Matches( $xmlText, "<(?:\\w+:)?para[^>]*>(?<Text>.*?)</(?:\\w+:)?para>", $options ) ) { $value += "<p>$( Html-Encode $match.Groups[ 'Text' ].Value )</p>" } } else { $value = Html-Encode $xmlText } $value } function Get-SyntaxHtml( [xml] $syntaxXml ) { $syntaxHtml = "" # generate the HTML for each form of the Cmdlet syntax foreach ( $syntaxItem in $syntaxXml.syntax.syntaxItem ) { if ( $syntaxHtml -ne "" ) { $syntaxHtml += "<br /><br />`n" } $syntaxHtml += " $( $syntaxItem.name.get_InnerText().Trim() ) " if ( $syntaxItem.parameter ) { foreach ( $parameter in $syntaxItem.parameter ) { $required = [bool]::Parse( $parameter.required ) $syntaxHtml += "<nobr>[-$( $parameter.name.get_InnerText().Trim() )" if ( $required ) { $syntaxHtml += "]" } if ( $parameter.parameterValue ) { $syntaxHtml += " &lt;$( $parameter.parameterValue.get_InnerText().Trim() )&gt;" } if ( !$required ) { $syntaxHtml += "]" } $syntaxHtml += "</nobr> " } } $syntaxHtml += " <nobr>[&lt;CommonParameters&gt;]</nobr>" } $syntaxHtml.Trim() } function Get-ParameterHtml( [xml] $parameterXml ) { $parameterHtml = "" # generate HTML for each parameter foreach ( $parameter in $parameterXml.parameters.parameter ) { if ( $parameterHtml -ne "" ) { $parameterHtml += " <br /><br />`n" } $parameterHtml += " <nobr><span class=`"boldtext`">-$( $parameter.name.get_InnerText().Trim() )" if ( $parameter.parameterValue ) { $parameterHtml += " &lt;$( $parameter.parameterValue.get_InnerText().Trim() )&gt;" } $parameterHtml += "</span></nobr>`n" $parameterHtml += @" <br /> <div id="contenttext"> $( Get-ParagraphedHtml $parameter.description.get_InnerXml().Trim() ) "@ if ( $parameter.possibleValues ) { foreach ( $possibleValue in $parameter.possibleValues.possibleValue ) { $parameterHtml += @" $( $possibleValue.value.Trim() )<br /> "@ if ( $possibleValue.description.get_InnerText().Trim() -ne "" ) { $parameterHtml += @" <div id="contenttext"> $( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() ) </div> "@ } } } $parameterHtml += @" <br /> </div> <table class="parametertable"> <tr> <td>Required</td> <td>$( $parameter.required )</td> </tr> <tr> <td>Position</td> <td>$( $parameter.position )</td> </tr> <tr> <td>Accepts pipeline input</td> <td>$( $parameter.pipelineInput )</td> </tr> <tr> <td>Accepts wildcard characters</td> <td>$( $parameter.globbing )</td> </tr> "@ if ( $parameter.defaultValue ) { if( $parameter.defaultValue.get_InnerText().Trim() -ne "" ) { $parameterHtml += @" <tr> <td>Default Value</td> <td>$( $parameter.defaultValue.get_InnerText().Trim() )</td> </tr> "@ } } $parameterHtml += @" </table> "@ } if ( $parameterHtml -ne "" ) { $parameterHtml += " <br /><br />`n" } $parameterHtml += @" <nobr><span class="boldtext">&lt;CommonParameters&gt;</span></nobr> <br /> <div id="contenttext"> <p> For more information about common parameters, type "Get-Help about_commonparameters". </p> </div> "@ $parameterHtml.Trim() } function Get-InputHtml( [xml] $inputXml ) { $inputHtml = "" $inputCount = 0 # generate HTML for each input type foreach ( $inputType in $inputXml.inputTypes.inputType ) { if ( $inputHtml -ne "" ) { $inputHtml += " <br /><br />`n" } if ( $inputType.type.name.get_InnerText().Trim() -ne "" -or $inputType.type.description.get_InnerText().Trim() -ne "" ) { $inputHtml += " $( $inputType.type.name.get_InnerText().Trim() )`n" $inputHtml += @" <div id="contenttext"> $( Get-ParagraphedHtml $inputType.type.description.get_InnerXml().Trim() ) </div> "@ $inputCount++ } } $inputHtml.Trim() $inputCount } function Get-ReturnHtml( [xml] $returnXml ) { $returnHtml = "" $returnCount = 0 # generate HTML for each return value foreach ( $returnValue in $returnXml.returnValues.returnValue ) { if ( $returnHtml -ne "" ) { $returnHtml += " <br /><br />`n" } if ( $returnValue.type.name.get_InnerText().Trim() -ne "" -or $returnValue.type.description.get_InnerText().Trim() -ne "" ) { $returnHtml += " $( $returnValue.type.name.get_InnerText().Trim() )`n" $returnHtml += @" <div id="contenttext"> $( Get-ParagraphedHtml $returnValue.type.description.get_InnerXml().Trim() ) </div> "@ $returnCount++ } } $returnHtml.Trim() $returnCount } function Get-ExampleHtml( [xml] $exampleXml ) { $exampleHtml = "" $exampleTotalCount = 0 $exampleCount = 0 foreach ( $example in $exampleXml.examples.example ) { $exampleTotalCount++ } # generate HTML for each example foreach ( $example in $exampleXml.examples.example ) { if ( $example.code -and $example.code.get_InnerText().Trim() -ne "" ) { if ( $exampleHtml -ne "" ) { $exampleHtml += " <br />`n" } if ( $exampleTotalCount -gt 1 ) { $exampleHtml += " <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n" } $exampleCodeHtml = "$( Html-Encode $example.introduction.get_InnerText().Trim() )" + "$( Html-Encode $example.code.get_InnerText().Trim() )" $exampleHtml += " <div class=`"syntaxregion`">$exampleCodeHtml</div>`n" $foundFirstPara = $false foreach ( $para in $example.remarks.para ) { if ( $para.get_InnerText().Trim() -ne "" ) { # the first para is generally the description of the example. # other para tags usually contain sample output if ( !$foundFirstPara ) { $exampleHtml += @" <div id="contenttext"> <p> $( Html-Encode $para.get_InnerText().Trim() ) </p> </div> "@ $foundFirstPara = $true } else { $exampleHtml += @" <pre class="syntaxregion">$( $( ( Html-Encode $para.get_InnerText().Trim() ) -replace "<br />", "`n" ) )</pre> "@ } } } $exampleCount++ } } $exampleHtml.Trim() $exampleCount } function Get-TaskExampleHtml( [xml] $exampleXml ) { $exampleHtml = "" $exampleCount = 0 $exampleTotalCount = 0 foreach ( $example in $exampleXml.examples.example ) { $exampleTotalCount++ } # generate HTML for each example foreach ( $example in $exampleXml.examples.example ) { if ( $exampleHtml -ne "" ) { $exampleHtml += " <br />`n" } if ( $exampleTotalCount -gt 1 ) { $exampleHtml += " <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n" } $exampleHtml += " <div>$( Get-ParagraphedHtml $example.introduction.get_InnerXml().Trim() )</div>`n" $exampleCodeHtml = ( Html-Encode $example.code.Trim() ) -replace "<br />", "`n" $exampleHtml += " <pre class=`"syntaxregion`">$exampleCodeHtml</pre>" $exampleHtml += " <div>$( Get-ParagraphedHtml $example.remarks.get_InnerXml().Trim() )</div>`n" $exampleCount++ } $exampleHtml.Trim() } function Get-LinkHtml( [xml] $linkXml ) { $linkHtml = "" $linkCount = 0 # generate HTML for each related link foreach ( $navigationLink in $linkXml.relatedLinks.navigationLink ) { if ( $navigationLink.linkText -and ` ( $helpHash.Keys | Foreach-Object { $_.ToUpper() } ) -contains $navigationLink.linkText.Trim().ToUpper() ) { $linkHtml += " $( $navigationLink.linkText.Trim() )<br />`n" $linkCount++ } } $linkHtml.Trim() $linkCount } function Get-TaskHtml( [xml] $taskXml ) { $taskHtml = "" $taskCount = 0 foreach ( $task in $taskXml.tasks.task ) { if ( $taskHtml -ne "" ) { $taskHtml += " <br />`n" } $taskHtml += " <nobr><span class=`"boldtext`">Task:</span> $( $task.title.Trim() )</nobr>`n" $taskDescriptionHtml = ( Get-ParagraphedHtml $task.description.get_InnerXml().Trim() ) $taskHtml += " <div id=`"contenttext`">$taskDescriptionHtml</div>`n" # add the example sections if ( $task.examples ) { $taskHtml += @" <div id="contenttext"> <p> $( Get-TaskExampleHtml ( [xml]$task.examples.get_OuterXml() ) ) </p> </div> "@ } $taskCount++ } $taskHtml.Trim() $taskCount } function Get-DynamicParameterHtml( [xml] $dynamicParameterXml ) { $dynamicParameterHtml = "" # generate HTML for each dynamic parameter foreach ( $dynamicParameter in $dynamicParameterXml.dynamicparameters.dynamicparameter ) { $dynamicParameterHtml += " <nobr><span class=`"boldtext`">-$( $dynamicParameter.name.Trim() )" if ( $dynamicParameter.type ) { $dynamicParameterHtml += " &lt;$( $dynamicParameter.type.name.Trim() )&gt;" } $dynamicParameterHtml += "</span></nobr>`n" $dynamicParameterHtml += @" <br /> <div id="contenttext"> <p> $( Html-Encode $dynamicParameter.description.Trim() ) </p> "@ if ( $dynamicParameter.possiblevalues ) { foreach ( $possibleValue in $dynamicParameter.possiblevalues.possiblevalue ) { $dynamicParameterHtml += @" <div id="contenttext"> <span class=`"boldtext`">$( $possibleValue.value )</span> <div id="contenttext"> $( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() ) </div> </div> "@ } } $dynamicParameterHtml += @" <br /> <span class=`"boldtext`">Cmdlets Supported</span> <div id="contenttext"> <p> $( Html-Encode $dynamicParameter.cmdletsupported.Trim() ) </p> </div> </div> <br /> "@ } $dynamicParameterHtml.Trim() } function Write-AboutTopic( [string] $topicName, [string] $topicPath ) { # just dump the contents of the about topic exactly as it is. the only changes needed # are to encode the special HTML characters and add topic links $topicHtml = @" <html> <head> <link rel="stylesheet" type="text/css" href="powershell.css" /> <title>About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() )</title> </head> <body> <div id="topicheading"> <div id="topictitle">PowerShell Help</div> About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() ) </div> <pre> $( ( Html-Encode ( [string]::Join( [Environment]::NewLine, ( Get-Content -Path $topicPath ) ) ) ) -replace "<br />" ) </pre> </body> </html> "@ $topicHtml = Add-Links $topicName $topicHtml Out-File -FilePath "$outDirectory\\Topics\\$topicName.html" -Encoding Ascii -Input $topicHtml } function Write-ProviderTopic( [string] $providerFullName, [xml] $providerXml ) { $providerName = $providerXml.providerhelp.Name.Trim() $topicHtml = @" <html> <head> <link rel="stylesheet" type="text/css" href="powershell.css" /> <title>$providerName Help</title> </head> <body> <div id="topicheading"> <div id="topictitle">PowerShell Help</div> $providerName Provider <div style="text-align: right; padding-right: 3px;"> $( $providerFullName -replace "^\\w+\\." ) </div> </div> <div class="categorytitle">Drives</div> <div id="contenttext"> $( Get-ParagraphedHtml $providerXml.providerhelp.drives.get_InnerXml().Trim() ) </div> <div class="categorytitle">Synopsis</div> <div id="contenttext"> <p>$( Html-Encode $providerXml.providerhelp.synopsis.Trim() )</p> </div> "@ $topicHtml += @" <div class="categorytitle">Description</div> <div id="contenttext"> $( Get-ParagraphedHtml $providerXml.providerhelp.detaileddescription.get_InnerXml().Trim() ) </div> "@ if ( $providerXml.providerhelp.capabilities.get_InnerText().Trim() -ne "" ) { $topicHtml += @" <div class="categorytitle">Capabilities</div> <div id="contenttext"> $( Get-ParagraphedHtml $providerXml.providerhelp.capabilities.get_InnerXml().Trim() ) </div> "@ } $taskHtml, $taskCount = Get-TaskHtml( $providerXml.providerhelp.tasks.get_OuterXml() ) if ( $taskCount -gt 0 ) { $topicHtml += @" <div class="categorytitle">Task$( if ( $taskCount -gt 1 ) { "s" } )</div> <div id="contenttext"> $taskHtml </div> "@ } if ( $providerXml.providerhelp.dynamicparameters ) { $topicHtml += @" <div class="categorytitle">Dynamic Parameters</div> <div id="contenttext"> $( Get-DynamicParameterHtml( $providerXml.providerhelp.dynamicparameters.get_OuterXml() ) ) </div> "@ } if ( $providerXml.providerhelp.notes.Trim() -ne "" ) { $topicHtml += @" <div class="categorytitle">Notes</div> <div id="contenttext"> <p>$( Html-Encode $providerXml.providerhelp.notes.Trim() )</p> </div> "@ } $topicHtml += @" <div class="categorytitle">Related Links</div> <div id="contenttext"> <p>$( Html-Encode $providerXml.providerhelp.relatedlinks.Trim() )</p> </div> <br /> </body> </html> "@ $topicHtml = Add-Links $providerName $topicHtml Out-File -FilePath "$outDirectory\\Topics\\$providerFullName.html" -Encoding Ascii -Input $topicHtml } function Write-CmdletTopic( [string] $cmdletFullName, [xml] $cmdletXml ) { $cmdletName = $cmdletXml.command.details.name.Trim() # add the heading, syntax section, and description $topicHtml = @" <html> <head> <link rel="stylesheet" type="text/css" href="powershell.css" /> <title>$cmdletName Help</title> </head> <body> <div id="topicheading"> <div id="topictitle">PowerShell Help</div> $cmdletName Cmdlet <div style="text-align: right; padding-right: 3px;"> $( $cmdletFullName -replace "^\\w+-\\w+\\." ) </div> </div> <div class="categorytitle">Synopsis</div> <div id="contenttext"> $( Get-ParagraphedHtml $cmdletXml.command.details.description.get_InnerXml().Trim() ) </div> <div class="categorytitle">Syntax</div> <div id="contenttext"> <div class="syntaxregion">$( Get-SyntaxHtml ( [xml]$cmdletXml.command.syntax.get_OuterXml() ) )</div> </div> <div class="categorytitle">Description</div> <div id="contenttext"> $( Get-ParagraphedHtml $cmdletXml.command.description.get_InnerXml().Trim() ) </div> "@ # add the parameters section if ( $cmdletXml.command.parameters ) { $topicHtml += @" <div class="categorytitle">Parameters</div> <div id="contenttext"> <p> $( Get-ParameterHtml ( [xml]$cmdletXml.command.parameters.get_OuterXml() ) ) </p> </div> "@ } else { $topicHtml += @" <div class="categorytitle">Parameters</div> <div id="contenttext"> <p> <nobr><span class="boldtext">&lt;CommonParameters&gt;</span></nobr><br /> <div id="contenttext"> <p> For more information about common parameters, type "Get-Help about_commonparameters". </p> </div> </p> </div> "@ } # add the input types section if ( $cmdletXml.command.inputTypes ) { $inputHtml, $inputCount = Get-InputHtml ( [xml]$cmdletXml.command.inputTypes.get_OuterXml() ) if ( $inputCount -gt 0 ) { $topicHtml += @" <div class="categorytitle">Input Type$( if ( $inputCount -gt 1 ) { "s" } )</div> <div id="contenttext"> $inputHtml </div> "@ } } # add the return values section if ( $cmdletXml.command.returnValue ) { $returnHtml, $returnCount = Get-ReturnHtml ( [xml]$cmdletXml.command.returnValues.get_OuterXml() ) if ( $returnCount -gt 0 ) { $topicHtml += @" <div class="categorytitle">Return Value$( if ( $returnCount -gt 1 ) { "s" } )</div> <div id="contenttext"> $returnHtml </div> "@ } } # add the notes section if ( $cmdletXml.command.alertSet ) { if ( $cmdletXml.command.alertSet.get_InnerText().Trim() -ne "" ) { $topicHtml += @" <div class="categorytitle">Notes</div> <div id="contenttext"> $( Get-ParagraphedHtml $cmdletXml.command.alertSet.get_InnerXml().Trim() ) </div> "@ } } # add the example section if ( $cmdletXml.command.examples ) { $exampleHtml, $exampleCount = Get-ExampleHtml ( [xml]$cmdletXml.command.examples.get_OuterXml() ) if ( $exampleCount -gt 0 ) { $topicHtml += @" <div class="categorytitle">Example$( if ( $exampleCount -gt 1 ) { "s" } )</div> <div id="contenttext"> <p> $exampleHtml </p> </div> "@ } } # add the related links section if ( $cmdletXml.command.relatedLinks ) { $linkHtml, $linkCount = Get-LinkHtml ( [xml]$cmdletXml.command.relatedLinks.get_OuterXml() ) if ( $linkCount -gt 0 ) { $topicHtml += @" <div class="categorytitle">Related Link$( if ( $linkCount -gt 1 ) { "s" } )</div> <div id="contenttext"> <p> $linkHtml </p> </div> <br /> "@ } else { $topicHtml += " <br />`n" } } else { $topicHtml += " <br />`n" } $topicHtml += @" </body> </html> "@ $topicHtml = Add-Links $cmdletName $topicHtml Out-File -FilePath "$outDirectory\\Topics\\$cmdletFullName.html" -Encoding Ascii -Input $topicHtml } function Add-Links( [string] $topicName, [string] $topicHtml ) { # we only want to add links for Cmdlets and about topics $helpHash.Keys | Where-Object { $_ -match "(^\\w+-\\w+|^about_)" } | Foreach-Object { $searchText = $_ # keys representing Cmdlets are formatted like this: # <Cmdlet Name>.<PSProvider name> if ( $_ -match "^\\w+-\\w+" ) { # we only want to search for the Cmdlet name $searchText = $matches[ 0 ] } # if the search text isn't the topic being processed if ( $searchText -ne $topicName ) { $topicHtml = $topicHtml -replace "\\b($searchText)\\b", "<a href=`"Topics\\$_.html`"><nobr>`$1</nobr></a>" } } $topicHtml } # file dumping functions function Write-Hhp { # write the contents of the Html Help Project file Out-File -FilePath "$outDirectory\\powershell.hhp" -Encoding Ascii -Input @" [OPTIONS] Binary TOC=Yes Compatibility=1.1 or later Compiled file=PowerShell.chm Contents file=powershell.hhc Default topic=Topics/default.html Full-text search=Yes Language=0x409 English (United States) Title=PowerShell Help [INFOTYPES] "@ } function Write-DefaultPage { $defaultHtml = @" <html> <head> <link rel="stylesheet" type="text/css" href="powershell.css" /> <title>PowerShell Help</title> </head> <body style="margin: 5px 5px 5px 5px; color: #FFFFFF; background-color: #C86400;"> <h2>Windows PowerShell Help</h2> <br /> This complied help manual contains the help for all of the built-in PowerShell Cmdlets and PSProviders, as well as the help for any Cmdlets or PSProviders added through Add-PSSnapin, if help for them is available. Also included are all of the "about" topics. <br /><br /> To use this manual from the PowerShell command line, add the following function and alias to your PowerShell profile: <div id="contenttext"> <pre class="syntaxregion">function Get-CompiledHelp( [string] `$topic ) { if ( `$topic ) { # Get-Command will fail if the topic is a PSProvider or an "about" topic. `$ErrorActionPreference = "SilentlyContinue" # we don't want Get-Command to resolve to an application or a function `$command = Get-Command `$topic | Where-Object { `$_.CommandType -match "Alias|Cmdlet" } # if the topic is an alias or a Cmdlet, combine its name with # its PSProvider to get the full name of the help file if ( `$command -and `$command.CommandType -eq "Alias" ) { `$topic = "`$( `$command.Definition ).`$( `$command.ReferencedCommand.PSSnapIn.Name )" } elseif ( `$command -and `$command.CommandType -eq "Cmdlet" ) { `$topic = "`$( `$command.Name ).`$( `$command.PSSnapIn.Name )" } else { # check to see if we have a PSProvider `$psProvider = Get-PSProvider `$topic if ( `$psProvider ) { `$topic = "`$( `$psProvider.Name ).`$( `$psProvider.PSSnapIn.Name )" } } hh.exe "mk:@MSITStore:$( Resolve-Path "$outDirectory" )\\PowerShell.chm::/Topics/`$topic.html" } else { hh.exe "$( Resolve-Path "$outDirectory" )\\PowerShell.chm" } } Set-Alias chelp Get-CompiledHelp</pre> </div> <br /> The path in the Get-CompliedHelp function corresponds to the location where this compiled help manual was originally created. If this file is moved to another location, the path in the function will need to be updated. <br /> <br /> To view the help topic for Get-ChildItem, type the following: <div id="contenttext"> <div class="syntaxregion">PS$ Get-CompiledHelp Get-ChildItem</div> </div> <br /> Because "ls" is an alias for Get-ChildItem, and "chelp" is an alias for Get-CompliedHelp, the following also works: <div id="contenttext"> <div class="syntaxregion">PS$ chelp ls</div> </div> </body> </html> "@ $defaultHtml = Add-Links "" $defaultHtml Out-File -FilePath "$outDirectory\\Topics\\default.html" -Encoding Ascii -Input $defaultHtml } function Write-Css { Out-File -FilePath "$outDirectory\\powershell.css" -Encoding Ascii -Input @" body { margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 70%; width: 100%; } div#topicheading { position: relative; left: 0px; padding: 5px 0px 5px 10px; border-bottom: 1px solid #999999; color: #FFFFFF; background-color: #C86400; font-size: 110%; font-weight: bold; text-align: left; } div#topictitle { padding: 5px 5px 5px 5px; color: #FFFFFF font-size: 90%; font-weight: normal; } div#contenttext { top: 0px; padding: 0px 25px 0px 25px; } p { margin: 5px 0px 5px 0px; } a:link { color: #0000FF; } a:visited { color: #0000FF; } a:hover { color: #3366FF; } table.parametertable { margin-left: 25px; font-size: 100%; border-collapse:collapse } table.parametertable td { font-size: 100%; border: solid #999999 1px; padding: 0in 5.4pt 0in 5.4pt } pre.syntaxregion, div.syntaxregion { background: #DDDDDD; padding: 4px 8px; cursor: text; margin-top: 1em; margin-bottom: 1em; margin-left: .6em; color: #000000; border-width: 1px; border-style: solid; border-color: #999999; } .categorytitle { padding-top: .8em; font-size: 110%; font-weight: bold; text-align: left; margin-left: 5px; } .boldtext { font-weight: bold; } "@ } ### main ### # create the topics directory New-Item -Type Directory -Path "$outDirectory" -Force | Out-Null New-Item -Type Directory -Path "$outDirectory\\Topics" -Force | Out-Null "`nRetrieving help content...`n" # initialize variables for HHC file $hhcContentsHtml = "" $cmdletCategoryHtml = "" $cmdletCategoryHash = @{} # help content hash $helpHash = @{} # get the Cmdlet help Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object { $psSnapInName = $_.Name $helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile # the culture needs to be added to the path on Vista if ( !( Test-Path $helpFilePath ) ) { $helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )" } if ( Test-Path $helpFilePath ) { $helpXml = [xml]( Get-Content $helpFilePath ) $cmdletCategoryContents = "" Get-Command -PSSnapIn $_ | Foreach-Object { $commandName = $_.Name $helpXml.helpitems.command | Where-Object { $_.details.name -and $_.details.name.Trim() -imatch "\\b$commandName\\b" } | Foreach-Object { # add the Xml Help of the Cmdlet to the help hashtable $helpHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $_.get_OuterXml() $cmdletTopicItem = @" <li><object type="text/sitemap"> <param name="Name" value="$commandName"> <param name="Local" value="Topics\\$( "{0}.{1}" -f $commandName, $psSnapInName ).html"> </object> "@ if ( $GroupByPSSnapIn ) { $cmdletCategoryContents += $cmdletTopicItem } else { # save the topics so they can be sorted properly and added to the HHC later $cmdletCategoryHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $cmdletTopicItem } } } if ( $GroupByPSSnapIn ) { # add a category in the HHC for this PSSnapIn and its Cmdlets $cmdletCategoryHtml += @" <li><object type="text/sitemap"> <param name="Name" value="$psSnapInName"> </object> <ul> $( $cmdletCategoryContents.Trim() ) </ul> "@ } } } # sort the Cmdlets so they are added to the HHC in a logical order if ( !$GroupByPSSnapIn ) { $cmdletCategoryHash.Keys | Sort-Object | Foreach-Object { $cmdletCategoryHtml += $cmdletCategoryHash[ $_ ] } } # add the Cmdlet category to the HHC $hhcContentsHtml += @" <li><object type="text/sitemap"> <param name="Name" value="Cmdlet Help"> </object> <ul> $( $cmdletCategoryHtml.Trim() ) </ul> "@ $providerCategoryHtml = "" $providerCategoryHash = @{} # get the PSProvider help Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object { $psSnapInName = $_.Name $helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile # the culture needs to be added to the path on Vista if ( !( Test-Path $helpFilePath ) ) { $helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )" } if ( Test-Path $helpFilePath ) { $helpXml = [xml]( Get-Content $helpFilePath ) $providerCategoryContents = "" Get-PSProvider | Where-Object { $_.PSSnapin.Name -eq $psSnapInName } | Foreach-Object { $psProviderName = $_.Name $helpXml.helpitems.providerhelp | Where-Object { $_.name.Trim() -imatch "\\b$psProviderName\\b" } | Foreach-Object { $helpHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $_.get_OuterXml() # add a category in the HHC for this PSProvider $providerTopicItem = @" <li><object type="text/sitemap"> <param name="Name" value="$psProviderName"> <param name="Local" value="Topics\\$( "{0}.{1}" -f $psProviderName, $psSnapInName ).html"> </object> "@ if ( $GroupByPSSnapIn ) { $providerCategoryContents += $providerTopicItem } else { # save the topics so they can be sorted properly and added to the HHC later $providerCategoryHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $providerTopicItem } } } if ( $GroupByPSSnapIn -and $providerCategoryContents -ne "" ) { # add a category in the HHC for this PSSnapIn and its Cmdlets $providerCategoryHtml += @" <li><object type="text/sitemap"> <param name="Name" value="$psSnapInName"> </object> <ul> $( $providerCategoryContents.Trim() ) </ul> "@ } } } # sort the PSProviders so they are added to the HHC in a logical order if ( !$GroupByPSSnapIn ) { $providerCategoryHash.Keys | Sort-Object | Foreach-Object { $providerCategoryHtml += $providerCategoryHash[ $_ ] } } # add the PSProvider category to the HHC $hhcContentsHtml += @" <li><object type="text/sitemap"> <param name="Name" value="Provider Help"> </object> <ul> $( $providerCategoryHtml.Trim() ) </ul> "@ # get the about topics $about_TopicPaths = @() $helpPath = "" if ( Resolve-Path "$pshome\\about_*.txt" ) { $helpPath = "$pshome" } elseif ( Resolve-Path "$pshome\\$( $Host.CurrentUICulture.Name )\\about_*.txt" ) { $helpPath = "$pshome\\$( $Host.CurrentUICulture.Name )" } if ( Test-Path $helpPath ) { $about_TopicPaths += Get-ChildItem "$helpPath\\about_*.txt" } # we SilentlyContinue with Get-ChildItem errors because the ModuleName # for the built-in PSSnapins doesn't resolve to anything, since the assemblies # are only in the GAC. $about_TopicPaths += Get-PSSnapin | Foreach-Object { ( Get-ChildItem $_.ModuleName -ErrorAction "SilentlyContinue" ).DirectoryName } | Foreach-Object { Get-ChildItem "$_\\about_*.txt" } if ( $about_TopicPaths.Count -gt 0 ) { $aboutCategoryHtml = "" $about_TopicPaths | Sort-Object -Unique -Property @{ Expression = { $_.Name.ToUpper() } }| Foreach-Object { # pull the topic name out of the file name $name = ( $_.Name -replace "(.xml)?.help.txt", "`$1" ) # add the path of the topic to the help hashtable $helpHash[ $name ] = $_.FullName $topicName = Capitalize-Words ( $name -replace "(about)?_", " " ).Trim() # add a category in the HHC for this about topic $aboutCategoryHtml += @" <li><object type="text/sitemap"> <param name="Name" value="$topicName"> <param name="Local" value="Topics\\$name.html"> </object> "@ } # add the About Topics category to the HHC $hhcContentsHtml += @" <li><object type="text/sitemap"> <param name="Name" value="About Topics"> </object> <ul> $( $aboutCategoryHtml.Trim() ) </ul> "@ } # write the contents file Out-File -FilePath "$outDirectory\\powershell.hhc" -Encoding Ascii -Input @" <!doctype html public "-//ietf//dtd html//en"> <html> <head> <meta name="Generator" content="Microsoft&reg; HTML Help Workshop 4.1"> <!-- Sitemap 1.0 --> </head> <body> <object type="text/site properties"> <param name="Window Styles" value="0x800025"> </object> <ul> <li><object type="text/sitemap"> <param name="Name" value="PowerShell Help"> <param name="Local" value="Topics\\default.html"> </object> $( $hhcContentsHtml.Trim() ) </ul> </body> </html> "@ $helpHash.Keys | Sort-Object | Foreach-Object { switch -regex ( $_ ) { # about topic "about_" { "Creating help for the $_ about topic..." Write-AboutTopic $_ $helpHash[ $_ ] } # Verb-Noun: Cmdlet "\\w+-\\w+" { "Creating help for the $( $_ -replace '(^\\w+-\\w+).*', '$1' ) Cmdlet..." Write-CmdletTopic $_ $helpHash[ $_ ] } # PSProvider default { "Creating help for the $( $_ -replace '(^\\w+).*', '$1' ) PSProvider..." Write-ProviderTopic $_ $helpHash[ $_ ] } } } Write-DefaultPage Write-Css Write-Hhp $progDir = "C:\\Program Files" if ( $(Test-Path env:"ProgramFiles(x86)") -eq $True ) { $progDir = $(get-item env:"ProgramFiles(x86)").value } if ( Test-Path $progDir + "\\HTML Help Workshop\\hhc.exe" ) { # compile the help "`nCompiling the help manual...`n" Push-Location Set-Location $outDirectory & $progDir + "\\HTML Help Workshop\\hhc.exe" powershell.hhp Pop-Location # open the help file & "$outDirectory\\PowerShell.chm" } else { Write-Host -ForegroundColor Red @" HTML Help Workshop is not installed, or it was not installed in its default location of "C:\\Program Files [x86]\\HTML Help Workshop". HTML Help Workshop is required to compile the help manual. It can be downloaded free of charge from Microsoft: http://www.microsoft.com/downloads/details.aspx?familyid=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en If you do not want to install HTML Help Workshop on this machine, all of the files necessary to compile the manual have been created here: $( Resolve-Path $outDirectory ) Copy these files to a machine with HTML Help Workshop, and you can compile the manual there, with the following command: <HTML Help Workshop location>\\hhc.exe powershell.hhp "@ }
PowerShellCorpus/PoshCode/Get-InstalledProgram.ps1
Get-InstalledProgram.ps1
function Get-InstalledProgram() { param ( [String[]]$Computer, $User ) ############################################################################################# if ($User -is [String]) { $Connection = Get-Credential -Credential $User } ############################################################################################# foreach ($Comp in $Computer){ if ($Connection -eq $null){ $Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } else { $Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } } ############################################################################################# }
PowerShellCorpus/PoshCode/VMtoolsUpgrade.ps1
VMtoolsUpgrade.ps1
##################################################################### # # Purpose: "Check and upgrade Tools during power cycling" # Author: David Chung # Support: IT Infrastructure # Docs: N/A # # Instruction: 1. Create CSV file with list of servers # 2. Execute script from PowerCLI # 3. Enter virtual server name # ##################################################################### $viserver = read-host "Please enter vCenter Server:" connect-viserver $viserver $vms = Import-Csv c:\\server.csv foreach ($vm.name in $vms) { Write-Host $vm.name " - Enabling VMTools Update at Power Cycle" $vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo $vmConfig.Tools.ToolsUpgradePolicy = "UpgradeAtPowerCycle" Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)} }
PowerShellCorpus/PoshCode/Short PS Prompt.ps1
Short PS Prompt.ps1
<# .Synopsis Dynamically shortens the prompt based upon window size .Notes I got really annoyed by having my PowerShell prompt extend across 2/3 of my window when in a deeply-nested directory structure. This shortens the prompt to roughly 1/3 of the window width, at a minimum showing the first and last piece of the path (usually the PSPROVIDER & the current directory) Additional detail is added, starting at the current directory's parent and working up from there. The omitted portion of the path is represented with an ellipsis (...) #> # Window title borrowed from Joel Bennett @ http://poshcode.org/1834 # This should go OUTSIDE the prompt function, it doesn't need re-evaluation # We're going to calculate a prefix for the window title # Our basic title is "PoSh - C:\\Your\\Path\\Here" showing the current path if(!$global:WindowTitlePrefix) { # But if you're running "elevated" on vista, we want to show that ... if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ... new-object Security.Principal.WindowsPrincipal ( [Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { $global:WindowTitlePrefix = "PoSh (ADMIN)" } else { $global:WindowTitlePrefix = "PoSh" } } function prompt { # Put the full path in the title bar for reference $host.ui.rawui.windowtitle = $global:WindowTitlePrefix + " - " + $(get-location); # Capture the maximum length of the prompt. If you want a longer prompt, adjust the math as necessary. $winWidth = $host.UI.RawUI.WindowSize.Width; $maxPromptPath = [Math]::Round($winWidth/3); # In the PowerShell ISE (version 2.0 at least), $host.UI.RawUI.WindowSize.Widthis $null. # For now, I'm just going to leave the default prompt for this scenario, as I don't work in the ISE. if (-not ($winWidth -eq $null)) { $currPath = (get-location).path; if ($currPath.length -ge $maxPromptPath){ $pathParts = $currPath.split([System.IO.Path]::DirectorySeparatorChar); # Absolute minimum path - PSPROVIDER and the current directory $myPrompt = $pathParts[0] + [System.IO.Path]::DirectorySeparatorChar+ "..." + [System.IO.Path]::DirectorySeparatorChar + $pathParts[$pathParts.length - 1]; $counter = $pathParts.length - 2; # This builds up the prompt until it reaches the maximum length we set earlier. # Start at the current directory's parent and keep going up until the whole prompt reaches the previously-determined limit. while( ($myPrompt.replace("...","..."+[System.IO.Path]::DirectorySeparatorChar+$pathParts[$counter]).length -lt $maxPromptPath) -and ($counter -ne 0)) { $myPrompt = $myPrompt.replace("...","..."+[System.IO.Path]::DirectorySeparatorChar+$pathParts[$counter]); $counter--; } $($myPrompt) + ">"; } else{ # If there's enough room for the full prompt, use the Powershell default prompt $(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' + $(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> ' } } }
PowerShellCorpus/PoshCode/d657a0f0-47e1-4233-9e3b-cffc0495188f.ps1
d657a0f0-47e1-4233-9e3b-cffc0495188f.ps1
function Start-ISE () { <# .synopsis Load some file into ISE .Description Load some file into ISE .Parameter fileObjOrFileName file to be loaded .ReturnValue $null .Notes Author: bernd kriszio e-mail: bkriszio@googlemail.com Created: 2008-12-28 Requires: V2 CTP 3 Todo: I do not see the solution using advanced functions for a variable number of arguments Start-ISE .\\foo.ps1 .\\bar.ps1 fails. .Example Start-ISE $profile .Example get-childitem *.ps1 | Start-ISE .Example 'foo.ps1', 'bar.ps1' | Start-ISE #> param( [Parameter(Position = 0, Mandatory=$false, ValueFromPipeline=$True)] $fileObjOrFileName ) PROCESS { if ($fileObjOrFileName -ne $null){ if ($fileObjOrFileName.gettype().Name -eq 'FileInfo'){ & "$PSHome\\powershell_ise.exe" $fileObjOrFileName.Fullname } elseif ($fileObjOrFileName.gettype().Name -eq 'String') { if(Test-path $fileObjOrFileName) { & "$PSHome\\powershell_ise.exe" "$fileObjOrFileName" } else { & "$PSHome\\powershell_ise.exe" "$(pwd)\\$fileObjOrFileName" } } } } <# End{ foreach ($file in $args) { if ($file.gettype().Name -eq 'FileInfo'){ & "$PSHome/powershell_ise.exe" $file.Fullname } elseif ($file.gettype().Name -eq 'String') { & "$PSHome/powershell_ise.exe" "$(pwd)\\$file" } } } #> }
PowerShellCorpus/PoshCode/Reflection Module 4.1.ps1
Reflection Module 4.1.ps1
#requires -version 2.0 # ALSO REQUIRES Autoload for some functionality (Latest version: http://poshcode.org/3173) # You should create a Reflection.psd1 with the contents: # @{ ModuleToProcess="Reflection.psm1"; RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="4.1.0.0" } #History: # 1.0 - First public release (March 19, 2010) # 2.0 - Private Build # - Included the Accelerator function inline # - Added a few default aliases # 3.0 - September 3, 2010 # - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!) # - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312 # 3.5 - January 28, 2011 # - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature # - Fixed alias exporting so aliases will show up now # - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies # 3.6 - January 28, 2011 # - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin # 3.7 - February 1, 2001 - NOT RELEASED # - Added [TransformAttribute] type # 3.8 - May 4, 2011 - NOT RELEASED # - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649) # 3.9 - May 25, 2011 - NOT RELEASED # - Added "Interface" parameter to Get-Type # 4.0 - Sept 27, 2011 # - Fix conflicts with PowerShell 3 # 4.1 - Oct 27, 2011 # - Fix PowerShell 3 changes so they don't break PowerShell 2 (huy!) Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TransformAttribute : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public override string ToString() { return string.Format("[Transform(Script='{{{0}}}')]", Script); } public override Object Transform( EngineIntrinsics engine, Object inputData) { try { Collection<PSObject> output = engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData ); if(output.Count > 1) { Object[] transformed = new Object[output.Count]; for(int i =0; i < output.Count;i++) { transformed[i] = output[i].BaseObject; } return transformed; } else if(output.Count == 1) { return output[0].BaseObject; } else { throw new ArgumentTransformationMetadataException(NoOutputMessage); } } catch (ArgumentTransformationMetadataException) { throw; } catch (Exception e) { throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e); } } public TransformAttribute() { this.Script = ScriptBlock.Create("{`$args}"); } public TransformAttribute( ScriptBlock Script ) { this.Script = Script; } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets information about one or more loaded types, or gets the possible values for an enumerated type or value. .Parameter Assembly The Assemblies to search for types. Can be an actual Assembly object or a regex to pass to Get-Assembly. .Parameter TypeName The type name(s) to search for (wildcard patterns allowed). .Parameter BaseType A Base type they should derive from (wildcard patterns allowed). .Parameter Interface An interface they should implement (wildcard patterns allowed). .Parameter Enum An enumeration to list all of enumeration values for .Parameter Namespace A namespace to restrict where we selsect types from (wildcard patterns allowed). .Parameter Force Causes Private types to be included .Example Get-Type Gets all loaded types (takes a VERY long time to print out) .Example Get-Type -Assembly ([PSObject].Assembly) Gets types from System.Management.Automation .Example [Threading.Thread]::CurrentThread.ApartmentState | Get-Type Gets all of the possible values for the ApartmentState property .Example [Threading.ApartmentState] | Get-Type Gets all of the possible values for an apartmentstate #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The assembly to collect types from [Parameter(ValueFromPipeline=$true)] [PsObject[]]$Assembly , # The type names to return from [Parameter(Mandatory=$false,Position=0)] [String[]]$TypeName , # The type names to return from [Parameter(Mandatory=$false)] [String[]]$Namespace , # A Base Type they should derive from [Parameter(Mandatory=$false)] [String[]]$BaseType , # An Interface they should implement [Parameter(Mandatory=$false)] [String[]]$Interface , # The enumerated value to get all of the possibilties of [Parameter(ParameterSetName="Enum")] [PSObject]$Enum , [Parameter()][Alias("Private","ShowPrivate")] [Switch]$Force ) process { if($psCmdlet.ParameterSetName -eq 'Enum') { if($Enum -is [Enum]) { [Enum]::GetValues($enum.GetType()) } elseif($Enum -is [Type] -and $Enum.IsEnum) { [Enum]::GetValues($enum) } else { throw "Specified Enum is neither an enum value nor an enumerable type" } } else { if($Assembly -as [Reflection.Assembly[]]) { ## This is what we expected, move along } elseif($Assembly -as [String[]]) { $Assembly = Get-Assembly $Assembly } elseif(!$Assembly) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } :asm foreach ($asm in $assembly) { Write-Verbose "Testing Types from Assembly: $($asm.Location)" if ($asm) { trap { if( $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) { $PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail") continue asm } Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail" Write-Debug $( $_.Exception.LoaderExceptions | Out-String ) continue asm } $asm.GetTypes() | Where { ( $Force -or $_.IsPublic ) -AND ( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND ( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND ( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND ( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 ) } } } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = "." , [Alias("Types")] [Switch]$Passthru , [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly. #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=0)] [string[]]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() | Where { $Assembly = $_ if($Name){ $( foreach($n in $Name){ if(Resolve-Path $n -ErrorAction 0) { $n = [Regex]::Escape( (Resolve-Path $n).Path ) } $Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n) } ) -contains $True } else { $true } } } } function Update-PSBoundParameters { #.Synopsis # Ensure a parameter value is set #.Description # Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it. #.Parameter Name # The name (key) of the parameter you want to set in PSBoundParameters #.Parameter Default # A Default value for the parameter, in case it's not already set #.Parameter Min # The Minimum allowed value for the parameter #.Parameter Max # The Maximum allowed value for the parameter #.Parameter PSBoundParameters # The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it) Param( [Parameter(Mandatory=$true, Position=0)] [String]$Name , [Parameter(Mandatory=$false, Position=1)] $Default , [Parameter()] $Min , [Parameter()] $Max , [Parameter(Mandatory=$true, Position=99)] $PSBoundParameters=$PSBoundParameters ) end { $outBuffer = $null ## If it's not set, and you passed a default, we set it to the default if($Default) { if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer)) { $PSBoundParameters[$Name] = $Default } } ## If you passed a $max, and it's set greater than $max, we set it to $max if($Max) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max) { $PSBoundParameters[$Name] = $Max } } ## If you passed a $min, and it's set less than $min, we set it to $min if($Min) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min) { $PSBoundParameters[$Name] = $Min } } $PSBoundParameters } } function Get-Constructor { <# .Synopsis Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type. .Description Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor. .Parameter Type The type to get the constructor for .Parameter Force Force inclusion of Private and Static constructors which are hidden by default. .Parameter NoWarn Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors. .Example Get-Constructor System.IO.FileInfo Description ----------- Gets all the information about the single constructor for a FileInfo object. .Example Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax Description ----------- Displays the constructor syntax for all of the *Info objects in the System.IO namespace. Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors. .Example $path = $pwd $driveName = $pwd.Drive $fileName = "$Profile" Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax } Description ----------- Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo. Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical. #> [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ParameterType")] [Type]$Type , [Switch]$Force , [Switch]$NoWarn ) process { $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *, @{ name = "TypeName"; expression = { $_.ReflectedType.FullName } }, @{ name = "Definition"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "Syntax"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "SafeSyntax"; expression = {Get-MemberSignature $_} } if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" } } } function Get-Method { <# .Synopsis Returns MethodInfo for the (public) methods of the specified Type. .Description Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method. .Parameter Type The type to get methods on .Parameter Name The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns) .Parameter Force Force inclusion of Private methods and property accessors which are hidden by default. #> [CmdletBinding(DefaultParameterSetName="Type")] param( [Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Type]$Type , [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)] [String[]]$Name ="*" , [Switch]$Definition , [Switch]$Force ) process { foreach($method in $type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } | # Hide the Property accessor methods Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } | Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } ) { $method | Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru | Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member AliasProperty Syntax Definition -Passthru | #Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru } } } function Get-MemberSignature { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [System.Reflection.MethodBase]$MethodBase, [Switch]$Simple ) process { $parameters = $( foreach($param in $MethodBase.GetParameters()) { # Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)" if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' } if($Simple) { '{0} {1}' -f $param.ParameterType.ToString(), $param.Name } else { '{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.ToString().TrimEnd('&'), $param.Name } } ) if($MethodBase.IsConstructor) { "New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')" } elseif($Simple) { "$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))" } elseif($MethodBase.IsStatic) { "[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))" } else { "[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))" } } } function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Get-Argument { param( [Type]$Target , [ref]$Method , [Array]$Arguments ) end { trap { write-error $_ break } $flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance" [Type[]]$Types = @( foreach($arg in $Arguments) { if($arg -is [type]) { $arg } else { $arg.GetType() } } ) try { Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)" $MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null) $Arguments if($MethodBase) { $Method.Value = $MethodBase.Name } } catch { } if(!$MethodBase) { Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):" $MethodBase = Get-Method $target $($Method.Value) if(@($MethodBase).Count -gt 1) { $i = 0 $i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:" [System.Reflection.MethodBase]$MethodBase = $MethodBase[$i] } ForEach($parameter in $MethodBase.GetParameters()) { $found = $false For($a =0;$a -lt $Arguments.Count;$a++) { if($argument[$a] -as $parameter.ParameterType) { Write-Output $argument[$a] if($a -gt 0 -and $a -lt $Arguments.Count) { $Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a) } elseif($a -eq 0) { $Arguments = $Arguments | Select -Last ($Arguments.Count - 1) } else { # a -eq count $Arguments = $Arguments | Select -First ($Arguments.Count - 1) } $found = $true break } } if(!$Found) { $userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)" if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) { Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType) } else { Write-Output ($userInput -as $parameter.ParameterType) } } } } } } function Invoke-Member { [CmdletBinding()] param( [parameter(position=10, valuefrompipeline=$true, mandatory=$true)] [allowemptystring()] $InputObject , [parameter(position=0, mandatory=$true)] [validatenotnullorempty()] $Member , [parameter(position=1, valuefromremainingarguments=$true)] [allowemptycollection()] $Arguments , [parameter()] [switch]$Static ) # begin { # if(!(get-member SafeSyntax -input $Member -type Property)){ # if(get-member Name -inpup $Member -Type Property) { # $Member = Get-Method $InputObject $Member.Name # } else { # $Member = Get-Method $InputObject $Member # } # } # $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax ) # } process { # if ($InputObject) # { # if ($InputObject | Get-Member $Member -static:$static) # { if ($InputObject -is [type]) { $target = $InputObject } else { $target = $InputObject.GetType() } if(Get-Member $Member -InputObject $InputObject -Type Properties) { $_.$Member } elseif($Member -match "ctor|constructor") { $Member = ".ctor" [System.Reflection.BindingFlags]$flags = "CreateInstance" $InputObject = $Null } else { [System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod" if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" } } [ref]$Member = $Member [Object[]]$Parameters = Get-Argument $Target $Member $Arguments [string]$Member = $Member.Value Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ") try { Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))" Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))" $target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters) } catch { Write-Warning $_.Exception if ($_.Exception.Innerexception -is [MissingMethodException]) { write-warning "Method argument count (or type) mismatch." } } # } else { # write-warning "Method $Member not found." # } # } } } function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias("Types")] [Type[]]$ParameterTypes , [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs , [Switch]$Static ) begin { if($Static) { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static" } else { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance" } } process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs -and -not $ParameterTypes) { $ParameterTypes = $withArgs | % { $_.GetType() } } elseif(!$ParameterTypes) { $ParameterTypes = [Type]::EmptyTypes } trap { continue } $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags) if(!$MemberInfo) { $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null) } if(!$MemberInfo) { $MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object { $MI = $_ [bool]$Accept = $MI.Name -eq $MethodName if($Accept){ Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)" [Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name) [Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value { $GenericTypes -Contains $this.ParameterType } -Passthru) $Accept = $ParameterTypes.Count -eq $Parameters.Count Write-Verbose " $Accept = $($Parameters.Count) Arguments" if($Accept) { for($i=0;$i -lt $Parameters.Count;$i++) { $Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType)) Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)" } } } return $Accept } | Sort { @($_.GetGenericArguments()).Count } | Select -First 1 } Write-Verbose "Time to make generic methods." Write-Verbose $MemberInfo [Type[]]$GenericParameters = @() [Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType) for($i=0;$i -lt $ParameterTypes.Count;$i++){ Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])" if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) { $GenericParameters += $ParameterTypes[$i] } $ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru } $ParameterTypes | Where-Object { $_.IsGeneric } Write-Verbose "$($GenericParameters -join ', ') generic parameters" $MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters ) Write-Verbose $MemberInfo if($WithArgs) { [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')" $MemberInfo.Invoke( $InputObject, $Arguments ) } else { $MemberInfo.Invoke( $InputObject ) } } } # get a reference to the Type $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") function Import-Namespace { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string]$Namespace , [Switch]$Force ) Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator } function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list System.Collections.Generic.List``1 $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator "List T", "GList" System.Collections.Generic.List``1 $list = New-Object "list t[string]" Creates two accelerators for the Generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate (without square brackets) .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64]) Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type]$Type ) process { # add a user-defined accelerator foreach($a in $Accelerator) { if($xlr8r::AddReplace) { $xlr8r::AddReplace( $a, $Type) } else { $null = $xlr8r::Remove( $a ) $xlr8r::Add( $a, $Type) } trap [System.Management.Automation.MethodInvocationException] { if($xlr8r::get.keys -contains $a) { if($xlr8r::get[$a] -ne $Type) { Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]" } Continue; } throw } } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator System.String Returns the KeyValue pair for the [System.String] accelerator(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pairs for the matching accelerator definition(s) .Parameter Accelerator One or more short form accelerators to search for (Accept wildcard characters). .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] param( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type[]]$Type ) process { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int Int64 Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator that you want to remove (Accept wildcard characters). .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","FullName")] [string[]]$Accelerator ) process { foreach($a in $Accelerator) { foreach($key in $xlr8r::Get.Keys -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]", "Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?", "Removing Type Accelerator" )) { # remove a user-defined accelerator $xlr8r::remove($key) } } } } } ############################################################################### ##### Imported from PowerBoots $Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree' $DependencyProperties = @{} if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) { #$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) ) $DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml } function Get-ReflectionModule { $executioncontext.sessionstate.module } function Set-ObjectProperties { [CmdletBinding()] param( $Parameters, [ref]$DObject ) if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() } if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White } foreach ($param in $Parameters) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" } ## INGORE DEPENDENCY PROPERTIES FOR NOW :) if($param.Key -eq "DependencyProps") { ## HANDLE EVENTS .... } elseif ($param.Key.StartsWith("On_")) { $EventName = $param.Key.SubString(3) if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" } $sb = $param.Value -as [ScriptBlock] if(!$sb) { $sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock } $Dobject.Value."Add_$EventName".Invoke( $sb ); # $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) ); # $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) ); } ## HANDLE PROPERTIES .... else { try { ## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here. if($DebugPreference -ne "SilentlyContinue") { Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray } if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) { $Values = @() foreach($sb in $param.Value) { $Values += & (Get-ReflectionModule) $sb } } else { $Values = $param.Value } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green } Set-Property $Dobject $Param.Key $Values if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta } if($DebugPreference -ne "SilentlyContinue") { if( $Dobject.Value.$($param.Key) -ne $null ) { Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green } } } catch [Exception] { Write-Host "COUGHT AN EXCEPTION" -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } while($DependencyProps) { $name, $value, $DependencyProps = $DependencyProps $name = ([string]@($name)[0]).Trim("-") if($name -and $value) { Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value } } } if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host } if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() } } function Set-Property { PARAM([ref]$TheObject, $Name, $Values) $DObject = $TheObject.Value if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta } $PropertyType = $DObject.GetType().GetProperty($Name).PropertyType if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green} # [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject ) # [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) ) # In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. [Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject ) [Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) ) $Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null $TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() ) } elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) { $Binding = @($Values)[0]; if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan} if(!$Binding.Source -and !$Binding.ElementName) { $Binding.Source = $DObject.DataContext } if($DependencyProperties.ContainsKey($Name)) { $field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType) if($field) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue } if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue} $DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null } else { throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )" } } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan } try { $DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow } } catch { Write-Host "Nope, was not able to set it." -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } } elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) { if($Values -is [System.Collections.IEnumerable]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan } $DObject.$($Name) = $Values } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan } $DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]" $DObject.$($Name).Add($Values) } } elseif($DObject.$($Name) -is [System.Collections.IList]) { foreach ($value in @($Values)) { try { $null = $DObject.$($Name).Add($value) } catch { # Write-Host "CAUGHT array problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) ) } else { Write-Error $_.Exception throw } } } } else { ## If they pass an array of 1 when we only want one, we just use the first value if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White} try { $DObject.$($Name) = $Values[0] } catch [Exception] { # Write-Host "CAUGHT collection value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $Values[0]) ) }else { throw } } } else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan} try { $DObject.$($Name) = $Values } catch [Exception] { # Write-Host "CAUGHT value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $values) ) }else { throw } } } } } function Set-DependencyProperty { [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true)] $Property , [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Element , [Parameter()] [Switch]$Passthru ) DYNAMICPARAM { $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter $Param1.Name = "Value" # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) ) $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) ) if( $Property ) { if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))) { $Param1.ParameterType = $Property.PropertyType } elseif($Property -is [string] -and $Property.Contains(".")) { $Class,$Property = $Property.Split(".") if($DependencyProperties.ContainsKey($Property)){ $type = $DependencyProperties.$Property.Keys -like "*$Class" if($type) { $Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType } } } elseif($DependencyProperties.ContainsKey($Property)){ if($Element) { if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) { $Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType } } else { $Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType } } else { $Param1.ParameterType = [PSObject] } } else { $Param1.ParameterType = [PSObject] } $paramDictionary.Add("Value", $Param1) return $paramDictionary } PROCESS { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red continue } if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])) ){ trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red continue } $Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType)) } else { if("$Property".Contains(".")) { $Class,$Property = "$Property".Split(".") } if( $DependencyProperties.ContainsKey("$Property" ) ) { $fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } ) if($fields.Count -eq 0 ) { $fields = @($DependencyProperties.$Property.Keys -like "*$Class" ) } if($fields.Count) { $success = $false foreach($field in $fields) { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red continue } $Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType))) if($?) { $success = $true; break } } if(!$success) { throw "food" } } else { Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red } } else { Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red } } if( $Passthru ) { $Element } } } Add-Type -Assembly WindowsBase function Add-ConstructorFunction { <# .Synopsis Add support for a new class by creating the dynamic constructor function(s). .Description Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias. Exposes all of the properties and events of the type as perameters to the function. NOTE: The Type MUST have a default parameterless constructor. .Parameter Assembly The Assembly you want to generate constructors for. All public types within it will be generated if possible. .Parameter Type The type you want to create a constructor function for. It must have a default parameterless constructor. .Example Add-ConstructorFunction System.Windows.Controls.Button Creates a new function for the Button control. .Example [Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) .Example Add-ConstructorFunction -Assembly PresentationFramework Will create constructor functions for all the WPF components in the PresentationFramework assembly. .Links http://HuddledMasses.org/powerboots .ReturnValue The name(s) of the function(s) created -- so you can export them, if necessary. .Notes AUTHOR: Joel Bennett http://HuddledMasses.org LASTEDIT: 2009-01-13 16:35:23 #> [CmdletBinding(DefaultParameterSetName="FromType")] PARAM( [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)] [type[]]$type , [Alias("FullName")] [Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)] [string[]]$Assembly , [Parameter()] [string]$Path = "$PSScriptRoot\\Types_Generated" , [switch]$Force , [switch]$ShortAliases , [Switch]$Quiet ) BEGIN { [Type[]]$Empty=@() if(!(Test-Path $Path)) { MkDir $Path } $ErrorList = @() } END { #Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties )) Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." } $ErrorList | Write-Error } PROCESS { if($PSCmdlet.ParameterSetName -eq "FromAssembly") { [type[]]$type = @() foreach($lib in $Assembly) { $asm = $null trap { continue } if(Test-Path $lib) { $asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") ) } if(!$asm) { ## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5 $asm = [Reflection.Assembly]::LoadWithPartialName( $lib ) } if($asm) { $type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and !$_.IsAbstract -and !$_.IsInterface -and $_.GetConstructor( "Instance,Public", $Null, $Empty, @() )} } else { Write-Error "Can't find the assembly $lib, please check your spelling and try again" } } } foreach($T in $type) { $TypeName = $T.FullName $ScriptPath = Join-Path $Path "New-$TypeName.ps1" Write-Verbose $TypeName ## Collect all dependency properties .... $T.GetFields() | Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } | ForEach-Object { [string]$Field = $_.DeclaringType::"$($_.Name)".Name [string]$TypeName = $_.DeclaringType.FullName if(!$DependencyProperties.ContainsKey( $Field )) { $DependencyProperties.$Field = @{} } $DependencyProperties.$Field.$TypeName = @{ Name = [string]$_.Name PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName } } if(!( Test-Path $ScriptPath ) -OR $Force) { $Pipelineable = @(); ## Get (or generate) a set of parameters based on the the Type Name $PropertyNames = New-Object System.Text.StringBuilder "@(" $Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n" ## Add all properties $Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") | Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) } $Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique foreach ($p in $Properties) { $null = $PropertyNames.AppendFormat(",'{0}'",$p.Name) switch( $p.MemberType ) { Event { $null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name) $null = $Parameters.AppendFormat(@' [Parameter()] [PSObject]${{On_{0}}} , '@, $p.Name) } Property { if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") { $null = $Parameters.AppendFormat(@' [Parameter(Position=1,ValueFromPipeline=$true)] [Object[]]${{{0}}} , '@, $p.Name) $Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru) } elseif($p.PropertyType -eq [System.Boolean]) { $null = $Parameters.AppendFormat(@' [Parameter()] [Switch]${{{0}}} , '@, $p.Name) } else { $null = $Parameters.AppendFormat(@' [Parameter()] [Object[]]${{{0}}} , '@, $p.Name) } } } } $null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)] [string[]]$DependencyProps )') $null = $PropertyNames.Remove(2,1).Append(')') $collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true) $ofs = "`n"; $function = $( " if(!( '$TypeName' -as [Type] )) { $( if( $T.Assembly.GlobalAssemblyCache ) { " `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) " } else { " `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) " } ) } ## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) { ## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`" ## # `$scriptParam = `$PSBoundParameters ## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`" ## } Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!"" function New-$TypeName { <# .Synopsis Create a new $($T.Name) object .Description Generates a new $TypeName object, and allows setting all of it's properties. (From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version)) .Notes GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org GENERATED : $(Get-Date) ASSEMBLY : $($T.Assembly.FullName) FULLPATH : $($T.Assembly.Location) #> $Parameters BEGIN { `$DObject = New-Object $TypeName `$All = $PropertyNames } PROCESS { " if(!$collectable) { " # The content of $TypeName is not a collection # So if we're in a pipeline, make a new $($T.Name) each time if(`$_) { `$DObject = New-Object $TypeName } " } @' foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) { $PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure() } Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject) '@ if(!$collectable) { @' Microsoft.PowerShell.Utility\\Write-Output $DObject } #Process '@ } else { @' } #Process END { Microsoft.PowerShell.Utility\\Write-Output $DObject } '@ } @" } ## New-$TypeName `@PSBoundParameters "@ ) Set-Content -Path $ScriptPath -Value $Function } # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName" } }#PROCESS } function Import-ConstructorFunctions { #.Synopsis # Autoload pre-generated constructor functions and generate aliases for them. #.Description # Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory. #.Parameter Path # The path to a folder with functions to preload param( [Parameter()] [Alias("PSPath")] [string[]]$Path = "$PSScriptRoot\\Types_Generated" ) end { $Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" }) Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")" foreach($script in Get-ChildItem $Paths -ErrorAction 0) { $TypeName = $script.Name -replace 'New-(.*).ps1','$1' $ShortName = ($TypeName -split '\\.')[-1] Write-Verbose "Importing constructor for type: $TypeName ($ShortName)" # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-Autoload -Name $Script.FullName -Alias "New-$TypeName" # Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String) Get-Command "New-$TypeName" } } } #.Parameter Snapin # The full path to where the snapin .dll is #.Parameter OutputPath # Force the module manifest(s) to output in a different location than where the snapin .dll is #.Parameter ModuleName # Override the snapin name(s) for the module manifest #.Parameter Author # Overrides the Company Name from the manifest when generating the module's "Author" comment #.Parameter Passthru # Returns the ModuleManifest (same as -Passthru on New-ModuleManifest) #.Example # New-ModuleManifestFromSnapin ".\\Quest Software\\Management Shell for AD" -ModuleName QAD # # Description # ----------- # Generates a new module manifest file: QAD.psd1 in the folder next to the Quest.ActiveRoles.ArsPowerShellSnapIn.dll #.Example # New-ModuleManifestFromSnapin "C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\\" -Output $pwd # # Description # ----------- # Generates module manifest files for the SqlServer PSSnapins and stores them in the current folder function New-ModuleManifestFromSnapin { param( [Parameter(Mandatory=$true, Position="0", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [String[]]$Snapin , [Parameter()] $OutputPath , [Parameter()] $ModuleName , [Parameter()] [String]$Author , [Switch]$Passthru ) # $SnapinPath = $(Get-ChildItem $SnapinPath -Filter *.dll) $EAP = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" Add-Assembly $Snapin $ErrorActionPreference = $EAP $SnapinTypes = Get-Assembly $Snapin | Get-Type -BaseType System.Management.Automation.PSSnapIn, System.Management.Automation.CustomPSSnapIn -WarningAction SilentlyContinue foreach($SnapinType in $SnapinTypes) { $Installer = New-Object $SnapinType if(!$PSBoundParameters.ContainsKey("OutputPath")) { $OutputPath = (Split-Path $SnapinType.Assembly.Location) } if(!$PSBoundParameters.ContainsKey("ModuleName")) { $ModuleName = $Installer.Vendor } if(!$PSBoundParameters.ContainsKey("Author")) { $Author = $Installer.Name } $ManifestPath = (Join-Path $OutputPath "$ModuleName.psd1") Write-Verbose "Creating Module Manifest: $ManifestPath" $RequiredAssemblies = @( $SnapinType.Assembly.GetReferencedAssemblies() | Get-Assembly | Where-Object { (Split-Path $_.Location) -eq (Split-Path $SnapinType.Assembly.Location) } | Select-Object -Expand Location | Resolve-Path -ErrorAction Continue) # New-ModuleManifest has a bad bug -- it makes paths relative to the current location (and it does it wrong). Push-Location $OutputPath if($Installer -is [System.Management.Automation.CustomPSSnapIn]) { $Cmdlets = $Installer.Cmdlets | Select-Object -Expand Name $Types = $Installer.Types | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } $Formats = $Installer.Formats | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } } else { $Types = $Installer.Types | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } $Formats = $Installer.Formats | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } } if(!$Cmdlets) { $Cmdlets = "*" } if(!$Types) { $Types = @() } if(!$Formats) { $Formats = @() } New-ModuleManifest -Path $ManifestPath -Author $Author -Company $Installer.Vendor -Description $Installer.Description ` -ModuleToProcess $SnapinType.Assembly.Location -Types $Types -Formats $Formats -Cmdlets $Cmdlets ` -RequiredAssemblies $RequiredAssemblies -Passthru:$Passthru ` -NestedModules @() -Copyright $Installer.Vendor -FileList @() Pop-Location } } Add-Accelerator list System.Collections.Generic.List``1 Add-Accelerator dictionary System.Collections.Generic.Dictionary``2 Set-Alias aasm Add-Assembly Set-Alias gt Get-Type Set-Alias gasm Get-Assembly Set-Alias gctor Get-Constructor
PowerShellCorpus/PoshCode/WriteFileName.ps1
WriteFileName.ps1
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate. # e.g. PS>.\\writefilename.ps1 c:\\ # call WriteFileName [string] # after done writing series of overwriting messages, call WriteFileNameEnd 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. # Features the ability to deal with end of console buffer overflows. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length $spaces = "" if ($global:lastlen -gt $writestr.length) { $spaces = " " * ($global:lastlen-$writestr.length) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to. if ($cwe -gt 0) { if (($ctop-$cwe0) -gt 0) { $ctop-=$cwe } else {$ctop=0} } write-host "$writestr" -nonewline $global:oldctop=[console]::cursortop if ([console]::cursorleft -ne 0) {$global:oldctop+=1} write-host "$spaces" -nonewline $global:lastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=0 } function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other { # and before printing something else if ($global:oldctop -eq $null) {return} [console]::cursortop=$global:oldctop [console]::cursorleft=0 } dir $args -recurse -ea 0 -force | %{$string="Test String. "*(get-random(100));$string+="Checking $($_.fullname) ..."; WriteFileName $string;sleep -seconds 1} #WriteFileName "Final Test String." WriteFileNameEnd write-host "Done! exiting."
PowerShellCorpus/PoshCode/AnalyzeScript.ps1
AnalyzeScript.ps1
<# .SYNOPSIS Analyzes script and gives starting lines & columns of script components .DESCRIPTION AnalyzeScript opens a dialog box for user selection; checks that input is a powershell script; parses and agrigates the script components into the following tokens: Unknown(s) Command(s) CommandParameter(s) CommandArgument(s) Variable(s) Member(s) LoopLabel(s) Attribute(s) Keyword(s) LineContinuation(s) .LINK None .NOTES Name: AnalizeScript.ps1 Author: Paul A. Drinnon Date Created: 03/24/2011 Date Revised: - (New Release) Version: 1.0 History: 1.0 This script can be altered to output other "Types" of tokenized content Below is a complete list Types ______________________________________ Name Example / Value Comment __________________ ___________ _____ Unknown 0 Command 1 CommandParameter 2 CommandArgument 3 Number 4 String 5 Variable -$! 6 Member 7 LoopLabel 8 Attribute 9 Type 10 Operator (-+*/=|...) 11 GroupStart ({ 12 GroupEnd )} 13 Keyword 14 Comment 15 StatementSeparator 16 NewLine 17 LineContinuation 18 Position 19 requires -Version 2.0 ** Licensed under a Creative Commons Attribution 3.0 License ** #> Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class WindowWrapper : IWin32Window { private IntPtr _hWnd; public WindowWrapper(IntPtr handle) { _hWnd = handle; } public IntPtr Handle { get { return _hWnd; } } } "@ -ReferencedAssemblies "System.Windows.Forms.dll" [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null $handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle $owner = New-Object WindowWrapper -ArgumentList $handle function Select-File { param ( [String]$Title = "Enter a Windows PowerShell script", [String]$InitialDirectory = $home, [String]$Filter = "All Files(*.*)|*.*" ) $dialog = New-Object System.Windows.Forms.OpenFileDialog $dialog.Filter = $filter $dialog.InitialDirectory = $initialDirectory $dialog.ShowHelp = $true $dialog.Title = $title $result = $dialog.ShowDialog($owner) if ($result -eq "OK") { return $dialog.FileName } else { Write-Error "Operation cancelled by user." } } function TokenName-Count ($file, $str) { $content = gc $file $a = [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) | ? { $_.Type -eq $str } | Measure-Object | select Count $su = $str.ToUpper() + "S" "$su`t`t$a" } function CustomTable ($file, $str) { $content = gc $file [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) | ? { $_.Type -eq $str } | ft content, startline, startcolumn -auto } $selectPSfile = "" while (-!($selectPSfile -match ".ps1|.psm1|.psd1|.ps1xml")) { $selectPSfile = Select-File } $TokenNames = ` "Unknown", ` "Command", ` "CommandParameter", ` "CommandArgument", ` "Variable", ` "Member", ` "LoopLabel",` "Attribute",` "Keyword", ` "LineContinuation" $date = (Get-Date).ToShortDateString() "`n$selectPSfile`t`t`t`t$date`n" $TokenNames | foreach { [string]$s = $_ TokenName-Count $selectPSfile $s CustomTable $selectPSfile $s }
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_9.ps1
TabExpansion for V2CTP_9.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 characters ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ## #Switch syntax option expansion ## switch -w<tab> -f<tab> ## #Better powershell.exe option expansion with '-' ## powershell -no<tab> -<tab> -en<tab> ## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* ) ## [par<tab> ## [cmd<tab> ## #Member expansion for CmdletBinding and Parameter attributes ## [Parameter(man<tab>,<tab>1,val<tab>$true)] ## [CmdletBinding( <tab>"foo", su<tab>$true)] ## #Several current date/time formats with Ctrl+D ## <Ctrl+D><tab><tab><tab><tab><tab>... ## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,') ## <command>;<tab> # push command ## <Ctrl+D><tab> # pop ## #Paste clipboard with Ctrl+V ## <Ctrl+V><tab> ## # Cut current line with Ctrl+X ## <command><Ctrl+X><tab> ## # Cut words with a character after Ctrl+X until the character ## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-' ## 2: PS > dir - ## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now ## # Cut last word in current line with Ctrl+Z ## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line ## 2: PS > Get-ChildItem ## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now ## #[ScriptBlock] member expansion for [ScriptBlock] literal ## { 1+1 }.inv<tab> ## #Help document's section name expansion at a line that has only spaces ## .syn<tab> ## .func<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> ## # Now command name expansion's priority is, ## alias -> function -> filter -> cmdlet -> script -> external command ## # PSDrive and item name expansion in variable notation ## ${fu<tab> ## ${function:cl<tab> ## ${c:*<tab>\\*<tab> ## ${c:\\win<tab>/sys<tab>/<tab> ## # Using Ctrl+K, characters insertion (bihind space or semi-coron or pipe operator) feature : it encloses tokens with parnthesis by default ## 1 - 1 - 1 - 1<Ctrl+K><tab> ## 1 - 1 - 1 - (1)<tab> ## 1 - 1 - 1 (- 1)<tab> ## 1 - 1 - (1 - 1)<tab><tab><tab>... ## with double Ctrl+K, it encloses tokens with $( ) ## for ( $i=0;$j=1<Ctrl+K><Ctrl+K><tab><tab> ## for ( $($i=0;$j=1) ## if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens ## 1+1 | {$_*2}<Ctrl+K>%<tab> ## 1+1 | %{$_*2} ## 1+1 +1+1<Ctrl+K>;<tab> ## 1+1 ;+1+1 ## if the character is ( or { or {, tokens are enclosed ( ) or { } or {} ## int<Ctrl+K>[<tab> ## [int] ## with double Ctrl+K, and if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens with '$' ## C:\\WINDOWS\\system32\\notepad.exe<Ctrl+K><Ctrl+K>{<tab> ## ${C:\\WINDOWS\\system32\\notepad.exe} ## % and ? are given special treatment with double Ctrl+K, these enclose tokens with % { } or ? { } behind '|' ## ls | $_.LastWriteTime -gt "2009/5"<Ctrl+K><Ctrl+K>?<tab> ## ls | ? {$_.LastWriteTime -gt "2009/5"} ## ls | $_.FullName<Ctrl+K><Ctrl+K>%<tab> ## ls | % {$_.FullName} ## # Parameter name (and command alias) expansion with Ctrl+E ## ls -f *.txt -r | ? { $_.LastWriteTime -lt "2009/5" } | Select-String powershell -e OEM<Ctrl+E><tab> ## ## Get-ChildItem -Filter *.txt -Recurse | Where-Object { $_.LastWriteTime -lt "2009/5" } | Select-String powershell -Exclude OEM<tab> ## Get-ChildItem -Filter *.txt -Recurse | Where-Object { $_.LastWriteTime -lt "2009/5" } | Select-String powershell -Encoding OEM<tab> ## Get-ChildItem -Filter *.txt -Recurse | Where-Object { $_.LastWriteTime -lt "2009/5" } | Select-String powershell -ErrorAction OEM<tab><tab>... ## # WMI Namespaces expansion for Get-WmiObject ## gwmi -Namespace <tab> ## Get-WmiObject -Namespace root\\asp<tab> ## # WMI Classes expansion which is corresponding to WMI Namespace (*) ## gwmi -Namespace ROOT\\CIMV2\\ms_409 -Class <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 Namespaces list... if ( Test-Path $PSHOME\\WMINamespaces.txt ) { $_WMINamespaces = type $PSHOME\\WMINamespaces.txt -ReadCount 0 } else { $_WMINamespaces = & { $sb = { param ($ns) gwmi __NAMESPACE -Namespace $ns -com . | % { $ns = $_.__NAMESPACE + "\\" + $_.Name $ns & $sb $ns } } & $sb root } $_WMINamespaces = $_WMINamespaces + "ROOT" | sort '$_WMINamespaces was updated...' | Out-Host Set-Content -Value $_WMINamespaces -Path $PSHOME\\WMINamespaces.txt -Verbose } ### Get default WMI Namespace... $_WMIdftNS = $_WMINamespaces -eq (Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\WBEM\\Scripting)."Default Namespace" ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_WMIClasses = Import-Clixml $PSHOME\\WMIClasses.txt } else { $_new = '=(New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ));' $_WMIClasses = iex ('@{"' + [String]::Join( "`"$_new`"", $_WMINamespaces ) + "`"$_new}") foreach ( $_namespace in $_WMINamespaces ) { foreach ( $_class in gwmi -Namespace $_namespace -List ) { $_WMIClasses.$_namespace.Add($_class.Name) } $_WMIClasses.$_namespace.Sort() } '$_WMIClasses was updated...' | Out-Host Export-Clixml -InputObject $_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 = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort $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 -like "[_\\]" ) { $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 = @(iex $str[$i+1])[0] } 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 '.') { $params = @{view = 'extended','adapted','base'} } else { $params = @{static=$true} } if ( $_val -is [Hashtable] ) { [Object[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } } if ( $_keys -ne $null ) { $_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat}) } else { $_members = (Get-Member @params -InputObject $_val $_pat) } foreach ($_m in $_members | 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+E command alias and parameter name expansion 5 { if ( $line -ne $( "=" + [Char]5 ) ) { $line = $line.SubString(0, $line.Length-1) $global:ctrlE = ""; $tail = 0 [Management.Automation.PSParser]::Tokenize($line, [ref]$null) | % { $word = $_.Content $head = $_.Start $spaces = ' ' * ($head-$tail) switch ( $_.Type ) { "Command" { $global:ctrlE = $global:ctrlE | % { $_ + $spaces + ($cmdinf = gcm ($word -replace '\\?','`?')).Definition.Split(" ")[0] } } "CommandParameter" { $_pat = $word.TrimStart("-") + "*" $global:ctrlE = $global:ctrlE | % { $temp = $_; $cmdinf.Parameters.Keys -like $_pat | % { $temp + $spaces + "-" + $_ } } } "Variable" { if ( $line[$head] -eq '$' ) { $sigil = '$' if ( $line[$head+1] -eq '{' ) { $global:ctrlE = $global:ctrlE | % { $_ + $spaces + '${' + $word + '}' } continue; } } elseif ( $line[$head] -eq '@' ) { $sigil = "@" } $global:ctrlE = $global:ctrlE | % { $_ + $spaces + $sigil + $word } } "String" { if ( $line[$head] -eq '"') { $quot = '"' } else { $quot = "'" } $global:ctrlE = $global:ctrlE | % { $_ + $spaces + $quot + $word + $quot } } default { $global:ctrlE = $global:ctrlE | % { $_ + $spaces + $word } } } $tail= $head + $_.Length } [Windows.Forms.SendKeys]::SendWait("{Esc}=^E{TAB}") } else { $global:ctrlE; } break TabExpansion; } # Ctrl+K put parentheses behind space or semi-coron or pipe operator 11 { if ( $line -ne $( "=" + [Char]11 ) ) { if ( $line[-2] -eq 11 ) { $left = '$' + "(" $line = $line.Substring(0,$line.length-2) } else { $left = "(" $line = $line.Substring(0,$line.length-1) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny(" ;|") $global:_ctrlk += $line.Insert($i+1, $left) + ")" $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") } else { $global:_ctrlk } break TabExpansion; } # Ctrl+L a part of history commands expansion 12 { Get-CommandLine $lastWord.SubString(0, $lastword.Length-1) break; } # Ctrl+P hand-operated pop from command buffer stack 16 { $_base = $lastword.SubString(0, $lastword.Length-1) $_base + $global:_cmdstack.Pop() 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) $_clip = New-Object System.Windows.Forms.TextBox $_clip.Multiline = $true $_clip.Paste() $_base + $_clip.Text break; } # 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; } # 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; } } switch ( [int]$line[-2] ) { # Ctrl+K put character behind space or semi-coron or pipe operator 11 { switch ( $line[-1] ) { '{' { $right = '}' } '(' { $right = ')' } '[' { $right = ']' } } $left = $line[-1] $delimiter = " ;|" if ( $line[-3] -eq 11 ) { if ( $line[-1] -eq '%' -or $line[-1] -eq '?' ) { $left = ' ' + $left + ' {'; $right = '}' $delimiter = '|' } else { $left = '$' + $left } $line = $line.Substring(0,$line.length-3) } else { $line = $line.Substring(0,$line.length-2) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny($delimiter) $global:_ctrlk += $line.Insert($i+1, $left) + $right $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") break TabExpansion; } # Ctrl+X cut words with a character after Ctrl+X until the character 24 { $line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break; } } 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 $global:_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] $_pat = $matches[4] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] 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 on [ScriptBlock] members... # 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
PowerShellCorpus/PoshCode/Find Local Group Members.ps1
Find Local Group Members.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" $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 ) { $Group= [ADSI]"WinNT://$Server/$LocalGroup,group" $Members = @($Group.psbase.Invoke("Members")) $Members | ForEach-Object { $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } $ChildGroups | ForEach-Object { $output = "" | Select-Object Server, Group, InLocalAdmin $output.Server = $Server $output.Group = $_ $output.InLocalAdmin = $MemberNames -contains $_ Write-Output $output } }
PowerShellCorpus/PoshCode/New-XVM_8.ps1
New-XVM_8.ps1
#Examples <# New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx' New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"} #> Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { Try { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Invoke-Expression -Command $command } End {} }
PowerShellCorpus/PoshCode/Findup_7.ps1
Findup_7.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; namespace Findup { public class FileInfoExt { public FileInfoExt(FileInfo fi) { FI = fi; } public FileInfo FI { get; private set; } public bool Checked { get; set; } public byte[] SHA512_1st1K { get; set; } public byte[] SHA512_All { get; set; } } class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (IE: *.*), and in directories in pathRec, to returnList { public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { Recursive(d, searchPattern, recursiveFlag, returnList); } return; } public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { if (File.Exists(pathRec)) { try { returnList.Add(new FileInfoExt(new FileInfo(pathRec))); } catch (Exception e) { Console.WriteLine("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { returnList.Add(new FileInfoExt(addf)); } } catch (Exception e) { Console.WriteLine("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { try { foreach (string d in (Directory.GetDirectories(pathRec))) { Recursive(d, searchPattern, recursiveFlag, returnList); } } catch (Exception e) { Console.WriteLine("Add Directory error: " + e.Message); } } } else { try { string filePart = Path.GetFileName(pathRec); string dirPart = Path.GetDirectoryName(pathRec); if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { Recursive(dirPart, filePart, recursiveFlag, returnList); } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } catch (Exception e) { Console.WriteLine("Parse error on: " + pathRec); Console.WriteLine("Make sure you don't end a directory with a \\\\ when using quotes. The console arg parser doesn't accept that."); Console.WriteLine("Exception: " + e.Message); return; } } return; } } class Findup { public static void Main(string[] args) { Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile."); Console.WriteLine(" "); string[] paths = new string[0]; System.Boolean recurse = false; System.Boolean delete = false; System.Boolean noprompt = false; System.Boolean b4b = false; List<FileInfoExt> fs = new List<FileInfoExt>(); long bytesInDupes = 0; // bytes in all the duplicates long numOfDupes = 0; // number of duplicate files found. long bytesRec = 0; // number of bytes recovered. long delFiles = 0; // number of files deleted. int c = 0; int i = 0; string deleteConfirm; for (i = 0; i < args.Length; i++) { if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help infomration."); Console.WriteLine(" -recurse - recurses through subdirectories."); Console.WriteLine(" -delete - deletes duplicates with confirmation prompt."); Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt."); Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Might be much slower, but most secure."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse"); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt"); Console.WriteLine(" findup.exe c:\\\\data .\\\\*.txt c:\\\\reports\\\\quarter.doc -recurse -b4b"); Console.WriteLine(" "); return; } if (System.String.Compare(args[i], "-recurse", true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i], "-delete", true) == 0) { delete = true; continue; } if (System.String.Compare(args[i], "-noprompt", true) == 0) { noprompt = true; continue; } if (System.String.Compare(args[i], "-b4b", true) == 0) { b4b = true; continue; } Array.Resize(ref paths, paths.Length + 1); paths[c] = args[i]; c++; } if (paths.Length == 0) { Console.WriteLine("No files specified, try findup.exe -help"); return; } Recurse recurseMe = new Recurse(); recurseMe.Recursive(paths, "*.*", recurse, fs); if (fs.Count < 2) { Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomNumber); // get SHA-512 salt. for (i = 0; i < fs.Count; i++) { if (fs[i].Checked == true) // If file was already matched, then skip to next. continue; for (c = i + 1; c < fs.Count; c++) { if (fs[c].Checked == true) // skip already matched inner loop files. continue; if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash. continue; if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match. continue; if (fs[i].SHA512_1st1K == null) // check/hash first 1K first. fs[i].SHA512_1st1K = Compute1KHash(fs[i].FI.FullName); if (fs[c].SHA512_1st1K == null) fs[c].SHA512_1st1K = Compute1KHash(fs[c].FI.FullName); if (CompareHash(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash.. continue; if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file. continue; if (b4b == true) // byte for byte comparison specified? { if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function continue; } else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes. { if (fs[i].SHA512_All == null) // check/hash the rest of the files. fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName); if (fs[c].SHA512_All == null) fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName); if (CompareHash(fs[i].SHA512_All, fs[c].SHA512_All) == false) continue; if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate. continue; } Console.WriteLine("Match : " + fs[i].FI.FullName); Console.WriteLine("with : " + fs[c].FI.FullName); fs[c].Checked = true; // do not check or match against this file again. numOfDupes++; // increase count of matches. bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. continue; if (noprompt == false) { Console.Write("Delete the duplicate file <Y/n>?"); deleteConfirm = Console.ReadLine(); if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) continue; } try { File.Delete(fs[c].FI.FullName); Console.WriteLine("Deleted: " + fs[c].FI.FullName); bytesRec += fs[c].FI.Length; delFiles++; } catch (Exception e) { Console.WriteLine("File delete error: " + e.Message); } } } Console.WriteLine(" "); Console.WriteLine("Files checked : {0:N0}", fs.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes); Console.WriteLine("Duplicates deleted : {0:N0}", delFiles); Console.WriteLine("Recovered bytes : {0:N0}", bytesRec); return; } private static Boolean B4b(string path1, string path2) { try { using (var stream = File.OpenRead(path1)) { using (var stream2 = File.OpenRead(path2)) { System.Boolean EOF = false; do { var length = stream.Read(largeBuf, 0, largeBuf.Length); var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length); if (length != length2) return false; if (length != largeBuf.Length) EOF = true; int i = 0; while (i < length) { if (largeBuf[i] != largeBuf2[i]) return false; i++; } } while (EOF == false); } } return true; } catch (Exception e) { Console.WriteLine("Byte for Byte comparison failed: " + e.Message); return false; } } private static Boolean CompareHash(byte[] hash1, byte[] hash2) { int i = 0; while (i < hash1.Length) { if (hash1[i] != hash2[i]) return false; i++; } return true ; } private static readonly byte[] readBuf = new byte[1024 + 64]; private static readonly byte[] readBuf2 = new byte[1024 + 64]; private static readonly byte[] largeBuf = new byte[10240 + 64]; private static readonly byte[] largeBuf2 = new byte[10240 + 64]; private static readonly byte[] randomNumber = new byte[64]; private static byte[] hash = new byte[64]; private static byte[] Compute1KHash(string path) { Buffer.BlockCopy(randomNumber, 0, readBuf, 0, randomNumber.Length); try { using (var stream = File.OpenRead(path)) { var length = stream.Read(readBuf, hash.Length, readBuf.Length - hash.Length); hash = SHA512.Create().ComputeHash(readBuf, 0, length + hash.Length); return (hash); } } catch (Exception e) { Console.WriteLine("Hash Error: " + e.Message); return (null); } } private static byte[] ComputeFullHash(string path) { Buffer.BlockCopy(randomNumber, 0, largeBuf, 0, randomNumber.Length); try { var _SHA = SHA512.Create(); using (var stream = File.OpenRead(path)) { System.Boolean EOF = false; while (EOF == false) { var length = stream.Read(largeBuf, hash.Length, largeBuf.Length - hash.Length); if (length != (largeBuf.Length - hash.Length)) EOF = true; hash = _SHA.ComputeHash(largeBuf, 0, length + hash.Length); Buffer.BlockCopy(hash, 0, largeBuf, 0, hash.Length); } return (hash); } } catch (Exception e) { Console.WriteLine("Hash error: " + e.Message); return (null); } } } }
PowerShellCorpus/PoshCode/Enable-RemotePsRemoting..ps1
Enable-RemotePsRemoting..ps1
##############################################################################\n##\n## Enable-RemotePsRemoting\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nEnables PowerShell Remoting on a remote computer. Requires that the machine\nresponds to WMI requests, and that its operating system is Windows Vista or\nlater.\n\n.EXAMPLE\n\nEnable-RemotePsRemoting <Computer>\n\n#>\n\nparam(\n ## The computer on which to enable remoting\n $Computername,\n\n ## The credential to use when connecting\n $Credential = (Get-Credential)\n)\n\nSet-StrictMode -Version Latest\n$VerbosePreference = "Continue"\n\n$credential = Get-Credential $credential\n$username = $credential.Username\n$password = $credential.GetNetworkCredential().Password\n\n$script = @"\n\n`$log = Join-Path `$env:TEMP Enable-RemotePsRemoting.output.txt\nRemove-Item -Force `$log -ErrorAction SilentlyContinue\nStart-Transcript -Path `$log\n\n## Create a task that will run with full network privileges.\n## In this task, we call Enable-PsRemoting\nschtasks /CREATE /TN 'Enable Remoting' /SC WEEKLY /RL HIGHEST ``\n /RU $username /RP $password ``\n /TR "powershell -noprofile -command Enable-PsRemoting -Force" /F |\n Out-String\nschtasks /RUN /TN 'Enable Remoting' | Out-String\n\n`$securePass = ConvertTo-SecureString $password -AsPlainText -Force\n`$credential =\n New-Object Management.Automation.PsCredential $username,`$securepass\n\n## Wait for the remoting changes to come into effect\nfor(`$count = 1; `$count -le 10; `$count++)\n{\n `$output = Invoke-Command localhost { 1 } -Cred `$credential ``\n -ErrorAction SilentlyContinue\n if(`$output -eq 1) { break; }\n\n "Attempt `$count : Not ready yet."\n Sleep 5\n}\n\n## Delete the temporary task\nschtasks /DELETE /TN 'Enable Remoting' /F | Out-String\nStop-Transcript\n\n"@\n\n$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($script)\n$encoded = [Convert]::ToBase64String($commandBytes)\n\nWrite-Verbose "Configuring $computername"\n$command = "powershell -NoProfile -EncodedCommand $encoded"\n$null = Invoke-WmiMethod -Computer $computername -Credential $credential `\n Win32_Process Create -Args $command\n\nWrite-Verbose "Testing connection"\nInvoke-Command $computername {\n Get-WmiObject Win32_ComputerSystem } -Credential $credential
PowerShellCorpus/PoshCode/Invoke-ResetPassword.ps1
Invoke-ResetPassword.ps1
# From: Brandon Shell # Purpose: To Reset Local User Account # Example: # -- To Reset user Password # PS> Add-User -user Jsmith -password H!Th3r3 -server myserver1 # With Creds # PS> Add-User -user Jsmith -password H!Th3r3 -server myserver1 -luser adminGuy -lPassword HateClearText! ################################################################# Param([string]$user,[string]$password,[string]$server,[switch]$auth) If(!($server)){$server = get-content env:COMPUTERNAME} $dePath = "WinNT://$server/$user,user" if($auth) { $lUser = Read-Host "Enter UserName" $lPassword = Read-Host "Enter Password" $myuser = new-Object System.DirectoryServices.DirectoryEntry($dePath,$lUser,$lPassword) } else { $myuser = new-Object System.DirectoryServices.DirectoryEntry($dePath) } $myuser.psbase.invoke("SetPassword",$password) $myuser.psbase.CommitChanges() if($?){Write-Host "Reset Password Successful!"}else{Write-Host "Reset Failed"}
PowerShellCorpus/PoshCode/18072022-fd64-4e12-ae6e-d021defcfff3.ps1
18072022-fd64-4e12-ae6e-d021defcfff3.ps1
# Name: zip.ps1 # Author: Shadow # Created: 05/12/2008 param([string]$zipfilename=$(throw "ZIP archive name needed!"), [string[]]$filetozip=$(throw "Supply the file(s) to compress (wildcards accepted)")) trap [Exception] {break;} #empyt zip file contents $emptyzipfile=80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0; #create a new file with $ZIPFILENAME and copy the above array into it $fmode = [System.IO.FileMode]::Create; $zipfile = new-object -type System.IO.FileStream $zipfilename, $fmode; $zipfile.Write($emptyzipfile,0,22); $zipfile.Flush(); $zipfile.Close(); #open the new zip file as folder from Windows Shell Application $shell=new-object -comobject Shell.Application; $foldername=(ls $zipfile.Name).FullName; $zipfolder=$shell.Namespace($foldername); #Iterate files to zip, copying them to zip folder. #In the process, the shell compress them Write-Host "Compressing:"; $filetozip| %{ls $_}| foreach{ ("`t"+$_.fullname); $zipfolder.copyhere($_.fullname,20); [System.Threading.Thread]::Sleep(250); } $shell=$null; $zipfolder=$null;
PowerShellCorpus/PoshCode/AD-GroupMembers_v2.ps1
AD-GroupMembers_v2.ps1
function AD-GroupMembers() { param ( $Domen, $Group, $User ) if ($User){$Connection = Get-Credential -Credential $user} if($Connection){$Member = Get-QADGroupMember -Service $Domen -Identity $Group -Credential $Connection -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-List Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} else{$Member = Get-QADGroupMember -Service $Domen -Identity $Group -SizeLimit 0 -ErrorAction SilentlyContinue | Sort Name | Format-List Name,NTAccountName,Sid,AccountIsDisabled -AutoSize} $Member }
PowerShellCorpus/PoshCode/Get-FirewallStatus2.ps1
Get-FirewallStatus2.ps1
filter global:get-firewallstatus2 ([string]$computer = $env:computername) { if ($_) { $computer = $_ } $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computer) $firewallEnabled = $reg.OpenSubKey("System\\ControlSet001\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\DomainProfile").GetValue("EnableFirewall") [bool]$firewallEnabled }
PowerShellCorpus/PoshCode/Locked accounts alerter.ps1
Locked accounts alerter.ps1
#Created By: Ty Lopes #Sept 2012 #Sript to be run by a scheduled task that monitors for a specific event ID (in this case account locked) #The sript then reads the last correstponding event ID and emails the details #I could only get this alert to work properly by using this method... There may be something easier/better for you out there. #This process will have to be followed for each domain controller (since any DC may lock the account and others may not trigger the event id #We have two DC's so this worked well for us #The account the task runs under obviously needs rights to read the event logs on the DC #Setup the Task #Create a scheduled task #On the general tab, Run Wether user is logged on or not and Run with highest priveledges #On the triggers tab, Select NEW, "On an Event". #Populate #log: Security #Source: Microsoft-Windows-security-auditing #Event ID: 4740 #Under Actions: New: STart a program: #Program: powershell.exe #Arguments: -command "& 'C:\\scripts\\accountLocked.ps1' " (pointing to wherever your script lives) #Script Start start-sleep 10 $dcName = "DomainController" $eventID = "4740" $mailServer = "smtpServer" $eSubject = "AD account locked" $emailAddy = "user@domain.com" $lockEvent = get-eventlog -logname security -computername $dcName -instanceid $eventID -newest 1 $emailBody = $lockEvent.message Send-MailMessage –From lockedAccount@domain.com –To $emailAddy –Subject $eSubject –Body $emailBody –SmtpServer $mailServer #Script end
PowerShellCorpus/PoshCode/Get-ImageMetaData_1.ps1
Get-ImageMetaData_1.ps1
function Get-ImageMetadata { #.Synopsis # pull EXIF, XMP, and other data from images using the BitmapMetaData #.Example # $image = Get-ImageMetadata C:\\Users\\JBennett\\Pictures\\3200x1200\\02179_piertonowhere_interfacelift_com.jpg -verbose # $image | fl *tiff* # $image | fl *exif* ## 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 ## - v2.0 - Refactor for clarity and PowerShell 2.0 features ##################################################################################################### param( [Parameter( ValueFromPipeLine = $true, ValueFromPipelineByPropertyname = $true, Mandatory = $true )] [ValidateScript( { Test-Path -Path $_ -PathType Leaf } )] [ValidatePattern('\\.(jpg|tiff|bmp|png|gif)$')] [Alias("PSPath")] [string]$File ) begin { $null = [Reflection.Assembly]::LoadWithPartialName("PresentationCore"); function Get-ImageMetadata { PARAM( [Parameter(ValueFromPipeline=$true)] [System.Windows.Media.Imaging.BitmapFrame]$bitmapFrame , [Parameter(ValueFromPipelineByPropertyName=$true)] $Metadata ) begin { $ImageMetaData = @{} } process { foreach($Meta in $Metadata) { ## 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 # } Write-Verbose "Getting metadata $Meta" $next = $bitmapFrame.MetaData.GetQuery($Meta); if($next.Location){ $next | ForEach-Object { $ImageMetaData += Get-ImageMetadata $bitmapFrame "$($next.Location)$_" } } else { # if($Meta.Split("/")[-1] -match "{ushort=(?<code>\\d+)}") { # # $path = "0x{0:X}" -f [int]$matches["code"] # $Meta = [int]$matches["code"] # } Write-Verbose "Metadata $Meta = $Next" $ImageMetaData.$Meta = $Next } } } end { write-output $ImageMetaData } } } process { $File = [string](Resolve-Path $File) try { $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" ) $ImageMetaData = $decoder.Frames[0] | Get-ImageMetadata } catch { Write-Error "WARNING: $_" continue; } finally { $stream.Close() $stream.Dispose() } $Output = New-Object IO.FileInfo $file foreach($key in $ImageMetaData.Keys) { Add-Member -in $Output -Type NoteProperty -Name $key -value $ImageMetaData.$key -Force } Write-Output $Output }} function Clear-ImageMetaData { <# .Synopsis Modification of @Jaykuls function that writes (cleanes) images metadata. .Description Cleans meta data from file at $Path. .Link http://poshcode.org/617 .Example Clear-ImageMetaData -Path c:\\temp\\test.jpg Opens test.jpg, reads, cleans metadata and closes it. .Example ls *.jpg | Clear-ImageMetaData Opens all .jpg files, and clears Meta Data for each one. #> [CmdletBinding()] param ( [Parameter( ValueFromPipeLine = $true, ValueFromPipelineByPropertyname = $true, Mandatory = $true )] [ValidateScript( { Test-Path -Path $_ -PathType Leaf } )] [ValidatePattern('\\.(jpg|tiff|bmp|png|gif)$')] [string]$Path ) process { try { $Path = [string](Resolve-Path $Path) $stream = New-Object IO.FileStream $Path, 'Open', 'ReadWrite', 'ReadWrite' $decoder = [System.Windows.Media.Imaging.BitmapDecoder]::Create( $stream, "PreservePixelFormat", "Default" ) $bitmapFrame = $decoder.Frames[0] foreach($meta in $bitmapFrame.MetaData) { $next = $bitmapFrame.MetaData.GetQuery($meta); 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 } $writer = $bitmapFrame.CreateInPlaceBitmapMetadataWriter() $Script = { param ($path) if($Writer.TrySave()) { foreach ($Element in $path) { $writer.SetQuery($Element,'') & $Script $Element } } else { Write-Error "Can't write metadata to $Path" } } & $script $Writer $Stream.Flush() $Stream.Close() $Stream.Dispose() } catch { Write-Verbose $_ } } } # END function Clear-ImageMetaData
PowerShellCorpus/PoshCode/Set-defaultBrowser.ps1
Set-defaultBrowser.ps1
function Set-defaultBrowser { param($defaultBrowser) switch ($defaultBrowser) { 'IE' { Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\ftp\\UserChoice' -name ProgId IE.FTP Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice' -name ProgId IE.HTTP Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' -name ProgId IE.HTTPS } 'FF' { Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\ftp\\UserChoice' -name ProgId FirefoxURL Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice' -name ProgId FirefoxURL Set-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice' -name ProgId FirefoxURL } } # thanks to http://newoldthing.wordpress.com/2007/03/23/how-does-your-browsers-know-that-its-not-the-default-browser/ <# (Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\ftp\\UserChoice').ProgId (Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice').ProgId (Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice').ProgId #> } # Set-defaultBrowser ff # Set-defaultBrowser ie
PowerShellCorpus/PoshCode/Autoload (beta 3).ps1
Autoload (beta 3).ps1
#Requires -Version 2.0 ## Version History ## beta 3 - 2010.05.10 ## fix for signed scripts (strip signature) ## beta 2 - 2010.05.09 ## implement module support ## beta 1 - 2010.04.14 ## Initial Release ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time. ## To use: ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments ## For example: <# function Skip-Object { param( [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $InputObject ) begin { if($Last) { $Queue = new-object System.Collections.Queue $Last } $e = $every; $UpTo++; $u = 0 } process { $InputObject | where { --$First -lt 0 } | foreach { if($Last) { $Queue.EnQueue($_) if($Queue.Count -gt $Last) { $Queue.DeQueue() } } else { $_ } } | foreach { if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo } } | foreach { if($every -and (--$e -le 0)) { $e = $every } else { $_ } } } } #> ## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1) ## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile) ## 4) Dot-source this file, or include it as part of your profile ## 5) Add one line to your profile (or on the commandline): <# autoload Skip-Object #> ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it. ## Now, you can just use the function: ## 1..10 | Skip-Object -first 2 -upto 2 $script:AutoloadHash = @{} function Autoloaded { [CmdletBinding()]Param() DYNAMICPARAM { $CommandName = $MyInvocation.InvocationName if(!$CommandName) { throw "Unable to determine command" } Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])" $ScriptName, $ModuleName = $Script:AutoloadHash[$CommandName] if($ModuleName) { $Module = Get-Module $ModuleName } else { $Module = $null } ## Determine the command name based on the alias used to invoke us ## Store the parameter set for use in the function later... $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary # $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript #$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript ) $externalScript = Get-Command $ScriptName -Type ExternalScript Write-Verbose "Processing Script: $($externalScript |Out-String)" $parserrors = $null $prev = $null $script = $externalScript.ScriptContents [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]::Reverse($tokens) ForEach($token in $tokens) { if($prev -and $token.Content -eq "# SIG # Begin signature block") { $script = $script.SubString(0, $token.Start ) } if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $CommandName ) { $script = $script.Insert( $prev.Start, "global:" ) } $prev = $token } if($Module) { $script = Invoke-Expression "{ $Script }" Write-Verbose "What the $($Module)" &$Module $Script | Out-Null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Module Function: $($command |Out-String)" } else { Invoke-Expression $script | out-null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Local Function: $($command |Out-String)" } if(!$command) { throw "Something went wrong autoloading the $($CommandName) function. Function definition doesn't exist in script: $($externalScript.Path)" } Remove-Item Alias::$($CommandName) Write-Verbose "Defined the function and removed the alias... $($command | Out-string)" foreach( $pkv in $command.Parameters.GetEnumerator() ){ $parameter = $pkv.Value if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue } $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes) $paramdictionary.Add($pkv.Key, $param) } return $paramdictionary }#DynamicParam begin { Write-Verbose "Autoloaded Begin: $($MyInvocation.InvocationName)" $command = $ExecutionContext.InvokeCommand.GetCommand( $MyInvocation.InvocationName, [System.Management.Automation.CommandTypes]::Function ) $scriptCmd = {& $command @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($true) } process { Write-Verbose "Autoloaded Process: $($MyInvocation.InvocationName) ($_)" try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } Write-Verbose "Autoloaded End: $($MyInvocation.InvocationName)" } }#AutoLoaded function autoload { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Name , [Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)] [Alias("BaseName")] $Alias = $Name , [Parameter(Position=2,Mandatory=$false)] [String]$Module , [Parameter(Mandatory=$false)] [String]$Scope = '2' ) begin { $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } } process { for($i=0;$i -lt $Name.Count;$i++){ if($Alias -is [Scriptblock]) { $a = $Name[$i] | &$Alias } elseif($Alias -is [Array]) { $a = $Alias[$i] } else { $a = $Alias } Write-Verbose "Set-Alias $aAutoloaded -Scope $Scope" Set-Alias $a Autoloaded -Scope $Scope $Script:AutoloadHash[$a] = $Name[$i],$Module } } }
PowerShellCorpus/PoshCode/Get-FreeRAM.ps1
Get-FreeRAM.ps1
function Get-FreeRam { #.Synopsis # Gets the FreePhysicalMemory from the specified computer(s) #.Parameter ComputerName # The name(s) of the computer(s) to get the Free Ram (FreePhysicalMemory) for. #.Example # Get-FreeRam SDI-JBennett, Localhost # # Computer FreePhysicalMemory # -------- ------------------ # SDI-JBENNETT 4180364 # SDI-JBENNETT 4179764 [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName='localhost' ) process { Get-WmiObject -ComputerName $ComputerName Win32_OperatingSystem | Select-Object -Property @{name="Computer";expression={$_.__SERVER}}, FreePhysicalMemory } }
PowerShellCorpus/PoshCode/Migrate-ADMTUser_1.ps1
Migrate-ADMTUser_1.ps1
###########################################################################" # # NAME: Migrate-ADMTUser.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: A function to migrate a single user in the Active Directory Migration Tool, based on the sample script Invoke-ADMTUserMigration.ps1: http://poshcode.org/2046 # # Instead of hardcoding the variables for the migration, you could add additional parameters to the function to define these. # # NOTE: Since ADMT is a 32-bit application, this script must be run from Windows PowerShell (x86). # It also requires elevated privileges. # # For more details, see the following blog-post: # http://blog.powershell.no/2010/08/04/automate-active-directory-migration-tool-using-windows-powershell # # 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 04.08.2010 - Initial release # 1.1 04.08.2010 - Added support for pipeline input # ###########################################################################" function Migrate-ADMTUser { <# .SYNOPSIS Migrate a single user object using ADMT .DESCRIPTION Migrates the specified source domain user object to the target domain. One mandatory parameter: samaccountname .PARAMETER samaccountname The samaccountname of the source domain user object to migrate .EXAMPLE Migrate-ADMTUser -samaccountname JDoe .NOTES AUTHOR: Jan Egil Ring BLOG: http://blog.powershell.no LASTEDIT: 04.08.2010 #> [CmdletBinding()] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string]$samaccountname ) ### BEGIN ADMT Scripting Constants ### # PasswordOption constants $admtComplexPassword = "&H0001" $admtCopyPassword = "&H0002" $admtDoNotUpdatePasswordsForExisting = "&H0010" # ConflictOptions constants $admtIgnoreConflicting = "&H0000" $admtMergeConflicting = "&H0001" $admtRemoveExistingUserRights = "&H0010" $admtRemoveExistingMembers = "&H0020" $admtMoveMergedAccounts = "&H0040" # DisableOption constants $admtLeaveSource = "&H0000" $admtDisableSource = "&H0001" $admtTargetSameAsSource = "&H0000" $admtDisableTarget = "&H0010" $admtEnableTarget = "&H0020" # SourceExpiration constant $admtNoExpiration = "-1" # Translation Option $admtTranslateReplace = "0" $admtTranslateAdd = "1" $admtTranslateRemove = "2" # Report Type $admtReportMigratedAccounts = "0" $admtReportMigratedComputers = "1" $admtReportExpiredComputers = "2" $admtReportAccountReferences = "3" $admtReportNameConflicts = "4" # Option constants $admtNone = "0" $admtData = "1" $admtFile = "2" $admtDomain = "3" $admtRecurse = "&H0100" $admtFlattenHierarchy = "&H0000" $admtMaintainHierarchy = "&H0200" # Event related constants # Progress type $admtProgressObjectMigration = "0" $admtProgressAgentDispatch = "1" $admtProgressAgentOperation = "2" $admtProgressMailboxMigration = "3" # Event type $admtEventNone = "0" $admtEventObjectInputPreprocessed = "1" $admtEventTaskStart = "2" $admtEventTaskFinish = "3" $admtEventObjectProcessed = "4" $admtEventGroupMembershipProcessed = "5" $admtEventAgentStatusUpdate ="6" $admtEventAgentNotStarted = "7" $admtEventAgentFailedToStart = "8" $admtEventAgentWaitingForReboot = "9" $admtEventAgentRunning = "10" $admtEventAgentCancelled = "11" $admtEventAgentPassed = "12" $admtEventAgentFailed = "13" $admtEventAgentWaitingForRetry = "14" $admtEventAgentSuccessful = "15" $admtEventAgentCompletedWithWarnings = "16" $admtEventAgentCompletedWithErrors = "17" $admtEventTaskLogSaved = "18" $admtAgentPreCheckPhase = "&H100" $admtAgentAgentOperationPhase = "&H200" $admtAgentPostCheckPhase = "&H300" $admtAgentStatusMask = "&HFF" $admtAgentPhaseMask = "&H300" # Status type $admtStatusSuccess = "0" $admtStatusWarnings = "1" $admtStatusErrors = "2" ### END ADMT Scripting Constants ### #Creates an instance of an ADMT migration object using the COM-object provided with ADMT $Migration = New-Object -ComObject "ADMT.Migration" $Migration.IntraForest = $false $Migration.SourceDomain = "contoso-old.local" $Migration.SourceDomainController = "dc01.contoso-old.local" $Migration.SourceOU = "Europe/Norway/Oslo" $Migration.TargetDomain = "contoso-new.local" $Migration.TargetDomainController = "dc02.contoso-new.local" $Migration.TargetOU = "Europe/Norway/Oslo" $Migration.PasswordOption = $admtComplexPassword $Migration.PasswordServer = "dc01.contoso-old.local" $Migration.PasswordFile = "C:\\WINDOWS\\ADMT\\Logs\\Passwords.txt" $Migration.ConflictOptions = $admtIgnoreConflicting $Migration.UserPropertiesToExclude = "" $Migration.InetOrgPersonPropertiesToExclude = "" $Migration.GroupPropertiesToExclude = "" $Migration.ComputerPropertiesToExclude = "" $Migration.SystemPropertiesToExclude = "" $Migration.PerformPreCheckOnly = $false $Migration.AdmtEventLevel = $admtStatusWarnings $Migration.CommandLine = $false #Creates an user migration object $UserMigration = $Migration.CreateUserMigration() $UserMigration.DisableOption = $admtTargetSameAsSource $UserMigration.SourceExpiration = $admtNoExpiration $UserMigration.MigrateSIDs = $true $UserMigration.TranslateRoamingProfile = $false $UserMigration.UpdateUserRights = $false $UserMigration.MigrateGroups = $false $UserMigration.UpdatePreviouslyMigratedObjects = $false $UserMigration.FixGroupMembership = $true $UserMigration.MigrateServiceAccounts = $false #Initiates user migration. Logs are written to C:\\Windows\\ADMT\\Logs by default. $UserMigration.Migrate($admtData,$samaccountname,$null) #Creates a password migration object $PasswordMigration = $Migration.CreatePasswordMigration() #Initiates password migration. Logs are written to C:\\Windows\\ADMT\\Logs by default. $PasswordMigration.Migrate($admtData,$samaccountname,$null) }
PowerShellCorpus/PoshCode/Get-Cpl.ps1
Get-Cpl.ps1
function Get-Cpl { dir $env:windir\\system32 | Where-Object {$_.Extension -eq ".cpl"} | Select-Object Name,@{Name="Description";Expression={$_.VersionInfo.FileDescription}} | Sort-Object Description | Format-Table -AutoSize }
PowerShellCorpus/PoshCode/Chassis Type_1.ps1
Chassis Type_1.ps1
$system = Get-WMIObject -class Win32_systemenclosure $type = $system.chassistypes Switch ($Type) { "1" {"Chassis type is: $Type - Other"} "2" {"Chassis type is: $type - Virtual Machine"} "3" {"Chassis type is: $type - Desktop"} "4" {"Chassis type is: $type - Low Profile Desktop"} "5" {"Chassis type is: $type - Pizza Box"} "6" {"Chassis type is: $type - Mini Tower"} "7" {"Chassis type is: $type - Tower"} "8" {"Chassis type is: $type - Portable"} "9" {"Chassis type is: $type - Laptop"} "10" {"Chassis type is: $type - Notebook"} "11" {"Chassis type is: $type - Handheld"} "12" {"Chassis type is: $type - Docking Station"} "13" {"Chassis type is: $type - All-in-One"} "14" {"Chassis type is: $type - Sub-Notebook"} "15" {"Chassis type is: $type - Space Saving"} "16" {"Chassis type is: $type - Lunch Box"} "17" {"Chassis type is: $type - Main System Chassis"} "18" {"Chassis type is: $type - Expansion Chassis"} "19" {"Chassis type is: $type - Sub-Chassis"} "20" {"Chassis type is: $type - Bus Expansion Chassis"} "21" {"Chassis type is: $type - Peripheral Chassis"} "22" {"Chassis type is: $type - Storage Chassis"} "23" {"Chassis type is: $type - Rack Mount Chassis"} "24" {"Chassis type is: $type - Sealed-Case PC"} Default {"Chassis type is: $type - Unknown"} }
PowerShellCorpus/PoshCode/FTP upload.ps1
FTP upload.ps1
$File = "D:\\Dev\\somefilename.zip" $ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip" "ftp url: $ftp" $webclient = New-Object System.Net.WebClient $uri = New-Object System.Uri($ftp) "Uploading $File..." $webclient.UploadFile($Uri, $File)
PowerShellCorpus/PoshCode/Compare-PathAcl.ps1
Compare-PathAcl.ps1
[CmdletBinding()] param( [string]$Path = 'C:\\', [string]$User1 = "$Env:USERDOMAIN\\$Env:UserName", [string]$User2 = "BuiltIn\\Administrators", [switch]$recurse ) foreach($fso in ls $path -recurse:$recurse) { $acl = @(get-acl $fso.FullName | select -expand Access | Where IdentityReference -in $user1,$user2) if($acl.Count -eq 1) { Write-Warning "Only $($acl[0].IdentityReference) has access to $($fso.FullName)" } elseif($acl.Count -eq 2) { if(compare-object $acl[0] $acl[1] -Property FileSystemRights, AccessControlType) { Write-Warning "Different rights to $($fso.FullName)" } } # if acl.count -eq 0 they're the same }
PowerShellCorpus/PoshCode/Remove-AeroPeek.ps1
Remove-AeroPeek.ps1
function Remove-AeroPeek { PARAM( [string]$Title="*", [string]$Process="*" ) BEGIN { try { $null = [Huddled.DWM] } catch { Add-Type -Type @" using System; using System.Runtime.InteropServices; namespace Huddled { public static class Dwm { [DllImport("dwmapi.dll", PreserveSig = false)] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); [Flags] public enum DwmWindowAttribute { NCRenderingEnabled = 1, NCRenderingPolicy, TransitionsForceDisabled, AllowNCPaint, CaptionButtonBounds, NonClientRtlLayout, ForceIconicRepresentation, Flip3DPolicy, ExtendedFrameBounds, HasIconicBitmap, DisallowPeek, ExcludedFromPeek, Last } [Flags] public enum DwmNCRenderingPolicy { UseWindowStyle, Disabled, Enabled, Last } public static void RemoveFromAeroPeek(IntPtr Hwnd) //Hwnd is the handle to your window { int renderPolicy = (int)DwmNCRenderingPolicy.Enabled; DwmSetWindowAttribute(Hwnd, (int)DwmWindowAttribute.ExcludedFromPeek, ref renderPolicy, sizeof(int)); } } } "@ [Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") function global:Select-Window { PARAM( [string]$Title="*", [string]$Process="*", [switch]$Recurse, [System.Windows.Automation.AutomationElement]$Parent = [System.Windows.Automation.AutomationElement]::RootElement ) PROCESS { $search = "Children" if($Recurse) { $search = "Descendants" } $Parent.FindAll( $search, [System.Windows.Automation.Condition]::TrueCondition ) | Add-Member -Type ScriptProperty -Name Title -Value { $this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty)} -Passthru | Add-Member -Type ScriptProperty -Name Handle -Value { $this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty)} -Passthru | Add-Member -Type ScriptProperty -Name ProcessId -Value { $this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)} -Passthru | Where-Object { ((Get-Process -Id $_.ProcessId).ProcessName -like $Process) -and ($_.Title -like $Title) } }} } } PROCESS { Foreach($window in Select-Window -Process $Process -Title $Title) { [Huddled.Dwm]::RemoveFromAeroPeek( $window.Handle ) } } } # Remove-AeroPeek "Miranda IM" # Remove-AeroPeek -Process Rainlendar2
PowerShellCorpus/PoshCode/Out-CliXml.ps1
Out-CliXml.ps1
function Out-CliXml { <# .SYNOPSIS Creates an XML-based representation of an object or objects and outputs it as a string. .DESCRIPTION The Out-Clixml cmdlet creates an XML-based representation of an object or objects and outputs it as a string. This cmdlet is similar to Export-CliXml except it doesn't output to a file. .PARAMETER Depth Specifies how many levels of contained objects are included in the XML representation. The default value is 2. .PARAMETER InputObject Specifies the object to be converted. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to Out-Clixml. .INPUTS System.Management.Automation.PSObject You can pipe any object to Out-Clixml. .OUTPUTS System.String .EXAMPLE PS C:\\> Get-Process -Id $PID | Out-CliXml Description ----------- Outputs the XML-based representation of the PowerShell process. #> [CmdletBinding()] Param ( [ValidateRange(1, [Int32]::MaxValue)] [Int32] $Depth = 2, [Parameter(ValueFromPipeline = $True, Mandatory = $True)] [PSObject] $InputObject ) PROCESS { [System.Management.Automation.PSSerializer]::Serialize($InputObject, $Depth) } }
PowerShellCorpus/PoshCode/f19ac581-ba99-480c-a4ec-92f9084f0d26.ps1
f19ac581-ba99-480c-a4ec-92f9084f0d26.ps1
Function Get-EmptyGroup { <# .Synopsis Retrieves all groups without members in a domain or container. .Description Retrieves all groups without members in a domain or container. .Notes Name : Get-EmptyGroup Author : Oliver Lipkau <oliver.lipkau@gmail.com> Date : 2010/05/24 19:13 #Requires -Version 2.0 .Inputs System.String, System.Integer .Parameter SearchRoot A search base (the distinguished name of the search base object) defines the location in the directory from which the LDAP search begins .Parameter SizeLimit Maximum of results shown for a query .Parameter SearchScope A search scope defines how deep to search within the search base. Base , or zero level, indicates a search of the base object only. One level indicates a search of objects immediately subordinate to the base object, but does not include the base object itself. Subtree indicates a search of the base object and the entire subtree of which the base object distinguished name is the topmost object. .Outputs System.DirectoryServices.DirectoryEntry .Example Get-EmptyGroup #> [CmdletBinding()] param( [string]$SearchRoot, [ValidateNotNullOrEmpty()] [int]$PageSize = 1000, [int]$SizeLimit = 0, [ValidateNotNullOrEmpty()] [ValidateSet("Base","OneLevel","Subtree")] [string]$SearchScope = "SubTree" ) Begin { Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started" $c = 0 $filter = "(&(objectClass=group)(!member=*))" } Process { $root= New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE") $searcher = New-Object System.DirectoryServices.DirectorySearcher $filter if (!($SearchRoot)) {$SearchRoot=$root.defaultNamingContext} elseif (!($SearchRoot) -or ![ADSI]::Exists("LDAP://$SearchRoot")) {Write-Error "$($MyInvocation.MyCommand.Name):: SearchRoot value: '$SearchRoot' is invalid, please check value";return} $searcher.SearchRoot = "LDAP://$SearchRoot" Write-Verbose "$($MyInvocation.MyCommand.Name):: Searching in: $($searcher.SearchRoot)" $searcher.SearchScope = $SearchScope $searcher.SizeLimit = $SizeLimit $searcher.PageSize = $PageSize Write-Verbose "$($MyInvocation.MyCommand.Name):: Searching for: $($searcher.filter)" $searcher.FindAll() | ` Foreach-Object ` { $c++ Write-Verbose "$($MyInvocation.MyCommand.Name):: Found: $($_.Properties.cn)" $_.GetDirectoryEntry() } } End { Write-Verbose "$($MyInvocation.MyCommand.Name):: Found $c results" Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended" } }
PowerShellCorpus/PoshCode/New-ADSubnet.ps1
New-ADSubnet.ps1
param ($Subnet, $SiteName, $Location, [switch]$Help) function Help { "" Write-Host "Usage: .\\New-ADSubnet.ps1 -Help" -foregroundcolor Yellow Write-Host "Usage: .\\New-ADSubnet.ps1 <Subnet> <SiteName> <Location>" -foregroundcolor Yellow Write-Host "Ex: .\\New-ADSubnet.ps1 10.150.0.0/16 Default-First-Site-Name USA/KY/Louisville" -foregroundcolor Yellow "" Break } if ($Help) {Help} if ($Subnet -eq $Null) {Write-Host "Please provide a Subnet!" -fore Red; Help} if ($Location -eq $Null) {Write-Host "Please provide a Location!" -fore Red; Help} if ($SiteName -eq $Null) {Write-Host "Please provide a Site Name!" -fore Red; Help} if ($SiteName -like "CN=*") { $SiteNameRDN = $SiteName } else { $SiteNameRDN = "CN=$($SiteName)" } $Description = $Subnet $RootDSE = [ADSI]"LDAP://RootDSE" $ConfigurationNC = $RootDSE.configurationNamingContext $SubnetRDN = "CN=$($Subnet)" $Description = $Subnet $SiteDN = "$($SiteNameRDN),CN=Sites,$($ConfigurationNC)" $SubnetsContainer = [ADSI]"LDAP://CN=Subnets,CN=Sites,$($ConfigurationNC)" $NewSubnet = $SubnetsContainer.Create("subnet",$SubnetRDN) $NewSubnet.Put("siteObject", $SiteDN) $NewSubnet.Put("description", $Description) $NewSubnet.Put("location", $Location) trap {Continue} $NewSubnet.SetInfo() if (!$?) { "" Write-Host "An Error has Occured! Please Validate Your Input." -foregroundcolor Red Write-Host "Error Message:" -foregroundcolor Red $Error[0].Exception "" } else { "" Write-Host "Subnet Created Successfully." -foregroundcolor Green "" }
PowerShellCorpus/PoshCode/PROMPT_ Battery life.ps1
PROMPT_ Battery life.ps1
# ============================================================================================== # # Microsoft PowerShell Source File -- Created with SAPIEN Technologies PrimalScript 2007 # # NAME: Battery-Prompt.ps1 # # AUTHOR: Jeremy D. Pavleck , Pavleck.NET # DATE : 12/18/2008 # # COMMENT: Lists the percentage of battery remaining above your prompt inside the console. # Difficulty level: OVER 9000!!!!!!!!!!!!!!!! # # ============================================================================================== $GLOBAL:BatteryDisplayAtPercent = 101 # When should get start displaying status # Anything over 100 means to show it all Function GLOBAL:Get-BattLevel($minLevel) { $charge = (Get-WmiObject -Class Win32_Battery).EstimatedChargeRemaining If(!$charge) {break} # Not on a laptop, or no battery, so exit Switch($charge) { {($charge -ge 101) -and ($minLevel -ge 101)} {Write-Host "Batt: CHARGING" -ForeGroundColor Green} {($charge -ge 80) -and ($charge -le 100) -and ($charge -le $minLevel)} {Write-Host "Batt: $charge%" -ForeGroundColor Green} {($charge -ge 40) -and ($charge -le 79) -and ($charge -le $minLevel)} {Write-Host "Batt: $charge%" -ForeGroundColor Yellow} {($charge -ge 16) -and ($charge -le 39) -and ($charge -le $minLevel)} {Write-Host "Batt: $charge%" -ForeGroundColor Magenta} {($charge -ge 1) -and ($charge -le 15) -and ($charge -le $minLevel)} {Write-Host "Batt: $charge%" -ForeGroundColor Red} default {break} } } function prompt() { Get-BattLevel $GLOBAL:BatteryDisplayAtPercent }
PowerShellCorpus/PoshCode/Create-Printers_1.ps1
Create-Printers_1.ps1
###########################################################################" # # NAME: Create-Printers.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # BLOG: http://blog.powershell.no # # COMMENT: Simple script to bulk-create printers on a print-server. Printers are imported from a csv-file. # Running the script from Windows Server 2003 returns an access denied error, possibly due to the impersonation-model in Windows Server 2003. # Created and tested from Windows Server 2008 against a remote Windows Server 2003 print-server. # Should work from Windows Vista, Windows 7, Windows Server 2008 and Windows Server 2008 R2 against remote print-servers (2000/2003/2008/2008 R2) # # 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 # 1.0 07.11.2009 - Initial release # ###########################################################################" function CreatePrinter { $server = $args[0] $print = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_Printer").createInstance() $print.drivername = $args[1] $print.PortName = $args[2] $print.Shared = $true $print.Sharename = $args[3] $print.Location = $args[4] $print.Comment = $args[5] $print.DeviceID = $args[6] $print.Put() } function CreatePrinterPort { $server = $args[0] $port = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_TCPIPPrinterPort").createInstance() $port.Name= $args[1] $port.SNMPEnabled=$false $port.Protocol=1 $port.HostAddress= $args[2] $port.Put() } $printers = Import-Csv c:\\printers.csv foreach ($printer in $printers) { CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername }
PowerShellCorpus/PoshCode/Log Lost Pings.ps1
Log Lost Pings.ps1
# Logpings.ps1 # Version: 1.0 # Author: Jacob Saaby Nielsen # Author E-Mail: jsy@systematic.com # Purpose: Repeatedly ping a host, document lost pings to a logfile # Syntax: .\\Logpings hostname interval (where interval is a value representing seconds) # Requirements: /n Software's NetCmdlets http://www.nsoftware.com/powershell/ $PingedHost = $Args[0] $PingTime = $Args[1] $LogPath = 'c:\\' $KillSwitch = 1 while ($KillSwitch -ne 0) { Send-Ping $PingedHost if ($PingedHost.Status -ne "OK") { 'Lost connectivity at: ' + $(Get-Date -format "dd-MM-yyyy @ hh:mm:ss") | Out-File $($LogPath + $(Get-Date -format "dd-MM-yyyy") + '.log') -noClobber -append $Error.Clear() Start-Sleep $PingTime } else { Start-Sleep $PingTime } }
PowerShellCorpus/PoshCode/Import-Certificate_7.ps1
Import-Certificate_7.ps1
#requires -Version 2.0 function Import-Certificate { param ( [IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."), [string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."), [switch] $LocalMachine, [switch] $CurrentUser, [string] $CertPassword, [switch] $Verbose ) begin { [void][System.Reflection.Assembly]::LoadWithPartialName("System.Security") } process { if ($Verbose) { $VerbosePreference = 'Continue' } if (-not $LocalMachine -and -not $CurrentUser) { Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'." } try { if ($_) { $certfile = $_ } $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword } catch { Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue } if ($cert -and $LocalMachine) { $StoreScope = "LocalMachine" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } if ($cert -and $CurrentUser) { $StoreScope = "CurrentUser" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } } end { } }
PowerShellCorpus/PoshCode/Get-User_7.ps1
Get-User_7.ps1
function Get-User($user) { # this function should be passed the CN of the user to be returned $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))" $user = $searcher.FindOne() [System.Collections.Arraylist]$names = $user.Properties.PropertyNames [System.Collections.Arraylist]$props = $user.Properties.Values $userobj = New-Object System.Object for ($i = 0; $i -lt $names.Count) { $userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i]) $i++ } $userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset) $userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp) return $userobj }
PowerShellCorpus/PoshCode/new get-parameter script.ps1
new get-parameter script.ps1
param ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) $command = Get-Command $Cmdlet -ea silentlycontinue # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = Get-Command ($command.definition) } if (-not $command) { return } foreach ($paramset in $command.ParameterSets){ $Output = @() foreach ($param in $paramset.Parameters) { if ( ! $ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa| ev|wv|ov|ob|wi|cf") { continue } } $process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory, Pipeline, PipelineByPropertyName $process.Name = $param.Name if ( $param.ParameterType.Name -eq "SwitchParameter" ) { $process.Type = "Boolean" } else { switch -regex ( $param.ParameterType ) { "Nullable``1\\[(.+)\\]" { $process.Type = $matches[1].Split('.')[-1] + " (nullable)" ; break } default { $process.Type = $param.ParameterType.Name } } } if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases if ( $param.Position -lt 0 ) { $process.Position = $null } else { $process.Position = $param.Position } $process.IsMandatory = $param.IsMandatory $process.Pipeline = $param.ValueFromPipeline $process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName $output += $process } if ( ! $Full ) { $Output | ft name,type,IsMandatory,pipeline -GroupBy parameterset -AutoSize } else { Write-Output $Output } }
PowerShellCorpus/PoshCode/f316d247-86b3-4eee-b61f-313e456fe5d5.ps1
f316d247-86b3-4eee-b61f-313e456fe5d5.ps1
# This is to remove the Hidden folder attribute and delete the autorun.inf and x.mpeg due to changeup virus! # 4-3-2013 John R Remillard # You need the exact root folder path to unhide and delete the proper files and folders. #$Pth = Read-Host "Enter full path to unhide" $Lst = Get-Content c:\\Shares.txt foreach ($Pth in $Lst) { $File1 = Test-Path $Pth"autorun.inf" if ($File1 -eq "True") { $Pth | Out-File c:\\changup_virus.txt -append Remove-item -Path $Pth"autorun.inf" -Force Remove-item -Path $Pth"x.mpeg" -Force get-childitem $pth -directory -hidden | foreach {$_.Attributes="Normal"} } }
PowerShellCorpus/PoshCode/Get-HardlinkInfo.ps1
Get-HardlinkInfo.ps1
# .SYNOPSIS # Returns information about NTFS hard links. Only available on Windows Vista or later. # # .DESCRIPTION # This script can be used to determine how many alternate file names (i.e. hard link # siblings) a particular file has or to return all hard link siblings as FileInfo # objects. It uses the Win32 APIs FindFirstFileNameW and FindNextFileNameW to return # the hard link siblings, and these APIs are only available on Windows Vista or later. # # .PARAMETER $filepath # The file path you want to get hard link info for # # .PARAMETER $count # Will cause the script to return the count instead of the filenames. This is more # efficient than using measure-object on the returned FileInfo objects. # # .PARAMETER $all # When specified, will cause the script to return the FileInfo for the provided # filepath as well. When not specified, the file specified by the filepath # parameter is not returned. param( [string] $filepath, [switch] $count, [switch] $all ) $typeDef = @' using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace HardLinkEnumerator { public static class Kernel32Api { [StructLayout(LayoutKind.Sequential)] public struct BY_HANDLE_FILE_INFORMATION { public uint FileAttributes; public FILETIME CreationTime; public FILETIME LastAccessTime; public FILETIME LastWriteTime; public uint VolumeSerialNumber; public uint FileSizeHigh; public uint FileSizeLow; public uint NumberOfLinks; public uint FileIndexHigh; public uint FileIndexLow; } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern SafeFileHandle CreateFile( string lpFileName, [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess, [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode, IntPtr lpSecurityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition, [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetFileInformationByHandle(SafeFileHandle handle, out BY_HANDLE_FILE_INFORMATION lpFileInformation); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool CloseHandle(SafeHandle hObject); [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr FindFirstFileNameW( string lpFileName, uint dwFlags, ref uint stringLength, StringBuilder fileName); [DllImport("kernel32.dll", SetLastError = true, CharSet=CharSet.Unicode)] static extern bool FindNextFileNameW( IntPtr hFindStream, ref uint stringLength, StringBuilder fileName); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FindClose(IntPtr fFindHandle); [DllImport("kernel32.dll")] static extern bool GetVolumePathName(string lpszFileName, [Out] StringBuilder lpszVolumePathName, uint cchBufferLength); [DllImport("shlwapi.dll", CharSet = CharSet.Auto)] static extern bool PathAppend([In, Out] StringBuilder pszPath, string pszMore); public static int GetFileLinkCount(string filepath) { int result = 0; SafeFileHandle handle = CreateFile(filepath, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Archive, IntPtr.Zero); BY_HANDLE_FILE_INFORMATION fileInfo = new BY_HANDLE_FILE_INFORMATION(); if (GetFileInformationByHandle(handle, out fileInfo)) result = (int)fileInfo.NumberOfLinks; CloseHandle(handle); return result; } public static string[] GetFileSiblingHardLinks(string filepath) { List<string> result = new List<string>(); uint stringLength = 256; StringBuilder sb = new StringBuilder(256); GetVolumePathName(filepath, sb, stringLength); string volume = sb.ToString(); sb.Length = 0; stringLength = 256; IntPtr findHandle = FindFirstFileNameW(filepath, 0, ref stringLength, sb); if (findHandle.ToInt32() != -1) { do { StringBuilder pathSb = new StringBuilder(volume, 256); PathAppend(pathSb, sb.ToString()); result.Add(pathSb.ToString()); sb.Length = 0; stringLength = 256; } while (FindNextFileNameW(findHandle, ref stringLength, sb)); FindClose(findHandle); return result.ToArray(); } return null; } } } '@ $type = Add-Type -TypeDefinition $typeDef function global:Get-HardlinkInfo( [string] $filepath, [switch] $count, [switch] $all ) { $filepath = resolve-path $filepath if ($count) { [HardLinkEnumerator.Kernel32Api]::GetFileLinkCount($filepath) } else { $links = [HardLinkEnumerator.Kernel32Api]::GetFileSiblingHardLinks($filepath) if ($all) { $links | get-childitem } else { $links | ? { $_ -ne $filepath } | get-childitem } } } Get-HardLinkInfo @PSBoundParameters
PowerShellCorpus/PoshCode/Out-Html_1.ps1
Out-Html_1.ps1
################################################################################ # Out-HTML - converts module functions or cmdlet help to HTML format # Minor modification of Vegard Hamar's OUT-HTML to support modules instead of pssnapin's # Based on Out-wiki by Dimitry Sotnikov (http://dmitrysotnikov.wordpress.com/2008/08/18/out-wiki-convert-powershell-help-to-wiki-format/) # # Modify the invocation line at the bottom of the script if you want to document # fewer command, subsets or snapins # Open default.htm to view in frameset or index.htm for index page with links. ################################################################################ # Created By: Vegard Hamar ################################################################################ param($outputDir = "./help") function FixString { param($in = "") if ($in -eq $null) { $in = "" } return $in.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;") } function Out-HTML { param($commands = $null, $outputDir = "./help") $commandsHelp = $commands | sort-object modulename, name | get-help -full #create an output directory if ( -not (Test-Path $outputDir)) { md $outputDir | Out-Null } #Generate frame page $indexFileName = $outputDir + "/index.htm" #Generate frameset @' <html> <head> <title>PowerShell Help</title> </head> <frameset cols="250,*"> <frame src="./index.htm" /> <frame src="" name="display"/> </frameset> </html> '@ | Out-File "$outputDir/default.htm" #Generate index @' <html> <head> <title>PowerShell Help</title> </head> <body> '@ | out-file $indexFileName $SnapIn = "" foreach ($c in $commandsHelp) { if ($SnapIn -ne $c.modulename) { "<a href='#" + $c.modulename + "'>* " + $c.modulename.Replace(".", " ") + "</a></br>" | out-file $indexFileName -Append $SnapIn = $c.modulename } } $SnapIn = "" foreach ($c in $commandsHelp) { if ($SnapIn -ne $c.modulename) { "<h3><a name='$($c.modulename)'>" +$c.modulename.Replace(".", " ") + "</a></h3>" | Out-File $indexFileName -Append $SnapIn = $c.modulename } "<a href='" + $c.name + ".htm' target='display'>* $($c.Name)</a></br>" | out-file $indexFileName -Append } #Generate all single help files $outputText = $null foreach ($c in $commandsHelp) { $fileName = ( $outputDir + "/" + $c.Name + ".htm" ) @" <html> <head> <title>$($c.Name)</title> </head> <body> <h1>$($c.Name)</h1> <div>$($c.synopsis)</div> <h2> Syntax </h2> <code>$(FixString($c.syntax | out-string -width 2000).Trim())</code> <h2> Detailed Description </h2> <div>$(FixString($c.Description | out-string -width 2000))</div> <h2> Related Commands </h2> <div> "@ | out-file $fileName foreach ($relatedLink in $c.relatedLinks.navigationLink) { if($relatedLink.linkText -ne $null -and $relatedLink.linkText.StartsWith("about") -eq $false){ " * <a href='$($relatedLink.linkText).htm'>$($relatedLink.linkText)</a><br/>" | out-file $fileName -Append } } @" </div> <h2> Parameters </h2> <table border='1'> <tr> <th>Name</th> <th>Description</th> <th>Required?</th> <th>Pipeline Input</th> <th>Default Value</th> </tr> "@ | out-file $fileName -Append $paramNum = 0 foreach ($param in $c.parameters.parameter ) { @" <tr valign='top'> <td>$($param.Name)&nbsp;</td> <td>$(FixString(($param.Description | out-string -width 2000).Trim()))&nbsp;</td> <td>$(FixString($param.Required))&nbsp;</td> <td>$(FixString($param.PipelineInput))&nbsp;</td> <td>$(FixString($param.DefaultValue))&nbsp;</td> </tr> "@ | out-file $fileName -Append } " </table>}" | out-file $fileName -Append # Input Type if (($c.inputTypes | Out-String ).Trim().Length -gt 0) { @" <h2> Input Type </h2> <div>$(FixString($c.inputTypes | out-string -width 2000).Trim())</div> "@ | out-file $fileName -Append } # Return Type if (($c.returnValues | Out-String ).Trim().Length -gt 0) { @" <h2> Return Values </h2> <div>$(FixString($c.returnValues | out-string -width 2000).Trim())</div> "@ | out-file $fileName -Append } # Notes if (($c.alertSet | Out-String).Trim().Length -gt 0) { @" <h2> Notes </h2> "<div>$(FixString($c.alertSet | out-string -Width 2000).Trim())</div> "@ | out-file $fileName -Append } # Examples if (($c.examples | Out-String).Trim().Length -gt 0) { " <h2> Examples </h2>" | out-file $fileName -Append foreach ($example in $c.examples.example) { @" <h3> $(FixString($example.title.Trim(('-',' '))))</h3> <pre>$(FixString($example.code | out-string ).Trim())</pre> <div>$(FixString($example.remarks | out-string -Width 2000).Trim())</div> "@ | out-file $fileName -Append } } @" </body> </html> "@ | out-file $fileName -Append } @" </body> </html> "@ | out-file $indexFileName -Append } Out-HTML ( get-command | where {$_.modulename -ne $null}) $outputDir
PowerShellCorpus/PoshCode/Get-PrivateProfileString.ps1
Get-PrivateProfileString.ps1
#############################################################################\n##\n## Get-PrivateProfileString\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\nRetrieves an element from a standard .INI file\n\n.EXAMPLE\n\nGet-PrivateProfileString c:\\windows\\system32\\tcpmon.ini `\n "<Generic Network Card>" Name\nGeneric Network Card\n\n#>\n\nparam(\n ## The INI file to retrieve\n $Path,\n\n ## The section to retrieve from\n $Category,\n\n ## The item to retrieve\n $Key\n)\n\nSet-StrictMode -Version Latest\n\n## The signature of the Windows API that retrieves INI\n## settings\n$signature = @'\n[DllImport("kernel32.dll")]\npublic static extern uint GetPrivateProfileString(\n string lpAppName,\n string lpKeyName,\n string lpDefault,\n StringBuilder lpReturnedString,\n uint nSize,\n string lpFileName);\n'@\n\n## Create a new type that lets us access the Windows API function\n$type = Add-Type -MemberDefinition $signature `\n -Name Win32Utils -Namespace GetPrivateProfileString `\n -Using System.Text -PassThru\n\n## The GetPrivateProfileString function needs a StringBuilder to hold\n## its output. Create one, and then invoke the method\n$builder = New-Object System.Text.StringBuilder 1024\n$null = $type::GetPrivateProfileString($category,\n $key, "", $builder, $builder.Capacity, $path)\n\n## Return the output\n$builder.ToString()
PowerShellCorpus/PoshCode/Get-UNCPath.ps1
Get-UNCPath.ps1
function Get-UNCPath {param( [string]$HostName, [string]$LocalPath) $NewPath = $LocalPath -replace(":","$") #delete the trailing \\, if found if ($NewPath.EndsWith("\\")) { $NewPath = [Text.RegularExpressions.Regex]::Replace($NewPath, "\\\\$", "") } "\\\\$HostName\\$NewPath" }
PowerShellCorpus/PoshCode/Import-Certificate_6.ps1
Import-Certificate_6.ps1
#requires -Version 2.0 function Import-Certificate { param ( [IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."), [string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."), [switch] $LocalMachine, [switch] $CurrentUser, [string] $CertPassword, [switch] $Verbose ) begin { [void][System.Reflection.Assembly]::LoadWithPartialName("System.Security") } process { if ($Verbose) { $VerbosePreference = 'Continue' } if (-not $LocalMachine -and -not $CurrentUser) { Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'." } try { if ($_) { $certfile = $_ } $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword } catch { Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue } if ($cert -and $LocalMachine) { $StoreScope = "LocalMachine" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } if ($cert -and $CurrentUser) { $StoreScope = "CurrentUser" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } } end { } }
PowerShellCorpus/PoshCode/Get-SpecialPath.ps1
Get-SpecialPath.ps1
############################################################################### ## Get-SpecialPath Function (should be an external function in your profile, really) ## This is an enhancement of [Environment]::GetFolderPath($folder) to add ## support for 8 additional folders, including QuickLaunch, and the common ## or "All Users" folders... while still supporting My Documents, Startup, etc. ## #FUNCTION Get-SpecialPath #{ param([string]$folder) BEGIN { if ($folder.Length -gt 0) { return $folder | &($MyInvocation.InvocationName); } else { $WshShellFolders=@{CommonDesktop=0;CommonStartMenu=1;CommonPrograms=2;CommonStartup=3;PrintHood=6;Fonts=8;NetHood=9}; } } PROCESS { if($_){ ## Eliminate the options that are easiest to eliminate if($_ -eq "QuickLaunch") { $f1 = [Environment]::GetFolderPath("ApplicationData") return Join-Path $f1 "\\Microsoft\\Internet Explorer\\Quick Launch" ## Test WshShellFolders first because it's easiest won't throw an exception } elseif($WshShellFolders.Contains($_)){ if(-not (Test-Path variable:\\global:WshShell)) { $global:WshShell = New-Object -com "WScript.Shell" } return ([string[]]$global:WshShell.SpecialFolders)[$WshShellFolders[$_]] } else { ## Finally, try GetFolderPath, and if it throws, change the error message: trap { throw new-object system.componentmodel.invalidenumargumentexception $( "Cannot convert value `"$_`" to type `"SpecialFolder`" due to invalid enumeration values. " + "Specify one of the following enumeration values and try again. The possible enumeration values are: " + "Desktop, Programs, Personal, MyDocuments, Favorites, Startup, Recent, SendTo, StartMenu, MyMusic, " + "DesktopDirectory, MyComputer, Templates, ApplicationData, LocalApplicationData, InternetCache, Cookies, " + "History, CommonApplicationData, System, ProgramFiles, MyPictures, CommonProgramFiles, CommonDesktop, " + "CommonStartMenu, CommonPrograms, CommonStartup, PrintHood, Fonts, NetHood, QuickLaunch") } return [Environment]::GetFolderPath($_) } } } #}
PowerShellCorpus/PoshCode/PowerCLI error report.ps1
PowerCLI error report.ps1
$moveVmScript = { Connect-VIServer yourVCenterServer Move-VM WinXP -Location yourDestinationHost } $ moveVmScript | Get-ErrorReport -ProblemScriptTimeoutSeconds 120 -ProblemDescription "An error is returned by Move-VM. The operation should be successful. The same can be done via the vClient." -Destination 'D:\\bug report' –DontIncludeServerLogs