full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/out-playlist.ps1
out-playlist.ps1
param( [parameter(Mandatory=$true)] [string] $name, [parameter(Mandatory=$true,ValueFromPipeline=$true)] $file ) begin { $script:files = @(); } process { $script:files += $file.fullname; } end { $count = $script:files.length; $mediaElements = $script:files | foreach{ "<media src='$_' />" }; [xml]$playlist = @" <?wpl version="1.0"?> <smil> <head> <meta name="Generator" content="out-playlist.ps1"/> <meta name="IsNetworkFeed" content="0"/> <meta name="ItemCount" content="$count"/> <title>$name</title> </head> <body> <seq> $mediaElements </seq> </body> </smil> "@; new-item "~\\documents\\my music\\playlists\\$name.wpl" -value '' -type file -force | out-null; $playlist.save( ("~\\documents\\my music\\playlists\\$name.wpl" | resolve-path) ); }
PowerShellCorpus/PoshCode/Backup-ModifiedGPOsv_1.1.ps1
Backup-ModifiedGPOsv_1.1.ps1
###########################################################################" # # NAME: Backup-ModifiedGPOs.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: All Group Policy Objects modified in the specified timespan are backup up to the specified backup path. # For more details, see the following blog-post: # http://blog.powershell.no/2010/06/15/backing-up-group-policy-objects-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 15.06.2010 - Initial release # # 1.1 17.11.2010 - Andy Helsby - Added check to create backup directory and report directory if it does not exist. # - Added optional parameter to allow backups of gpo's modified in last X days (defaults to 1 otherwise) # - Note if no group policies were modified in the previous X days, the script does throw an error about Name not being provided. ###########################################################################" #Requires -Version 2.0 Import-Module grouppolicy $BackupPath = "C:\\GPO Backup" $ReportPath = "C:\\GPO Backup\\Reports\\" if (!(Test-Path -path $ReportPath)) {New-Item $ReportPath -type directory} [int]$NumberofDaysBackup = $args[0] #Above line throws error if parameter was not numeric - safe to ignore due to next line #Set value to 1 if not already passed in parameter if ($NumberofDaysBackup -lt 1) {$NumberofDaysBackup = 1} $Timespan = (Get-Date).AddDays(-1) $ModifiedGPOs = Get-GPO -all | Where-Object {$_.ModificationTime -gt $Timespan} Write-Host "The following "$ModifiedGPOs.count" GPOs were successfully backed up:" -ForegroundColor yellow Foreach ($GPO in $ModifiedGPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $BackupPath $Path = $ReportPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html" Get-GPOReport -Name $GPO.DisplayName -path $Path -ReportType HTML Write-Host $GPO.DisplayName }
PowerShellCorpus/PoshCode/ef87bae5-0285-4381-94e0-6da00a3d4525.ps1
ef87bae5-0285-4381-94e0-6da00a3d4525.ps1
while($cell.value2.length -ge 0) { $name = $cell.value2 $sam = $cell.offset(0,1).value2 $givenName = $cell.offset(0,2).value2 $surName = $cell.offset(0,3).value2 $displayName = $cell.offset(0,4).value2 $password = $cell.offset(0, 5).value2 write-host "navn:" $name "`t`t,sam:" $sam "`t,GivenName:" $givenName "`t, surname:" $surName "`t,displayName:" $displayName "`t, password:" $password #new cell one row down $cell = $cell.offset(1, 0) }
PowerShellCorpus/PoshCode/DefaultParameterValues.ps1
DefaultParameterValues.ps1
#requires -Version 3.0 function Join-Hashtable { param( [Hashtable]$First, [Hashtable]$Second, [Switch]$Force ) $Firsts = $First.Keys $Output = @{} + $First foreach($key in $Second.Keys) { if($Firsts -notcontains $Key) { $Output.$Key = $Second.$Key } elseif($Force) { $Output.$Key = $Second.$Key } } $Output } function Export-DefaultParameterValues { param( $Path = "DefaultParameterValues.ps1xml", [Switch]$AllUsers ) if((Split-Path $Path -Leaf) -eq $Path) { if($AllUsers) { $Path = Join-Path (Split-Path $Profile.AllUsersAllHosts) $Path } else { $Path = Join-Path (Split-Path $Profile.CurrentUserAllHosts) $Path } } Export-Clixml -InputObject $PSDefaultParameterValues -Path $Path } function Import-DefaultParameterValues { param( $Path = "DefaultParameterValues.ps1xml", [Switch]$AllUsers, [Switch]$Force ) if((Split-Path $Path -Leaf) -eq $Path) { if($AllUsers) { $Path = Join-Path (Split-Path $Profile.AllUsersAllHosts) $Path } else { $Path = Join-Path (Split-Path $Profile.CurrentUserAllHosts) $Path } } if($PSDefaultParameterValues.Count -eq 0) { $Global:PSDefaultParameterValues = Import-Clixml -Path $Path } else { $PSD = Import-Clixml -Path $Path $Global:PSDefaultParameterValues = Join-Hashtable $PSDefaultParameterValues $PSD -Force:$Force } }
PowerShellCorpus/PoshCode/User Obj ProxyAddresses.ps1
User Obj ProxyAddresses.ps1
Function Get-Proxy() { Process { $objDomain = New-Object System.DirectoryServices.DirectoryEntry $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = "(cn=$_)" $objSearcher.SearchScope = "Subtree" $objUser = $objSearcher.FindOne() [String]$DN = $objUser.properties.distinguishedname $UserObj = [ADSI]"LDAP://$DN" [String]$displayname = $UserObj.displayname [String]$exchalias = $UserObj.mailnickname [Array]$exchproxy = $UserObj.proxyaddresses $displayname $exchalias ForEach($proxy In $exchproxy) { $proxy } } } [String]$UserCN = "bricep" $UserCN | Get-Proxy
PowerShellCorpus/PoshCode/CSV-DVS.ps1
CSV-DVS.ps1
$vmlist = Import-Csv toolboxesx.csv #vsphere settings $vsphere_server = "" $cluster_name = "" #dvSwitch Names to connect each side to $prod_net = "" $aux_net = "" #Networks to temporarally add the vmxnet3 nics to before connecting to dvSwitch $prod_temp_net = "" $aux_temp_net = "" #Folder to add VM's to $folder_id = "" #Script Start $vsphere = Connect-VIServer $vsphere_server $cluster = Get-Cluster $cluster_name $datacenter = Get-Datacenter -cluster $cluster $folder = Get-Folder -Id $folder_id foreach($vm in $vmlist) { $vmhost = $cluster | Get-VMHost | Sort-Object -Property MemoryUsageMB | Where-Object {$_.State -eq "Connected"} if ($vmhost.length -gt 1) { $vmhost = $vmhost[0] } $datastore = $vmhost | Get-Datastore | Sort-Object -Property FreeSpaceMB -desc | Where-Object {$_.CapacityMB -gt 100000} | Where-Object {$_.FreeSpaceMB -gt 30000} #using 100gb as threshold for local storage vs san storage and not adding to any datastore with less than 30gb free space if ($datastore.length -gt 1) { $datastore = $datastore[0] } $vmdisk =[Math]::Round([Int32]::Parse($vm.Disk)*1024) $esx = $vmhost | Get-View Write-Host Finding Prod/Aux Switches on $vmhost foreach($netMoRef in $esx.Network){ if($netMoRef.Type -eq "DistributedVirtualPortGroup"){ $net = Get-View -Id $netMoRef if($net.Name -eq $prod_net){ $prod_PGKey = $net.MoRef.Value $prod_Uuid = (Get-View -Id $net.Config.DistributedVirtualSwitch).Summary.Uuid } if($net.Name -eq $aux_net){ $aux_PGKey = $net.MoRef.Value $aux_Uuid = (Get-View -Id $net.Config.DistributedVirtualSwitch).Summary.Uuid } } } Write-Host Creating $vm.Name on host $vmhost New-VM -Debug -name $vm.Name -vmhost $vmhost -Location $folder -DiskStorageFormat thick -NumCpu 2 -DiskMB $vmdisk -memoryMB $vm.Memory -Datastore $datastore.Name -GuestID $vm.OS -Description $vm.Description $adapter = Get-NetworkAdapter -VM $vm.Name Remove-NetworkAdapter -NetworkAdapter $adapter -confirm:$false $vm = Get-VM $vm.Name New-NetworkAdapter -VM $vm -NetworkName $prod_temp_net -Type "vmxnet3" -StartConnected New-NetworkAdapter -VM $vm -NetworkName $aux_temp_net -Type "vmxnet3" -StartConnected $view = $vm | Get-View $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec foreach($tempdev in $view.Config.Hardware.Device){ if($tempdev.DeviceInfo.Label -eq "Network adapter 1"){ Write-Host "Connecting VM to Prod Switch $prod_net" $devSpec = New-Object VMware.Vim.VirtualDeviceConfigSpec $dev = New-Object ("VMware.Vim." + $tempdev.GetType().Name) $dev.deviceInfo = New-Object VMware.Vim.Description $dev.deviceInfo.label = $tempdev.DeviceInfo.Label $dev.deviceInfo.summary = $tempdev.DeviceInfo.Summary $dev.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo $dev.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection $dev.Backing.Port.PortgroupKey = $prod_PGKey $dev.Backing.Port.SwitchUuid = $prod_Uuid $dev.Key = $tempdev.Key $devSpec.Device = $dev $devSpec.Operation = "edit" $vmConfigSpec.deviceChange += $devSpec } if($tempdev.DeviceInfo.Label -eq "Network adapter 2"){ Write-Host "Connecting VM to Aux Switch $aux_net" $devSpec = New-Object VMware.Vim.VirtualDeviceConfigSpec $dev = New-Object ("VMware.Vim." + $tempdev.GetType().Name) $dev.deviceInfo = New-Object VMware.Vim.Description $dev.deviceInfo.label = $tempdev.DeviceInfo.Label $dev.deviceInfo.summary = $tempdev.DeviceInfo.Summary $dev.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo $dev.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection $dev.Backing.Port.PortgroupKey = $aux_PGKey $dev.Backing.Port.SwitchUuid = $aux_Uuid $dev.Key = $tempdev.Key $devSpec.Device = $dev $devSpec.Operation = "edit" $vmConfigSpec.deviceChange += $devSpec } } Write-Host "Reconfiguring VM" foreach($v in $view){ $v.ReconfigVM($vmConfigSpec) } $vm | Start-VM -Confirm:$false Write-Host $vm.Name "Done" }
PowerShellCorpus/PoshCode/Get-NestedGroups v_1.ps1
Get-NestedGroups v_1.ps1
Function Global:Get-NestedGroups { <# .SYNOPSIS Enumerate all AD group memberships of an account (including nested membership). .DESCRIPTION This script will return the AD group objects for each group the user is a member of. .PARAMETER UserName The username whose group memberships to find. .EXAMPLE Get-NestedGroups johndoe | Out-GridView Get-NestedGroups johndoe, janedoe | % { $_ | Out-GridView } Get-ADUser -Filter "cn -like 'john*'" | % { Get-NestedGroups $_ | Sort-Object Name | Out-GridView -Title "Groupmembership for $($_)" } "johndoe","janedoe" | % { Get-NestedGroups $_ | Sort-Object Name | Export-CSV Groupmembership-$($_.Name).csv -Delimiter ";" } "johndoe","janedoe" | Get-NestedGroups | % { Sort-Object Name | Out-GridView } .NOTES ScriptName : Get-NestedGroups Created By : Gilbert van Griensven Date Coded : 06/17/2012 Updated : 08/11/2012 The script iterates through all nested groups and skips circular nested groups. .LINK #> [CmdletBinding(SupportsShouldProcess=$True)] Param ( [Parameter(Mandatory=$True,ValueFromPipeline=$True,HelpMessage="Please enter a username")] $UserName ) Begin { $PipelineInput = -not $PSBoundParameters.ContainsKey("UserName") Write-Verbose "Looking for ActiveDirectory module" $Script:ADModuleUnload = $False If (!(Get-Module ActiveDirectory)) { Write-Verbose "ActiveDirectory module not loaded - checking availability" If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) { Write-Verbose "ActiveDirectory module is available - loading module" Import-Module ActiveDirectory } Else { Write-Verbose "ActiveDirectory Module is not available" $Script:ADModuleUnload = $True } } Else { Write-Verbose "ActiveDirectory Module is already loaded" $Script:ADModuleUnload = $True } Function GetNestedGroups { Get-ADGroup $_ -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % { If (!(($Script:GroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains (Get-ADGroup $_).DistinguishedName)) { $Script:GroupMembership += (Get-ADGroup $_) GetNestedGroups $_ } } } Function GetDirectGroups { $InputType = $_.GetType().Name If (($InputType -ne "ADUser") -and ($InputType -ne "String")) { Write-Error "Invalid input type `'$($_.GetType().FullName)`'" -Category InvalidType -TargetObject $_ Break } If ($InputType -eq "String") { Try { Write-Verbose "Querying Active Directory for user `'$($_)`'" $UserObject = Get-ADUser $_ } Catch { Write-Verbose "$_" Write-Error $_ -Category ObjectNotFound -TargetObject $_ Break } } Else { $UserObject = $_ } $Script:GroupMembership = @() $Script:GroupMembership += (Get-ADGroup "Domain Users") Get-ADUser $UserObject -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % { $Script:GroupMembership += (Get-ADGroup $_) } $Script:GroupMembership | ForEach-Object {GetNestedGroups $_} } } Process { If ($PipelineInput) { GetDirectGroups $_ , $Script:GroupMembership } Else { $UserName | ForEach-Object { GetDirectGroups $_ $Script:GroupMembership } } } End { If (!($Script:ADModuleUnload)) { Write-Verbose "Removing module ActiveDirectory" Remove-Module ActiveDirectory -ErrorAction SilentlyContinue } } }
PowerShellCorpus/PoshCode/Import-Delimited.ps1
Import-Delimited.ps1
################################################################################ ## Convert-Delimiter - A function to convert between different delimiters. ## E.g.: commas to tabs, tabs to spaces, spaces to commas, etc. ################################################################################ ## Written primarily as a way of enabling the use of Import-CSV when ## the source file was a columnar text file with data like services.txt: ## ip service port ## 13.13.13.1 http 8000 ## 13.13.13.2 https 8001 ## 13.13.13.1 irc 6665-6669 ## ## Sample Use: ## Get-Content services.txt | Convert-Delimiter " +" "," | Set-Content services.csv ## would convert the file above into something that could passed to: ## Import-Csv services.csv ## ## Get-Content Delimited.csv | Convert-Delimiter "," "`t" | Set-Content Delimited.tab ## would convert a simple comma-separated-values file to a tab-delimited file ## Function Convert-Delimiter([regex]$from,[string]$to) { process { ## replace the original delimiter with the new one, wrapping EVERY block in Þ ## if there's quotes around some text with a delimiter, assume it doesn't count ## if there are two quotes "" stuck together inside quotes, assume they're an 'escaped' quote $_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:((?:.(?!$from))*.)(?:$from|`$))","Þ`$1`$2Þ$to" ## clean up the end where there might be duplicates $_ = $_ -replace "Þ(?:$to|Þ)?`$","Þ" ## normalize quotes so that they're all double "" quotes $_ = $_ -replace "`"`"","`"" -replace "`"","`"`"" ## remove the Þ wrappers if there are no quotes inside them $_ = $_ -replace "Þ((?:[^Þ`"](?!$to))+)Þ($to|`$)","`$1`$2" ## replace the Þ with quotes, and explicitly emit the result write-output $_ -replace "Þ","`"" } } ################################################################################ ## Import-Delimited - A replacement function for Import-Csv that can handle other ## delimiters, and can import text (and collect it together) from the pipeline!! ## Dependends on the Convert-Delimiter function. ################################################################################ ## NOTICE that this means you can use this to import multitple CSV files as one: ## Sample Use: ## ls ..\\*.txt | export-csv textfiles.csv ## ls *.doc | export-csv docs.csv ## ls C:\\Windows\\System32\\*.hlp | export-csv helpfiles.csv ## ## $files = ls *.csv | Import-Delimited ## OR ## Import-Delimited " +" services1.txt ## OR ## gc *.txt | Import-Delimited " +" ################################################################################ ## Version History ## Version 1.0 ## First working version ## Version 2.0 ## Filter #TYPE lines ## Remove dependency on Convert-Delimiter if the files are already CSV ## Change to use my Template-Pipeline format (removing the nested Import-String function) ## Version 2.1 ## Fix a stupid bug ... ## Add filtering for lines starting with "--", hopefully that's not a problem for other people... ## Added Write-DEBUG output for filtered lines... Function Import-Delimited([regex]$delimiter=",", [string]$PsPath="") { BEGIN { if ($PsPath.Length -gt 0) { write-output ($PsPath | &($MyInvocation.InvocationName) $delimiter); } else { $script:tmp = [IO.Path]::GetTempFileName() write-debug "Using tempfile $($script:tmp)" } } PROCESS { if($_ -and $_.Length -gt 0 ) { if(Test-Path $_) { if($delimiter -eq ",") { Get-Content $_ | Where-Object {if($_.StartsWith("#TYPE") -or $_.StartsWith("--")){ write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp } else { Get-Content $_ | Convert-Delimiter $delimiter "," | Where-Object { if( $_.StartsWith("--") ) { write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp } } else { if($delimiter -eq ",") { $_ | Where-Object {-not $_.StartsWith("#TYPE")} | Add-Content $script:tmp } else { $_ | Convert-Delimiter $delimiter "," | Add-Content $script:tmp } } } } END { # Need to guard against running this twice when you pass PsPath if ($PsPath.Length -eq 0) { Write-Output (Import-Csv $script:tmp) } } }
PowerShellCorpus/PoshCode/map network drive.ps1
map network drive.ps1
# map2_gps_prod.ps1 # Maps a network drive using PowerShell # # # # $Drive = "O:" $UNC = "\\\\ampwcsqlsvr2\\nam401k" cls # if the drive exists just remove it if (((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object ` {$_ -eq $Drive})) { # true remove drive # Create the Com object with New-Object -com $net = $(New-Object -comobject WScript.Network) $net.RemoveNetworkDrive($Drive,1) } # if the drive does not exist just add it if (!((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object ` {$_ -eq $Drive})) { # Create the Com object with New-Object -com $net = $(New-Object -comobject WScript.Network) $net.mapnetworkdrive($Drive,$Unc) } # Launches windows Explorer and goes to the maped drive explorer.exe $Drive
PowerShellCorpus/PoshCode/Convert-PowerPack2Ps_2.ps1
Convert-PowerPack2Ps_2.ps1
####################################################################### # Convert-PowerPack2Ps1 # # Converts PowerGUI .PowerPack files to ps1 PowerShell script library # v1 - raw conversion, no name changes, only script elements converted ###################################################################### # Example: # & .\\Convert-PowerPack2Ps1.ps1 "ActiveDirectory.powerpack" "ActiveDirectory.ps1" # . .\\ActiveDirectory.ps1 # Get-QADUser 'Dmitry Sotnikov' | MemberofRecursive ###################################################################### # # (c) Dmitry Sotnikov # http://dmitrysotnikov.wordpress.com # ##################################################################### param( $PowerPackFile = $(throw 'Please supply path to source powerpack file'), $OutputFilePath = $(throw 'Please supply path to output ps1 file') ) #region Functions function IterateTree { # processes all script nodes param($segment) if ( $segment.Type -like 'Script*' ) { $name = $segment.name -replace ' |\\(|\\)', '' $code = $segment.script.PSBase.InnerText @" ######################################################################## # Function: $name # Return type: $($segment.returntype) ######################################################################## function $name { $code } "@ | Out-File $OutputFilePath -Append } # recurse folders if ($segment.items.container -ne $null) { $segment.items.container | ForEach-Object { IterateTree $_ } } } function Output-Link { PROCESS { if ( $_.script -ne $null ) { $name = $_.name -replace ' |\\(|\\)', '' $code = $_.script.PSBase.InnerText @" ######################################################################## # Function: $name # Input type: $($_.type) # Return type: $($_.returntype) ######################################################################## function $name { $code } "@ | Out-File $OutputFilePath -Append } } } #endregion $sourcefile = Get-ChildItem $PowerPackFile if ($sourcefile -eq $null) { throw 'File not found' } @" ######################################################################## # Generated from: $PowerPackFile # by Convert-PowerPack2Ps1 script # on $(get-date) ######################################################################## "@ | Out-File $OutputFilePath $pp = [XML] (Get-Content $sourcefile) @" # Scripts generated from script nodes "@ | Out-File $OutputFilePath -Append IterateTree $pp.configuration.items.container[0] @" # Scripts generated from script links "@ | Out-File $OutputFilePath -Append $pp.configuration.items.container[1].items.container | where { $_.id -eq '481eccc0-43f8-47b8-9660-f100dff38e14' } | ForEach-Object { $_.items.item, $_.items.container | Output-Link } @" # Scripts generated from script actions "@ | Out-File $OutputFilePath -Append $pp.configuration.items.container[1].items.container | where { $_.id -eq '7826b2ed-8ae4-4ad0-bf29-1ff0a25e0ece' } | ForEach-Object { $_.items.item, $_.items.container | Output-Link }
PowerShellCorpus/PoshCode/New-GenericType.ps1
New-GenericType.ps1
## New-GenericObject.ps1 ## Creates an object of a generic type: ## ## Usage: ## ## # Simple generic collection ## $list = New-GenericObject System.Collections.ObjectModel.Collection System.Int32 ## ## # Generic dictionary with two types ## New-GenericObject System.Collections.Generic.Dictionary System.String,System.Int32 ## ## # Generic list as the second type to a generic dictionary ## $secondType = New-GenericObject System.Collections.Generic.List Int32 ## New-GenericObject System.Collections.Generic.Dictionary System.String,$secondType.GetType() ## ## # Generic type with a non-default constructor ## New-GenericObject System.Collections.Generic.LinkedListNode System.Int32 10 ## param( [string] $typeName = $(throw "Please specify a generic type name"), [type[]] $typeParameters = $(throw "Please specify the type parameters"), [object[]] $constructorParameters ) ## Create the generic type name [Type]$genericType = $typeName + '`' + $typeParameters.Count if(-not $genericType) { throw "Could not find generic type $genericTypeName" } ## Bind the type arguments to it [type[]] $typedParameters = $typeParameters $closedType = $genericType.MakeGenericType($typedParameters) if(-not $closedType) { throw "Could not make closed type $genericType" } ## Create the closed version of the generic type ,[Activator]::CreateInstance($closedType, $constructorParameters)
PowerShellCorpus/PoshCode/Set Logfile length_2.ps1
Set Logfile length_2.ps1
################################################################################ # Set-FileLines.ps1 (V 1003) # This script will maintain the PS Transcript file (default setting), or any # text file, at a fixed length, ie matching the number of lines entered. # However, setting no lines will just remove any blank lines; and including the # -Blanks switch will do both. Can be included in $profile. # Examples: # Set-FileLines -File c:\\Scripts\\anyfile.txt # Set-FileLines 1500 -Blanks # Set-FileLines # The author can be contacted via www.SeaStarDevelopmet.Bravehost.com ################################################################################ Param ([int] $lines = 0, [String]$file = "$pwd\\Transcript.txt", [Switch]$blanks) If ($file -notlike "*.txt") { [System.Media.SystemSounds]::Hand.Play() Write-Error "This script can only process .txt files" Exit 1 } If (!(Test-Path $file)) { [System.Media.SystemSounds]::Hand.Play() Write-Error "File $file does not exist" Exit 1 } [int]$count = 0 [int]$blankLines = 0 $errorActionPreference = 'SilentlyContinue' $content = (Get-Content $file) If ($lines -eq 0) { #Input 0 lines to have just blank lines removed. [int]$extra = 1 [int]$count = 1 [switch]$blanks = $true #Otherwise no blanks will be deleted below. } Else { $fileLength = ($content | Measure-Object -line) [int]$extra = $fileLength.Lines - $lines #The number of lines to remove. } If ($extra -gt 0) { $tempfile = [IO.Path]::GetTempFileName() Write-Output "Starting maintenance on file <$file>" $content | ForEach-Object { $count += 1 If($count -gt $extra) { #Ignore the first $extra lines. If (($blanks) -and ($_ -match '^\\s*$')) { #Skip blank lines. $blankLines++ } Else { $_ | Out-File $tempfile -Append -Force #Create new file. } } } If ($file -like "*transcript.txt") { Stop-Transcript | Out-Null } Remove-Item $file Move-Item $tempfile -Destination $file If ($lines -eq 0) { #Only interested in blank lines here. $tag = "$blankLines blank lines removed." } ElseIf ($blanks) { $tag = "$extra lines removed (+ $blankLines blank)." } Else { #Not interested in blank lines. $tag = "$extra lines removed." } If ($file -like "*transcript.txt") { Start-Transcript -append -path $file -force | Out-Null } Write-Output "Maintenance of file completed: $tag" } $ErrorActionPreference = 'Continue'
PowerShellCorpus/PoshCode/Backup-DatabaseObject.ps1
Backup-DatabaseObject.ps1
add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" add-type -AssemblyName "Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" ####################### <# .SYNOPSIS Backs up a database object definition. .DESCRIPTION The Backup-DatabaseObject function backs up a database object definition by scripting out the object to a .sql text file. .EXAMPLE Backup-DatabaseObject -ServerInstance Z002 -Database AdventureWorks -Schema HumanResources -Name vEmployee -Path "C:\\Users\\Public" This command backups up the vEmployee view to a .sql file. .NOTES Version History v1.0 - Chad Miller - Initial release #> function Backup-DatabaseObject { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$ServerInstance, [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$Database, [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$Schema, #Database Object Name [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$Name, [Parameter(Mandatory=$true)] [ValidateNotNullorEmpty()] [string]$Path ) $server = new-object Microsoft.SqlServer.Management.Smo.Server($ServerInstance) $db = $server.Databases[$Database] #Create a UrnCollection. URNs are used by SMO as unique identifiers of objects. You can think of URN like primary keys #The URN format is similar to XPath $urns = new-object Microsoft.SqlServer.Management.Smo.UrnCollection #Get a list of database object which match the schema and object name specified #New up an URN object and add the URN to the urns collection $db.enumobjects() | where {$_.schema -eq $Schema -and $_.name -eq $Name } | foreach {$urn = new-object Microsoft.SqlServer.Management.Sdk.Sfc.Urn($_.Urn); $urns.Add($urn) } if ($urns.Count -gt 0) { #Create a scripter object with a connection to the server object created above $scripter = new-object Microsoft.SqlServer.Management.Smo.Scripter($server) #Set some scripting option properties $scripter.options.ScriptBatchTerminator = $true $scripter.options.FileName = "$Path\\BEFORE_$Schema.$Name.sql" $scripter.options.ToFileOnly = $true $scripter.options.Permissions = $true $scripter.options.DriAll = $true $scripter.options.Triggers = $true $scripter.options.Indexes = $true $scripter.Options.IncludeHeaders = $true #Script the collection of URNs $scripter.Script($urns) } else { write-warning "Object $Schema.$Name Not Found!" } } #Backup-DatabaseObject
PowerShellCorpus/PoshCode/HttpRest 1.0.1.ps1
HttpRest 1.0.1.ps1
## Http Rest #################################################################################################### ## The first implementation of the HttpRest module, as a bunch of script functions ## Based on the REST api from MindTouch's Dream SDK ## ## INSTALL: ## You need log4net.dll mindtouch.core.dll mindtouch.dream.dll and SgmlReaderDll.dll from the SDK ## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074 ## Unpack it, and you can find these dlls in the "dist" folder. ## Make sure to put them in the folder with the module. ## ## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream #################################################################################################### ## Version History ## 1.0 First Release ## 1.0.1 Added Get-WebPageContent #################################################################################################### ## Usage: ## function Get-Google { ## Invoke-Http GET http`://www.google.com/search @{q=$args} | ## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText ## } ## ######################################################################### ## function Get-WebFile($url,$cred) { ## Invoke-Http GET $url -auth $cred | Receive-Http File ## } ## ######################################################################### ## function Send-Paste { ## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file) ## PROCESS { ## if($_){[IO.FileInfo]$file=$_} ## ## if($file.Exists) { ## $ofs="`n" ## $result = Invoke-Http POST $PastebinURI @{ ## format="posh" # PowerShell ## expiry="d" # (d)ay or (m)onth or (f)orever ## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1]) ## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter. ## paste="Send" ## } -Type FORM_URLENCODED -Wait ## $xml = $result.AsDocument().ToXml() ## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href ## } else { throw "File Not Found" } ## }} ## #################################################################################################### if(!$PSScriptRoot){ Write-Debug $($MyInvocation.MyCommand | out-string) $PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent) } # Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)" # Write-Debug "Invocation: $($MyInvocation.MyCommand)" # Write-Debug "Invocation: $($MyInvocation)" Write-Debug "PSScriptRoot: '$PSScriptRoot'" # This Module depends on MindTouch.Dream $null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" ) # MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll) # This Module also depends on utility functions from System.Web $null = [Reflection.Assembly]::LoadWithPartialName("System.Web") ## Some utility functions are defined at the bottom [uri]$global:url = "" [System.Management.Automation.PSCredential]$global:HttpRestCredential = $null function Get-DreamMessage($Content,$Type) { if(!$Content) { return [MindTouch.Dream.DreamMessage]::Ok() } if( $Content -is [System.Xml.XmlDocument]) { return [MindTouch.Dream.DreamMessage]::Ok( $Content ) } if(Test-Path $Content -EA "SilentlyContinue") { return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content))); } if($Type -is [String]) { $Type = [MindTouch.Dream.MimeType]::$Type } if($Type -is [MindTouch.Dream.DreamMessage]) { return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content ) } else { return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content ) } } function Get-DreamPlug { PARAM ( $Url, [hashtable]$With ) if($Url -is [array]) { if($Url[0] -is [hashtable]) { $plug = [MindTouch.Dream.Plug]::New($global:url) foreach($param in $url.GetEnumerator()) { if($param.Value) { $plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)") } else { $plug = $plug.At($param.Key) } } } else { [URI]$uri = Join-Url $global:url $url $plug = [MindTouch.Dream.Plug]::New($uri) } } elseif($url -is [string]) { [URI]$uri = $url if(!$uri.IsAbsoluteUri) { $uri = Join-Url $global:url $url } $plug = [MindTouch.Dream.Plug]::New($uri) } else { $plug = [MindTouch.Dream.Plug]::New($global:url) } if($with) { foreach($param in $with.GetEnumerator()) { if($param.Value) { $plug = $plug.With($param.Key,$param.Value) } } } return $plug } #CMDLET Receive-Http { Function Receive-Http { PARAM( # [Parameter(Position=1, Mandatory=$false)] # [ValidateSet("Xml", "File", "Text","Bytes")] # [Alias("As")] $Output = "Xml" , # [Parameter(Position=2, Mandatory=$false)] [string]$Path , # [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")] # [Alias("IO")] # [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]] $InputObject #, # [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")] # [MindTouch.Dream.DreamMessage] # $response ) BEGIN { if($InputObject) { Write-Output $inputObject | Receive-Http $Output $Path } # else they'd better pass it in on the pipeline ... } PROCESS { $response = $null if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) { $response = $_.Wait() } elseif($_ -is [MindTouch.Dream.DreamMessage]) { $response = $_ } elseif($_) { throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects" } if($response) { Write-Debug $($response | Out-String) if(!$response.IsSuccessful) { Write-Error $($response | Out-String) Write-Verbose $response.AsText() throw "ERROR: '$($response.Status)' Response Status." } else { switch($Output) { "File" { ## Joel's magic filename guesser ... if(!$Path) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value $Path = $fileName.trim("\\/""'") if(!$Path) { $fileName = $response.ResponseUri.Segments[-1] $Path = $fileName.trim("\\/") if(!([IO.FileInfo]$Path).Extension) { $Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1] } } } $File = Get-FileName $Path [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File ) Get-ChildItem $File } "XDoc" { if($Path) { $response.AsDocument()[$Path] } else { $response.AsDocument()#.ToXml() } } "Xml" { if($Path) { $response.AsDocument().ToXml().SelectNodes($Path) } else { $response.AsDocument().ToXml() } } "Text" { if($Path) { $response.AsDocument()[$Path] | % { $_.AsText } } else { $response.AsText() } } "Bytes" { $response.AsBytes() } } } } } } ## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html ## Nobody actually uses HEAD or OPTIONS, right? ## And nobody's even heard of TRACE or CONNECT ;) # CMDLET Invoke-Http { Function Invoke-Http { PARAM( # [Parameter(Position=0, Mandatory=$false)] # [ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up [string]$Verb = "Get" , # [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)] # [string] $Path , # [Parameter(Position=2, Mandatory=$false)] [hashtable]$with , # [Parameter(Position=3, Mandatory=$false)] $Content , $Type # Of Content , $authenticate , [switch]$waitForResponse ) BEGIN { $Verbs = "Post", "Get", "Put", "Delete", "Head", "Options" if($Verbs -notcontains $Verb) { Write-Warning "The specified verb '$Verb' is NOT one of the common verbs: $Verbs" } if($Path) { if($Content) { Write-Output ($Path | Invoke-Http $Verb -With $With -Content $Content -Type $Type -Authenticate $authenticate -waitForResponse:$WaitForResponse) } else { Write-Output ($Path | Invoke-Http $Verb -With $With -Type $Type-Authenticate $authenticate -waitForResponse:$WaitForResponse) } } # else they'd better pass it in on the pipeline ... } PROCESS { if($_) { $Path = $_ $plug = Get-DreamPlug $Path $With Write-Verbose "Content Type: $Type" Write-Verbose "Content: $Content" ## Special Handling for FORM_URLENCODED if($Type -like "Form*" -and !$Content) { $dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri ) $Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath ) Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)" } else { $dream = Get-DreamMessage $Content $Type } if(!$plug -or !$dream) { throw "Can't come up with a request!" } Write-Verbose $( $dream | Out-String ) if($authenticate){ Write-Verbose "AUTHENTICATE AS $($authenticate.UserName)" if($authenticate -is [System.Management.Automation.PSCredential]) { Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)" $plug = $plug.WithCredentials($authenticate.UserName, ($authenticate.GetNetworkCredential().Password)) } elseif($authenticate -is [System.Net.NetworkCredential]) { Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)" $plug = $plug.WithCredentials($authenticate.UserName, $authenticate.Password) } else { Get-HttpCredential Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)" $plug = $plug.WithCredentials($global:HttpRestCredential.UserName, $global:HttpRestCredential.Password) } } Write-Verbose $plug.Uri ## DEBUG: Write-Debug "URI: $($Plug.Uri)" Write-Debug "Verb: $($Verb.ToUpper())" Write-Debug $($dream | Out-String) $result = $plug.InvokeAsync( $Verb.ToUpper(), $dream ) Write-Debug $($result | Out-String) # if($DebugPreference -eq "Continue") { # Write-Debug $($result.Wait() | Out-String) # } if($waitForResponse) { $result = $result.Wait() } write-output $result trap [MindTouch.Dream.DreamResponseException] { Write-Error @" TRAPPED DreamResponseException $($_.Exception.Response | Out-String) $($_.Exception.Response.Headers | Out-String) "@ break; } } } } function Get-WebPageContent { #[CmdletBinding()] param( # [Parameter(Position=0,Mandatory=$true)] [string]$url , # [Parameter(Position=1,Mandatory=$false)] [string]$xpath="" , # [Parameter(Mandatory=$false)] [hashtable]$with=@{} , # [Parameter(Position=2,Mandatory=$false)] [switch]$AsXml ) BEGIN { $out = "Text"; if($AsXml) { $out="Xml" } } PROCESS { invoke-http get $url $with | receive-http $out $xpath } } new-alias gwpc Get-WebPageContent -EA "SilentlyContinue" new-alias http Invoke-Http -EA "SilentlyContinue" new-alias rcv Receive-Http -EA "SilentlyContinue" # function Get-Http { return Invoke-Http "GET" @args } # function New-Http { return Invoke-Http "PUT" @args } # function Update-Http { return Invoke-Http "POST" @args } # function Remove-Http { return Invoke-Http "DELETE" @args } # new-alias Set-Http Update-Http # new-alias Put-Http New-Http # new-alias Post-Http Update-Http # new-alias Delete-Http Remove-Http function Set-HttpDefaultUrl { PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service")) $global:url = $baseUri } function Set-HttpCredential { param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" ` -Message "Your login for $($global:url.Host)" ` -Domain $($global:url.Host)) ) if($Credential -is [System.Management.Automation.PSCredential]) { $global:HttpRestCredential = $Credential } elseif($Credential -is [System.Net.NetworkCredential]) { $global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password) } } function Get-HttpCredential([switch]$Secure) { if(!$global:url) { Set-HttpDefaultUrl } if(!$global:HttpRestCredential) { Set-HttpCredential } if(!$Secure) { return $global:HttpRestCredential.GetNetworkCredential(); } else { return $global:HttpRestCredential } } # function Authenticate-Http { # PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential)) # $plug = [MindTouch.Dream.Plug]::New( $global:url ) # $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get() # } function Encode-Twice { param([string]$text) return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) ) } function Join-Url ( [uri]$baseUri=$global:url ) { $ofs="/";$BaseUrl = "" if($BaseUri -and $baseUri.AbsoluteUri) { $BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/" } return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))" } function ConvertTo-SecureString { Param([string]$input) $result = new-object System.Security.SecureString foreach($c in $input.ToCharArray()) { $result.AppendChar($c) } $result.MakeReadOnly() return $result } ## Unit-Test Get-FileName ## Should return TRUE ## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and ## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and ## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and ## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" function Get-FileName { param($fileName=$([IO.Path]::GetRandomFileName()), $path) $fileName = $fileName.trim("\\/""'") ## if the $Path has a file name, and it's folder exists: if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) { $path ## if the $Path is just a folder (and it exists) } elseif($Path -and (Test-Path $path -Type Container)) { $fileName = Split-Path $fileName -leaf Join-Path $path $fileName ## If there's no valid $Path, and the $FileName has a folder... } elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) { $fileName } else { Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf) } } function Get-UtcTime { Param($Format="yyyyMMddhhmmss") [DateTime]::Now.ToUniversalTime().ToString($Format) } ## Get-CredentialBetter ## An improvement over the default cmdlet which has no options ... ################################################################################################### ## History ## 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-CredentialBetter{ PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console) $ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds" ## Carefully EA=SilentlyContinue because by default it's MISSING, not $False $cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue") ## Compare to $True, because by default it's $null ... $cp = $cp.ConsolePrompting -eq $True if($Console -and !$cp) { Set-ItemProperty $ShellIdKey ConsolePrompting $True } elseif(!$Console -and $Console.IsPresent -and $cp) { Set-ItemProperty $ShellIdKey ConsolePrompting $False } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. $Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default") ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True) Set-ItemProperty $ShellIdKey ConsolePrompting $cp }
PowerShellCorpus/PoshCode/Get-Netstat 1,3.ps1
Get-Netstat 1,3.ps1
$null, $null, $null, $null, $netstat = netstat -a -n -o $ps = Get-Process [regex]$regexTCP = '(?<Protocol>\\S+)\\s+(?<LAddress>\\S+):(?<LPort>\\S+)\\s+(?<RAddress>\\S+):(?<RPort>\\S+)\\s+(?<State>\\S+)\\s+(?<PID>\\S+)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+(?<LAddress>\\S+):(?<LPort>\\S+)\\s+(?<RAddress>\\S+):(?<RPort>\\S+)\\s+(?<PID>\\S+)' [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName foreach ($net in $netstat) { switch -regex ($net.Trim()) { $regexTCP { $process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName $process continue } $regexUDP { $process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName $process continue } } }
PowerShellCorpus/PoshCode/Xml Module 6.2.ps1
Xml Module 6.2.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 # Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms! # Note: when using strings for xslt, make sure you single quote them or escape the $ signs. # Version 4.7 Fixed a typo in the namespace parameter of Select-Xml # Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace # Version 5.0 Added Update-Xml to allow setting xml attributes or node content # Version 6.0 Major cleanup, breaking changes. # - Added Get-XmlContent and Set-XmlContent for loading/saving XML from files or strings # - Removed Path and Content parameters from the other functions (it greatly simplifies thost functions, and makes the whole thing more maintainable) # - Updated Update-Xml to support adding nodes "before" and "after" other nodes, and to support "remove"ing nodes # Version 6.1 Update for PowerShell 3.0 # Version 6.2 Minor tweak in exception handling for CliXml 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 } } } } &{ $local:xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") $local: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] } | Add-Accelerator Add-Accelerator "Dictionary" "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Add-Accelerator "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Add-Accelerator "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" } function Get-XmlContent { #.Synopsis # Load an XML file as an XmlDocument param( # Specifies a string that contains the XML to load, or a path to a file which has the XML to load (wildcards are permitted). [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath","Path")] [String[]]$Content , # If set, loads XML with all namespace qualifiers removed, and all entities expanded. [Alias("Rn","Rm")] [Switch]$RemoveNamespace ) begin { [Text.StringBuilder]$XmlContent = [String]::Empty [bool]$Path = $true } process { if($Path -and ($Path = Test-Path @($Content)[0] -EA 0)) { foreach($file in Resolve-Path $Content) { $xml = New-Object System.Xml.XmlDocument; if($file.Provider.Name -eq "FileSystem") { Write-Verbose $file.ProviderPath $xml.Load( $file.ProviderPath ) } else { $ofs = "`n" $xml.LoadXml( ([String](Get-Content $file)) ) } if($RemoveNamespace) { [System.Xml.XmlNode[]]$Xml = @(Remove-XmlNamespace -Xml $node) } Write-Output $xml } } else { # If the "path" parameter isn't actually a path, assume that it's actually content foreach($line in $content) { $null = $XmlContent.AppendLine( $line ) } } } end { if(!$Path) { $xml = New-Object System.Xml.XmlDocument; $xml.LoadXml( $XmlContent.ToString() ) if($RemoveNamespace) { $Xml = @(Remove-XmlNamespace -Xml $xml) } Write-Output $xml } }} Set-Alias Import-Xml Get-XmlContent Set-Alias ipxml Get-XmlContent Set-Alias ipx Get-XmlContent Set-Alias Get-Xml Get-XmlContent Set-Alias gxml Get-XmlContent Set-Alias gx Get-XmlContent function Set-XmlContent { param( [Parameter(Mandatory=$true, Position=1)] [Alias("PSPath")] [String]$Path , # Specifies one or more XML nodes to search. [Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [Xml]$Xml ) process { $xml.Save( $Path ) } } Set-Alias Export-Xml Set-XmlContent Set-Alias epxml Set-XmlContent Set-Alias epx Set-XmlContent Set-Alias Set-Xml Set-XmlContent Set-Alias sxml Set-XmlContent Set-Alias sx Set-XmlContent function 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 # [CmdletBinding()] 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 ) process { ## 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 Set-Alias fx Format-Xml -EA 0 function Select-XmlNodeInternal { [CmdletBinding()] param([Xml.XmlNode[]]$Xml, [String[]]$XPath, [Hashtable]$NamespaceManager) begin { Write-Verbose "XPath = $($XPath -join ',')" foreach($node in $xml) { if($NamespaceManager) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $NamespaceManager.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } Write-Verbose "Names = $($nsManager | % { @{ $_ = $nsManager.LookupNamespace($_) } } | Out-String)" } foreach($path in $xpath) { $node.SelectNodes($path, $nsManager) } } }} 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. [CmdletBinding(DefaultParameterSetName="Xml")] param( # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. [Parameter(ParameterSetName="Content",Mandatory=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , # Specifies the path and file names of the XML files to search. Wildcards are permitted. [Parameter(Position=5,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , # Specifies one or more XML nodes to search. [Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. [Parameter(Position=10,Mandatory=$false)] [ValidateNotNullOrEmpty()] [Alias("Ns")] [Hashtable]$Namespace , # 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. [Alias("Rn","Rm")] [Switch]$RemoveNamespace ) begin { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } $XmlNodes = New-Object System.Xml.XmlNode[] 1 if($PSCmdlet.ParameterSetName -eq "Content") { $XmlNodes = ConvertTo-Xml $Content -RemoveNamespace:$RemoveNamespace Select-XmlNodeInternal $XmlNodes $XPath $NSM } } process { switch($PSCmdlet.ParameterSetName) { "Path" { $node = ConvertTo-Xml $Path -RemoveNamespace:$RemoveNamespace Select-XmlNodeInternal $node $XPath $NSM } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { [Xml]$node = Remove-XmlNamespace -Xml $node } Select-XmlNodeInternal $node $XPath $NSM } } } }} Set-Alias slxml Select-Xml -EA 0 Set-Alias slx Select-Xml -EA 0 function Update-Xml { #.Synopsis # The Update-XML cmdlet lets you use XPath queries to replace text in nodes in XML documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Allows you to update an attribute value, xml node contents, etc. # #.Notes # We still need to implement RemoveNode and RemoveAttribute and even ReplaceNode [CmdletBinding(DefaultParameterSetName="Set")] param( # Specifies an XPath for an element where you want to insert the new node. [Parameter(ParameterSetName="Before",Mandatory=$true)] [ValidateNotNullOrEmpty()] [Switch]$Before , # Specifies an XPath for an element where you want to insert the new node. [Parameter(ParameterSetName="After",Mandatory=$true)] [ValidateNotNullOrEmpty()] [Switch]$After , # If set, the new value will be added as a new child of the node identified by the XPath [Parameter(ParameterSetName="Append",Mandatory=$true)] [Switch]$Append , # If set, the node identified by the XPath will be removed instead of set [Parameter(ParameterSetName="Remove",Mandatory=$true)] [Switch]$Remove , # If set, the node identified by the XPath will be Replace instead of set [Parameter(ParameterSetName="Replace",Mandatory=$true)] [Switch]$Replace , # Specifies an XPath for the node to update. This could be an element node *or* an attribute node (remember: //element/@attribute ) [Parameter(Position=1,Mandatory=$true)] [ValidateNotNullOrEmpty()] [String[]]$XPath , # The new value to place in the xml [Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [String]$Value , # Specifies one or more XML nodes to search. [Parameter(Position=5,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. [Parameter(Position=10,Mandatory=$false)] [ValidateNotNullOrEmpty()] [Alias("Ns")] [Hashtable]$Namespace , # Output the XML documents after adding updating them [Switch]$Passthru ) process { foreach($XmlNode in $Xml) { $select = @{} $select.Xml = $XmlNode $select.XPath = $XPath if($Namespace) { $select.Namespace = $Namespace } $document = if($XmlNode -is [System.Xml.XmlDocument]) { $XmlNode } else { $XmlNode.get_OwnerDocument() } if($xValue = $Value -as [Xml]) { $xValue = $document.ImportNode($xValue.SelectSingleNode("/*"), $true) } $nodes = Select-Xml @Select | Where-Object { $_ } if(@($nodes).Count -eq 0) { Write-Warning "No nodes matched your XPath, nothing will be updated" } foreach($node in $nodes) { $select.XPath = "$XPath/parent::*" $parent = Select-Xml @Select if(!$xValue) { if($node -is [System.Xml.XmlAttribute] -and $Value.Contains("=")) { $aName, $aValue = $Value.Split("=",2) if($aName.Contains(":")){ $ns,$name = $aName.Split(":",2) $xValue = $document.CreateAttribute( $name, $Namespace[$ns] ) } else { $xValue = $document.CreateAttribute( $aName ) } $xValue.Value = $aValue } } switch($PSCmdlet.ParameterSetName) { "Before" { $null = $parent.InsertBefore( $xValue, $node ) } "After" { $null = $parent.InsertAfter( $xValue, $node ) } "Append" { $null = $parent.AppendChild( $xValue ) } "Remove" { $null = $parent.RemoveChild( $node ) } "Replace" { if(!$xValue) { $xValue = $document.CreateTextNode( $Value ) } $null = $parent.ReplaceChild( $xValue, $node ) } "Set" { if(!$xValue -and $node."#text") { $node."#text" = $Value } else { if($node -is [System.Xml.XmlElement]) { if(!$xValue) { $xValue = $document.CreateTextNode( $Value ) } $null = $node.set_innerXml("") $null = $node.AppendChild($xValue) } elseif($node -is [System.Xml.XmlAttribute]) { $node.Value = $Value } else { Write-Warning "$XPath selects a node of type $($node.GetType()), which we haven't handled. Please add that handler!" } } } } } if($Passthru) { Write-Output $XmlNode } } }} Set-Alias uxml Update-Xml -EA 0 Set-Alias ux Update-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets [CmdletBinding(DefaultParameterSetName="Reader")] param( [Parameter(ParameterSetName="ByNode",Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlNode]$Node , [Parameter(ParameterSetName="Reader",Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader , [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet , [Parameter(Position=2,Mandatory=$false)] [Alias("Parameters")] [hashtable]$Arguments ) PROCESS { if($PSCmdlet.ParameterSetName -eq "ByNode") { $XmlReader = New-Object Xml.XmlNodeReader $node } $output = New-Object IO.StringWriter $argList = $null if($Arguments) { $argList = New-Object System.Xml.Xsl.XsltArgumentList foreach($arg in $Arguments.GetEnumerator()) { $namespace, $name = $arg.Key -split ":" ## Fix namespace if(!$name) { $name = $Namespace $namespace = "" } Write-Verbose "ns:$namespace name:$name value:$($arg.Value)" $argList.AddParam($name,"$namespace",$arg.Value) } } $StyleSheet.Transform( $XmlReader, $argList, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description # Documentation TODO [CmdletBinding(DefaultParameterSetName="Xml")] param( # Specifies one or more XML nodes to process. [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , # Specifies an Xml StyleSheet to transform with... [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String]$Xslt , # Specify arguments to the XSL Transformation [Alias("Parameters")] [hashtable]$Arguments ) begin { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path $Xslt -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path $Xslt)" $StyleSheet.Load( (Resolve-Path $Xslt) ) } else { $OFS = "`n" Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $Xslt)))) } } process { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments } } } 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="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml ) 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 { $Xml | Convert-Node $StyleSheet } } Set-Alias rmns Remove-XmlNamespace -EA 0 Set-Alias rmxns Remove-XmlNamespace -EA 0 ######## Helper functions for working with CliXml function ConvertFrom-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$InputObject ) begin { $OFS = "`n" [String]$xmlString = "" } process { $xmlString += $InputObject } end { $type = [psobject].assembly.gettype("System.Management.Automation.Deserializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null) $sr = new-object System.IO.StringReader $xmlString $xr = new-object System.Xml.XmlTextReader $sr $deserializer = $ctor.invoke($xr) $method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1] $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") while (!$done.invoke($deserializer, @())) { try { $method.invoke($deserializer, "") } catch { write-warning "Could not deserialize $xmlString" } } $xr.Close() $sr.Dispose() } } function ConvertTo-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [PSObject[]]$InputObject ) begin { $type = [psobject].assembly.gettype("System.Management.Automation.Serializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null) $sw = new-object System.IO.StringWriter $xw = new-object System.Xml.XmlTextWriter $sw $serializer = $ctor.invoke($xw) $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") } process { try { [void]$method.invoke($serializer, $InputObject) } catch { write-warning "Could not serialize $($InputObject.gettype()): $InputObject" } } end { [void]$done.invoke($serializer, @()) $sw.ToString() $xw.Close() $sw.Dispose() } } ######## From here down is all the code related to my XML DSL: 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.# # [CmdletBinding()] 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 { Write-Verbose "XAttribute $attrib = $value" 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 [CmdletBinding()] 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. :) [CmdletBinding()] Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$tag , [AllowNull()][AllowEmptyString()][AllowEmptyCollection()] [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) 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 } } ) } } 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") )) } ######## Xaml # if($PSVersionTable.CLRVersion -ge "4.0"){ # trap { continue } # [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null # if("System.Xaml.XamlServices" -as [type]) { # } # } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Get-XmlContent, Set-XmlContent, ConvertTo-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml # SIG # Begin signature block # MIIdZgYJKoZIhvcNAQcCoIIdVzCCHVMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUtjycTLbprXSw4krXhTfs6eQf # geWgghkkMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B # AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp # BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw # NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xNDAyBgNVBAMTK1N5bWFudGVjIFRpbWUg # U3RhbXBpbmcgU2VydmljZXMgU2lnbmVyIC0gRzMwgZ8wDQYJKoZIhvcNAQEBBQAD # gY0AMIGJAoGBAKlZZnTaPYp9etj89YBEe/5HahRVTlBHC+zT7c72OPdPabmx8LZ4 # ggqMdhZn4gKttw2livYD/GbT/AgtzLVzWXuJ3DNuZlpeUje0YtGSWTUUi0WsWbJN # JKKYlGhCcp86aOJri54iLfSYTprGr7PkoKs8KL8j4ddypPIQU2eud69RAgMBAAGj # geMwgeAwDAYDVR0TAQH/BAIwADAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js # LnZlcmlzaWduLmNvbS90c3MtY2EuY3JsMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI # MDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AudmVyaXNp # Z24uY29tMA4GA1UdDwEB/wQEAwIHgDAeBgNVHREEFzAVpBMwETEPMA0GA1UEAxMG # VFNBMS0zMB0GA1UdDgQWBBS0t/GJSSZg52Xqc67c0zjNv1eSbzANBgkqhkiG9w0B # AQUFAAOCAQEAHpiqJ7d4tQi1yXJtt9/ADpimNcSIydL2bfFLGvvV+S2ZAJ7R55uL # 4T+9OYAMZs0HvFyYVKaUuhDRTour9W9lzGcJooB8UugOA9ZresYFGOzIrEJ8Byyn # PQhm3ADt/ZQdc/JymJOxEdaP747qrPSWUQzQjd8xUk9er32nSnXmTs4rnykr589d # nwN+bid7I61iKWavkugszr2cf9zNFzxDwgk/dUXHnuTXYH+XxuSqx2n1/M10rCyw # SMFQTnBWHrU1046+se2svf4M7IV91buFZkQZXZ+T64K6Y57TfGH/yBvZI1h/MKNm # oTkmXpLDPMs3Mvr1o43c1bCj6SU2VdeB+jCCA8QwggMtoAMCAQICEEe/GZXfjVJG # Q/fbbUgNMaQwDQYJKoZIhvcNAQEFBQAwgYsxCzAJBgNVBAYTAlpBMRUwEwYDVQQI # EwxXZXN0ZXJuIENhcGUxFDASBgNVBAcTC0R1cmJhbnZpbGxlMQ8wDQYDVQQKEwZU # aGF3dGUxHTAbBgNVBAsTFFRoYXd0ZSBDZXJ0aWZpY2F0aW9uMR8wHQYDVQQDExZU # aGF3dGUgVGltZXN0YW1waW5nIENBMB4XDTAzMTIwNDAwMDAwMFoXDTEzMTIwMzIz # NTk1OVowUzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMSsw # KQYDVQQDEyJWZXJpU2lnbiBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIENBMIIBIjAN # BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqcqypMzNIK8KfYmsh3XwtE7x38EP # v2dhvaNkHNq7+cozq4QwiVh+jNtr3TaeD7/R7Hjyd6Z+bzy/k68Numj0bJTKvVIt # q0g99bbVXV8bAp/6L2sepPejmqYayALhf0xS4w5g7EAcfrkN3j/HtN+HvV96ajEu # A5mBE6hHIM4xcw1XLc14NDOVEpkSud5oL6rm48KKjCrDiyGHZr2DWFdvdb88qiaH # XcoQFTyfhOpUwQpuxP7FSt25BxGXInzbPifRHnjsnzHJ8eYiGdvEs0dDmhpfoB6Q # 5F717nzxfatiAY/1TQve0CJWqJXNroh2ru66DfPkTdmg+2igrhQ7s4fBuwIDAQAB # o4HbMIHYMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3Au # dmVyaXNpZ24uY29tMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYDVR0fBDowODA2oDSg # MoYwaHR0cDovL2NybC52ZXJpc2lnbi5jb20vVGhhd3RlVGltZXN0YW1waW5nQ0Eu # Y3JsMBMGA1UdJQQMMAoGCCsGAQUFBwMIMA4GA1UdDwEB/wQEAwIBBjAkBgNVHREE # HTAbpBkwFzEVMBMGA1UEAxMMVFNBMjA0OC0xLTUzMA0GCSqGSIb3DQEBBQUAA4GB # AEpr+epYwkQcMYl5mSuWv4KsAdYcTM2wilhu3wgpo17IypMT5wRSDe9HJy8AOLDk # yZNOmtQiYhX3PzchT3AxgPGLOIez6OiXAP7PVZZOJNKpJ056rrdhQfMqzufJ2V7d # uyuFPrWdtdnhV/++tMV+9c8MnvCX/ivTO1IbGzgn9z9KMIIETzCCA7igAwIBAgIE # BydYPTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RF # IENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMs # IEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEdsb2JhbCBSb290MB4XDTEw # MDExMzE5MjAzMloXDTE1MDkzMDE4MTk0N1owbDELMAkGA1UEBhMCVVMxFTATBgNV # BAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkG # A1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgRVYgUm9vdCBDQTCCASIwDQYJ # KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0tMqbf5YE/yc0lSbZx # KsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMSOO7z # SW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9 # vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu # 5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8 # J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsgEsxBu24LUTi4S8sCAwEAAaOC # AW8wggFrMBIGA1UdEwEB/wQIMAYBAf8CAQEwUwYDVR0gBEwwSjBIBgkrBgEEAbE+ # AQAwOzA5BggrBgEFBQcCARYtaHR0cDovL2N5YmVydHJ1c3Qub21uaXJvb3QuY29t # L3JlcG9zaXRvcnkuY2ZtMA4GA1UdDwEB/wQEAwIBBjCBiQYDVR0jBIGBMH+heaR3 # MHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNV # BAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RF # IEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3SCAgGlMEUGA1UdHwQ+MDwwOqA4oDaGNGh0 # dHA6Ly93d3cucHVibGljLXRydXN0LmNvbS9jZ2ktYmluL0NSTC8yMDE4L2NkcC5j # cmwwHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUA # A4GBAC52hdk3lm2vifMGeIIxxEYHH2XJjrPJVHjm0ULfdS4eVer3+psEwHV70Xk8 # Bex5xFLdpgPXp1CZPwVZ2sZV9IacDWejSQSVMh3Hh+yFr2Ru1cVfCadAfRa6SQ2i # /fbfVTBs13jGuc9YKWQWTKMggUexRJKEFhtvSrwhxgo97TPKMIIGnzCCBYegAwIB # AgIQDmkGmMIUyHq1tgS5FjzRkDANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJV # UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu # Y29tMTIwMAYDVQQDEylEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBDb2RlIFNpZ25p # bmcgQ0EtMTAeFw0xMjAzMjAwMDAwMDBaFw0xMzAzMjIxMjAwMDBaMG0xCzAJBgNV # BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazEXMBUGA1UEBxMOV2VzdCBIZW5yaWV0 # dGExGDAWBgNVBAoTD0pvZWwgSC4gQmVubmV0dDEYMBYGA1UEAxMPSm9lbCBILiBC # ZW5uZXR0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2ogGAG89d1jM # fRJv2d3U1lCsW8ok7GkjnLYDn0zC1ALq11rWN5NVwVbn133i+KV0O8kM5vd2M7xE # 8CnVAgybjkrvRD2IqMtp4SrwQuiGiVGsNVWO3vSLHcWsS/I7N0UIpS5PhTuFB4Pc # Oy/MHR4F2g6JLMrAtkpYWxauAFZfFwuEfm6vqWobHTDt5wG+zqOTxMSi1UvL5fEM # DoejGqqriIx5mKDzrvUb/ALNKZ1rGPWlT7O0/UHrV5VuOfgij4XVKBAdcg9JLxky # AEIJ+VvVQ2Jn3lVONCCHbfu5IVhddMru81U/v5Wrj80Zrwh2TH25qlclUKr6eXRL # tP+xFm23CwIDAQABo4IDMzCCAy8wHwYDVR0jBBgwFoAUl0gD6xUIa7myWCPMlC7x # xmXSZI4wHQYDVR0OBBYEFJicRKq/XsBWRuKzU6eTUCBCCU65MA4GA1UdDwEB/wQE # AwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzBpBgNVHR8EYjBgMC6gLKAqhihodHRw # Oi8vY3JsMy5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMC6gLKAqhihodHRw # Oi8vY3JsNC5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMIIBxAYDVR0gBIIB # uzCCAbcwggGzBglghkgBhv1sAwEwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3 # LmRpZ2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUH # AgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQBy # AHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBj # AGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAg # AEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQ # AGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBt # AGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBj # AG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBl # AHIAZQBuAGMAZQAuMIGGBggrBgEFBQcBAQR6MHgwJAYIKwYBBQUHMAGGGGh0dHA6 # Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBQBggrBgEFBQcwAoZEaHR0cDovL2NhY2VydHMu # ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUNvZGVTaWduaW5nQ0Et # MS5jcnQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQUFAAOCAQEAHIfeYpO0Jtdi # /TpcI6eWQIYU2ALO847Q91jLE6WiU6u8wN6tkHqgeOls070SDUK+C1rVoXKKZ0Je # c2k1dYukKPkyf3qURPyh/aC3hJ0Wwbje7fK79Lt9ZHwJORpesJrwa8T63l3qLLLl # PaIYo/bqiMpNZRfOclukKg2hO67yMaQl8DEL/D5UP1XZShF2zbauH627zEC5KXGZ # Y2yUbmWG2N0oHxr+q4Gyfd0MPtU5avWOILB0ZsN+br+SCVVK6nKzauXMk4HXmKHa # X7cysqpmQiFb7/J7tPQ037KQKHCY/Z+fl0arRCiHih/Q/5owv51WSKPiaUrkBvdJ # 0mKVK+McHzCCBr8wggWnoAMCAQICEAgcV+5dcOuboLFSDHKcGwkwDQYJKoZIhvcN # AQEFBQAwbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG # A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBB # c3N1cmFuY2UgRVYgUm9vdCBDQTAeFw0xMTAyMTAxMjAwMDBaFw0yNjAyMTAxMjAw # MDBaMHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNV # BAsTEHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNz # dXJhbmNlIENvZGUgU2lnbmluZyBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A # MIIBCgKCAQEAxfkj5pQnxIAUpIAyX0CjjW9wwOU2cXE6daSqGpKUiV6sI3HLTmd9 # QT+q40u3e76dwag4j2kvOiTpd1kSx2YEQ8INJoKJQBnyLOrnTOd8BRq4/4gJTyY3 # 7zqk+iJsiMlKG2HyrhBeb7zReZtZGGDl7im1AyqkzvGDGU9pBXMoCfsiEJMioJAZ # Gkwx8tMr2IRDrzxj/5jbINIJK1TB6v1qg+cQoxJx9dbX4RJ61eBWWs7qAVtoZVvB # P1hSM6k1YU4iy4HKNqMSywbWzxtNGH65krkSz0Am2Jo2hbMVqkeThGsHu7zVs94l # ABGJAGjBKTzqPi3uUKvXHDAGeDylECNnkQIDAQABo4IDVDCCA1AwDgYDVR0PAQH/ # BAQDAgEGMBMGA1UdJQQMMAoGCCsGAQUFBwMDMIIBwwYDVR0gBIIBujCCAbYwggGy # BghghkgBhv1sAzCCAaQwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQu # Y29tL3NzbC1jcHMtcmVwb3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFS # AEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBj # AGEAdABlACAAYwBvAG4AcwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBu # AGMAZQAgAG8AZgAgAHQAaABlACAARABpAGcAaQBDAGUAcgB0ACAARQBWACAAQwBQ # AFMAIABhAG4AZAAgAHQAaABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAg # AEEAZwByAGUAZQBtAGUAbgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABp # AGEAYgBpAGwAaQB0AHkAIABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwBy # AGEAdABlAGQAIABoAGUAcgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBl # AC4wDwYDVR0TAQH/BAUwAwEB/zB/BggrBgEFBQcBAQRzMHEwJAYIKwYBBQUHMAGG # GGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcwAoY9aHR0cDovL2Nh # Y2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENB # LmNydDCBjwYDVR0fBIGHMIGEMECgPqA8hjpodHRwOi8vY3JsMy5kaWdpY2VydC5j # b20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290Q0EuY3JsMECgPqA8hjpodHRw # Oi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290 # Q0EuY3JsMB0GA1UdDgQWBBSXSAPrFQhrubJYI8yULvHGZdJkjjAfBgNVHSMEGDAW # gBSxPsNpA/i/RwHUmCYaCALvY2QrwzANBgkqhkiG9w0BAQUFAAOCAQEAggXpha+n # TL+vzj2y6mCxaN5nwtLLJuDDL5u1aw5TkIX2m+A1Av/6aYOqtHQyFDwuEEwomwqt # CAn584QRk4/LYEBW6XcvabKDmVWrRySWy39LsBC0l7/EpZkG/o7sFFAeXleXy0e5 # NNn8OqL/UCnCCmIE7t6WOm+gwoUPb/wI5DJ704SuaWAJRiac6PD//4bZyAk6ZsOn # No8YT+ixlpIuTr4LpzOQrrxuT/F+jbRGDmT5WQYiIWQAS+J6CAPnvImQnkJPAcC2 # Fn916kaypVQvjJPNETY0aihXzJQ/6XzIGAMDBH5D2vmXoVlH2hKq4G04AF01K8Ui # hssGyrx6TT0mRjGCA6wwggOoAgEBMIGHMHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMjAwBgNV # BAMTKURpZ2lDZXJ0IEhpZ2ggQXNzdXJhbmNlIENvZGUgU2lnbmluZyBDQS0xAhAO # aQaYwhTIerW2BLkWPNGQMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3AgEMMQowCKAC # gAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsx # DjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBTBjSgoFuawl9Ao5Tv2xqPO # 3Kl4sDANBgkqhkiG9w0BAQEFAASCAQA5AQUWDBjbcGyAveEi6lzwSWZf7xIx87zm # U80EVwu1VDqIcgN4jyUMf7ni8qrZsSZoc4e4xj3tSRmMjZPd7M5C+DL8ZBitU4VV # X6VT86ANs+njcZ+2eVZtZW9jYYG42TJN507NcDL1KilaSRyrUUJfBcSFaa+UN2pQ # n0/GNPYoZxZwdho0IVdIJifBO61IqYVCWNL3CNfaTvBVVbEXA70LG3yKUoQdEvpV # /3Eyd3fJzdmHZGpKwq8Wf/tlMN7dVM59GG0SGE81FASCJNno18MKKY7vWLGoo3Fc # drZCFDm8Wq/Q/M10mKEFWzlztThqxeUx/3oA2TKLM2eUtA4PVw+QoYIBfzCCAXsG # CSqGSIb3DQEJBjGCAWwwggFoAgEBMGcwUzELMAkGA1UEBhMCVVMxFzAVBgNVBAoT # DlZlcmlTaWduLCBJbmMuMSswKQYDVQQDEyJWZXJpU2lnbiBUaW1lIFN0YW1waW5n # IFNlcnZpY2VzIENBAhB5oqWF+dEVQhPZuD72to3tMAkGBSsOAwIaBQCgXTAYBgkq # hkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMjA2MjEwNTA1 # MTJaMCMGCSqGSIb3DQEJBDEWBBS/y8ZQJu39fwfbrPlsNYHdOEbIWjANBgkqhkiG # 9w0BAQEFAASBgBVlS+jMlhYAmeerqAJAXyX18fe2m/quZkq09V6c2OOSzWmcHMwT # +sgJDVKPmImnn7YT0tL8SyIflxmVVapR3pAnzFq5XXVmYqxu3+g1rSRxUQyCmEwU # p84MHiU+17yfE+KbvT0/Y+jv71MnbkUOeqAKH2+fGdiR6pSO+zKoiH/q # SIG # End signature block
PowerShellCorpus/PoshCode/Start-Selected.ps1
Start-Selected.ps1
#Hightlight the name of a file or URL and this will opened or shown in browser if ($PSVersionTable.BuildVersion.build -le 7000) { # PowerShell V2 CTP3 function Start-Selected { $ed = $psise.CurrentOpenedFile.Editor start $ed.SelectedText } } else { # PowerShell W7 function Start-Selected { $file = $psIse.CurrentPowerShellTab.Output.SelectedText if ($file -eq '') { $file = $psise.CurrentFile.Editor.SelectedText } if ($file) { start $file } } } #Set-CustomMenu "Start Selected" {Start-Selected} 'Ctrl+Shift+S'
PowerShellCorpus/PoshCode/Resolve-Error.ps1
Resolve-Error.ps1
#############################################################################\n##\n## Resolve-Error\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\nDisplays detailed information about an error and its context\n\n#>\n\nparam(\n ## The error to resolve\n $ErrorRecord = ($error[0])\n)\n\nSet-StrictMode -Off\n\n""\n"If this is an error in a script you wrote, use the Set-PsBreakpoint cmdlet"\n"to diagnose it."\n""\n\n'Error details ($error[0] | Format-List * -Force)'\n"-"*80\n$errorRecord | Format-List * -Force\n\n'Information about the command that caused this error ' +\n '($error[0].InvocationInfo | Format-List *)'\n"-"*80\n$errorRecord.InvocationInfo | Format-List *\n\n'Information about the error''s target ' +\n '($error[0].TargetObject | Format-List *)'\n"-"*80\n$errorRecord.TargetObject | Format-List *\n\n'Exception details ($error[0].Exception | Format-List * -Force)'\n"-"*80\n\n$exception = $errorRecord.Exception\n\nfor ($i = 0; $exception; $i++, ($exception = $exception.InnerException))\n{\n "$i" * 80\n $exception | Format-List * -Force\n}
PowerShellCorpus/PoshCode/File Archive by Creation.ps1
File Archive by Creation.ps1
# ============================================================================================== # # NAME: FileArchivingCrTime.ps1 # # AUTHOR: Saehrig ,Steven # DATE : 5/19/2008 # # COMMENT: This script will search a directory and archive files based on create time -7 days. # for specified extension. # ============================================================================================== #variables - This section defines the source and destination locations @@$source = 'sourcefilepath' @@$archive = 'DestinationFilepath' #Functions - This section defines all the functions to be called below. function ArchiveFiles{ foreach ($a in Get-ChildItem $source) { @@ if ($a.Extension.Equals('.pdf') -and ($a.creationtime -lt ($(Get-Date).Adddays(-7)))) { $cm = $a.creationtime.month $cy = $a.creationtime.year if (Test-Path $archive\\$cy-$cm){ Move-Item $a.FullName $archive\\$cy-$cm } else { New-Item -path $archive -name $cy-$cm -type directory Move-Item $a.FullName $archive\\$cy-$cm } } } } #Execution of Script will begin here. ArchiveFiles
PowerShellCorpus/PoshCode/Out-IseFile.ps1
Out-IseFile.ps1
function Out-IseFile { [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True) ] $msg, [Parameter(Position = 1, Mandatory = $False, ValueFromPipeline = $False)] $path = $null, [Parameter(Position = 2, Mandatory = $False, ValueFromPipeline = $False)] $width = 2000, [switch]$fl, [switch]$passEditor ) Begin { $cnt = 0 $count = $psise.CurrentPowerShellTab.Files.count $null = $psIse.CurrentPowerShellTab.Files.Add() $Newfile = $psIse.CurrentPowerShellTab.Files[$count] if ($path) { $NewFile.SaveAs($path) $NewFile.Save([Text.Encoding]::default) } $Editor = $Newfile.Editor filter Remove-TrailingBlanks { $_ -replace '(?m)\\s*$', '' } #filter Remove-TrailingBlanks { $_.TrimEnd() } } Process { $cnt++ # if ($msg) { $msg | gm | Write-Verbose } if ($cnt -eq 1) { $cmsg = @($msg) } else { $cmsg = $cmsg + @($msg) } } End { if ($cnt -gt 1) { $msg = $cmsg } if ($fl) { $msg = $msg | Format-list | out-string -width $width | Remove-trailingBlanks } else { $msg = $msg | out-string -width $width | Remove-trailingBlanks } $msg = $msg + "`r`n" #$Editor.SetCaretPosition($Editor.LineCount, 1) $Editor.InsertText($msg) if ($passEditor){ $Newfile } Write-Verbose "Anzahl = $cnt len msg = $($msg.count)" } } <# $profile.psextended | out-IseFile -fl -verb get-help * | out-string -width 2000| out-ISEFile -verb get-help * | out-ISEFile -verb get-help * | out-ISEFile $a = $profile.psextended out-IseFile $a -fl $a = get-help * | out-string -width 2000 out-IseFile $a #>
PowerShellCorpus/PoshCode/Get-ChildItemRecurse.ps1
Get-ChildItemRecurse.ps1
function Get-ChildItemRecurse { <# .Synopsis Does a recursive search through a PSDrive up to n levels. .Description Does a recursive directory search, allowing the user to specify the number of levels to search. .Parameter path The starting path. .Parameter fileglob (optional) the search string for matching files .Parameter levels The numer of levels to recurse. .Example # Get up to three levels of files PS> Get-ChildItemRecurse *.* -levels 3 .Notes NAME: Get-ChildItemRecurse AUTHOR: tojo2000 #Requires -Version 2.0 #> Param([Parameter(Mandatory = $true, ValueFromPipeLine = $false, Position = 0)] [string]$path = '.', [Parameter(Mandatory = $false, Position = 1, ValueFromPipeLine = $false)] [string]$fileglob = '*.*', [Parameter(Mandatory = $false, Position = 2, ValueFromPipeLine = $false)] [int]$levels = 0) if (-not (Test-Path $path)) { Write-Error "$path is an invalid path." return $false } $files = @(Get-ChildItem $path) foreach ($file in $files) { if ($file -like $fileglob) { Write-Output $file } if ($file.GetType().FullName -eq 'System.IO.DirectoryInfo') { if ($levels -gt 0) { Get-ChildItemRecurse -path $file.FullName ` -fileglob $fileglob ` -levels ($levels - 1) } } } }
PowerShellCorpus/PoshCode/Split-String_2.ps1
Split-String_2.ps1
function Split-String { #.Synopsis # Split a string and execute a scriptblock to give access to the pieces #.Description # Splits a string (by default, on whitespace), and assigns it to $0, and the first 9 words to $1 through $9 ... and then calls the specified scriptblock #.Example # echo "this is one test ff-ff-00 a crazy" | split {$2, $1.ToUpper(), $6, $4, "?"} # # outputs 5 strings: is, THIS, a, test, ? # #.Example # echo "this is one test ff-ff-00 a crazy" | split {$0[-1]} # # outputs the last word in the string: "crazy" # #.Parameter pattern # The regular expression to split on. By default "\\s+" (any number of whitespace characters) #.Parameter action # The scriptblock to execute. By default {$0} which returns the whole split array #.Parameter InputObject # The string to split [CmdletBinding(DefaultParameterSetName="DefaultSplit")] Param( [Parameter(Position=0, ParameterSetName="SpecifiedSplit")] [string]$pattern="\\s+" , [Parameter(Position=0,ParameterSetName="DefaultSplit")] [Parameter(Position=1,ParameterSetName="SpecifiedSplit")] [ScriptBlock]$action={$0} , [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [string]$InputObject ) BEGIN { if(!$pattern){[regex]$re="\\s+"}else{[regex]$re=$pattern} } PROCESS { $0 = $re.Split($InputObject) $1,$2,$3,$4,$5,$6,$7,$8,$9,$n = $0 &$action } } # #This one is v1-compatible # function Split-String { # Param([scriptblock]$action={$0},[regex]$split=" ") # PROCESS { # if($_){ # $0 = $split.Split($_) # $1,$2,$3,$4,$5,$6,$7,$8,$9,$n = $0 # &$action # } # } # }
PowerShellCorpus/PoshCode/c29a0542-1603-4048-b8e2-365fa886bbcf.ps1
c29a0542-1603-4048-b8e2-365fa886bbcf.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/UIAutomation 1.2.ps1
UIAutomation 1.2.ps1
# # # Select-Window Notepad | Remove-Window -passthru # # ## And later ... # # Select-Window Notepad | Select-ChildWindow | Send-Keys "%N" # # ## OR ## # # Select-Window Notepad | Select-ChildWindow | # # Select-Control -title "Do&n't Save" -recurse | Send-Click # # # # # # PS notepad | Select-Window | Select-ChildWindow | %{ New-Object Huddled.Wasp.Window $_ } # # # # cp C:\\Users\\Joel\\Projects\\PowerShell\\Wasp\\trunk\\WASP\\bin\\Debug\\Wasp.dll .\\Modules\\WASP\\ # # Import-Module WASP # function formatter { END { # $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto # }} Add-Type -AssemblyName UIAutomationClient Add-Type -AssemblyName UIAutomationTypes $SWA = "System.Windows.Automation" Import-Module Accelerators Add-Accelerator AutoElement "$SWA.AutomationElement" -EA SilentlyContinue Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue Add-Accelerator AndCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator OrCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator NotCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue function New-UIAElement { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Element ) PROCESS { $Element | Add-Member -Name Text -Type ScriptProperty -PassThru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::NameProperty) } | Add-Member -Name ClassName -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ClassNameProperty) } | Add-Member -Name FrameworkId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::FrameworkIdProperty) } | Add-Member -Name ProcessId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ProcessIdProperty) } | Add-Member -Name ControlType -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::LocalizedControlTypeProperty) } } } function Select-Window { [CmdletBinding()] PARAM( [Parameter()] [Alias("Name")] [string]$Text="*" , [Parameter()] [string]$ClassName="*" , [Parameter()] [string]$ControlType="*" , [Parameter()] [switch]$Recurse , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Parent = [AutoElement]::RootElement ) PROCESS { if($Recurse) { $Parent.FindAll( "Descendants", $TrueCondition ) | New-UIAElement | Where-Object { ($_.ClassName -like $ClassName) -AND ($_.Text -like $Text) -AND ($_.ControlType -like $ControlType) } } else { $Parent.FindAll( "Children", $TrueCondition ) | New-UIAElement | Where-Object { ($_.ClassName -like $ClassName) -AND ($_.Text -like $Text) -AND ($_.ControlType -like $ControlType) } } } } function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Invoke-Element { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.GetCurrentPattern([InvokePattern]::Pattern).Invoke() } } function Set-ElementText { [CmdletBinding()] PARAM( [Parameter()] [string]$Text , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.SetFocus(); $textPattern = $valuePattern = $null try { $textPattern = $Target.GetCurrentPattern([TextPattern]::Pattern) Write-Host "textPattern:`n$($textPattern | gm)" } catch { } try { $valuePattern = $Target.GetCurrentPattern([ValuePattern]::Pattern) Write-Host "valuePattern:`n$($valuePattern | gm)" } catch { } $Target.SetFocus(); if($valuePattern) { $valuePattern.SetValue( $Text ) } if($textPattern) { [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } } }
PowerShellCorpus/PoshCode/Detect SCCM 2007.ps1
Detect SCCM 2007.ps1
function global:test-sccmagent { param($PC) [boolean]$result=get-wmiobject -Query "Select * from win32_service where Name = 'CcmExec'" -ComputerName $PC return $result }
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_5.ps1
Send-HTMLFormattedEmail_5.ps1
################################################## # cmdlets ################################################## #------------------------------------------------- # Send-HTMLFormattedEmail #------------------------------------------------- # Usage: Send-HTMLFormattedEmail -? #------------------------------------------------- function Send-HTMLFormattedEmail { <# .Synopsis Used to send an HTML Formatted Email. .Description Used to send an HTML Formatted Email that is based on an XSLT template. .Parameter To Email address or addresses for whom the message is being sent to. Addresses should be seperated using ;. .Parameter ToDisName Display name for whom the message is being sent to. .Parameter CC Email address if you want CC a recipient. Addresses should be seperated using ;. .Parameter BCC Email address if you want BCC a recipient. Addresses should be seperated using ;. .Parameter From Email address for whom the message comes from. .Parameter FromDisName Display name for whom the message comes from. .Parameter Subject The subject of the email address. .Parameter Content The content of the message (to be inserted into the XSL Template). .Parameter Relay FQDN or IP of the SMTP relay to send the message to. .XSLPath The full path to the XSL template that is to be used. #> param( [Parameter(Mandatory=$True)][String]$To, [Parameter(Mandatory=$True)][String]$ToDisName, [String]$CC, [String]$BCC, [Parameter(Mandatory=$True)][String]$From, [Parameter(Mandatory=$True)][String]$FromDisName, [Parameter(Mandatory=$True)][String]$Subject, [Parameter(Mandatory=$True)][String]$Content, [Parameter(Mandatory=$True)][String]$Relay, [Parameter(Mandatory=$True)][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 Message Object $Message = New-Object System.Net.Mail.MailMessage # Now Populate the Message Object. $Message.Subject = $Subject $Message.Body = $Body $Message.IsBodyHTML = $True # Add From $MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName $Message.From = $MessFrom # Add To $To = $To.Split(";") # Make an array of addresses. $To | foreach {$Message.To.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. # Add CC if ($CC){ $CC = $CC.Split(";") # Make an array of addresses. $CC | foreach {$Message.CC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. } # Add BCC if ($BCC){ $BCC = $BCC.Split(";") # Make an array of addresses. $BCC | foreach {$Message.BCC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. } # Create SMTP Client $Client = New-Object System.Net.Mail.SmtpClient $Relay # Send The Message $Client.Send($Message) } catch { throw $_ } } ################################################## # Main ################################################## Export-ModuleMember Send-HTMLFormattedEmail ### 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/4f560e57-408c-430b-a2c5-84a1d6d4c928.ps1
4f560e57-408c-430b-a2c5-84a1d6d4c928.ps1
<# .SYNOPSIS Gets the bogon list. .DESCRIPTION The Get-BogonList script retrieves the bogon prefix list maintained by Team Cymru. A bogon prefix is a route that should never appear in the Internet routing table. A packet routed over the public Internet (not including over VPNs or other tunnels) should never have a source address in a bogon range. These are commonly found as the source addresses of DDoS attacks. Bogons are defined as Martians (private and reserved addresses defined by RFC 1918 and RFC 3330) and netblocks that have not been allocated to a regional internet registry (RIR) by the Internet Assigned Numbers Authority. .PARAMETER Aggregated By default the unaggregated bogon list is retrieved. Use this switch parameter to retrieve the aggregated list. .OUTPUTS PSObject .EXAMPLE Get-BogonList Retrieves the unaggregated bogon list from Team Cymru. .EXAMPLE Get-BogonList -Aggregated Retrieves the aggregated bogon list from Team Cymru. .NOTES Name: Get-BogonList Author: Rich Kusak (rkusak@cbcag.edu) Created: 2010-01-31 Version: 1.0.0 #Requires -Version 2.0 .LINK http://www.team-cymru.org/Services/Bogons/ #> param ( [switch]$Aggregated ) $webClient = New-Object System.Net.WebClient $version = $webClient.DownloadString("http://www.cymru.com/Documents/bogon-list.html") -split "`n" | Where-Object {$_ -cmatch "TITLE"} | ForEach-Object {$_.Remove(0,7).Replace('</TITLE>',"").Trim()} if ($Aggregated) { foreach ($bogon in $webClient.DownloadString("http://www.cymru.com/Documents/bogon-bn-agg.txt") -split "`n" | Where-Object {$_ -notlike $null}) { New-Object PSObject -Property @{$version = $bogon} } } else { foreach ($bogon in $webClient.DownloadString("http://www.cymru.com/Documents/bogon-bn-nonagg.txt") -split "`n" | Where-Object {$_ -notlike $null}) { New-Object PSObject -Property @{$version = $bogon} } }
PowerShellCorpus/PoshCode/VM Disk Report_1.ps1
VM Disk Report_1.ps1
$VMs = get-vm $Results = @() foreach ($VM in $VMs) { $Result = new-object PSObject $Result | add-member -membertype NoteProperty -name "Name" -value $VM.Name $Result | add-member -membertype NoteProperty -name "Description" -value $VM.Notes $VMDiskCount = 1 get-harddisk $VM | foreach { $disk = $_ $Result | add-member -name "Disk($VMDiskCount)SizeGB" -value ([math]::Round($disk.CapacityKB / 1MB)) -membertype NoteProperty $Result | add-member -name "Disk($VMDiskCount)Type" -value $disk.DiskType -membertype NoteProperty $VMDiskCount++ } $Results += $Result } $Results | select-object * | export-csv -notypeinformation E:\\VCBDiskReport.csv
PowerShellCorpus/PoshCode/Lock-WorkStation.ps1
Lock-WorkStation.ps1
Function Lock-WorkStation { $signature = @" [DllImport("user32.dll", SetLastError = true)] public static extern bool LockWorkStation(); "@ $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru $LockWorkStation::LockWorkStation() | Out-Null }
PowerShellCorpus/PoshCode/Modified WOL impl_1..ps1
Modified WOL impl_1..ps1
function SendUdpWol { #Packet construction reference: #- http://wiki.wireshark.org/WakeOnLAN #- http://en.wikipedia.org/wiki/Wake-on-LAN # #This code is a modified version of: # - http://thepowershellguy.com/blogs/posh/archive/2007/04/01/powershell-wake-on-lan-script.aspx param ( [parameter(Mandatory=$true)] [ValidateLength(17,17)] [ValidatePattern("[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}:[0-9|A-F]{2}")] [String] $MacAddress, [parameter(Mandatory=$false)] [int[]] $Ports=@(0,7,9) ) [int]$MAGICPACKETLENGTH=102 #'Constant' defining total magic packet length. [Byte[]]$magicPacket=[Byte[]](,0xFF * $MAGICPACKETLENGTH) #Initialize packet all 0xFF for packet length. [Byte[]]$byteMac=$MacAddress.Split(":") |% { #Convert the string MacAddress to a byte array (6 bytes). [Byte]("0x" + $_) } #Starting from byte 6 till 101, fill the packet with the MAC address (= 16 times). 6..($magicPacket.Length - 1) |% { $magicPacket[$_]=$byteMac[($_%6)] } #Setup the UDP client socket. [System.Net.Sockets.UdpClient] $UdpClient = new-Object System.Net.Sockets.UdpClient foreach ($port in $Ports) { $UdpClient.Connect(([System.Net.IPAddress]::Broadcast),$port) #Send packet on each defined port. Write-Verbose $("Sending magic packet to {0} port {1}" -f $MacAddress,$port) [Void]$UdpClient.Send($magicPacket,$magicPacket.Length) #Don't return the packet length => [void] } $UdpClient.Close() }
PowerShellCorpus/PoshCode/Create SP2010 Farm V_3.ps1
Create SP2010 Farm V_3.ps1
############################################################################ ## Create-SPFarm ## V 0.3 ## Jos.Verlinde ############################################################################ Param ( [String] $Farm = "SP2010", [String] $SQLServer = $env:COMPUTERNAME, [String] $Passphrase = "pass@word1", [int] $CAPort = 26101 , [switch] $Force = $false ) # Disable the Loopback Check on stand alone demo servers. # This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1 New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword #region Process Input Parameters $SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force $Passphrase = $null ## get Farm Account $cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" ) #Endregion # Create a new farm New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm # Create Central Admin New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM" #Install Help Files Install-SPApplicationContent #Secure resources Initialize-SPResourceSecurity #Install (all) features If ( $Force ) { $Features = Install-SPFeature –AllExistingFeatures -force } else { $Features = Install-SPFeature –AllExistingFeatures } ## Report features installed $Features # Provision all Services works only on stand alone servers (ie one-click-install ) # Install-SPService -Provision ## Todo : Check for Errors in the evenlog ## ## Start Central Admin Start-Process "http://$($env:COMPUTERNAME):$CAPort" ## Run Farm configuration Wizard Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome" ##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
PowerShellCorpus/PoshCode/check-nsca.ps1
check-nsca.ps1
#region vars $statvalues=("mem.usage.average", "cpu.usage.average") $nsca_stat = "" [int]$warnlevel = 85 [int]$criticallevel = 90 $status = "" $nagsrv = "nagios-srv.local" #endregion $vms = Get-VM | Where-Object { $_.PowerState -eq "PoweredOn" } | sort-object foreach ($vm in $vms) { $statvalues | foreach { [int]$statavg = ($vm | Get-Stat -Stat $_ -Start ((get-date).AddMinutes(-5)) -MaxSamples 500 | Measure-Object -Property Value -Average).Average $vmdns = ($vm | Get-VMGuest).Hostname switch ($_) { "mem.usage.average" { $nsca_stat = "mem_vm"; $desc = "Memory Usage" } "cpu.usage.average" { $nsca_stat = "cpu_vm"; $desc = "CPU Usage" } } if ($statavg -gt $criticallevel) { $status = "2" $desc = "CRITICAL: " + $desc } elseif ($statavg -gt $warnlevel) { $status = "1" $desc = "WARNING: " + $desc } elseif ($statavg -lt $warnlevel) { $status = "0" } $nsca = "${vmdns};${nsca_stat};${status};${desc} ${statavg}% | ${nsca_stat}=${statavg};$warnlevel;$criticallevel;0;100" Write-Host $nsca if ($vmdns) { echo $nsca | ./send_nsca.exe -H $nagsrv -c send_nsca.cfg -d ";" } } }
PowerShellCorpus/PoshCode/Start-Demo 3.3.1.ps1
Start-Demo 3.3.1.ps1
## Start-Demo.ps1 ################################################################################################## ## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett ## ## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time) ## As a result, I've changed the names and keys for a lot of the operations, so that they make ## sense with only a single letter to tell them apart (sorry if you had them memorized). ## ## I've also been adding features as I come across needs for them, and you'll contribute your ## improvements back to the PowerShell Script repository as well. ################################################################################################## ## Revision History (version 3.3) ## 3.3.1 Added: Fixed a bracket in the script ## 3.3 - Added: Added a "Clear Screen" option ## - Added: Added a "Rewind" function (which I'm not using much) ## 3.2 - Fixed: Put back the trap { continue; } ## 3.1 - Fixed: No Output when invoking Get-Member (and other cmdlets like it???) ## 3.0 - Fixed: Commands which set a variable, like: $files = ls ## - Fixed: Default action doesn't continue ## - Changed: Use ReadKey instead of ReadLine ## - Changed: Modified the option prompts (sorry if you had them memorized) ## - Changed: Various time and duration strings have better formatting ## - Enhance: Colors are settable: prompt, command, comment ## - Added: NoPauseAfterExecute switch removes the extra pause ## If you set this, the next command will be displayed immediately ## - Added: Auto Execute mode (FullAuto switch) runs the rest of the script ## at an automatic speed set by the AutoSpeed parameter (or manually) ## - Added: Automatically append an empty line to the end of the demo script ## so you have a chance to "go back" after the last line of you demo ################################################################################################## ## param( $file=".\\demo.txt", [int]$command=0, [System.ConsoleColor]$promptColor="Yellow", [System.ConsoleColor]$commandColor="White", [System.ConsoleColor]$commentColor="Green", [switch]$FullAuto, [int]$AutoSpeed = 3, [switch]$NoPauseAfterExecute ) $RawUI = $Host.UI.RawUI $hostWidth = $RawUI.BufferSize.Width # A function for reading in a character function Read-Char() { $_OldColor = $RawUI.ForeGroundColor $RawUI.ForeGroundColor = "Red" $inChar=$RawUI.ReadKey("IncludeKeyUp") # loop until they press a character, so Shift or Ctrl, etc don't terminate us while($_input.Character -eq 0){ $inChar=$RawUI.ReadKey("IncludeKeyUp") } $RawUI.ForeGroundColor = $_OldColor return $inChar.Character } function Rewind($lines, $index, $steps = 1) { $started = $index; $index -= $steps; while(($index -ge 0) -and ($lines[$index].Trim(" `t").StartsWith("#"))){ $index-- } if( $index -lt 0 ) { $index = $started } return $index } $file = Resolve-Path $file while(-not(Test-Path $file)) { $file = Read-Host "Please enter the path of your demo script (Crtl+C to cancel)" $file = Resolve-Path $file } Clear-Host $_lines = Get-Content $file # Append an extra (do nothing) line on the end so we can still go back after the last line. $_lines += "Write-Host 'The End'" $_starttime = [DateTime]::now $FullAuto = $false Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth) Write-Host -nonew -back black -fore $promptColor @" <Demo Started :: $(split-path $file -leaf)>$(' ' * ($hostWidth -(18 + $(split-path $file -leaf).Length))) "@ Write-Host -nonew -back black -fore $promptColor "Press" Write-Host -nonew -back black -fore Red " ? " Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth -17))" Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth) # We use a FOR and an INDEX ($_i) instead of a FOREACH because # it is possible to start at a different location and/or jump # around in the order. for ($_i = $Command; $_i -lt $_lines.count; $_i++) { # Put the current command in the Window Title along with the demo duration $Dur = [DateTime]::Now - $_StartTime $RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f $dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i]) # Echo out the commmand to the console with a prompt as though it were real Write-Host -nonew -fore $promptColor "[$_i]PS> " if ($_lines[$_i].Trim(" ").StartsWith("#")) { Write-Host -fore $commentColor "$($_Lines[$_i]) " continue } else { Write-Host -nonew -fore $commandColor "$($_Lines[$_i]) " } if( $FullAuto ) { Start-Sleep $autoSpeed; $ch = [char]13 } else { $ch = Read-Char } switch($ch) { "?" { Write-Host -Fore $promptColor @" Running demo: $file (n) Next (p) Previous (q) Quit (s) Suspend (t) Timecheck (v) View $(split-path $file -leaf) (g) Go to line by number (f) Find lines by string (a) Auto Execute mode (c) Clear Screen "@ $_i-- # back a line, we're gonna step forward when we loop } "n" { # Next (do nothing) Write-Host -Fore $promptColor "<Skipping Line>" } "p" { # Previous Write-Host -Fore $promptColor "<Back one Line>" while ($_lines[--$_i].Trim(" ").StartsWith("#")){} $_i-- # back a line, we're gonna step forward when we loop } "x" { # EXECUTE (Go Faster) $AutoSpeed = [int](Read-Host "Pause (seconds)") $FullAuto = $true; Write-Host -Fore $promptColor "<eXecute Remaining Lines>" $_i-- # Repeat this line, and then just blow through the rest } "q" { # Quit Write-Host -Fore $promptColor "<Quiting demo>" $_i = $_lines.count; break; } "v" { # View Source $lines[0..($_i-1)] | Write-Host -Fore Yellow $lines[$_i] | Write-Host -Fore Green $lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow $_i-- # back a line, we're gonna step forward when we loop } "t" { # Time Check $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( "{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f $dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString())) $_i-- # back a line, we're gonna step forward when we loop } "s" { # Suspend (Enter Nested Prompt) Write-Host -Fore $promptColor "<Suspending demo - type 'Exit' to resume>" $Host.EnterNestedPrompt() $_i-- # back a line, we're gonna step forward when we loop } "g" { # GoTo Line Number $i = [int](Read-Host "line number") if($i -le $_lines.Count) { if($i -gt 0) { # extra line back because we're gonna step forward when we loop $_i = Rewind $_lines $_i (($_i-$i)+1) } else { $_i = -1 # Start negative, because we step forward when we loop } } } "f" { # Find by pattern $match = $_lines | Select-String (Read-Host "search string") if($match -eq $null) { Write-Host -Fore Red "Can't find a matching line" } else { $match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) } if($match.Count -lt 1) { $_i = $match.lineNumber - 2 # back a line, we're gonna step forward when we loop } else { $_i-- # back a line, we're gonna step forward when we loop } } } "c" { Clear-Host $_i-- # back a line, we're gonna step forward when we loop } "$([char]13)" { # on enter Write-Host trap [System.Exception] {Write-Error $_; continue;} Invoke-Expression ($_lines[$_i]) | out-default if(-not $NoPauseAfterExecute -and -not $FullAuto) { $null = $RawUI.ReadKey("NoEcho,IncludeKeyUp") # Pause after output for no apparent reason... ;) } } default { Write-Host -Fore Green "`nKey not recognized. Press ? for help, or ENTER to execute the command." $_i-- # back a line, we're gonna step forward when we loop } } } $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( "<Demo Complete -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s>" -f $dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString()) Write-Host -Fore $promptColor $([DateTime]::now) Write-Host
PowerShellCorpus/PoshCode/Set-Domain_3.ps1
Set-Domain_3.ps1
function Set-Domain { param( [switch]$help, [string]$domain=$(read-host "Please specify the domain to join"), [System.Management.Automation.PSCredential]$credential = $(Get-Crdential) ) $usage = "`$cred = get-credential `n" $usage += "Set-AvaDomain -domain corp.avanade.org -credential `$cred`n" if ($help) {Write-Host $usage;exit} $username = $credential.GetNetworkCredential().UserName $password = $credential.GetNetworkCredential().Password $computer = Get-WmiObject Win32_ComputerSystem $computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3) }
PowerShellCorpus/PoshCode/Show-HtmlHelp.ps1
Show-HtmlHelp.ps1
##############################################################################\n##\n## Show-HtmlHelp\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\nLaunches the CHM version of PowerShell help.\n\n.EXAMPLE\n\nShow-HtmlHelp\n\n#>\n\nSet-StrictMode -Version Latest\n\n$path = (Resolve-Path c:\\windows\\help\\mui\\*\\WindowsPowerShellHelp.chm).Path\nhh "$path::/html/defed09e-2acd-4042-bd22-ce4bf92c2f24.htm"
PowerShellCorpus/PoshCode/Invoke-RemoteCommand_1.ps1
Invoke-RemoteCommand_1.ps1
<# # Script FileName: func_Invoke-RemoteCommand.ps1 # Current Version: A03 # Description: Run command on a remote computer as the currently logged on user. # Created By: Adam Listek # Version Notes # A01 - Initial Release # A02 - Conversion to Function # A03 - Abstracted to generic purpose #> Function Global:Invoke-RemoteCommand { [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact="Low" )] # Terminate CmdletBinding Param ( [Parameter( ValueFromPipeline=$true, Position=0)] [String]$computerName = "localhost", [Parameter(Position=1)][String]$inputCode, [Parameter(Position=2)][String]$outputFile = "C:\\Temp\\Output.ps1", [Switch]$passthru ) # Terminate Param Begin { If ($MyInvocation.BoundParameters.Verbose -match $true) { $local:VerbosePreference = "Continue" $local:ErrorActionPreference = "Continue" $local:verbose = $true } Else { $local:VerbosePreference = "SilentlyContinue" $local:ErrorActionPreference = "SilentlyContinue" $local:verbose = $false } # Terminate If - Verbose Parameter Check # Define Internal Functions @@ Function local:Test-AdministratorPrivileges { Write-Verbose "Get user that script context is being run in." $identity = [Security.Principal.WindowsIdentity]::GetCurrent() Write-Verbose "Create a new Security Principal object to retrieve rights." $principal = new-object Security.Principal.WindowsPrincipal $identity Write-Verbose "Retrieve if user is currently in an Administrator role." $result = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) If ($result) { Write-Output $true } Else { Write-Output $false } # Terminate If - Result } # Terminate Function # Verify whether the current user context for the function is an Administrator @@ If (Test-AdministratorPrivileges -Verbose:$verbose) { Write-Verbose "Function is being run as an Administrator." } Else { Write-Host "Current user, {0}, is not an Administrator." ` -F ([Security.Principal.WindowsIdentity]::GetCurrent()) ` -ForegroundColor Red Break } # Terminate Test for Administrative Privileges # Global Variables $servicePath = "C:\\Temp" $serviceName = "ps_service" } # Terminate Begin Process { # Required if running in Powershell ISE, will set for the shell also. If ($MyInvocation.BoundParameters.Debug -match $true) { # Must be set per pipeline run $local:DebugPreference = "Continue" } Else { $local:DebugPreference = "SilentlyContinue" } # Terminate If - Debug $scriptblock = { Param( $inputCode, $outputFile, $servicePath, $serviceName ) # Parse the results of the current sessions using the built-in executable, Query.exe. $results = c:\\windows\\system32\\query.exe session # Create object array of Query results $active = $results | %{ $line = $_.ToString().Split(" ") $array = $line | Where { $_ -ne "" } Switch ($array.count) { 3 { $sessionname = $array[0] $username = $null $id = $array[1] $state = $array[2] $type = $null Break } 4 { $sessionname = $array[0] $username = $array[1] $id = $array[2] $state = $array[3] $type = $null Break } 5 { $sessionname = $array[0] $username = $array[1] $id = $array[2] $state = $array[3] $type = $array[4] Break } } # Terminate Switch $object = New-Object PSObject -Property @{ sessionname = $sessionname username = $username ID = $id state = $state type = $type } Write-Output $object } | Where { $_.State -eq "Active" } If ($active) { # The data is the local Powershell script that you want to run on the remote system # Using a HereString @'' (does not parse variables within), @"" (will parse variables) Write-Verbose $outputFile Write-Verbose $inputCode # Generate the script file on the fly on the remote computer Out-File -FilePath $outputFile -InputObject $inputCode -Encoding ascii # We want to hide the powershell window and override the execution policy to make sure it runs $command = "powershell.exe -NonInteractive -WindowStyle hidden -NoLogo -File $outputFile -ExecutionPolicy RemoteSigned" $serviceDisplayName = "PS Emulate Session" Write-Verbose $command Write-Verbose $serviceDisplayName # The code to actually generate the service $source = @" using System; using System.Text; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Diagnostics; namespace PS { public class Emulate : System.ServiceProcess.ServiceBase { public Emulate() { this.ServiceName = "$serviceDisplayName"; } static void Main(string[] args) { System.ServiceProcess.ServiceBase.Run(new Emulate()); } protected override void OnStart(string[] args) { base.OnStart(args); EmulateSession.StartProcessInSession($($active.Id), @"$command"); } protected override void OnStop() { base.OnStop(); } public static void WriteToEventLog(string message) { string cs = "PS_Emulate_Service"; EventLog elog = new EventLog(); if (!EventLog.SourceExists(cs)) { EventLog.CreateEventSource(cs, "Application"); } elog.Source = cs; elog.EnableRaisingEvents = true; EventLog.WriteEntry(cs, message, EventLogEntryType.Information); } } static public class EmulateSession { /* structs, enums, and external functions defined at end of code */ public static System.Diagnostics.Process StartProcessInSession(int sessionID, String commandLine) { Emulate.WriteToEventLog("Inside StartProcessInSession"); Emulate.WriteToEventLog("Session ID: " + sessionID.ToString()); IntPtr userToken; if (WTSQueryUserToken(sessionID, out userToken)) { //note that WTSQueryUserToken only works when in context of local system account with SE_TCB_NAME IntPtr lpEnvironment; Emulate.WriteToEventLog("Token: " + userToken.ToString()); if (CreateEnvironmentBlock(out lpEnvironment, userToken, false)) { Emulate.WriteToEventLog("User Env: " + lpEnvironment.ToString()); StartupInfo si = new StartupInfo(); si.cb = Marshal.SizeOf(si); si.lpDesktop = "winsta0\\\\default"; si.dwFlags = STARTF.STARTF_USESHOWWINDOW; // Using the SW_HIDE will make the window hidden, see in the bottom section for more commands si.wShowWindow = ShowWindow.SW_HIDE; ProcessInformation pi; // Note the CreationFlags, they make this work as it must have both the CREATE_NEW_CONSOLE and CREATE_UNICODE_ENVIRONMENT if (CreateProcessAsUser(userToken, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, false, CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref si, out pi)) { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); //context.Undo(); try { return System.Diagnostics.Process.GetProcessById(pi.dwProcessId); } catch (ArgumentException) { // I had to remove the ArgumentException e (I removed the e), it threw up a compiler warning //The process ID couldn't be found - which is what always happens because it has closed return null; } } else { Emulate.WriteToEventLog("Could Not Create Process."); int err = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(err, "Could not create process.\\nWin32 error: " + err.ToString()); } } else { Emulate.WriteToEventLog("Could not create environment block."); int err = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(err, "Could not create environment block.\\nWin32 error: " + err.ToString()); } } else { Emulate.WriteToEventLog("No Token"); int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (err == 1008) return null; //There is no token throw new System.ComponentModel.Win32Exception(err, "Could not get the user token from session " + sessionID.ToString() + " - Error: " + err.ToString()); } } [DllImport("wtsapi32.dll", SetLastError = true)] static extern bool WTSQueryUserToken(Int32 sessionId, out IntPtr Token); [DllImport("userenv.dll", SetLastError = true)] static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation); [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hHandle); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct StartupInfo { public Int32 cb; public String lpReserved; public String lpDesktop; public String lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public STARTF dwFlags; public ShowWindow wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] internal struct ProcessInformation { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } /// <summary> /// The following process creation flags are used by the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, and CreateProcessWithTokenW functions. They can be specified in any combination, except as noted. /// </summary> [Flags] enum CreationFlags : int { /// <summary> /// Not specified by MSDN??? /// </summary> NONE = 0, /// <summary> /// The calling thread starts and debugs the new process and all child processes created by the new process. It can receive all related debug events using the WaitForDebugEvent function. /// A process that uses DEBUG_PROCESS becomes the root of a debugging chain. This continues until another process in the chain is created with DEBUG_PROCESS. /// If this flag is combined with DEBUG_ONLY_THIS_PROCESS, the caller debugs only the new process, not any child processes. /// </summary> DEBUG_PROCESS = 0x00000001, /// <summary> /// The calling thread starts and debugs the new process. It can receive all related debug events using the WaitForDebugEvent function. /// </summary> DEBUG_ONLY_THIS_PROCESS = 0x00000002, /// <summary> /// The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called. /// </summary> CREATE_SUSPENDED = 0x00000004, /// <summary> /// For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console. /// This value cannot be used with CREATE_NEW_CONSOLE. /// </summary> DETACHED_PROCESS = 0x00000008, /// <summary> /// The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console. /// This flag cannot be used with DETACHED_PROCESS. /// </summary> CREATE_NEW_CONSOLE = 0x00000010, /// <summary> /// The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process identifier of the new process group is the same as the process identifier, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a CTRL+BREAK signal to a group of console processes. /// If this flag is specified, CTRL+C signals will be disabled for all processes within the new process group. /// This flag is ignored if specified with CREATE_NEW_CONSOLE. /// </summary> CREATE_NEW_PROCESS_GROUP = 0x00000200, /// <summary> /// If this flag is set, the environment block pointed to by lpEnvironment uses Unicode characters. Otherwise, the environment block uses ANSI characters. /// </summary> CREATE_UNICODE_ENVIRONMENT = 0x00000400, /// <summary> /// This flag is valid only when starting a 16-bit Windows-based application. If set, the new process runs in a private Virtual DOS Machine (VDM). By default, all 16-bit Windows-based applications run as threads in a single, shared VDM. The advantage of running separately is that a crash only terminates the single VDM; any other programs running in distinct VDMs continue to function normally. Also, 16-bit Windows-based applications that are run in separate VDMs have separate input queues. That means that if one application stops responding momentarily, applications in separate VDMs continue to receive input. The disadvantage of running separately is that it takes significantly more memory to do so. You should use this flag only if the user requests that 16-bit applications should run in their own VDM. /// </summary> CREATE_SEPARATE_WOW_VDM = 0x00000800, /// <summary> /// The flag is valid only when starting a 16-bit Windows-based application. If the DefaultSeparateVDM switch in the Windows section of WIN.INI is TRUE, this flag overrides the switch. The new process is run in the shared Virtual DOS Machine. /// </summary> CREATE_SHARED_WOW_VDM = 0x00001000, /// <summary> /// The process is to be run as a protected process. The system restricts access to protected processes and the threads of protected processes. For more information on how processes can interact with protected processes, see Process Security and Access Rights. /// To activate a protected process, the binary must have a special signature. This signature is provided by Microsoft but not currently available for non-Microsoft binaries. There are currently four protected processes: media foundation, audio engine, Windows error reporting, and system. Components that load into these binaries must also be signed. Multimedia companies can leverage the first two protected processes. For more information, see Overview of the Protected Media Path. /// Windows Server 2003 and Windows XP/2000: This value is not supported. /// </summary> CREATE_PROTECTED_PROCESS = 0x00040000, /// <summary> /// The process is created with extended startup information; the lpStartupInfo parameter specifies a STARTUPINFOEX structure. /// Windows Server 2003 and Windows XP/2000: This value is not supported. /// </summary> EXTENDED_STARTUPINFO_PRESENT = 0x00080000, /// <summary> /// The child processes of a process associated with a job are not associated with the job. /// If the calling process is not associated with a job, this constant has no effect. If the calling process is associated with a job, the job must set the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit. /// </summary> CREATE_BREAKAWAY_FROM_JOB = 0x01000000, /// <summary> /// Allows the caller to execute a child process that bypasses the process restrictions that would normally be applied automatically to the process. /// Windows 2000: This value is not supported. /// </summary> CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, /// <summary> /// The new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. /// This feature is particularly useful for multi-threaded shell applications that run with hard errors disabled. /// The default behavior is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior. /// </summary> CREATE_DEFAULT_ERROR_MODE = 0x04000000, /// <summary> /// The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set. /// This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS. /// </summary> CREATE_NO_WINDOW = 0x08000000, } [Flags] public enum STARTF : uint { STARTF_USESHOWWINDOW = 0x00000001, STARTF_USESIZE = 0x00000002, STARTF_USEPOSITION = 0x00000004, STARTF_USECOUNTCHARS = 0x00000008, STARTF_USEFILLATTRIBUTE = 0x00000010, STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms STARTF_FORCEONFEEDBACK = 0x00000040, STARTF_FORCEOFFFEEDBACK = 0x00000080, STARTF_USESTDHANDLES = 0x00000100, } public enum ShowWindow : short { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_FORCEMINIMIZE = 11, SW_MAX = 11 } } } "@ Write-Verbose $source # Using the OutputAssembly and OutputType we can make an executable out of this. It requires the System.ServiceProcess assembly also to inherit the ServiceBase class. Add-Type -TypeDefinition $source -Language CSharpVersion3 -OutputAssembly ("$servicePath$serviceName.exe") -OutputType ConsoleApplication -ReferencedAssemblies "System.ServiceProcess" # Use WMI to create the service, it does not require DesktopInteract # The computer is the localhost cause this code will be run on the remote computer locally. $computer = "." $class = "Win32_Service" $method = "Create" $mc = [wmiclass]"\\\\$computer\\ROOT\\CIMV2:$class" $inparams = $mc.PSBase.GetMethodParameters($method) $inparams.DesktopInteract = $false $inparams.DisplayName = $serviceDisplayName $inparams.ErrorControl = 0 $inparams.LoadOrderGroup = $null $inparams.LoadOrderGroupDependencies = $null $inparams.Name = $serviceDisplayName.Replace(" " ,"_") $inparams.PathName = ("$servicePath$serviceName.exe") $inparams.ServiceDependencies = $null $inparams.ServiceType = 16 $inparams.StartMode = "Automatic" # Will start as localsystem builtin if null $inparams.StartName = $null $inparams.StartPassword = $null $result = $mc.PSBase.InvokeMethod($method,$inparams,$null) Start-Service -DisplayName $serviceDisplayName # Loop until the child process of Powershell.exe is gone. $baseproc = Get-WMIObject Win32_Process | Where { $_.Name -eq $serviceName } While (Get-WMIObject Win32_Process | Where { $_.ParentProcessId -eq $baseproc.ProcessId }) { Sleep 1 } # Terminate While Stop-Service -DisplayName $serviceDisplayName # Use sc.exe to delete the service, if you only use WMI to do this, it will not disappear until next restart, this deletes it immediately C:\\Windows\\System32\\sc.exe delete $serviceDisplayName.Replace(" " ,"_") | Out-Null # Clean up created files Remove-Item -Path ("$servicePath$serviceName.exe") -Force Remove-Item -Path ("$servicePath$serviceName.pdb") -Force Remove-Item -Path $outputFile -Force } Else { Write-Host "No active sessions" } # Terminate If - Active User } # Terminate Scriptblock If (Test-Connection $computerName -Quiet) { Try { Invoke-Command ` -ComputerName $computerName ` -ScriptBlock $scriptblock ` -ArgumentList $inputCode,$outputFile,$servicePath,$serviceName } Catch { Write-Warning "Unable to create remote session: $($_.Exception.Message)" Break } # Terminate Try-Catch } # Terminate If - Test Connection } # Terminate Process <# .SYNOPSIS Invoke remote code impersonating the currently logged on user. .PARAMETER computername Computer to run the remote code on. .PARAMETER inputCode The code to run on the remote computer. .PARAMETER outputFile The output data from a file. .INPUTS The input is a computer. .OUTPUTS The output is the returned data from .EXAMPLE C:\\PS> $code = "Out-File -FilePath c:\\temp\\output.txt -InputObject ([Security.Principal.WindowsIdentity]::GetCurrent())" C:\\PS> Invoke-RemoteCommand -inputCode $code #> } # Terminate Function
PowerShellCorpus/PoshCode/Console Function Run.ps1
Console Function Run.ps1
function Run ([String]$scriptName = '-BLANK-') { <# The next function records any running scripts started in the console session (from $pwd) in the Scripts Event Log. It should be placed in the Console $profile. Scripts should be started by typing 'Run example' to capture example.ps1, for example. The default logfile is that used by the Windows Script Monitor Service, available from www.SeaStarDevelopment.Bravehost.com #> if ($host -ne 'ConsoleHost') { return } $logfile = "$env:programfiles\\Sea Star Development\\" + "Script Monitor Service\\ScriptMon.txt" $parms = $myInvocation.Line -replace "run(\\s+)$scriptName(\\s*)" $script = $scriptName -replace "\\.ps1\\b" #Replace from word end only. $script = $script + ".ps1" if (Test-Path $pwd\\$script) { if(!(Test-Path Variable:\\Session.Script.Job)) { Set-Variable Session.Script.Job -value 1 -scope global ` -description "Script counter" } $Job = Get-Variable -name Session.Script.Job $number = $job.Value.ToString().PadLeft(4,'0') $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$startTime [$script] start. --> $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PS$number) started." Invoke-Expression -command "$pwd\\$script $parms" $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$endTime [$script] ended. --> $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PS$number) ended." $job.Value += 1 } else { Write-Error "$pwd\\$script does not exist." } }
PowerShellCorpus/PoshCode/New-PInvoke_1.ps1
New-PInvoke_1.ps1
function New-PInvoke { <# .Synopsis Generate a powershell function alias to a Win32|C api function .Description Creates C# code to access a C function, and exposes it via a powershell function .Example New-PInvoke user32 "void FlashWindow(IntPtr hwnd, bool bInvert)" Generates a function for FlashWindow which ignores the boolean return value, and allows you to make a window flash to get the user's attention. Once you've created this function, you could use this line to make a PowerShell window flash at the end of a long-running script: C:\\PS>FlashWindow (ps -id $pid).MainWindowHandle $true .Parameter Library A C Library containing code to invoke .Parameter Signature The C# signature of the external method .Parameter OutputText If Set, retuns the source code for the pinvoke method. If not, compiles the type. #> param( [Parameter(Mandatory=$true, HelpMessage="The C Library Containing the Function, i.e. User32")] [String] $Library, [Parameter(Mandatory=$true, HelpMessage="The Signature of the Method, i.e.: int GetSystemMetrics(uint Metric)")] [String] $Signature, [Switch] $OutputText ) process { if ($Library -notlike "*.dll*") { $Library+=".dll" } if ($signature -notlike "*;") { $Signature+=";" } if ($signature -notlike "public static extern*") { $signature = "public static extern $signature" } $name = $($signature -replace "^.*?\\s(\\w+)\\(.*$",'$1') $MemberDefinition = "[DllImport(`"$Library`")]`n$Signature" if (-not $OutputText) { $type = Add-Type -PassThru -Name "PInvoke$(Get-Random)" -MemberDefinition $MemberDefinition iex "New-Item Function:Global:$name -Value { [$($type.FullName)]::$name.Invoke( `$args ) }" } else { $MemberDefinition } } }
PowerShellCorpus/PoshCode/Get-MyDomain.ps1
Get-MyDomain.ps1
Function Get-MyDomain() { # Written by Jeremy D. Pavleck - Pavleck.NET $IP = ((Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property IPAddress -First 1).IPAddress[0]) trap { return "Unknown:$($IP)" } return [System.Net.DNS]::GetHostByAddress($IP).HostName }
PowerShellCorpus/PoshCode/Get-WifiNetwork.ps1
Get-WifiNetwork.ps1
function Get-WifiNetwork { end { netsh wlan sh net mode=bssid | % -process { if ($_ -match '^SSID (\\d+) : (.*)$') { $current = @{} $networks += $current $current.Index = $matches[1].trim() $current.SSID = $matches[2].trim() } else { if ($_ -match '^\\s+(.*)\\s+:\\s+(.*)\\s*$') { $current[$matches[1].trim()] = $matches[2].trim() } } } -begin { $networks = @() } -end { $networks|% { new-object psobject -property $_ } } } } ps> Get-WifiNetwork| select index, ssid, signal, 'radio type' | sort signal -desc | ft -auto
PowerShellCorpus/PoshCode/ISE-Comments_2.ps1
ISE-Comments_2.ps1
#requires -version 2.0 ## ISE-Comments module v 1.1 ############################################################################################################## ## Provides Comment cmdlets for working with ISE ## ConvertTo-BlockComment - Comments out selected text with <# before and #> after ## ConvertTo-BlockUncomment - Removes <# before and #> after selected text ## ConvertTo-Comment - Comments out selected text with a leeding # on every line ## ConvertTo-Uncomment - Removes leeding # on every line of selected text ## ## Usage within ISE or Microsoft.PowershellISE_profile.ps1: ## Import-Module ISE-Comments.psm1 ## ## Note: The IsePack, a part of the PowerShellPack, also contains a "Toggle Comments" command, ## but it does not support Block Comments ## http://code.msdn.microsoft.com/PowerShellPack ## ############################################################################################################## ## History: ## 1.1 - Minor alterations to work with PowerShell 2.0 RTM and Documentation updates (Hardwick) ## 1.0 - Initial release (Poetter) ############################################################################################################## ## ConvertTo-BlockComment ############################################################################################################## ## Comments out selected text with <# before and #> after ## This code was originaly designed by Jeffrey Snover and was taken from the Windows PowerShell Blog. ## The original function was named ConvertTo-Comment but as it comments out a block I renamed it. ############################################################################################################## function ConvertTo-BlockComment { $editor = $psISE.CurrentFile.Editor $CommentedText = "<#`n" + $editor.SelectedText + "#>" # INSERTING overwrites the SELECTED text $editor.InsertText($CommentedText) } ## ConvertTo-BlockUncomment ############################################################################################################## ## Removes <# before and #> after selected text ############################################################################################################## function ConvertTo-BlockUncomment { $editor = $psISE.CurrentFile.Editor $CommentedText = $editor.SelectedText -replace ("^<#`n", "") $CommentedText = $CommentedText -replace ("#>$", "") # INSERTING overwrites the SELECTED text $editor.InsertText($CommentedText) } ## ConvertTo-Comment ############################################################################################################## ## Comments out selected text with a leeding # on every line ############################################################################################################## function ConvertTo-Comment { $editor = $psISE.CurrentFile.Editor $CommentedText = $editor.SelectedText.Split("`n") # INSERTING overwrites the SELECTED text $editor.InsertText( "#" + ( [String]::Join("`n#", $CommentedText))) } ## ConvertTo-Uncomment ############################################################################################################## ## Comments out selected text with <# before and #> after ############################################################################################################## function ConvertTo-Uncomment { $editor = $psISE.CurrentFile.Editor $CommentedText = $editor.SelectedText.Split("`n") -replace ( "^#", "" ) # INSERTING overwrites the SELECTED text $editor.InsertText( [String]::Join("`n", $CommentedText)) } ############################################################################################################## ## Inserts a submenu Comments to ISE's Custum Menu ## Inserts command Block Comment Selected to submenu Comments ## Inserts command Block Uncomment Selected to submenu Comments ## Inserts command Comment Selected to submenu Comments ## Inserts command Uncomment Selected to submenu Comments ############################################################################################################## if (-not( $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | where { $_.DisplayName -eq "Comments" } ) ) { $commentsMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Comments",$null,$null) $null = $commentsMenu.Submenus.Add("Block Comment Selected", {ConvertTo-BlockComment}, "Ctrl+SHIFT+B") $null = $commentsMenu.Submenus.Add("Block Uncomment Selected", {ConvertTo-BlockUncomment}, "Ctrl+Alt+B") $null = $commentsMenu.Submenus.Add("Comment Selected", {ConvertTo-Comment}, "Ctrl+SHIFT+C") $null = $commentsMenu.Submenus.Add("Uncomment Selected", {ConvertTo-Uncomment}, "Ctrl+Alt+C") } # If you are using IsePack (http://code.msdn.microsoft.com/PowerShellPack) and IseCream (http://psisecream.codeplex.com/), # you can use this code to add your menu items. The added benefits are that you can specify the order of the menu items and # if the shortcut already exists it will add the menu item without the shortcut instead of failing as the default does. # Add-IseMenu -Name "Comments" @{ # "Block Comment Selected" = {ConvertTo-BlockComment}| Add-Member NoteProperty order 1 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+SHIFT+B" -PassThru # "Block Uncomment Selected" = {ConvertTo-BlockUncomment}| Add-Member NoteProperty order 2 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+B" -PassThru # "Comment Selected" = {ConvertTo-Comment}| Add-Member NoteProperty order 3 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+SHIFT+C" -PassThru # "Uncomment Selected" = {ConvertTo-Uncomment}| Add-Member NoteProperty order 4 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+C" -PassThru # }
PowerShellCorpus/PoshCode/Get-User_1.ps1
Get-User_1.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/Connect-AccessDB_2.ps1
Connect-AccessDB_2.ps1
# Functions for connecting to and working with Access databases # Matt Wilson # May 2009 function Connect-AccessDB ($global:dbFilePath) { # Test to ensure valid path to database file was supplied if (-not (Test-Path $dbFilePath)) { Write-Error "Invalid Access database path specified. Please supply full absolute path to database file!" } # TO-DO: Add check to ensure file is either MDB or ACCDB # Create a new ADO DB connection COM object, which will give us useful methods & properties such as "Execute"! $global:AccessConnection = New-Object -ComObject ADODB.Connection # Actually open the database so we can start working with its contents # Access 00-03 (MDB) format has a different connection string than 2007 if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.mdb$") { Write-Host "Access 2000-2003 format (MDB) detected! Using Microsoft.Jet.OLEDB.4.0." $AccessConnection.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source= $dbFilePath") } # Here's the check for if 2007 connection is necessary if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.accdb$") { Write-Host "Access 2007 format (ACCDB) detected! Using Microsoft.Ace.OLEDB.12.0." $AccessConnection.Open("Provider = Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; Data Source= $dbFilePath") } } function Open-AccessRecordSet ($global:SqlQuery) { # Ensure SQL query isn't null if ($SqlQuery.length -lt 1) { Throw "Please supply a SQL query for the recordset selection!" } # Variables used for the connection itself. Leave alone unless you know what you're doing. $adOpenStatic = 3 $adLockOptimistic = 3 # Create the recordset object using the ADO DB COM object $global:AccessRecordSet = New-Object -ComObject ADODB.Recordset # Finally, go and get some records from the DB! $AccessRecordSet.Open($SqlQuery, $AccessConnection, $adOpenStatic, $adLockOptimistic) } function Get-AccessRecordSetStructure { # TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records # Cycle through the fields in the recordset, but only pull out the properties we care about @@ return $AccessRecordSet.Fields | Select-Object Name,Attributes,DefinedSize,type } function Convert-AccessRecordSetToPSObject { # TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records # Get an array of field names which we will later use to create custom PoSh object names $fields = Get-AccessRecordSetStructure # Move to the very first record in the RecordSet before cycling through each one $AccessRecordSet.MoveFirst() # Cycle through each RECORD in the set and create that record to an object do { # Create a SINGLE blank object we can use in a minute to add properties/values to $record = New-Object System.Object # For every FIELD in the DB, lookup the CURRENT value of that field and add a new PoSh object property with that name and value foreach ($field in $fields) { $fieldName = $field.Name # This makes working with the name a LOT easier in Write-Host, etc. #Write-Host "Working with field: $fieldName" #Write-Host "Preparing to set value to: $($AccessRecordset.Fields.Item($fieldName).Value)" $record | Add-Member -type NoteProperty -name $fieldName -value $AccessRecordSet.Fields.Item($fieldName).Value } # Output the custom object we just created Write-Output $record # Tell the recordset to advance forward one before doing this again with another object $AccessRecordset.MoveNext() } until ($AccessRecordset.EOF -eq $True) } function Execute-AccessSQLStatement ($query) { $AccessConnection.Execute($query) } function Convert-AccessTypeCode ([string]$typeCode) { # Build some lookup tables for our Access type codes so we can convert values pretty easily $labelLookupHash = @{"AutoNumber"="3"; "Text"="202"; "Memo"="203"; "Date/Time"="7"; "Currency"="6"; "Yes/No"="11"; "OLE Object"="205"; "Byte"="17"; "Integer"="2"; "Long Integer"="3"; "Single"="4"; "Double"="5"} $codeLookupHash = @{"3"="AutoNumber"; "202"="Text"; "203"="Memo"; "7"="Date/Time"; "6"="Currency"; "11"="Yes/No"; "205"="OLE Object"; "17"="Byte"; "2"="Integer"; "3"="Long Integer"; "4"="Single"; "5"="Double"} # Convert a value depending on what type of data was supplied if ($typeCode -match [regex]"^\\d{1,3}$") { $valueFound = $codeLookupHash.$typeCode if ($valueFound) { Write-Output $valueFound } else { Write-Output "Unknown" } } else { $valueFound = $labelLookupHash.$typeCode if ($valueFound) { Write-Output $valueFound } else { Write-Output "Unknown" } } } function Close-AccessRecordSet { $AccessRecordSet.Close() } function Disconnect-AccessDB { $AccessConnection.Close() } # Connect-AccessDB "C:\\fso\\ConfigurationMaintenance.accdb" # Open-AccessRecordSet "SELECT * FROM printers" # $printersDB = Convert-AccessRecordSetToPSObject | Select-Object caption,driverName | Format-Table -AutoSize; $printersDB # Close-AccessRecordSet # Disconnect-AccessDB
PowerShellCorpus/PoshCode/ScriptTransforms module_2.ps1
ScriptTransforms module_2.ps1
function New-ParameterTransform { #.Synopsis # Generates Parameter Transformation Attributes in simple PowerShell syntax #.Description # New-ParameterTransform allows the creation of .Net Attribute classes which can be applied to PowerShell parameters to transform or manipulate data as it's being passed in. #.Example # Transform TrimBraces { # param($string) # if($string -is [String] -and $string.Length -gt 2 -and $string[0] -eq '[' -and $string[-1] -eq ']') { # $string.SubString(1, $string.Length-2) # } else { # $string # } # } # # function Where-Type { # param( # [Type][TrimBraces()][String] # [Parameter(Mandatory=$true, Position=0)] # $Type, # # [Parameter(ValueFromPipeline=$true)] # $InputObject # ) # process { # if($InputObject -is $Type) { $InputObject } # } # } # # Description # ----------- # This example allows us to pass the "Type" to Where-Type with or without the [Braces] which would normally cause an exception when casting to a type: # # Get-ChildItem | Where-Type IO.FileInfo # # Get-ChildItem | Where-Type [IO.FileInfo] # # Get-ChildItem | Where-Type ([IO.FileInfo]) # #.Notes # It is now possible to redefine transforms by name by running the New-ParameterTransform command again, but type aliases that are generated are bound at function definition time, so any functions that are using the transform before it is redefined must also be redefined to take advantage of the new transform definition. [cmdletbinding()] param( # The name of the parameter transform to generate [Parameter(Mandatory=$true,Position=0)] [string] $name, # The script definition of the parameter transform [Parameter(Mandatory=$true, Position=1)] [scriptblock] $script ) end { $className = [Convert]::ToBase64String( ([Guid]::NewGuid().ToByteArray()) ).Replace('+','ñ').Replace('/','�').TrimEnd('=') $Type = Add-Type -Passthru -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ${name}Attribute${className} : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public ${name}Attribute${className}() { this.Script = ScriptBlock.Create( @" $($script.ToString() -replace '"','""' ) " ); } public override string ToString() { return Script.ToString(); } 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 ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") if($xlr8r::AddReplace) { $xlr8r::AddReplace( ${name}, $Type) } else { $null = $xlr8r::Remove( ${name} ) $xlr8r::Add( ${name}, $Type) } }} New-Alias -Name Transform -Value New-ParameterTransform; Export-ModuleMember -Alias Transform -Function * # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUTPVAYxC0ZjgQ4fcYFMPNexV5 # qYegggUrMIIFJzCCBA+gAwIBAgIQHCAgf57pVOnJcjKrMO/dtjANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTExMDQyNTAwMDAwMFoXDTEyMDQyNDIzNTk1OVowgZUx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj # dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY # BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh # dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANaXR+8W+aH6ofiO # bZRdIRBuvemJ/8c2fDwbHVLBMieiG9Eqs5+XKZ3M17Sz8GBNzQ4bluk2esIycr9z # yR/ISBjVxz1RcxH79vuvM6husOAKc2YhnGqA6vmfWokmEfDrOH1qLKA4226tPXBE # eNTSDrYtXFZ6jYWv9kqGcRMBzV7NPvJwQoMDEl1dbNAXo99RaHGjAfVkCSNYMM11 # jzZ2/DyAqVgKVnNviRQ+Wq8HPxP7Eqg/6b2DVw1Nokg3IDeyFRlo2he09YwVEV+r # GLvjUBmVRQPauJIr1EUgz85byWtYAUWOXNIFiWrqOKj/Clvi5Y9M05a1TwSi4o0F # yfa4keECAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L # PMnYMB0GA1UdDgQWBBTKaDgQ0lToUHAI+jy/CDn0BluXFjAOBgNVHQ8BAf8EBAMC # B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC # AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC # ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg # M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0 # LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv # bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAeGVyb3guY29tMA0G # CSqGSIb3DQEBBQUAA4IBAQAzwUwy00sEOggAavqrNoNeEVr0o623DgG2/2EuTsA6 # 2wI0Arb5D0s/icanshHgWwJZBEMZeHa17Ai/E3foCpj6rA3Y4vIQXHukluiSmjU6 # bWTgF5VbNTpvhlOO6E7Ya/rBr4oj4dqTEErkS7acgBHKrjPOptCiU4BSDqtl0k5z # OIiawyRSITHYEcCcI0Yl7VIz8EDblOQI3b4JGYcmJ7D+peYrnI2zoQyXDigcIj4l # VlipnjnvYsF+JbPkQY8XbMO+Yc490Bh8BMXPtuLR1KMuIXPK7DKX7JPmJcY7kKF/ # SPviyk0HE7Rldsses73UF8wT3lgj57FiUqX8FdTa7NllMYICTDCCAkgCAQEwgaow # gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl # IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY # aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0 # LU9iamVjdAIQHCAgf57pVOnJcjKrMO/dtjAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC # NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUAZ76oQxT # FCS/GTPt3vFPxINoPS0wDQYJKoZIhvcNAQEBBQAEggEA0e7s3o95oxMWZXzdu0XE # c3y1fnKXmgN1gfAFh3lvWQWiiKPBAd0/PBfyAZmendJ7wsLTAafxB21ks74q3WqM # FJ3/BW8FAZtm8QBuseNkbP3R5pEEhnrEaRo4ZKGez+TfEZe7Swyzo1Vqv8by8a1I # PCqbZzH6CzU1IR9aoApCvM/OY2Rxp9f4ozdCRqk91Kk6/ryjor/ZJOroAh4ZmEpC # Z0fRsnKWJ9x3YI8M3dZG53/cBEfaS06GjQvFQasx3BJK1VMQ6suaYYWU4Q/49VWc # pZ7FhQjw79gZlweVJWENw2dWk2u0OHYTIN+IPVtnLmxgtLRfhenS8TsdjaI3ebUA # 7w== # SIG # End signature block
PowerShellCorpus/PoshCode/HTML Hardware Reports wi.ps1
HTML Hardware Reports wi.ps1
Function Get-HardwareReport { [CmdletBinding()] Param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]]$devices ) Begin {Write-Host " Starting Hardware Reports"} Process { foreach ($device in $devices) { $name=$device $filepath="$home\\$name.html" $PingDevice=Test-Connection $name -count 1 -quiet;trap{continue} #Ping Test, then Server is online so get the hardware info If ($PingDevice -eq “True”) { Write-Host " Processing info for $name " #### HTML Output Formatting ####### $a = "<style>" $a = $a + "BODY{background-color:Lavender ;}" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}" $a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:skyblue}" $a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:lightyellow}" $a = $a + "</style><Title>$name Hardware Report</Title>" #################################### ConvertTo-Html -Head $a -Body "<h1> Computer Name : $name </h1>" > "$filepath" # MotherBoard: Win32_BaseBoard # You can Also select Tag,Weight,Width Get-WmiObject -ComputerName $name Win32_BaseBoard | Select Name,Manufacturer,Product,SerialNumber,Status | ConvertTo-html -Body "<H2> MotherBoard Information</H2>" >> "$filepath" # BIOS Get-WmiObject win32_bios -ComputerName $name | Select Manufacturer,Name,@{name='biosversion' ; Expression={$_.biosversion -join '; '}}, @{name='ListOfLanguages' ; Expression={$_.ListOfLanguages -join '; '}},PrimaryBIOS,ReleaseDate,SMBIOSBIOSVersion,SMBIOSMajorVersion,SMBIOSMinorVersion | ConvertTo-html -Body "<H2> BIOS Information </H2>" >>"$filepath" # CD ROM Drive Get-WmiObject Win32_CDROMDrive -ComputerName $name | select Name,Drive,MediaLoaded,MediaType,MfrAssignedRevisionLevel | ConvertTo-html -Body "<H2> CD ROM Information</H2>" >> "$filepath" # System Info Get-WmiObject Win32_ComputerSystemProduct -ComputerName $name | Select Vendor,Version,Name,IdentifyingNumber,UUID | ConvertTo-html -Body "<H2> System Information </H2>" >> "$filepath" # Hard-Disk Get-WmiObject win32_diskDrive -ComputerName $name | select Model,SerialNumber,InterfaceType,Size,Partitions | ConvertTo-html -Body "<H2> Harddisk Information </H2>" >> "$filepath" # NetWord Adapters -ComputerName $name Get-WmiObject win32_networkadapter -ComputerName $name | Select Name,Manufacturer,Description ,AdapterType,Speed,MACAddress,NetConnectionID | ConvertTo-html -Body "<H2> Network Card Information</H2>" >> "$filepath" # Memory Get-WmiObject Win32_PhysicalMemory -ComputerName $name | select BankLabel,DeviceLocator,Capacity,Manufacturer,PartNumber,SerialNumber,Speed | ConvertTo-html -Body "<H2> Physical Memory Information</H2>" >> "$filepath" # Processor Get-WmiObject Win32_Processor -ComputerName $name | Select Name,Manufacturer,Caption,DeviceID,CurrentClockSpeed,CurrentVoltage,DataWidth,L2CacheSize,L3CacheSize,NumberOfCores,NumberOfLogicalProcessors,Status | ConvertTo-html -Body "<H2> CPU Information</H2>" >> "$filepath" ## System enclosure Get-WmiObject Win32_SystemEnclosure -ComputerName $name | Select Tag,InstallDate,LockPresent,PartNumber,SerialNumber | ConvertTo-html -Body "<H2> System Enclosure Information </H2>" >> "$filepath" ## Invoke Expressons invoke-Expression "$filepath" # Closing If Statement }else {Write-Host " $name is offline - will not be included in the reports"} #Closing For Loop } # Closing Process } End {Write-Host "Ending Hardware Report for $name"} #Closing Function Get-HardwareReport }
PowerShellCorpus/PoshCode/Remove-DownloadFlag.ps1
Remove-DownloadFlag.ps1
function Set-DownloadFlag { <# .Synopsis Sets the ZoneTransfer flag which marks a file as being downloaded from the internet. .Description Creates a Zone.Identifier alternate data stream (on NTFS file systems) and writes the ZoneTransfer marker .Parameter Path The file you wish to block .Parameter Passthru If set, outputs the FileInfo object #> [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [string] $Path , [Switch]$Passthru ) $FS = new-object NTFS.FileStreams($Path) $null = $fs.add('Zone.Identifier') $stream = $fs.Item('Zone.Identifier').open() $sw = [System.IO.streamwriter]$stream $Sw.writeline('[ZoneTransfer]') $sw.writeline('ZoneID=4') $sw.close() $stream.close() if($Passthru){ Get-ChildItem $Path } } function Remove-DownloadFlag { <# .Synopsis Removes the ZoneTransfer flag which marks a file as being downloaded from the internet. .Description Deletes the Zone.Identifier alternate data stream (on NTFS file systems) .Parameter Path The file you wish to block .Parameter Passthru If set, outputs the FileInfo object #> [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [string] $Path , [Switch]$Passthru ) $FS = new-object NTFS.FileStreams($Path) $null = $fs['Zone.Identifier'].delete() if($Passthru){ Get-ChildItem $Path } } Add-Type -TypeDefinition @' using System; using System.IO; using System.Collections; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; ///<summary> ///Encapsulates access to alternative data streams of an NTFS file. ///Adapted from a C++ sample by Dino Esposito, ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp ///</summary> namespace NTFS { /// <summary> /// Wraps the API functions, structures and constants. /// </summary> internal class Kernel32 { public const char STREAM_SEP = ':'; public const int INVALID_HANDLE_VALUE = -1; public const int MAX_PATH = 256; [Flags()] public enum FileFlags : uint { WriteThrough = 0x80000000, Overlapped = 0x40000000, NoBuffering = 0x20000000, RandomAccess = 0x10000000, SequentialScan = 0x8000000, DeleteOnClose = 0x4000000, BackupSemantics = 0x2000000, PosixSemantics = 0x1000000, OpenReparsePoint = 0x200000, OpenNoRecall = 0x100000 } [Flags()] public enum FileAccessAPI : uint { GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000 } /// <summary> /// Provides a mapping between a System.IO.FileAccess value and a FileAccessAPI value. /// </summary> /// <param name="Access">The <see cref="System.IO.FileAccess"/> value to map.</param> /// <returns>The <see cref="FileAccessAPI"/> value.</returns> public static FileAccessAPI Access2API(FileAccess Access) { FileAccessAPI lRet = 0; if ((Access & FileAccess.Read)==FileAccess.Read) lRet |= FileAccessAPI.GENERIC_READ; if ((Access & FileAccess.Write)==FileAccess.Write) lRet |= FileAccessAPI.GENERIC_WRITE; return lRet; } [StructLayout(LayoutKind.Sequential)] public struct LARGE_INTEGER { public int Low; public int High; public long ToInt64() { return (long)High * 4294967296 + (long)Low; } } [StructLayout(LayoutKind.Sequential)] public struct WIN32_STREAM_ID { public int dwStreamID; public int dwStreamAttributes; public LARGE_INTEGER Size; public int dwStreamNameSize; } [DllImport("kernel32")] public static extern SafeFileHandle CreateFile(string Name, FileAccessAPI Access, FileShare Share, int Security, FileMode Creation, FileFlags Flags, int Template); [DllImport("kernel32")] public static extern bool DeleteFile(string Name); [DllImport("kernel32")] public static extern bool CloseHandle(SafeFileHandle hObject); [DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, IntPtr pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context); [DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, ref WIN32_STREAM_ID pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context); [DllImport("kernel32")] public static extern bool BackupSeek(SafeFileHandle hFile, int dwLowBytesToSeek, int dwHighBytesToSeek, ref int dwLow, ref int dwHigh, ref int Context); } /// <summary> /// Encapsulates a single alternative data stream for a file. /// </summary> public class StreamInfo { private FileStreams _parent; private string _name; private long _size; internal StreamInfo(FileStreams Parent, string Name, long Size) { _parent = Parent; _name = Name; _size = Size; } /// <summary> /// The name of the stream. /// </summary> public string Name { get { return _name; } } /// <summary> /// The size (in bytes) of the stream. /// </summary> public long Size { get { return _size; } } public override string ToString() { return String.Format("{1}{0}{2}{0}$DATA", Kernel32.STREAM_SEP, _parent.FileName, _name); } public override bool Equals(Object o) { if (o is StreamInfo) { StreamInfo f = (StreamInfo)o; return (f._name.Equals(_name) && f._parent.Equals(_parent)); } else if (o is string) { return ((string)o).Equals(ToString()); } else return base.Equals(o); } public override int GetHashCode() { return ToString().GetHashCode(); } #region Open /// <summary> /// Opens or creates the stream in read-write mode, with no sharing. /// </summary> /// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns> public FileStream Open() { return Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } /// <summary> /// Opens or creates the stream in read-write mode with no sharing. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param> /// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns> public FileStream Open(FileMode Mode) { return Open(Mode, FileAccess.ReadWrite, FileShare.None); } /// <summary> /// Opens or creates the stream with no sharing. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param> /// <param name="Access">The <see cref="System.IO.FileAccess"/> level for the stream.</param> /// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns> public FileStream Open(FileMode Mode, FileAccess Access) { return Open(Mode, Access, FileShare.None); } /// <summary> /// Opens or creates the stream. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> action for the stream.</param> /// <param name="Access">The <see cref="System.IO.FileAccess"/> level for the stream.</param> /// <param name="Share">The <see cref="System.IO.FileShare"/> level for the stream.</param> /// <returns>A <see cref="System.IO.FileStream"/> wrapper for the stream.</returns> public FileStream Open(FileMode Mode, FileAccess Access, FileShare Share) { try { SafeFileHandle hFile = Kernel32.CreateFile(ToString(), Kernel32.Access2API(Access), Share, 0, Mode, 0, 0); return new FileStream(hFile, Access); } catch { return null; } } #endregion #region Delete /// <summary> /// Deletes the stream from the file. /// </summary> /// <returns>A <see cref="System.Boolean"/> value: true if the stream was deleted, false if there was an error.</returns> public bool Delete() { return Kernel32.DeleteFile(ToString()); } #endregion } /// <summary> /// Encapsulates the collection of alternative data streams for a file. /// A collection of <see cref="StreamInfo"/> objects. /// </summary> public class FileStreams : CollectionBase { private FileInfo _file; #region Constructors public FileStreams(string File) { _file = new FileInfo(File); initStreams(); } public FileStreams(FileInfo file) { _file = file; initStreams(); } /// <summary> /// Reads the streams from the file. /// </summary> private void initStreams() { //Open the file with backup semantics SafeFileHandle hFile = Kernel32.CreateFile(_file.FullName, Kernel32.FileAccessAPI.GENERIC_READ, FileShare.Read, 0, FileMode.Open, Kernel32.FileFlags.BackupSemantics, 0); if (hFile.IsInvalid) return; try { Kernel32.WIN32_STREAM_ID sid = new Kernel32.WIN32_STREAM_ID(); int dwStreamHeaderSize = Marshal.SizeOf(sid); int Context = 0; bool Continue = true; while (Continue) { //Read the next stream header int lRead = 0; Continue = Kernel32.BackupRead(hFile, ref sid, dwStreamHeaderSize, ref lRead, false, false, ref Context); if (Continue && lRead == dwStreamHeaderSize) { if (sid.dwStreamNameSize>0) { //Read the stream name lRead = 0; IntPtr pName = Marshal.AllocHGlobal(sid.dwStreamNameSize); try { Continue = Kernel32.BackupRead(hFile, pName, sid.dwStreamNameSize, ref lRead, false, false, ref Context); char[] bName = new char[sid.dwStreamNameSize]; Marshal.Copy(pName,bName,0,sid.dwStreamNameSize); //Name is of the format ":NAME:$DATA\\0" string sName = new string(bName); int i = sName.IndexOf(Kernel32.STREAM_SEP, 1); if (i>-1) sName = sName.Substring(1, i-1); else { //This should never happen. //Truncate the name at the first null char. i = sName.IndexOf('\\0'); if (i>-1) sName = sName.Substring(1, i-1); } //Add the stream to the collection base.List.Add(new StreamInfo(this,sName,sid.Size.ToInt64())); } finally { Marshal.FreeHGlobal(pName); } } //Skip the stream contents int l = 0; int h = 0; Continue = Kernel32.BackupSeek(hFile, sid.Size.Low, sid.Size.High, ref l, ref h, ref Context); } else break; } } finally { Kernel32.CloseHandle(hFile); } } #endregion #region File /// <summary> /// Returns the <see cref="System.IO.FileInfo"/> object for the wrapped file. /// </summary> public FileInfo FileInfo { get { return _file; } } /// <summary> /// Returns the full path to the wrapped file. /// </summary> public string FileName { get { return _file.FullName; } } /// <summary> /// Returns the size of the main data stream, in bytes. /// </summary> public long FileSize { get {return _file.Length;} } /// <summary> /// Returns the size of all streams for the file, in bytes. /// </summary> public long Size { get { long size = this.FileSize; foreach (StreamInfo s in this) size += s.Size; return size; } } #endregion #region Open /// <summary> /// Opens or creates the default file stream. /// </summary> /// <returns><see cref="System.IO.FileStream"/></returns> public FileStream Open() { return new FileStream(_file.FullName, FileMode.OpenOrCreate); } /// <summary> /// Opens or creates the default file stream. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param> /// <returns><see cref="System.IO.FileStream"/></returns> public FileStream Open(FileMode Mode) { return new FileStream(_file.FullName, Mode); } /// <summary> /// Opens or creates the default file stream. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param> /// <param name="Access">The <see cref="System.IO.FileAccess"/> for the stream.</param> /// <returns><see cref="System.IO.FileStream"/></returns> public FileStream Open(FileMode Mode, FileAccess Access) { return new FileStream(_file.FullName, Mode, Access); } /// <summary> /// Opens or creates the default file stream. /// </summary> /// <param name="Mode">The <see cref="System.IO.FileMode"/> for the stream.</param> /// <param name="Access">The <see cref="System.IO.FileAccess"/> for the stream.</param> /// <param name="Share">The <see cref="System.IO.FileShare"/> for the stream.</param> /// <returns><see cref="System.IO.FileStream"/></returns> public FileStream Open(FileMode Mode, FileAccess Access, FileShare Share) { return new FileStream(_file.FullName, Mode, Access, Share); } #endregion #region Delete /// <summary> /// Deletes the file, and all alternative streams. /// </summary> public void Delete() { for (int i=base.List.Count;i>0;i--) { base.List.RemoveAt(i); } _file.Delete(); } #endregion #region Collection operations /// <summary> /// Add an alternative data stream to this file. /// </summary> /// <param name="Name">The name for the stream.</param> /// <returns>The index of the new item.</returns> public int Add(string Name) { StreamInfo FSI = new StreamInfo(this, Name, 0); int i = base.List.IndexOf(FSI); if (i==-1) i = base.List.Add(FSI); return i; } /// <summary> /// Removes the alternative data stream with the specified name. /// </summary> /// <param name="Name">The name of the string to remove.</param> public void Remove(string Name) { StreamInfo FSI = new StreamInfo(this, Name, 0); int i = base.List.IndexOf(FSI); if (i>-1) base.List.RemoveAt(i); } /// <summary> /// Returns the index of the specified <see cref="StreamInfo"/> object in the collection. /// </summary> /// <param name="FSI">The object to find.</param> /// <returns>The index of the object, or -1.</returns> public int IndexOf(StreamInfo FSI) { return base.List.IndexOf(FSI); } /// <summary> /// Returns the index of the <see cref="StreamInfo"/> object with the specified name in the collection. /// </summary> /// <param name="Name">The name of the stream to find.</param> /// <returns>The index of the stream, or -1.</returns> public int IndexOf(string Name) { return base.List.IndexOf(new StreamInfo(this, Name, 0)); } public StreamInfo this[int Index] { get { return (StreamInfo)base.List[Index]; } } public StreamInfo this[string Name] { get { int i = IndexOf(Name); if (i==-1) return null; else return (StreamInfo)base.List[i]; } } #endregion #region Overrides /// <summary> /// Throws an exception if you try to add anything other than a StreamInfo object to the collection. /// </summary> protected override void OnInsert(int index, object value) { if (!(value is StreamInfo)) throw new InvalidCastException(); } /// <summary> /// Throws an exception if you try to add anything other than a StreamInfo object to the collection. /// </summary> protected override void OnSet(int index, object oldValue, object newValue) { if (!(newValue is StreamInfo)) throw new InvalidCastException(); } /// <summary> /// Deletes the stream from the file when you remove it from the list. /// </summary> protected override void OnRemoveComplete(int index, object value) { try { StreamInfo FSI = (StreamInfo)value; if (FSI != null) FSI.Delete(); } catch {} } public new StreamEnumerator GetEnumerator() { return new StreamEnumerator(this); } #endregion #region StreamEnumerator public class StreamEnumerator : object, IEnumerator { private IEnumerator baseEnumerator; public StreamEnumerator(FileStreams mappings) { this.baseEnumerator = ((IEnumerable)(mappings)).GetEnumerator(); } public StreamInfo Current { get { return ((StreamInfo)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } #endregion } } '@ Set-Alias block Set-DownloadFlag Set-Alias unblock Remove-DownloadFlag #Export-ModuleMember -Function Remove-DownloadFlag, Set-DownloadFlag -alias block, unblock
PowerShellCorpus/PoshCode/JSON_1.ps1
JSON_1.ps1
#requires -version 2.0 # Version History: # v 0.5 - First Public version # v 1.0 - Made ConvertFrom-Json work with arbitrary JSON # - switched to xsl style sheets for ConvertTo-JSON # There is no help (yet) because I'm still changing and renaming everything every time I mess with this code # Full RoundTrip capability: # # > ls | ConvertTo-Json | ConvertFrom-Json # > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json # # You may frequently want to use the DEPTH or NoTypeInformation parameters: # # > ConvertTo-Json -Depth 2 -NoTypeInformation # # But then you have to specify the type when you reimport (and you can't do that for deep objects). # This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject). # For Example: # # > PS | Select PM, WS, CPU, ID, ProcessName | # >> ConvertTo-json -NoType | # >> ConvertFrom-json -Type System.Diagnostics.Process Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization $utf8 = [System.Text.Encoding]::UTF8 function Write-String { PARAM( [Parameter()]$stream, [Parameter(ValueFromPipeline=$true)]$string ) PROCESS { $bytes = $utf8.GetBytes($string) $stream.Write( $bytes, 0, $bytes.Length ) } } function Convert-JsonToXml { PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json) BEGIN { $mStream = New-Object System.IO.MemoryStream } PROCESS { $json | Write-String -stream $mStream } END { $mStream.Position = 0 $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max) try { $xml = New-Object Xml.XmlDocument $xml.Load($jsonReader) $xml } finally { $jsonReader.Close() $mStream.Dispose() } } } function Convert-XmlToJson { PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml) PROCESS { $mStream = New-Object System.IO.MemoryStream $jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream) try { $xml.Save($jsonWriter) $bytes = $mStream.ToArray() [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length) } finally { $jsonWriter.Close() $mStream.Dispose() } } } ## Rather than rewriting ConvertTo-Xml ... Function ConvertTo-Json { [CmdletBinding()] Param( [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject , [Parameter(Mandatory=$false)][Int]$Depth=1 , [Switch]$NoTypeInformation ) END { ## You must output ALL the input at once ## ConvertTo-Xml outputs differently if you just have one, so your results would be different $input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson } } Function Convert-CliXmlToJson { PARAM( [Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml ) BEGIN { $xmlToJsonXsl = @' <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- CliXmlToJson.xsl Copyright (c) 2006,2008 Doeke Zanstra Copyright (c) 2009 Joel Bennett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/> <xsl:strip-space elements="*"/> <!--contant--> <xsl:variable name="d">0123456789</xsl:variable> <!-- ignore document text --> <xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/> <!-- string --> <xsl:template match="text()"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="."/> </xsl:call-template> </xsl:template> <!-- Main template for escaping strings; used by above template and for object-properties Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string --> <xsl:template name="escape-string"> <xsl:param name="s"/> <xsl:text>"</xsl:text> <xsl:call-template name="escape-bs-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> <xsl:text>"</xsl:text> </xsl:template> <!-- Escape the backslash (\\) before everything else. --> <xsl:template name="escape-bs-string"> <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,'\\')"> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/> </xsl:call-template> <xsl:call-template name="escape-bs-string"> <xsl:with-param name="s" select="substring-after($s,'\\')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Escape the double quote ("). --> <xsl:template name="escape-quot-string"> <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,'&quot;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&quot;'),'\\&quot;')"/> </xsl:call-template> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="substring-after($s,'&quot;')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash or double quote here, because they don't replace characters (&#x0; becomes \\t), but they prefix characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be processed first. This function can't do that. --> <xsl:template name="encode-string"> <xsl:param name="s"/> <xsl:choose> <!-- tab --> <xsl:when test="contains($s,'&#x9;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#x9;'),'\\t',substring-after($s,'&#x9;'))"/> </xsl:call-template> </xsl:when> <!-- line feed --> <xsl:when test="contains($s,'&#xA;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#xA;'),'\\n',substring-after($s,'&#xA;'))"/> </xsl:call-template> </xsl:when> <!-- carriage return --> <xsl:when test="contains($s,'&#xD;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#xD;'),'\\r',substring-after($s,'&#xD;'))"/> </xsl:call-template> </xsl:when> <xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise> </xsl:choose> </xsl:template> <!-- number (no support for javascript mantise) --> <xsl:template match="text()[not(string(number())='NaN' or (starts-with(.,'0' ) and . != '0'))]"> <xsl:value-of select="."/> </xsl:template> <!-- boolean, case-insensitive --> <xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template> <xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template> <!-- root object(s) --> <xsl:template match="*" name="base"> <xsl:if test="not(preceding-sibling::*)"> <xsl:choose> <xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when> <xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <!-- check type of node --> <xsl:choose> <!-- null nodes --> <xsl:when test="count(child::node())=0">null</xsl:when> <!-- other nodes --> <xsl:otherwise> <xsl:apply-templates select="child::node()"/> </xsl:otherwise> </xsl:choose> <!-- end of type check --> <xsl:if test="following-sibling::*">,</xsl:if> <xsl:if test="not(following-sibling::*)"> <xsl:choose> <xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when> <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- properties of objects --> <xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)&gt;1]"> <xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/> <xsl:if test="not(preceding-sibling::*)"> <xsl:choose> <xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when> <xsl:otherwise> <xsl:text>{</xsl:text> <xsl:if test="../@Type"> <xsl:text>"__type":</xsl:text> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="../@Type"/> </xsl:call-template> <xsl:text>,</xsl:text> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:if> <xsl:choose> <xsl:when test="not(child::node())"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="@Name"/> </xsl:call-template> <xsl:text>:null</xsl:text> </xsl:when> <xsl:when test="$inArray"> <xsl:apply-templates select="child::node()"/> </xsl:when> <!-- <xsl:when test="not(@Name) and not(@Type)"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="local-name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:when> --> <xsl:when test="not(@Name)"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="local-name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:when> <xsl:otherwise> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="@Name"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:otherwise> </xsl:choose> <xsl:if test="following-sibling::*">,</xsl:if> <xsl:if test="not(following-sibling::*)"> <xsl:choose> <xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when> <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- convert root element to an anonymous container --> <xsl:template match="/"> <xsl:apply-templates select="node()"/> </xsl:template> </xsl:stylesheet> '@ } PROCESS { if(Get-Member -InputObject $xml -Name root) { Write-Verbose "Ripping to Objects" $xml = $xml.root.Objects } else { Write-Verbose "Was already Objects" } Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl } } Function ConvertFrom-Xml { [CmdletBinding(DefaultParameterSetName="AutoType")] PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)] [Xml.XmlNode] $xml , [Parameter(Mandatory=$true,ParameterSetName="ManualType")] [Type]$Type , [Switch]$ForceType ) PROCESS{ if(Get-Member -InputObject $xml -Name root) { return $xml.root.Objects | } elseif(Get-Member -InputObject $xml -Name Objects) { return $xml.Objects | } $propbag = @{} foreach($name in Get-Member -InputObject $xml -MemberType Property | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) { Write-Verbose "$Name Type: $($xml."$Name".type)" switch( $xml."$Name".type ) { "object" { $propbag."$Name" = ConvertFrom-Xml -Xml $xml."$Name" break } "string" { $propbag."$Name" = $xml."$Name".get_InnerText() $MightBeADate = $xml."$Name".get_InnerText() -as [DateTime] ## Strings that are actually dates (*grumble* JSON is crap) if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) { $propbag."$Name" = $MightBeADate } break } "number" { $number = $xml."$Name".get_InnerText() if($number -eq ($number -as [int])) { $propbag."$Name" = $number -as [int] } elseif($number -eq ($number -as [double])) { $propbag."$Name" = $number -as [double] } else { $propbag."$Name" = $number -as [decimal] } break } "boolean" { $propbag."$Name" = [bool]::parse($xml."$Name".get_InnerText()) } "null" { $propbag."$Name" = $null } default { $propbag."$Name" = $xml."$Name" break } } } if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type } if($ForceType -and $Type) { try { $output = New-Object $Type -Property $propbag } catch { $output = New-Object PSObject -Property $propbag $output.PsTypeNames.Insert(0, $xml.__type) } } else { $output = New-Object PSObject -Property $propbag if($Type) { $output.PsTypeNames.Insert(0, $Type) } } Write-Output $output } } Function ConvertFrom-Json { [CmdletBinding(DefaultParameterSetName="AutoType")] PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)][string]$InputObject , [Parameter(Mandatory=$true,ParameterSetName="ManualType")][Type]$Type , [Switch]$ForceType ) PROCESS { $null = $PSBoundParameters.Remove("InputObject") (Convert-JsonToXml $InputObject).Root.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters } } ######### ### The JSON library is dependent on Convert-Xml from my Xml script module function Convert-Node { 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] -ErrorAction 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 } } } New-Alias fromjson ConvertFrom-Json New-Alias tojson ConvertTo-Json #New-Alias ipjs Import-Json #New-Alias epjs Export-Json #Import-Json, Export-Json, Export-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *
PowerShellCorpus/PoshCode/List Object Discoveries_1.ps1
List Object Discoveries_1.ps1
# Enumerate OpsMgr 2007 Object Discoveries targeted to Windows Server # Date: 20/10/2008 # Author: Stefan Stranger (help from Jeremy Pavleck and Marco Shaw) # Author: Cory Delamarter (increased speed) get-discovery | ? {$_.Target -match $(get-monitoringclass -Name "Microsoft.Windows.Server.Computer").Id} | ft Name, DisplayName
PowerShellCorpus/PoshCode/Get-NistNtpServer_1.ps1
Get-NistNtpServer_1.ps1
function Get-NistNtpServer { <# .SYNOPSIS Gets the list NIST NTP servers. .DESCRIPTION The Get-NistNtpServer function retrieves the list of NIST NTP server names, IP addresses, locations, and status. .EXAMPLE Get-NistNtpServer Returns the list of NIST NTP servers. .INPUTS None .OUTPUTS PSObject .NOTES Name: Get-NistNtpServer Author: Rich Kusak Created: 2011-12-31 LastEdit: 2012-06-18 18:31 Version: 1.1.0.0 .LINK http://tf.nist.gov/tf-cgi/servers.cgi #> [CmdletBinding()] param () begin { $uri = 'http://tf.nist.gov/tf-cgi/servers.cgi' $webClient = New-Object -TypeName System.Net.WebClient $regex = '(td align = "center">.*)|(;">.*)' } # begin end { try { $webpage = $webClient.DownloadString($uri) } catch { throw $_ } $list = ([regex]::Matches($webpage, $regex) | Select-Object -ExpandProperty Value) -replace '.*>' | Where-Object { $_ -notlike $null } for ($i = 0 ; $i -lt $list.Count ; $i += 4) { New-Object -TypeName PSObject -Property @{ 'Name' = $list[(0 + $i)] 'IPAddress' = $list[(1 + $i)] 'Location' = $list[(2 + $i)] 'Status' = $list[(3 + $i)] } | Select-Object -Property 'Name','IPAddress','Location','Status' } # for } # end } # function Get-NistNtpServer
PowerShellCorpus/PoshCode/Deploy Multiple VMs v1.1.ps1
Deploy Multiple VMs v1.1.ps1
############################################################# # Deploy-VM.ps1 v1.1 # David Summers 2011/8/2 # Script to deploy VM(s) from Template(s) and set appropriate # IP config for Windows VMs. Also sets # of CPUs, MemoryMB, # port group, and several custom attributes. # Moves deployed VM to specific VMs/Template blue folder. # Assumptions: # not connected to viserver before running # Customization spec and templates in place and tested ############################################################# # Syntax and sample for CSV File: # template,datastore,diskformat,vmhost,custspec,vmname,ipaddress,subnet,gateway,pdns,sdns,pwins,swins,datacenter,folder,dvpg,memsize,cpucount,appgroup,owner,techcontact,vmdescription,createdate,reviewdate,creator # template.2008ent64R2sp1,DS1,thick,host1.domain.com,2008r2CustSpec,Guest1,10.50.35.10,255.255.255.0,10.50.35.1,10.10.0.50,10.10.0.51,10.10.0.50,10.10.0.51,DCName,FldrNm,dvpg.10.APP1,2048,1,Monitoring,Road Runner,WE Coyote,App1 Prod Web,2011.07.28,2014.07.28,Elmer Fudd # $vmlist = Import-CSV "H:\\Flats\\Scripts\\Input\\deployVMserverinfo.csv" # Load PowerCLI $psSnapInName = "VMware.VimAutomation.Core" if (-not (Get-PSSnapin -Name $psSnapInName -ErrorAction SilentlyContinue)) { # Exit if the PowerCLI snapin can't be loaded Add-PSSnapin -Name $psSnapInName -ErrorAction Stop } connect-viserver virtualcenter.yourdom.com foreach ($item in $vmlist) { # Map variables $template = $item.template $datastore = $item.datastore $diskformat = $item.diskformat $vmhost = $item.vmhost $custspec = $item.custspec $vmname = $item.vmname $ipaddr = $item.ipaddress $subnet = $item.subnet $gateway = $item.gateway $pdns = $item.pdns $pwins = $item.pwins $sdns = $item.sdns $swins = $item.swins $datacenter = $item.datacenter $destfolder = $item.folder $dvpg = $item.dvpg $memsize = $item.memsize $cpucount = $item.cpucount $appgroup = $item.appgroup $owner = $item.owner $technicalcontact = $item.techcontact $description = $item.vmdescription $createdate = $item.createdate $reviewdate = $item.reviewdate $creator = $item.creator #Configure the Customization Spec info Get-OSCustomizationSpec $custspec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $ipaddr -SubnetMask $subnet -DefaultGateway $gateway -Dns $pdns,$sdns -Wins $pwins,$swins #Deploy the VM based on the template with the adjusted Customization Specification New-VM -Name $vmname -Template $template -Datastore $datastore -DiskStorageFormat $diskformat -VMHost $vmhost | Set-VM -OSCustomizationSpec $custspec -Confirm:$false #Move VM to Application Group's folder Get-vm -Name $vmname | move-vm -Destination $(Get-Folder -Name $DestFolder -Location $(Get-Datacenter $Datacenter)) #Set the Port Group Network Name (Match PortGroup names with the VLAN name) Get-VM -Name $vmname | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $dvpg -Confirm:$false #Set the number of CPUs and MB of RAM Get-VM -Name $vmname | Set-VM -MemoryMB $memsize -NumCpu $cpucount -Confirm:$false #Set the Custom Attribute Annotations #Comment out or adjust to fit your environment Set-annotation -Entity $vmname -CustomAttribute "App Group" -Value $AppGroup -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Owner" -Value $Owner -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Technical Contact" -Value $TechnicalContact -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Description" -Value $Description -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Create Date" -Value $CreateDate -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Review Date" -Value $ReviewDate -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Creator" -Value $Creator -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Timeline" -Value "New" -Confirm:$false Set-annotation -Entity $vmname -CustomAttribute "Datacenter" -Value $item.datacenter -Confirm:$false }
PowerShellCorpus/PoshCode/UIAutomation V1.ps1
UIAutomation V1.ps1
Add-Type -AssemblyName UIAutomationClient Add-Type -AssemblyName UIAutomationTypes ############################################################################################################## ## REQUIRES -Module Accelerators -URI http://www.poshcode.org/762 Import-Module Accelerators $SWA = "System.Windows.Automation" Add-Accelerator AutoElement "$SWA.AutomationElement" -EA SilentlyContinue Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue Add-Accelerator AndCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator OrCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator NotCondition "$SWA.TextPattern" -EA SilentlyContinue Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue function New-UIAElement { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Element ) PROCESS { $Element | Add-Member -Name Text -Type ScriptProperty -PassThru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::NameProperty) } | Add-Member -Name ClassName -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ClassNameProperty) } | Add-Member -Name FrameworkId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::FrameworkIdProperty) } | Add-Member -Name ProcessId -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::ProcessIdProperty) } | Add-Member -Name ControlTypeL18D -Type ScriptProperty -Passthru -Value { $this.GetCurrentPropertyValue([AutoElementIds]::LocalizedControlTypeProperty) } } } function Select-Window { [CmdletBinding()] PARAM( [Parameter()] [Alias("Name")] [string]$Text="*" , [Parameter()] [string]$ClassName="*" , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Parent = [AutoElement]::RootElement ) PROCESS { $Parent.FindAll( "Children", $TrueCondition ) | New-UIAElement | Where-Object { ($_.ClassName -like $ClassName) -AND ($_.Text -like $Text) } } } function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Invoke-Element { [CmdletBinding()] PARAM( [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.GetCurrentPattern([InvokePattern]::Pattern).Invoke() } } function Set-ElementText { [CmdletBinding()] PARAM( [Parameter()] [string]$Text , [Parameter(ValueFromPipeline=$true)] [AutoElement]$Target ) PROCESS { $Target.SetFocus(); $textPattern = $valuePattern = $null try { $textPattern = $Target.GetCurrentPattern([TextPattern]::Pattern) Write-Host "textPattern:`n$($textPattern | gm)" } catch { } try { $valuePattern = $Target.GetCurrentPattern([ValuePattern]::Pattern) Write-Host "valuePattern:`n$($valuePattern | gm)" } catch { } $Target.SetFocus(); if($valuePattern) { $valuePattern.SetValue( $Text ) } if($textPattern) { [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } } }
PowerShellCorpus/PoshCode/Get-WebFile _2.1.ps1
Get-WebFile _2.1.ps1
## Get-WebFile.ps1 (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## - added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## #function wget { param( $url = (Read-Host "The URL to download"), $fileName ) $req = [System.Net.HttpWebRequest]::Create($url); $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName)) { # if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not ))) [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($res.StatusCode -eq 200) { $reader = new-object System.IO.StreamReader $res.GetResponseStream() $writer = new-object System.IO.StreamWriter $fileName # TODO: stick this in a loop and give progress reports $writer.Write($reader.ReadToEnd()) $reader.Close(); $writer.Close(); } $res.Close(); ls $fileName #}
PowerShellCorpus/PoshCode/Suspend-Process.ps1
Suspend-Process.ps1
Add-Type -Name Threader -Namespace "" -Member @" [Flags] public enum ThreadAccess : int { Terminate = (0x0001), SuspendResume = (0x0002), GetContext = (0x0008), SetContext = (0x0010), SetInformation = (0x0020), GetInformation = (0x0040), SetThreadToken = (0x0080), Impersonate = (0x0100), DirectImpersonation = (0x0200) } [Flags] public enum ProcessAccess : uint { Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, SuspendResume = 0x00000800, Synchronize = 0x00100000, All = 0x001F0FFF } [DllImport("ntdll.dll", EntryPoint = "NtSuspendProcess", SetLastError = true)] public static extern uint SuspendProcess(IntPtr processHandle); [DllImport("ntdll.dll", EntryPoint = "NtResumeProcess", SetLastError = true)] public static extern uint ResumeProcess(IntPtr processHandle); [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(ProcessAccess dwDesiredAccess, bool bInheritHandle, uint dwProcessId); [DllImport("kernel32.dll")] public static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll")] public static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] public static extern int ResumeThread(IntPtr hThread); "@ function Suspend-Process { param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [System.Diagnostics.Process] $Process ) process { if(($pProc = [Threader]::OpenProcess("SuspendResume", $false, $Process.Id)) -ne [IntPtr]::Zero) { Write-Verbose "Suspending Process: $pProc" $result = [Threader]::SuspendProcess($pProc) if($result -ne 0) { Write-Error "Failed to Suspend: $result" ## TODO: GetLastError() } [Threader]::CloseHandle($pProc) } else { Write-Error "Unable to open Process $($Process.Id), are you running elevated?" ## TODO: Check if they're elevated and otherwise GetLastError() } } } function Resume-Process { param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [System.Diagnostics.Process] $Process ) process { if(($pProc = [Threader]::OpenProcess("SuspendResume", $false, $Process.Id)) -ne [IntPtr]::Zero) { Write-Verbose "Resuming Process: $pProc" $result = [Threader]::ResumeProcess($pProc) if($result -ne 0) { Write-Error "Failed to Suspend: $result" ## TODO: GetLastError() } [Threader]::CloseHandle($pProc) } else { Write-Error "Unable to open Process $($Process.Id), are you running elevated?" ## TODO: Check if they're elevated and otherwise GetLastError() } } } function Suspend-Thread { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [System.Diagnostics.ProcessThread[]] [Alias("Threads")] $Thread ) process { if(($pThread = [Threader]::OpenThread("SuspendResume", $false, $Thread.Id)) -ne [IntPtr]::Zero) { Write-Verbose "Suspending Thread: $pThread" [Threader]::SuspendThread($pThread) [Threader]::CloseHandle($pThread) } else { Write-Error "Unable to open Thread $($Thread.Id), are you running elevated?" ## TODO: Check if they're elevated and otherwise GetLastError() } } } function Resume-Thread { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [System.Diagnostics.ProcessThread[]] [Alias("Threads")] $Thread ) process { if(($pThread = [Threader]::OpenThread("SuspendResume", $false, $Thread.Id)) -ne [IntPtr]::Zero) { Write-Verbose "Resuming Thread: $pThread" [Threader]::ResumeThread($pThread) [Threader]::CloseHandle($pThread) } else { Write-Error "Unable to open Thread $($Thread.Id), are you running elevated?" ## TODO: Check if they're elevated and otherwise GetLastError() } } }
PowerShellCorpus/PoshCode/ESXi Config Backup Scrip.ps1
ESXi Config Backup Scrip.ps1
###ESXi Configuration Backup Script #DESCRIPION: This Script takes a CSV file with the hostname, username, and password of a list of ESXi servers, and backs up their configurations to a specified Destination #USAGE: This script is meant to be run as a regular scheduled task or a pre-script for a backup job. There is no version control, so it is recommended to use an external backup program (Such as Backup Exec) to scan this. #LAST MODIFIED: 15 Dec 2009 by JGrote <jgrote AT enpointe NOSPAMDOT-com> #REQUIREMENTS: #VMWare Remote CLI (Tested with 4.0U1) ### SETTINGS #Location of the VMWare Remote CLI vicfg-cfgbackup.pl command (will be different for 32-bit systems) $vSphereCLIPath = "C:\\Program Files (x86)\\VMware\\VMware vSphere CLI\\" #Backup Destination Folder $BackupDest = "E:\\Backup\\ESXi" #Path to ESXi CSV File. APPLY STRICT PERMISSIONS TO THIS FILE SO THAT ONLY THE SCRIPTAND ADMINISTRATORS CAN READ IT! #Format: #1st Field - HOSTNAME - ESXi IP Address or Hostname #2nd Field - USERNAME - Local Username (usually root) #3rd Field - PASSWORD - Password # #Example: #HOSTNAME,USERNAME,PASSWORD #server1,root,password #server2,root,password2 #It is recommended to create and edit this file using Excel (Save as CSV) $ESXiCSV = "C:\\Scripts\\ESXiBackupList.csv" ### PREPARATION #Create an ESXi Backup Event Source if it doesn't already exist $eventsource = "Backup-ESXi" $eventlog = "Application" if (!(get-eventlog -logname $eventlog -source $eventsource)) {new-eventlog -logname $eventlog -source $eventsource} #Write an error and exit the script if an exception is ever thrown trap {write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Error" -Message "An Error occured during $($eventsource): $_ . Script run from $($MyInvocation.MyCommand.Definition)"; exit} #Verify the Destination Directory Exists: #Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script. $ESXiCSVIsPresentTest = Get-Item $ESXiCSV ### SCRIPT #Read Each Host from the File and back up the config to the backup directory import-csv $ESXiCSV | ForEach-Object { $BackupResult = invoke-expression "& '$vSphereCLIPath\\perl\\bin\\perl.exe' '$vSphereCLIPath\\bin\\vicfg-cfgbackup.pl' --server $($_.HOSTNAME) --username $($_.USERNAME) --password $($_.PASSWORD) --save $($BackupDest)\\$($_.HOSTNAME)-cfgbackup.tgz" if ($LastExitCode -ne 0) {throw "An Error occurred while executing $BackupBin for $($_.HOSTNAME): $BackupResult"} } #Compose and Write Success Event $successText = "ESXi Configurations were successfully backed up to $BackupDest. Script run from $($MyInvocation.MyCommand.Definition)"" write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Information" -Message $successText
PowerShellCorpus/PoshCode/ESXiMgmt module sample _1.ps1
ESXiMgmt module sample _1.ps1
####################################################################################################################### # File: ESXiMgmt_machines_poweroff_sample.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param([string]$Server, [string]$User, [string]$Password, [string]$DatastoreName, [string]$MachinePrefix, [int]$OperationTimeout ) # USAGE: .\\ESXiMgmt_machines_poweroff_sample.ps1 192.168.1.1 root 123 datastore3 XPSP2 10 cls Set-StrictMode -Version Latest Import-Module ESXiMgmt -Force; Connect-ESXi -Server $Server -Port 443 ` -Protocol HTTPS -User $User -Password $Password ` -DatastoreName $DatastoreName; $VerbosePreference = [System.Management.Automation.ActionPreference]::Continue; $VMs = Get-VM * foreach($vm in $VMs) { if ($vm.Name -like "$($MachinePrefix)*" -and ` $vm.PowerState -eq 1) #PoweredOn { Write-Verbose "$($vm.Name) is stopping"; Stop-ESXiVM -Server $Server ` -User $User -Password $Password ` -Id (Get-ESXiVMId $vm); sleep -Seconds $OperationTimeout; } } Disconnect-ESXi # to restart virtual machines instead of shutdown them # simply call the ESXiMgmt_machines_poweron_sample.ps1 script: # USAGE: .\\ESXiMgmt_machines_poweron_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 XPSP2 300
PowerShellCorpus/PoshCode/7c573254-14a1-4559-9c68-e51bc0f502b2.ps1
7c573254-14a1-4559-9c68-e51bc0f502b2.ps1
[/HTML) [Http://]
PowerShellCorpus/PoshCode/Send-Growl 2.0.ps1
Send-Growl 2.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 $appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Global:PowerGrowlerNotices)) { $global:PowerGrowlerNotices = @{} } ## We can safely recreate these, they don't do much [Growl.Connector.Application]$script:GrowlApp = $appName $script:GrowlApp.Icon = Convert-Path (Resolve-Path "$PSScriptRoot\\default.ico") $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" function Set-GrowlPassword { #.Synopsis # Set the Growl password #.Description # Set the password and optionally, the encryption algorithm, for communicating with Growl #.Parameter Password # The password for Growl #.Parameter Encryption # The algorithm to be used for encryption (defaults to AES) #.Parameter KeyHash # The algorithm to be used for key hashing (defaults to SHA1) PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$Password , [Parameter(Mandatory=$false,Position=1)] [ValidateSet( "AES", "DES", "RC2", "TripleDES", "PlainText" )] [String]$Encryption = "AES" , [Parameter(Mandatory=$false,Position=2)] [ValidateSet( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" )] [String]$KeyHash = "SHA1" ) $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$Encryption" $script:PowerGrowler.KeyHashAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$KeyHash" $script:PowerGrowler.Password = $Password } function Register-GrowlType { #.Synopsis # Register a new Type name for growl notices from PowerGrowl #.Description # Creates a new type name that can be used for sending growl notices #.Parameter Name # The type name to be used sending growls #.Parameter DisplayName # The test to use for display (defaults to use the same value as the type name) #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter MachineName # The name of a remote machine to register remotely instead of locally. #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Register-GrowlType "Command Completed" # # Registers the type "Command Completed," using the default icon, for sending notifications to the local PC # PARAM( [Parameter(Mandatory=$true,Position=0)] [ValidateScript( {!$global:PowerGrowlerNotices.ContainsKey($_)} )] [String]$Name , [Parameter(Mandatory=$false,Position=1)] [String]$Icon , [Parameter(Mandatory=$false,Position=2)] [String]$DisplayName = $NoticeName , [Parameter(Mandatory=$false,Position=3)] [String]$MachineName ) [Growl.Connector.NotificationType]$Notice = $Name $Notice.DisplayName = $DisplayName if($Icon) { $Notice.Icon = Convert-Path (Resolve-Path $Icon)$Icon } if($MachineName) { $Notice.MachineName = $MachineName } $global:PowerGrowlerNotices.Add( $Name, $Notice ) $script:PowerGrowler.Register( $script:GrowlApp, @($global:PowerGrowlerNotices.Values) ) } ## Register the "Default" notice type, just so everything works out of the box Register-GrowlType "Default" function Register-GrowlCallback { #.Synopsis # Register a script to be called when each notice is finished. #.Description # Registers a scriptblock as a handler for the NotificationCallback event. You should accept two parameters, a Growl.Connector.Response and a Growl.Connector.CallbackData object. # # The NotificationCallback only happens when a callback is requested, which in this Growl library only happens if you pass both CallbackData and CallbackType to the Send-Growl function. #.Example # Register-GrowlCallback { PARAM( $response, $context ) # Write-Host "Response $($response|out-string)" -fore Cyan # Write-Host "Context $($context|gm|out-string)" -fore Green # Write-Host $("Response Type: {0}`nNotification ID: {1}`nCallback Data: {2}`nCallback Data Type: {3}`n" -f $context.Result, $context.NotificationID, $context.Data, $context.Type) -fore Yellow # } # # Registers an informational debugging-style handler. # PARAM( [Parameter(Mandatory=$true)] [Scriptblock]$Handler ) Register-ObjectEvent $script:PowerGrowler NotificationCallback -Action $Handler } 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 , [Parameter(Mandatory=$true, Position=1)] [string]$Message , [Parameter(Mandatory=$false, Position=2)] [string]$CallbackData , [Parameter(Mandatory=$false, Position=3)] [string]$CallbackType , [Parameter(Mandatory=$false)][Alias("Type")] [ValidateScript( {$global:PowerGrowlerNotices.ContainsKey($_)} )] [string]$NoticeType="Default" , [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, Set-GrowlPassword, Register-GrowlCallback, Register-GrowlType
PowerShellCorpus/PoshCode/Test-QADObject.ps1
Test-QADObject.ps1
<# .SYNOPSIS Quick way to see whether the object exists in AD. .DESCRIPTION Returns $true if at least one object matching the criteria exists and false otherwise. .PARAMETER Identity Specify the DN, SID, GUID, UPN or Domain\\Name of the directory object you want to find .EXAMPLE PS C:\\> Test-QADObject dsotniko .EXAMPLE PS C:\\> Test-QADObject 5ae7197e-cac3-42bf-9541-e06fa33ed965 .EXAMPLE PS C:\\> Test-QADObject 'OU=demo,DC=quest,DC=local' .INPUTS System.String,System.String[] .OUTPUTS System.Boolean .NOTES (c) Dmitry Sotnikov, http://dmitrysotnikov.wordpress.com Requires Quest AD cmdlets which are a free download from http://www.quest.com/activeroles-server/arms.aspx .LINK Get-QADObject #> function Test-QADObject { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [System.String] $Identity ) (Get-QADObject $Identity -DontUseDefaultIncludedProperties ` -WarningAction SilentlyContinue -ErrorAction SilentlyContinue ` -SizeLimit 1) -ne $null } Set-Alias -Name Test-QADPath -Value Test-QADObject
PowerShellCorpus/PoshCode/Start-Countdown_1.ps1
Start-Countdown_1.ps1
function Start-Countdown{ <# .Synopsis Initiates a countdown on your session. Can be used instead of Start-Sleep. Use case is to provide visual countdown progress during "sleep" times .Example Start-Countdown -Seconds 10 This method will clear the screen and display descending seconds .Example Start-Countdown -Seconds 10 -ProgressBar This method will display a progress bar on screen without clearing. .Link http://www.vtesseract.com/ .Description ==================================================================== Author(s): Josh Atwell <josh.c.atwell@gmail.com> File: Start-Countdown.ps1 Date: 2012-04-19 Revision: 1.0 References: www.vtesseract.com ==================================================================== Disclaimer: This script is written as best effort and provides no warranty expressed or implied. Please contact the author(s) if you have questions about this script before running or modifying ==================================================================== #> Param( [INT]$Seconds = (Read-Host "Enter seconds to countdown from"), [Switch]$ProgressBar, [String]$Message = "Blast Off!" ) Clear-Host while ($seconds -ge 1){ If($ProgressBar){ Write-Progress -Activity "Countdown" -SecondsRemaining $Seconds -Status "Time Remaining" Start-Sleep -Seconds 1 }ELSE{ Write-Output $Seconds Start-Sleep -Seconds 1 Clear-Host } $Seconds -- } Write-Output $Message }
PowerShellCorpus/PoshCode/GPPreferencesPrinters.ps1
GPPreferencesPrinters.ps1
###########################################################################" # # NAME: GPPreferencesPrinters.psm1 # # AUTHOR: Jan Egil Ring # BLOG: http://blog.crayon.no/blogs/janegil # # COMMENT: Script module for working with shared printer connections in Group Policy Preferences. # Contains a function for adding a shared printer connection, and a function for retrieving shared printer connections from a specified GPO. # Requires the Group Policy Automation Engine from SDM Software, available from here (commercial product): http://www.sdmsoftware.com/group_policy_scripting.php # Additional functions and parameters will later be added to the script module, i.e. Remove-GPPreferencesPrinter and Item-Level Targeting. # Note that example usage for Item-Level Targeting are provided in the Group Policy Automation Engine User Manual. # # 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 18.01.2010 - Initial release # ###########################################################################" #Imports the Group Policy Automation Engine from SDM Software Import-Module SDM-GroupPolicy function Add-GPPreferencesPrinter { ################################################################ #.Synopsis # Adds a shared printer connection to the specified Group Policy`s User Preferences. #.Parameter GPOName # The name to the Group Policy Object you want to add the shared printer connection to. ################################################################ param( [Parameter(Mandatory=$true)][string]$GPOName,[Parameter(Mandatory=$true)][string]$Printername,[Parameter(Mandatory=$true)][string]$Sharepath,[Parameter(Mandatory=$true)][string]$Action,[Parameter(Mandatory=$false)][string]$Default,[Parameter(Mandatory=$false)][string]$DefaulIfNoLocalPrinters) $domain = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain() $domainname = $domain.name $gpo = Get-SDMgpobject -gpoName "gpo://$domainname/$GPOName" -openByName $container = $gpo.GetObject("User Configuration/Preferences/Control Panel Settings/Printers/Shared printer") $add = $container.Settings.AddNew("$Printername") $add.put("Action",[GPOSDK.EAction]$Action) $add.put("Share path",$Sharepath) $add.put("Default",$Default) $add.put("Default if no local printers",$DefaulIfNoLocalPrinters) $add.Save() } function Get-GPPreferencesPrinter { ################################################################ #.Synopsis # Enumerates and displays printer connections defined in the specified Group Policy`s User Preferences. #.Parameter GPOName # The name to the Group Policy Object you want to get information from ################################################################ param( [Parameter(Mandatory=$true)] [string]$GPOName ) $domain = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain() $domainname = $domain.name $gpo = Get-SDMgpobject -gpoName "gpo://$domainname/$GPOName" -openByName $container = $gpo.GetObject("User Configuration/Preferences/Control Panel Settings/Printers/Shared printer") $setting = $container.Settings $printers = @() $count = $setting.Count $counter = $count; while($counter -ge 1) {$counter = $counter - 1 $printer = $Setting.Item($counter) foreach ($i in $printer) { $printerinfo = @{} $printerinfo.Name = $i.Name $printerinfo.Sharepath = ($setting.Item($counter)).Get("Share path") $printerinfo.Action = ($setting.Item($counter)).Get("Action") $printerinfo.SetDefault = ($setting.Item($counter)).Get("Default") $printerinfo.SetDefaulIfNoLocalPrinters = ($setting.Item($counter)).Get("Default if no local printers") $printers += $printerinfo } } $printers | Select-Object @{Name="Name"; Expression = {$_.name}},@{Name="Sharepath"; Expression = {$_.sharepath}},@{Name="Action"; Expression = {$_.Action}},@{Name="SetDefault"; Expression = {$_.SetDefault}},@{Name="SetDefaulIfNoLocalPrinters"; Expression = {$_.SetDefaulIfNoLocalPrinters}} | ft Name,Sharepath,Action,SetDefault,SetDefaulIfNoLocalPrinters }
PowerShellCorpus/PoshCode/Measure-Total.ps1
Measure-Total.ps1
#.Synopsis # Calculate sums on top of Measure-Object #.Description # Pipe in objects with numerical properties, and get an extra output item # with the sum of all the specified properties #.Parameter Property # The names of the properties to total #.Example # wc *.ps1 | total words, lines # # Calculates line, word, and character counts for powershell script files in the current directory, # and THEN adds a total row with totals for words and lines (but not Chars) #.Example # wc *.rb | total # # Calculates line, word, and character counts for rubyscript files in the current directory, # and THEN adds a total row with totals for ALL NUMERIC PROPERTIES ;-) function measure-total { PARAM([string[]]$property) END { $input # output the input ## "Magically" figure out the numeric properties if(!$property) { $input.reset() $property = $input | gm -type Properties | where { trap{continue} ( new-object "$(@($_.Definition -split " ")[0])" ) -as [double] -ne $null } | foreach { $_.Name } $input.reset() } $input.reset() # then calculate the sum of the numeric properties $sum = $input | measure $property -sum -erroraction 0 # and make a new object to hold the sums $output = new-object PSObject $sum | % { Add-Member -input $output -Type NoteProperty -Name $_.Property -Value $_.Sum } $output # output the output }} new-alias total measure-total
PowerShellCorpus/PoshCode/TabExpansion_9.ps1
TabExpansion_9.ps1
## Tab-Completion ################# ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion ## 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> ## #Type accelerators expansion with no charactors ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, "bar````[1````].txt", "foo bar .txt" # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, "bar````[1````].xml" # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\ProgIDs.txt $_ProgID = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } 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 ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames.txt $_TypeNames = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } 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 ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames_System.txt $_TypeNames_System = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\WMIClasses.txt $_WMIClasses = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref", "Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml" iex (@' function prompt { if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru | Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru | Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru | Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru | Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru | Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru | Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru | Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru | Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru | Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru | Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru | Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru | Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru | Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru | Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru | Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru | Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru | Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru | Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru | Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru | Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru | Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru | Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru | Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru | Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru | Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru | Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru | Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru | Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru | Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru | Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru | Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru | Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru | Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru | Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru | Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru | Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru | Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru | Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru | Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru | Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru | Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru | Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru | Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru | Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru | Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru | Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru | Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru | Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru | Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru | Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru | Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru | Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru | Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru | Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru | Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru | Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru | Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru | Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru | Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru | Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru | Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru | Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru | Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru | Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru | Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru | Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru | Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru | Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru | Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru | Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru | Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru | Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru | Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru | Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru | Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru | Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru | Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru | Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru | Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru | Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru | Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru | Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru | Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru | Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru | Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru | Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru | Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru | Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru | Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru | Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru | Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru | Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = Get-EventLog Windows` PowerShell -Newest 1 } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function TabExpansion { param($line, $lastWord) & { function Write-Members ($sep='.') { Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $members = ( [Object[]](Get-Member -InputObject $_val.PSextended $_pat) + [Object[]](Get-Member -InputObject $_val.PSadapted $_pat) + [Object[]](Get-Member -InputObject $_val.PSbase $_pat) ) if ( $_val -is [Hashtable] ) { [Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } $members += [Object[]]$_keys | ? { $_.Name -like $_pat } } foreach ($_m in $members | sort membertype,name -Unique) { if ($_m.MemberType -band $_method) { $_base + $_expression + $sep + $_m.name + '(' } else { $_base + $_expression + $sep + $_m.name } } } else { foreach ($_m in Get-Member -Static -InputObject $_val $_pat | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { $_base + $_expression + $sep + $_m.name + '(' } else { $_base + $_expression + $sep + $_m.name } } } } switch -regex ($lastWord) { '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] $_pat = $matches[4] + '*' if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } '(^.*)(\\[(\\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; } '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } '(^.*\\$)(.*\\:)(\\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; } '(^.*)(\\$((\\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; } '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } '^(\\[(\\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; } '^(.*)\\)((\\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; } '^\\[((\\w+\\.?)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } '^\\$(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') } } } '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ('"$0"') $fse = $fse -replace '([\\[\\]])', '````$1' -replace '^.*([\\[\\]]).*$', ('"$0"') $fse = $fse -replace '""', '"' $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_base + $global:_cmdstack.Pop() } else { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' $_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 '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 ( $_cmdlet.CommandType -eq "Cmdlet" ) { foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { ( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace ` '^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ } } break; } elseif ( $_command -eq $null ) { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } 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 -match '(function|filter)\\s+(\\w*)$') { $_pat = 'function:\\' + $Matches[2] + '*' Get-ChildItem $_pat| % { $_.Name } break; } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] $_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" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { $_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 ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { 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] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { $Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" | % { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } | ? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ } } break; } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $pattern = $command + "*" "begin {", "break", "catch {", "continue", "data {", "do {", "else {", "elseif (", "end {", "exit", "filter ", "for (", "foreach ", "from", "function ", "if (", "in", "param (", "process {", "return", "switch ", "throw ", "trap ", "until (", "while (" ` -like $pattern | % { $_base + $_ } gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/Get-SvnInfo.ps1
Get-SvnInfo.ps1
Function Get-SvnInfo { [cmdletbinding()] Param( [ValidateScript({Test-Path $_})] [string]$rootDir = "C:\\Build\\", [ValidateScript({Test-Path $_})] [string]$buildDir = "C:\\Build\\build_dir\\", [ValidateScript({Test-Path $_})] [string]$outputDir = "C:\\Build\\output_dir\\", [ValidateScript({Test-Path $_})] [string]$svnDir = "C:\\Build\\build_dir\\vacuum", [ValidateNotNullorEmpty()] [string]$svnUrl = "http://vacuum-im.googlecode.com/svn/trunk/" ) Write-Verbose -Message "Starting $($MyInvocation.Mycommand)" Try { Write-Verbose "Loading SharpSvn assembly" $dll = Add-Type -AssemblyName "SharpSvn" -ErrorAction Stop <# I don't have this available so I can't completely test, but if this file, SharpSvn-x64\\SharpSvn.dll, is registered with the .Net framework, you should be able to load it by its name, which I think is SharpSvn. #> } Catch { $msg = "Failed to load required SharpSvn assembly. {0}" -f $_.Exception.message Write-Warning -Message $msg } If ($dll) { #Only run this code if the assembly was found and loaded Write-Verbose -Message "Creating SvnClient" $svnClient = New-Object SharpSvn.SvnClient Write-Verbose -Message "Creating SvnUriTarget $svnUrl" $repoUri = New-Object SharpSvn.SvnUriTarget($svnUrl) Write-Host "Getting source code from subversion repository $repoUri" -ForegroundColor Green Write-Verbose -Message "Checking out to $svnDir" $svnClient.CheckOut($repoUri, $svnDir) Write-Verbose -Message "Getting info" $svnClient.GetInfo($SvnDir, ([ref]$svnInfo)) $rev = $svnInfo.Revision #write revision info to the pipeline Write-Output $rev } Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" } #end function
PowerShellCorpus/PoshCode/Compiled-Help 1.1.ps1
Compiled-Help 1.1.ps1
#requires -version 2.0 # 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. # More tweaks by John Robbins. (October 2, 2009) # - Fixed a problem where PowerShell 2.0 examples now have "Description" and # "-----------" and was messing up parsing. Those two strings are now skipped. # - Fixed a problem where Related Links were not put into the output correctly. # This fix required minor changes to to cmdlets, providers, and about items # processing. # - Now that PowerShell 2.0 help reports the online version for cmdlet help, I # added support so you can see the documentation on TechNet.microsoft.com # - Added an index to the help file. # - Added a requires statement to the script as I'm sure this no longer works # on PowerShell 1.0. # - Fixed a problem where about help was assumed to not have dashes in the name. 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 ( "", "Description", "-----------" -notcontains $para.get_InnerText().Trim() ) { # 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() } ) -match $navigationLink.linkText.Trim().ToUpper() ) { $linkHtml += " $( $navigationLink.linkText.Trim() )<br />`n" $linkCount++ } elseif ( $navigationLink.linkText -eq "Online version:" ) { $linkHtml += " <a href=$( $navigationLink.uri.Trim() ) target=_blank>TechNet Online Version</a><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> "@ } $linkHtml, $linkCount = Get-LinkHtml ( [xml]$providerXml.providerhelp.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" } $topicHtml += @" </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] Auto Index=Yes Binary TOC=Yes Compatibility=1.1 or later Compiled file=PowerShell.chm Contents file=powershell.hhc Index file=PowerShell.hhk Default topic=Topics/default.html Full-text search=Yes Language=0x409 English (United States) Title=PowerShell 2.0 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> "@ # write the index file Out-File -FilePath "$outDirectory\\powershell.hhk" -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> $( $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+" { # Some of the about values have dashes in the names now. I'm to # lazy to come up with the regular expression here. :) if ( $_ -notmatch "about_" ) { "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-WebFile 3.7.ps1
Get-WebFile 3.7.ps1
## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7 - [int] to [long] to support files larger than 2.0 GB ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## function Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) $req = [System.Net.HttpWebRequest]::Create($url); $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [long]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [long]$total = [long]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/Disable AD Users_1.ps1
Disable AD Users_1.ps1
$NumDays = 90 $LogDir = ".\\Disabled-User-Accounts.log" $currentDate = [System.DateTime]::Now $currentDateUtc = $currentDate.ToUniversalTime() $lltstamplimit = $currentDateUtc.AddDays(- $NumDays) $lltIntLimit = $lltstampLimit.ToFileTime() $adobjroot = [adsi]'' $objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot) $objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))" $users = $objstalesearcher.findall() Write-Output `n`n"----------------------------------------" "ACCOUNTS OLDER THAN "$NumDays" DAYS" "PROCESSED ON:" $currentDate "----------------------------------------" ` | Out-File $LogDir -append if ($users.Count -eq 0) { Write-Output " No account needs to be disabled." | Out-File $LogDir -append } else { foreach ($user in $users) { # Read the user properties [string]$adsPath = $user.Properties.adspath [string]$displayName = $user.Properties.displayname [string]$samAccountName = $user.Properties.samaccountname [string]$lastLogonInterval = $user.Properties.lastlogontimestamp # Disable the user $account=[ADSI]$adsPath $account.psbase.invokeset("AccountDisabled", "True") $account.setinfo() # Convert the date and time to the local time zone $lastLogon = [System.DateTime]::FromFileTime($lastLogonInterval) Write-Output " Disabled user " $displayName" | Username: "$samAccountName" | Last Logon: "$lastLogon"`n" ` | Out-File $LogDir -append } }
PowerShellCorpus/PoshCode/chkhash_12.ps1
chkhash_12.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { foreach($s in $second) { if ($first -eq $s) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=$args $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { do { $i++ if ($i -ge $args2.count) {break} $exclude+=@($args2[$i]) # collect array of excluded directories. if (($i+1) -ge $args2.count) {break} } while ($args2[$i+1] -notlike "-*") continue } $args3+=@($args2[$i]) # Add files/dirs } "ChkHash.ps1 - .\\chkhash.ps1 -h for usage." "" if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } $xfiles=@(import-clixml $hashespath) # Load database } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} $xfiles=@(import-clixml $hashespath) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es) from $hashespath" $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} # Update and continue is specified. $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Update VM Tools_3.ps1
Update VM Tools_3.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/Translate Service DACLS.ps1
Translate Service DACLS.ps1
Function Get-ServiceDACL { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] [String]$Servicename, [Parameter(Mandatory=$false,Position=1)] [String]$Computername= ".") $sddl = Invoke-expression -Command "c:\\Windows\\System32\\sc.exe \\\\$Computername sdshow $Servicename" # $Servicename $sddl $parts = $sddl -split(":") #$parts.Length $i = 0 Write-Host "Getting Service DACL for $ServiceName on $Computername" While ($i -lt $parts.length) { $part = $parts[$i] Switch ($part) { "D" { $i++; Parse-DACL $parts[$i] } } $i++ } $sddl = "" } Function Parse-DACL { Param([String]$SDDLIN) [Array]$sddls = ($SDDLIN).split('(') Foreach ($SDDLI in $sddls) { #($SDDLI).replace(')';'') #$SDDLI $tokens = (($SDDLI).replace(')','')).split(";") If ($tokens[5]) { If ($tokens[5].length -gt 3) { [wmi]$obj = 'Win32_SID.SID="{0}"' -f $($tokens[5]) $encoded = [System.Convert]::ToBase64String($obj.BinaryRepresentation) $obj | Add-Member -MemberType NoteProperty -Name base64_sid -Value $encoded Write-Host "$($obj.ReferencedDomainName)\\$($obj.AccountName)" -ForegroundColor red } Else { Write-Host "$($Trustees.get_item($tokens[5]))" -ForegroundColor red } " " + $AceType.get_item($tokens[0]) [regex]::split($tokens[2], '(.{2})') | % {Write-host " $($PermissionType.get_item($_)) `n" -NoNewline} } } } $AceType = @{"A" = "ACCESS ALLOWED"; "D" = "ACCESS DENIED"; "OA" = "OBJECT ACCESS ALLOWED: ONLY APPLIES TO A SUBSET OF THE OBJECT(S)."; "OD" = "OBJECT ACCESS DENIED: ONLY APPLIES TO A SUBSET OF THE OBJECT(S)."; "AU" = "SYSTEM AUDIT"; "AL" = "SYSTEM ALARM"; "OU" = "OBJECT SYSTEM AUDIT"; "OL" = "OBJECT SYSTEM ALARM"; "ML" = "MANDATORY LABEL"} $AceFlags = @{ "CI" = "CONTAINER INHERIT: Child objects that are containers, such as directories, inherit the ACE as an explicit ACE."; "OI" = "OBJECT INHERIT: Child objects that are not containers inherit the ACE as an explicit ACE."; "NP" = "NO PROPAGATE: ONLY IMMEDIATE CHILDREN INHERIT THIS ACE."; "IO" = "INHERITANCE ONLY: ACE DOESN'T APPLY TO THIS OBJECT; BUT MAY AFFECT CHILDREN VIA INHERITANCE."; "ID" = "ACE IS INHERITED"; "SA" = "SUCCESSFUL ACCESS AUDIT"; "FA" = "FAILED ACCESS AUDIT" } $PermissionType = @{ "CC" = "Query Conf"; "DC" = "Change Conf"; "LC" = "QueryStat"; "SW" = "EnumDeps"; "RP" = "Start"; "WP" = "Stop"; "DT" = "Pause"; "LO" = "Interrogate"; "CR" = "UserDefined"; "GA" = "Generic All"; "GX" = "Generic Execute"; "GW" = "Generic Write"; "GR" = "Generic Read"; "SD" = "Standard Delete"; "RC" = "Read Control"; "WD" = "Write DAC"; "WO" = "Write Owner" } $Trustees = @{ "AO" = "Account operators"; "RU" = "Alias to allow previous Windows 2000"; "AN" = "Anonymous logon"; "AU" = "Authenticated users"; "BA" = "Built-in administrators"; "BG" = "Built-in guests"; "BO" = "Backup operators"; "BU" = "Built-in users"; "CA" = "Certificate server administrators"; "CG" = "Creator group"; "CO" = "Creator owner"; "DA" = "Domain administrators"; "DC" = "Domain computers"; "DD" = "Domain controllers"; "DG" = "Domain guests"; "DU" = "Domain users"; "EA" = "Enterprise administrators"; "ED" = "Enterprise domain controllers"; "WD" = "Everyone"; "PA" = "Group Policy administrators"; "IU" = "Interactively logged-on user"; "LA" = "Local administrator"; "LG" = "Local guest"; "LS" = "Local service account"; "SY" = "Local system"; "NU" = "Network logon user"; "NO" = "Network configuration operators"; "NS" = "Network service account"; "PO" = "Printer operators"; "PS" = "Personal self"; "PU" = "Power users"; "RS" = "RAS servers group"; "RD" = "Terminal server users"; "RE" = "Replicator"; "RC" = "Restricted code"; "SA" = "Schema administrators"; "SO" = "Server operators"; "SU" = "Service logon user" } #Example below queries the WinRM service on RemoteServer Get-ServiceDACL winrm RemoteServer
PowerShellCorpus/PoshCode/Get-ProxyAddress.ps1
Get-ProxyAddress.ps1
Param ( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, HelpMessage="Enter SMTP address to search for in Active-Directory." )] [string]$objSMTP ) Function Get-ProxyAddresses ([string]$Address){ $objAD = $null $objAD = Get-QADObject -LdapFilter "(proxyAddresses=*$Address*)" -IncludeAllProperties -SizeLimit 0 -ErrorAction SilentlyContinue Write-Output $objAD }#Close Function #Validate Quest PSSnapin is loaded Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue #Run Function to search AD for SMTP address $Results = $null $Results = Get-ProxyAddresses -Address $objSMTP | Select-Object Name,DisplayName,ObjectClass,Email,AccountisDisabled,AccountisLockedOut,MailNickName,LegacyExchangeDN -ErrorAction SilentlyContinue IF($Results -eq $null){ Write-Host "" Write-Host "No Object Found with .attribute[proxyAddress] containing $objSMTP."} Else{$Results | Format-List *} #End
PowerShellCorpus/PoshCode/Take-Screenshot.ps1
Take-Screenshot.ps1
Function Take-ScreenShot { <# .SYNOPSIS Used to take a screenshot of the desktop or the active window. .DESCRIPTION Used to take a screenshot of the desktop or the active window and save to an image file if needed. .PARAMETER screen Screenshot of the entire screen .PARAMETER activewindow Screenshot of the active window .PARAMETER file Name of the file to save as. Default is image.bmp .PARAMETER imagetype Type of image being saved. Can use JPEG,BMP,PNG. Default is bitmap(bmp) .INPUTS .OUTPUTS .NOTES Name: Take-ScreenShot Author: Boe Prox DateCreated: 07/25/2010 .EXAMPLE Take-ScreenShot -activewindow Takes a screen shot of the active window .EXAMPLE Take-ScreenShot -Screen Takes a screenshot of the entire desktop .EXAMPLE Take-ScreenShot -activewindow -file "C:\\image.bmp" -imagetype bmp Takes a screenshot of the active window and saves the file named image.bmp with the image being bitmap .EXAMPLE Take-ScreenShot -screen -file "C:\\image.png" -imagetype png Takes a screenshot of the entire desktop and saves the file named image.png with the image being png #> #Requires -Version 2 [cmdletbinding( SupportsShouldProcess = $True, DefaultParameterSetName = "screen", ConfirmImpact = "low" )] Param ( [Parameter( Mandatory = $False, ParameterSetName = "screen", ValueFromPipeline = $True)] [switch]$screen, [Parameter( Mandatory = $False, ParameterSetName = "window", ValueFromPipeline = $False)] [switch]$activewindow, [Parameter( Mandatory = $False, ParameterSetName = "", ValueFromPipeline = $False)] [string]$file, [Parameter( Mandatory = $False, ParameterSetName = "", ValueFromPipeline = $False)] [string] [ValidateSet("bmp","jpeg","png")] $imagetype = "bmp" ) # C# code $code = @' using System; using System.Runtime.InteropServices; using System.Drawing; using System.Drawing.Imaging; namespace ScreenShotDemo { /// <summary> /// Provides functions to capture the entire screen, or a particular window, and save it to a file. /// </summary> public class ScreenCapture { /// <summary> /// Creates an Image object containing a screen shot the active window /// </summary> /// <returns></returns> public Image CaptureActiveWindow() { return CaptureWindow( User32.GetForegroundWindow() ); } /// <summary> /// Creates an Image object containing a screen shot of the entire desktop /// </summary> /// <returns></returns> public Image CaptureScreen() { return CaptureWindow( User32.GetDesktopWindow() ); } /// <summary> /// Creates an Image object containing a screen shot of a specific window /// </summary> /// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param> /// <returns></returns> private Image CaptureWindow(IntPtr handle) { // get te hDC of the target window IntPtr hdcSrc = User32.GetWindowDC(handle); // get the size User32.RECT windowRect = new User32.RECT(); User32.GetWindowRect(handle,ref windowRect); int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; // create a device context we can copy to IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); // create a bitmap we can copy it to, // using GetDeviceCaps to get the width/height IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height); // select the bitmap object IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap); // bitblt over GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY); // restore selection GDI32.SelectObject(hdcDest,hOld); // clean up GDI32.DeleteDC(hdcDest); User32.ReleaseDC(handle,hdcSrc); // get a .NET image object for it Image img = Image.FromHbitmap(hBitmap); // free up the Bitmap object GDI32.DeleteObject(hBitmap); return img; } /// <summary> /// Captures a screen shot of the active window, and saves it to a file /// </summary> /// <param name="filename"></param> /// <param name="format"></param> public void CaptureActiveWindowToFile(string filename, ImageFormat format) { Image img = CaptureActiveWindow(); img.Save(filename,format); } /// <summary> /// Captures a screen shot of the entire desktop, and saves it to a file /// </summary> /// <param name="filename"></param> /// <param name="format"></param> public void CaptureScreenToFile(string filename, ImageFormat format) { Image img = CaptureScreen(); img.Save(filename,format); } /// <summary> /// Helper class containing Gdi32 API functions /// </summary> private class GDI32 { public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest, int nWidth,int nHeight,IntPtr hObjectSource, int nXSrc,int nYSrc,int dwRop); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject); } /// <summary> /// Helper class containing User32 API functions /// </summary> private class User32 { [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC); [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); } } } '@ #User Add-Type to import the code add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing' #Create the object for the Function $capture = New-Object ScreenShotDemo.ScreenCapture #Take screenshot of the entire screen If ($Screen) { Write-Verbose "Taking screenshot of entire desktop" #Save to a file If ($file) { If ($file -eq "") { $file = "$pwd\\image.bmp" } Write-Verbose "Creating screen file: $file with imagetype of $imagetype" $capture.CaptureScreenToFile($file,$imagetype) } Else { $capture.CaptureScreen() } } #Take screenshot of the active window If ($ActiveWindow) { Write-Verbose "Taking screenshot of the active window" #Save to a file If ($file) { If ($file -eq "") { $file = "$pwd\\image.bmp" } Write-Verbose "Creating activewindow file: $file with imagetype of $imagetype" $capture.CaptureActiveWindowToFile($file,$imagetype) } Else { $capture.CaptureActiveWindow() } } }
PowerShellCorpus/PoshCode/Backup AdventureWorks.ps1
Backup AdventureWorks.ps1
Invoke-SqlBackup -sqlserver "WIN7\\Kilimanjaro" -dbname "AdventureWorks" ` -filepath "C:\\Temp\\AdventureWorks_db_$(((Get-Date).ToString("yyyyMMddHHmm"))).bak"
PowerShellCorpus/PoshCode/ConvertTo-Hex_7.ps1
ConvertTo-Hex_7.ps1
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx param ( [string]$SidString ) # Create SID .NET object using SID string provided $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring # Create a byte array of the proper length $sidBytes = New-Object byte[] $sid.BinaryLength #Convert to bytes $sid.GetBinaryForm( $sidBytes, 0 ) # Iterate through bytes, converting each to the hexidecimal equivalent $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } # Join the hex array into a single string for output $hexArr -join ''
PowerShellCorpus/PoshCode/a83538ba-c3bf-4a64-9961-04a6b9a4f0a9.ps1
a83538ba-c3bf-4a64-9961-04a6b9a4f0a9.ps1
# This script supports being run with -WhatIf and -Confirm parameters. [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')] param ( # Regex of the states that should be included in the process killing field. [string]$IncludeStates = '^(Disc)$', # Only DISCONNECTED sessions by default. # Regex of the processes to kill [string]$KillProcesses = '^(OUTLOOK)$' # Only OUTLOOK by default. ) function Get-Sessions { # `qwinsta` is the same as `query session` # `query session`: http://technet.microsoft.com/en-us/library/cc785434(v=ws.10).aspx # Possible session states: <# http://support.microsoft.com/kb/186592 Active. The session is connected and active. Conn. The session is connected. No user is logged on. ConnQ. The session is in the process of connecting. If this state continues, it indicates a problem with the connection. Shadow. The session is shadowing another session. Listen. The session is ready to accept a client connection. Disc. The session is disconnected. Idle. The session is initialized. Down. The session is down, indicating the session failed to initialize correctly. Init. The session is initializing. #> # Snippet from http://poshcode.org/3062 # Parses the output of `qwinsta` into PowerShell objects. $c = query session 2>&1 | where {$_.gettype().equals([string]) } $starters = New-Object psobject -Property @{"SessionName" = 0; "Username" = 0; "ID" = 0; "State" = 0; "Type" = 0; "Device" = 0;}; foreach($line in $c) { try { if($line.trim().substring(0, $line.trim().indexof(" ")) -eq "SESSIONNAME") { $starters.Username = $line.indexof("USERNAME"); $starters.ID = $line.indexof("ID"); $starters.State = $line.indexof("STATE"); $starters.Type = $line.indexof("TYPE"); $starters.Device = $line.indexof("DEVICE"); continue; } New-Object psobject -Property @{ "SessionName" = $line.trim().substring(0, $line.trim().indexof(" ")).trim(">") ;"Username" = $line.Substring($starters.Username, $line.IndexOf(" ", $starters.Username) - $starters.Username) ;"ID" = $line.Substring($line.IndexOf(" ", $starters.Username), $starters.ID - $line.IndexOf(" ", $starters.Username) + 2).trim() ;"State" = $line.Substring($starters.State, $line.IndexOf(" ", $starters.State)-$starters.State).trim() ;"Type" = $line.Substring($starters.Type, $starters.Device - $starters.Type).trim() ;"Device" = $line.Substring($starters.Device).trim() } } catch { throw $_; #$e = $_; #Write-Error -Exception $e.Exception -Message $e.PSMessageDetails; } } } # Get a list of all terminal sessions that are in the state we care about. $IncludedSessions = Get-Sessions ` | Where { $_.State -match $IncludeStates } ` | Select -ExpandProperty ID # Get a list of all processes in one of those terminal sessions # that match a process we want to kill. $SessionProcesses = $IncludedSessions ` | % { $id = $_; Get-Process ` | Where { $_.SessionID -eq $id -and $_.Name -match $KillProcesses } } if ($SessionProcesses -ne $null) { $SessionProcesses | Stop-Process }
PowerShellCorpus/PoshCode/TruncatePath.ps1
TruncatePath.ps1
### # TruncatePath # Version 1.0.6 (05 Nov 2008) # Description: Replaces long provider paths in the prompt with ellipses # Notes: Place in your profile # # By Mike Hays, http://www.mike-hays.net ### $maxPathLength = 40 $showFullPath = $false Function Prompt { $currentPath = (Get-Location).Path if ( ($currentPath.Length -gt $maxPathLength) -and ($showFullPath -ne $true) -and (($currentPath.Split("\\")).Count -gt 3) ) { $currentPathSplit = $currentPath.Split("\\") $truncatedPath = $currentPathSplit[0] + "\\" + $currentPathSplit[1] + "\\" + "..." + "\\" + $currentPathSplit[$currentPathSplit.Length - 1] if ($truncatedPath.Length -lt $currentPath.Length) { $displayPath = $truncatedPath } else { $displayPath = get-location } } else { $displayPath = get-location } Write-Host ("PS ") -NoNewLine -ForegroundColor DarkYellow ; Write-Host ("" + $displayPath + ">") -NoNewLine return " " }
PowerShellCorpus/PoshCode/validate an IP address_4.ps1
validate an IP address_4.ps1
# validate given IP address as an IPAdress (given string input) PARAM($IP=$(read-host "Enter any IP Address")) ## YOU could do this, but ... # $IP -match "(\\d{1,3}).(\\d{1,3}).(\\d{1,3}).(\\d{1,3})" -and -not ([int[]]$matches[1..4] -gt 255) ## you shouldn't parse things yourself when it's in the framework. You might make a mistake ;-) #trap { return $false } #[IPAddress]$IP # Just cast it to an IPAddress ... if it's valid, it will work. #return $true ## no trap needed if tryparse is used #[system.net.IPAddress]::tryparse($ip,[ref]$null) # when you still need the parsed IP number : [ref]$a = $null [system.net.IPAddress]::tryparse($ip,$a)
PowerShellCorpus/PoshCode/Backup-ModifiedGPOsv1.1.ps1
Backup-ModifiedGPOsv1.1.ps1
###########################################################################" # # NAME: Backup-ModifiedGPOs.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: All Group Policy Objects modified in the specified timespan are backup up to the specified backup path. # For more details, see the following blog-post: # http://blog.powershell.no/2010/06/15/backing-up-group-policy-objects-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 15.06.2010 - Initial release # @@# 1.1 17.11.2010 - Andy Helsby - Added check to create backup directory and report directory if it does not exist. @@# - Added optional parameter to allow backups of gpo's modified in last X days (defaults to 1 otherwise) @@# - Note if no group policies were modified in the previous X days, the script does throw an error about Name not being provided. ###########################################################################" #Requires -Version 2.0 Import-Module grouppolicy $BackupPath = "C:\\GPO Backup" $ReportPath = "C:\\GPO Backup\\Reports\\" @@if (!(Test-Path -path $ReportPath)) {New-Item $ReportPath -type directory} @@[int]$NumberofDaysBackup = $args[0] @@#Above line throws error if parameter was not numeric - safe to ignore due to next line @@#Set value to 1 if not already passed in parameter $Timespan = (Get-Date).AddDays(-1) $ModifiedGPOs = Get-GPO -all | Where-Object {$_.ModificationTime -gt $Timespan} Write-Host "The following "$ModifiedGPOs.count" GPOs were successfully backed up:" -ForegroundColor yellow Foreach ($GPO in $ModifiedGPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $BackupPath $Path = $ReportPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html" Get-GPOReport -Name $GPO.DisplayName -path $Path -ReportType HTML Write-Host $GPO.DisplayName }
PowerShellCorpus/PoshCode/Get-NaShares.ps1
Get-NaShares.ps1
# Glenn Sizemore www . Get-Admin . Com # Requires the NetApp OnTap SDK v3.5 # # Will connect to the destination Filer and retrieve all cifs shares, # and there permissions. While we can get cifs information directly # from a filer we can't get ACL information easily. The only options # are either RPC(too hard for me) or a screen scrape. # # Usage: # Connect to the filler # $Filer = 'TOASTER' # $NetApp = New-Object NetApp.Manage.NaServer($filer,1,0) # $NetApp.SetAdminUser(UserName,Password) # # Call the function # Get-NaShares -Server $NetApp Function Get-NaShares { Param( [NetApp.Manage.NaServer]$Server ) Begin { $obj=$null } Process { $NaElement = New-Object NetApp.Manage.NaElement("system-cli") $arg = New-Object NetApp.Manage.NaElement("args") $arg.AddNewChild('arg','cifs') $arg.AddNewChild('arg','shares') $NaElement.AddChildElement($arg) $CifsString = $Server.InvokeElem($naelement).GetChildContent("cli-output") $null, $null, $Lines = $CifsString.Split("`n") Foreach ($l in $Lines) { Switch -regex ($l) { "^(?<Volume>\\S+)\\s+(?<Mount>\\S+)\\s+(?<Description>.+)" { IF ($obj) { $obj.Access = $ACL write-output $obj } $ACL = @() $obj = ""|Select Share,Path,Description,Access $obj.Share = $matches.Volume $obj.Path = $matches.Mount $obj.Description = $matches.Description Break; } "\\s+(?<Domain>\\S+)\\\\(?<User>\\S+)\\s+\\/\\s+(?<Perms>\\S+(\\s)?(\\S+)?)$" { $ACL += $Matches|Select @{ N='Domain' E={$_.Domain} }, @{ N='UserName' E={$_.User} }, @{ N='Permissions' E={$_.Perms} } Break; } "(?<User>\\S+)\\s+\\/\\s+(?<Perms>\\S+(\\s)?(\\S+)?)$" { $ACL += $Matches|Select @{ N='Domain' E={''} }, @{ N='UserName' E={$_.User} }, @{ N='Permissions' E={$_.Perms} } Break; } } } $obj.Access = $ACL write-output $obj } }
PowerShellCorpus/PoshCode/UIAutomation Simple 2.ps1
UIAutomation Simple 2.ps1
[Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") [Reflection.Assembly]::Load("UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") function Select-Window { PARAM( [string]$Text="*", [switch]$Recurse, [System.Windows.Automation.AutomationElement]$Parent = [System.Windows.Automation.AutomationElement]::RootElement ) PROCESS { if($Recurse) { $Parent.FindAll( "Descendants", [System.Windows.Automation.Condition]::TrueCondition ) | Where-Object { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElementIdentifiers]::NameProperty) -like $Text } | Add-Member -Name Window -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.WindowPattern]::Pattern )} -Passthru | Add-Member -Name Transform -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.TransformPattern]::Pattern )} -Passthru } else { $Parent.FindAll( "Children", [System.Windows.Automation.Condition]::TrueCondition ) | Where-Object { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElementIdentifiers]::NameProperty) -like $Text }| Add-Member -Name Window -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.WindowPattern]::Pattern )} -Passthru | Add-Member -Name Transform -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.TransformPattern]::Pattern )} -Passthru } }} ### To minimize all notepad windows # select-window *notepad | ForEach { $_.Window.SetWindowVisualState("Minimized") } ### To Close all notepad windows # select-window *notepad | ForEach { $_.Window.Close() } ### To resize all notepad windows, be sure to make then "Normal" first (not minimized/maximized) # select-window *notepad | ForEach { $_.Window.SetWindowVisualState("Normal"); $_.Transform.Resize( 400, 600) } ### To tile two notepad windows # Add-Type -Assembly System.Windows.Forms # so we can figure out the screen size # $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds # # Select-window *notepad | Select -First 2 | Tee -Var Windows | # ForEach { # $_.Window.SetWindowVisualState("Normal") # $_.Transform.Resize( ($bounds.Width/2), $bounds.Height ) # } # $windows[0].Transform.Move( ($bounds.Left), ($bounds.Top) ) # $windows[1].Transform.Move( ($bounds.Left + $bounds.Width/2),($bounds.Top) )
PowerShellCorpus/PoshCode/ADFS MSOL update.ps1
ADFS MSOL update.ps1
Add-PSSnapin Microsoft.Adfs.Powershell Import-Module MSOnline $cred = Get-Credential $AdfsServer = Read-Host "Please type the name of the ADFS server" Write-Host "Connecting to MSOnline..." Connect-MsolService -credential:$cred Write-Host "Setting the local ADFS server..." Set-MSOLADFSContext -Computer:$AdfsServer Write-Host "Updating the ADFS server configuration..." Update-MSOLFederatedDomain -DomainName:Domain.com Write-host "Below is a list of the Federated domains..." -foreground "Green" Get-MsolDomain
PowerShellCorpus/PoshCode/Invoke-Command.ps1
Invoke-Command.ps1
Param($file,$cmd,[switch]$whatif,[switch]$verbose) Begin{ function Ping-Server { Param([string]$srv) $pingresult = Get-WmiObject win32_pingstatus -f "address='$srv'" if($pingresult.statuscode -eq 0) {$true} else {$false} } $servers = @() } Process{ if($_) { if($_.ServerName){$servers += $_.ServerName} else{$servers += $_} } } End{ if($file){Get-Content $file | %{$servers += $_}} foreach($server in $servers) { if(ping-server $server) { if($verbose){Write-Host "+ Processing Server $Server"} $mycmd = $cmd -replace "\\%S\\%",$Server if($whatif){Write-Host " - WOULD RUN $mycmd"} else{if($verbose){Write-Host " - Running $mycmd"};invoke-Expression $mycmd} } else { Write-Host "+ $Server FAILED PING" -foregroundcolor RED } } }
PowerShellCorpus/PoshCode/chkhash_15.ps1
chkhash_15.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]" " [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, store hashes in c:\\users\\eve\\hashes\\private.xml]" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" " [hash all files in c:\\users\\eve and subdirs, save hashes to c:\\users\\eve\\hashes\\private.xml, exclude " " c:\\users\\eve\\hashes directory and subdirs]" " PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u" " [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to" " existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { while (($i+1) -lt $args2.count) { $i++ if ($args2[$i] -like "-*") {break} $exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories. } continue } $args3+=@($args2[$i]) # Add files/dirs } "ChkHash.ps1 - .\\chkhash.ps1 -h for usage." "" if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es) from $hashespath" $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Down with SOPA!.ps1
Down with SOPA!.ps1
<# .Synopsis Let's fill the logs of the US House and Senate servers with the message we don't want SOPA or E-Parasite! .Description Runs an while(1) loop that grabs a couple URI's from each branch's website and sleeps for 1 second between requests. #> # twitter tags #occupyUSSenate #occupyUSHouse #sopa #eparasite while(1){ try{ (new-object net.webclient).downloadstring("http://www.house.gov/downWithSOPA") | Out-Null; } catch{} try{ (new-object net.webclient).downloadstring("http://www.senate.gov/downWithE-Parasite") | out-n } catch{} sleep 1; }
PowerShellCorpus/PoshCode/Start-Job proxy function_1.ps1
Start-Job proxy function_1.ps1
<# Example on how to use Proxy Cmdlets in combination with object events. For more information see: http://blog.powershell.no/2011/02/07/powershell-using-proxy-cmdlets-in-combination-with-object-events For more information about proxy functions, see the following article on the Microsoft PowerShell Team blog: http://blogs.msdn.com/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx #> function Start-Job { <# To create a proxy function for the Start-Job cmdlet, paste the results of the following command into the body of this function and then remove this comment: [Management.Automation.ProxyCommand]::Create((New-Object Management.Automation.CommandMetaData (Get-Command Start-Job))) #> [CmdletBinding(DefaultParameterSetName='ComputerName')] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [System.String] ${Name}, [Parameter(ParameterSetName='ComputerName', Mandatory=$true, Position=0)] [Alias('Command')] [System.Management.Automation.ScriptBlock] ${ScriptBlock}, [System.Management.Automation.PSCredential] ${Credential}, [Parameter(ParameterSetName='FilePathComputerName', Position=0)] [Alias('PSPath')] [System.String] ${FilePath}, [System.Management.Automation.Runspaces.AuthenticationMechanism] ${Authentication}, [Parameter(Position=1)] [System.Management.Automation.ScriptBlock] ${InitializationScript}, [Switch] ${RunAs32}, [System.Management.Automation.ScriptBlock] ${OnCompletionAction}, [Parameter(ValueFromPipeline=$true)] [System.Management.Automation.PSObject] ${InputObject}, [Alias('Args')] [System.Object[]] ${ArgumentList}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Start-Job', [System.Management.Automation.CommandTypes]::Cmdlet) # define string variable to become the target command line #region Initialize helper variable to create command $scriptCmdPipeline = '' #endregion # add new parameter handling #region Process and remove the Path parameter if it is present if ($OnCompletionAction) { $PSBoundParameters.Remove('OnCompletionAction') | Out-Null $scriptCmdPipeline += " | foreach-object{ `$job = Register-ObjectEvent -InputObject `$_ -EventName StateChanged -SourceIdentifier JobEndAlert -Action { if(`$sender.State -eq 'Completed') { `& { $OnCompletionAction } Unregister-Event -SourceIdentifier JobEndAlert -Force } } }" } #endregion $scriptCmd = {& $wrappedCmd @PSBoundParameters } $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock( [string]$scriptCmd + $scriptCmdPipeline ) $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Start-Job .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/PoshCode/ConvertFrom-Property 3.7.ps1
ConvertFrom-Property 3.7.ps1
<# .SYNOPSIS Converts data from flat or single-level property files into PSObjects .DESCRIPTION Converts delimited string data such as .ini files, or the format-list output of PowerShell, into objects .EXAMPLE netsh http show sslcert | join-string "`n" | ConvertFrom-PropertyString -ValueSeparator " +: " -AutomaticRecords | Format-Table Application*, IP*, Certificate* Converts the output of netsh show into pseudo-objects, and then uses Format-Table to display them .EXAMPLE ConvertFrom-PropertyString config.ini Reads in an ini file (which has key=value pairs), using the default settings .EXAMPLE @" ID:3468 Type:Developer StartDate:1998-02-01 Code:SWENG3 Name:Baraka ID:11234 Type:Management StartDate:2005-05-21 Code:MGR1 Name:Jax "@ |ConvertFrom-PropertyString -sep ":" -RecordSeparator "\\r\\n\\s*\\r\\n" | Format-Table Code StartDate Name ID Type ---- --------- ---- -- ---- SWENG3 1998-02-01 Baraka 3468 Developer MGR1 2005-05-21 Jax 11234 Management Reads records from a key:value string with records separated by blank lines. NOTE that in this example you could also have used -AutomaticRecords or -Count 5 instead of specifying a RecordSeparator .EXAMPLE @" Name=Fred Address=Street1 Number=123 Name=Janet Address=Street2 Number=345 "@ | ConvertFrom-PropertyString -RecordSeparator "`n(?=Name=)" Reads records from a key=value string and uses a look-ahead record separator to start a new record whenever "Name=" is encountered NOTE that in this example you could have used -AutomaticRecords or -Count 3 instead of specifying a RecordSeparator .EXAMPLE ConvertFrom-PropertyString data.txt -ValueSeparator ":" Reads in a property file which has key:value pairs .EXAMPLE Get-Content data.txt -RecordSeparator "`r`n`r`n" | ConvertFrom-PropertyString -ValueSeparator ";" Reads in a property file with key;value pairs, and records separated by blank lines, and converts it to objects .EXAMPLE ls *.data | ConvertFrom-PropertyString Reads in a set of *.data files which have an object per file defined with key:value pairs of properties, one-per line. .EXAMPLE ConvertFrom-PropertyString data.txt -RecordSeparator "^;(.*?)\\r*\\n" -ValueSeparator ";" Reads in a property file with key:value pairs, and sections with a header that starts with the comment character ';' .NOTES 3.6 2013 Apr 6 - Add AllowEmptyValue parameter to supports data that just has a header and a list of properties (without values) 3.5 2012 July 26 - Changed defaults so that lines which don't have a -ValueSeparator in them don't get output - Changed pipelining so that it works more the way I expect it to, nowadays - Fixed some problems with -RecordSeparator getting truncated to a single character when you use a capture group and add it as a PSName property Clearly I need to write some test cases around this to make sure that I'm not breaking functionality, because these changes felt like things that should have already worked... 3.0 2010 Aug 4 - Renamed most of the parameters because I couldn't tell which did what from the Syntax help - Added a -AutomaticRecords switch which creates new output objects whenevr it encounters a duplicated property - Added a -SimpleOutput swicth which prevents the output of the PSChildName property - Added a -CountOfPropertiesPerRecord parameter which allows splitting input by count instead of regex or automatic 2.0 2010 July 9 http://poshcode.org/get/1956 - changes the output so that if there are multiple instances of the same key, we collect the values in an array 1.0 2010 June 15 http://poshcode.org/get/1915 - Initial release #> # function ConvertFrom-PropertyString { [CmdletBinding(DefaultParameterSetName="Data")] param( # The text to be parsed [Parameter(Position=99, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Data")] [Alias("Data","Content","IO")] [AllowEmptyString()] [string]$InputObject, # A file containing text to be parsed (so you can pipeline files to be processed) [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")] [Alias("PSPath")] [string]$FilePath, # The value separator string used between name=value pairs. Allows regular expressions. # Typical values are "=" or ":" # Defaults to "=" [Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)] [Alias("VS","Separator")] [String]$ValueSeparator="\\s*(?:=|:)\\s*", # The property separator string used between sets of name=value pairs. Allows regular expressions. # Typical values are "\\n" or "\\n\\n" or "\\n\\s*\\n" # Defaults to "\\n\\s*\\n?" [Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)] [Alias("PS","Delimiter")] [String]$PropertySeparator='(?:\\s*\\n+\\s*)+', # The record separator string is used between records or sections in a text file. # Typical values are "\\n\\s*\\n" or "\\n\\[(.*)\\]\\s*\\n" # Defaults to "(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n" (the correct value for ini files). # To support named sections or records, make sure to use a regular expression here that has a capture group defined. [Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)] [Alias("RS")] [String]$RecordSeparator='(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n', # Supports guessing when a new record starts based on the repetition of a property name. You can use this whenever your input has multiple records and the properties are always in the same order. [Parameter(ParameterSetName="Data")] [Alias("MultiRecords","MR","MultipleRecords","AR","AutoRecords")] [Switch]$AutomaticRecords, # Separate the input into groups of a certain number of properties. # If your input file has no specific record separator, you can usually match the first property by using a look-ahead expression *(See Example 2)* # However, if the properties aren't in the same order each time or regular expressions make you queasy, and each of your records have the same number of properties on each record, you can use this to separate them by count. [Parameter()] [int]$CountOfPropertiesPerRecord, # Prevent outputting the PSName parameter which indicates the source of the object when pipelineing file names [Parameter()] [Switch]$SimpleOutput, # Discard the first record, assuming that it is merely some lines of header introductory text [Parameter()] [Switch]$HasHeader, # Discard the last record, assuming that it is merely some lines of footer summary text [Parameter()] [Switch]$HasFooter, # Allow Empty Values if there's no value separator [switch]$AllowEmptyValue ) begin { function new-output { [CmdletBinding()] param( [Switch]$SimpleOutput , [AllowNull()][AllowEmptyString()] [String]$Key , [AllowNull()][AllowEmptyString()] $FilePath ) end { if(!$SimpleOutput -and ("" -ne $Key)) { @{"PSName"=$key} } elseif(!$SimpleOutput -and $FilePath) { @{"PSName"=((get-item $FilePath).PSChildName)} } else { @{} } } } function out-output { [CmdletBinding()] param([Hashtable]$output) end { ## If we made arrays out of single values, unwrap those foreach($k in $Output.Keys | Where { @($Output.$_).Count -eq 1 } ) { $Output.$k = @($Output.$k)[0] } if($output.Count) { New-Object PSObject -Property $output } } } $OutputCount = 0 [String]$InputString = [String]::Empty Write-Verbose "Setting up the regular expressions: `n`tRecord: '$RecordSeparator' `n`tProperty: '$PropertySeparator' `n`tValue: '$ValueSeparator'" [Regex]$ReRecordSeparator = New-Object Regex ([System.String]"\\s*$RecordSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") [Regex]$RePropertySeparator = New-Object Regex ([System.String]"\\s*$PropertySeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") [Regex]$ReValueSeparator = New-Object Regex ([System.String]"\\s*$ValueSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } process { if($PSCmdlet.ParameterSetName -eq "File") { $AutomaticRecords = $true $InputString += $(Get-Content $FilePath -Delimiter ([char]0)) + "`n`n" } else { $InputString += "$InputObject`n" } } end { ## some kind of PowerShell bug when expecting pipeline input: if(!"$ReRecordSeparator"){ Write-Verbose "Setting up the record regex in the PROCESS block: '$RecordSeparator'" [Regex]$ReRecordSeparator = New-Object Regex ([System.String]"\\s*$RecordSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } if(!"$RePropertySeparator"){ Write-Verbose "Setting up the property regex in the PROCESS block: '$PropertySeparator'" [Regex]$RePropertySeparator = New-Object Regex ([System.String]"\\s*$PropertySeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } if(!"$ReValueSeparator") { Write-Verbose "Setting up the value regex in the PROCESS block: '$ValueSeparator'" [Regex]$ReValueSeparator = New-Object Regex ([System.String]"\\s*$ValueSeparator\\s*"), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } Write-Verbose "ParameterSet: $($PSCmdlet.ParameterSetName)" Write-Verbose "ValueSeparator: $($ReValueSeparator)" $InputData = @{} if($PSCmdlet.ParameterSetName -eq "File") { $AutomaticRecords = $true $InputString = Get-Content $FilePath -Delimiter ([char]0) } ## Separate RecordText with the RecordSeparator if the user asked us to: if($PsBoundParameters.ContainsKey('RecordSeparator') -or $AutomaticRecords ) { $Records = $ReRecordSeparator.Split( $InputString ) # | Where-Object { $_ } ## Instead of using WhereObject and removing all the empty rows, allow empties AFTER record separators, but not before... if(!@($Records)[0]) { $Records = $Records[1..$($Records.Count-1)] } Write-Verbose "There are $($ReRecordSeparator.GetGroupNumbers().Count) groups and $(@($Records).Count) records!" if($ReRecordSeparator.GetGroupNumbers().Count -gt 1 -and @($Records).Count -gt 1) { if($HasHeader) { $Records = $Records[2..$($Records.Count -1)] } if($HasFooter) { $Records = $Records[0..$($Records.Count -3)] } while($Records) { $Key,$Value,$Records = @($Records) Write-Verbose "RecordSeparator with grouping: $Key = $Value" $InputData.$Key += @($Value) } } elseif(@($Records).Count -gt 1) { $InputData."" = @($Records) $InputString = $Records } else { $InputString = $Records } } ## Separate RecordText into properties and group them together by count if we were told a count if($PsBoundParameters.ContainsKey('CountOfPropertiesPerRecord')) { $Properties = $RePropertySeparator.Split($InputString) Write-Verbose "Separating Records by Property count = $CountOfPropertiesPerRecord of $($Properties.Count)" for($Index = 0; $Index -lt $Properties.Count; $Index += $CountOfPropertiesPerRecord) { $InputData."" += @($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0)) Write-Verbose "Record ($Index..) $($Index/$CountOfPropertiesPerRecord) = $(@($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0)))" } ## We have to manually set the PropertySeparator because we can't generate text from your regex pattern to match your regex pattern $SetPropertySeparator = $RePropertySeparator [Regex]$RePropertySeparator = New-Object Regex ([System.String][char]0), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled") } if($InputData.Keys.Count -eq 0){ Write-Verbose "Keyless entry enabled!" $InputData."" = @($InputString) } Write-Verbose "InputData: $($InputData.GetEnumerator() | ft -auto -wrap| out-string)" ## Process each Record foreach($key in $InputData.Keys) { foreach($record in $InputData.$Key) { Write-Verbose "Record($Key): $record" $output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath foreach($Property in $RePropertySeparator.Split("$record") | ? {$_}) { if($ReValueSeparator.IsMatch($Property)) { [string[]]$data = $ReValueSeparator.split($Property,2) | foreach { $_.Trim() } | where { $_ } Write-Verbose "Property: $Property --> $($data -join ': ')" if($AutomaticRecords -and $Output.ContainsKey($Data[0])) { out-output $output $output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath } switch($data.Count) { 1 { $output.($Data[0]) += @($null) } 2 { $output.($Data[0]) += @($Data[1]) } } } elseif($AllowEmptyValue) { $output.$Property = $true } } out-output $output } } ## Put this back in case there's more input $RePropertySeparator = $SetPropertySeparator } #}
PowerShellCorpus/PoshCode/ScriptTransforms module.ps1
ScriptTransforms module.ps1
function new-parameterTransform { [cmdletbinding()] param( [Parameter(Mandatory=$true,Position=0)] [string] $name, [Parameter(Mandatory=$true, Position=1)] [scriptblock] $script ) add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ${name}Attribute : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public ${name}Attribute() { this.Script = ScriptBlock.Create( @" $($script.ToString() -replace '"','""' ) " ); } public override string ToString() { return Script.ToString(); } 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 ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ } New-Alias -Name Transform -Value New-ParameterTransform; Export-ModuleMember -Alias Transform -Function *
PowerShellCorpus/PoshCode/chkhash_4.ps1
chkhash_4.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { foreach($s in $second) { if ($first -eq $s) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=$args $nu = 0 $errs = 0 $fc = 0 $upd = $false $create = $false for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" "" "Note: files in subdirectories of any specified directory are automatically processed." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path if ($args2[$i] -like "-e*") # Exclude files, dirs { do { $i++ if ($i -ge $args2.count) {break} $exclude+=@($args2[$i]) # collect array of excluded directories. if (($i+1) -ge $args2.count) {break} } while ($args2[$i+1] -notlike "-*") continue } $args3+=@($args2[$i]) # Add files/dirs } "ChkHash.ps1 - .\\chkhash.ps1 -h for usage." "" if ($args3.count -eq 0) {exit} # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } $xfiles=@(import-clixml $hashespath) "Loaded $($xfiles.count) file hash(es) from $hashespath" $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing $($f.fullname) ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} # Update and continue is specified. $fc++ # increment files checked. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. { continue } $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fc file(s) SHA512 matched." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Select-Random.ps1
Select-Random.ps1
param([array]$Collection) begin { $result = $Seed if ($args -eq '-?') { '' 'Usage: Select-Random [[-Collection] <array>]' '' 'Parameters:' ' -Collection : The collection from which to select a random entry.' ' -? : Display this usage information' '' 'Examples:' ' PS> $arr = 1..5; Select-Random $arr' ' PS> 1..5 | Select-Random' '' exit } $coll = @() if ($collection.count -gt 0) { $coll += $collection } } process { if ($_) { $coll += $_; } } end { if ($coll) { $randomIndex = Get-Random -Min 0 -Max ($coll.Count) $coll[$randomIndex] } }
PowerShellCorpus/PoshCode/Added_Deleted AD Objects_1.ps1
Added_Deleted AD Objects_1.ps1
#REQUIRES -pssnapin quest.activeroles.admanagement #REQUIRES -pssnapin Pscx begin { # Build variables $strSMTPServer = "192.168.xx.xx"; $strEmailFrom = "AD_Admin@yourdomain.com"; $strEmailTo = "admin@yourdomain.com"; $borders = "=" * 25; [int]$days = -60 function TombStonedObjects { # create Directory Searcher object and set properties to search # for tombstoned objects $ds = New-Object System.DirectoryServices.DirectorySearcher $ds.Tombstone = $TRUE $ds.Filter = "isDeleted=TRUE" # Query for objects and filter for DN $DSResults=$DS.FindAll() | select path # Build simple RegExp to get just Common Name $r=[regex]"(?<=CN=).+(?=\\\\)" $DSR2=$DSResults | % { $r.Matches($_);$script:delCount++} foreach ($DSobject in $DSR2) { $delMessage += "Deleted object: " + $DSobject.value.trim() + "`n" } $delMessage # end function } function AddedComputersAndUsers { # Query AD for Computer and users created in the last 'x' amount of days. $ADObjects=Get-QADObject | ? {$_.type -match ("computer|user")} | ? {$_.whencreated -gt ((get-date).addDays($days))} if ($ADObjects) { foreach ($ADObject in $ADObjects) { switch ($ADObject.Type) { 'user' { $usrCount ++; $ADObject | fl * | Out-Null; #This is needed for some reason some objects are not returned without it $usrMessage += "Display Name: " + $ADobject.displayname + "`n"; $usrMessage += "SAMAccountName: " + $ADObject.get_LogonName() + "`n"; $usrMessage += "Container: " + $ADObject.parentcontainer + "`n"; $usrMessage += "When Created: " + $ADObject.whencreated + "`n"; $usrMessage += "Principal Name: " + $ADObject.userPrincipalName + "`n"; $usrMessage += "Groups: `n"; # Build array of groups and populate $usrMessage variable $groups=$adobject.MemberOf foreach ($group in $groups) { $usrMessage += "$group `n"} $usrMessage += "`n"; } 'computer' { $computerCount ++; $ADObject | fl * | Out-Null; #This is needed for some reason some objects are not returned without it $compMessage += "DNS HostName: " + $ADObject.dnsname + "`n"; $compMessage += "OperatingSystem: " + $ADObject.osName + "`n"; $compMessage += "OS Service Pack: " + $ADObject.osservicepack + "`n"; $compMessage += "Computer Role: " + $ADObject.computerrole + "`n"; $compMessage += "When Created: " + $ADObject.whencreated + "`n"; $compMessage += "Container: " + $ADObject.parentcontainer + "`n"; $compMessage += "`n"; } } } $deletedobjects = TombStonedObjects # Build emailBody with the Usermessage and ComputerMessage variables $script:emailMessage = "AD User/Computer Objects created in the last " + [math]::abs($days) + " day(s).`n"; if ($usrMessage) {$script:emailMessage += "$borders Users $borders`n" + $usrMessage;} if ($compMessage) {$script:emailMessage += "$borders Computers $borders`n" + $compMessage;} if ($deletedobjects) {$script:emailMessage += "$borders Deleted Objects for the last 60 days $borders `n" + $deletedobjects;} $script:emailSubject = "Users Added: " + $usrCount + ". Computers Added: " + $computerCount + ". Objects Deleted: " + $script:delCount + "."; } else { # No users or computers found created in the last 'x' days. $deletedobjects = TombStonedObjects $script:emailSubject = "Users Added: " + $usrCount + ". Computers Added: " + $computerCount + ". Objects Deleted: " + $script:delCount + "."; $script:emailMessage = "No Users or Computers have been added in the last " + [math]::abs($days) + " day(s). `n"; if ($deletedobjects) {$script:emailMessage += "$borders Deleted Objects for the last 60 days $borders `n" + $deletedobjects;} } # end function } # end Begin } process { AddedComputersAndUsers Send-SmtpMail -Subject $script:emailSubject -To $strEmailTo -From $strEmailFrom -SmtpHost $strSMTPServer -Body $script:emailMessage; # end Process }
PowerShellCorpus/PoshCode/Find-DuplicateSMTP_1.ps1
Find-DuplicateSMTP_1.ps1
####################################################################### #### Written By: Kevin Dunn #### #### Date: 1/21/2009 #### #### #### #### FindDuplicateSMTPAddr.ps1 #### #### #### #### Requires Quest Active Directory cmdlets #### #### Requires Excel (tested on 2007) #### ####################################################################### #User defined Variables $SMTPServer = "127.0.0.1" $SenderAddress = "FromAddress@yourdomain.com" $RecipientAddresses = "You@yourdomain.com" $Subject = "Duplicate SMTP Address Report" $Domain = "yourdomain.com" #Set this to a literal path i.e. "C:\\scripts\\" if not running as a .ps1 #This location is where the spreadsheet will be saved to #$ScriptPath = "C:\\Scripts\\" $ScriptPath = ($myInvocation.MyCommand.Path).Replace($myInvocation.MyCommand.Name, "") if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorVariable Err -ErrorAction SilentlyContinue if ($Err) { Write-Host "`tError loading Quest.ActiveRoles.ADManagement" -ForeGroundColor Green exit } } #Gather proxyaddresses information from AD Write-Host "`n`tGathering email addresses from Active Directory" -ForeGroundColor Yellow $Filter = '(|(&(objectClass=user)(homeMDB=*))(&(mailNickName=*)(objectClass=Contact))(&(mailNickName=*)(objectClass=group)))' $MailObjects = get-qadobject -service $Domain -sizeLimit 0 -ldapfilter $Filter -DontUseDefaultIncludedProperties ` -IncludedProperties proxyAddresses | Select proxyAddresses, ClassName $NumberMailobjects = $MailObjects.count Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberMailobjects " -noNewLine -ForeGroundColor Green Write-Host "mail enabled objects" -ForeGroundColor Yellow #Count and Write proxyaddresses information to hashtable Write-Host "`n`tCounting proxyAddresses Data" -ForeGroundColor Yellow $EmailCount = @{} $EmailTypeCount = @{} $EmailDomainCount = @{} $oldPos = $host.UI.RawUI.CursorPosition Foreach ($MailObject in $MailObjects){ $ObjectType = $MailObject.ClassName $MailObject.ProxyAddresses | Foreach { #Count Type of Addresses $Type = [string]$_.split(":")[0] if($EmailTypeCount.ContainsKey($Type) -eq $False) { $EmailTypeCount.Add($Type, 1) } Else { $Count = $EmailTypeCount.Get_Item($Type) $Count++ $EmailTypeCount.Set_Item($Type, $Count) } #Count Unique Email Addresses if($EmailCount.ContainsKey($_) -eq $False) { $EmailCount.Add($_, 1) } Else { $Count = $EmailCount.Get_Item($_) $Count++ $EmailCount.Set_Item($_, $Count) } #Count Mail domains $Domain = [string]$_.Split("@")[1] if($Domain -ne $null) { if($EmailDomainCount.ContainsKey($Domain) -eq $False) { $EmailDomainCount.Add($Domain, 1) } Else { $Count = $EmailDomainCount.Get_Item($Domain) $Count++ $EmailDomainCount.Set_Item($Domain, $Count) } } } #Keep the output refresh from eating CPU $UpdateOutPut = $False If ($NumberAddType -lt $EmailTypeCount.Count){$UpdateOutPut = $True} elseIf ($NumberMailDomains -lt $EmailDomainCount.Count){$UpdateOutPut = $True} elseIf (($EmailCount.Count % 100) -eq 0){$UpdateOutPut = $True} If ($UpdateOutPut -eq $True) { $NumberAddType = $EmailTypeCount.Count $NumberAddresses = $EmailCount.Count $NumberMailDomains = $EmailDomainCount.Count $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberAddresses " -noNewLine -ForeGroundColor Green Write-Host "unique email addresses" -ForeGroundColor Yellow Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberAddType " -noNewLine -ForeGroundColor Green Write-Host "address types" -ForeGroundColor Yellow Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberMailDomains " -noNewLine -ForeGroundColor Green Write-Host "mail domains`n" -ForeGroundColor Yellow } } $EmailDomains = $EmailDomainCount.GetEnumerator() | Sort Key $EmailTypes = $EmailTypeCount.GetEnumerator() | Sort Key #Filter proxyaddresses data for duplicates Write-Host "`n`tFiltering for duplicate email addresses" -ForeGroundColor Yellow $Duplicates = $EmailCount.GetEnumerator() | ? {$_.Value -gt 1} $Duplicates = $Duplicates | Sort $NumberDuplicates = $Duplicates.Count Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberDuplicates " -noNewLine -ForeGroundColor Green Write-Host "duplicate email addresses`n" -ForeGroundColor Yellow #Retrieve additional information about objects with duplicate proxyaddresses Write-Host "`n`tGathering information about the objects with duplicate email addresses" -ForeGroundColor Yellow $DupeOutput = @() $Count = 0 $oldPos = $host.UI.RawUI.CursorPosition $Duplicates | Foreach { $count++ [string]$Email = $_.Key $Filter = "(proxyAddresses=*$Email*)" $ObjectsWithDupes = get-qadobject -service $Domain -ldapFilter $Filter ` -DontUseDefaultIncludedProperties -includedProperties extensionAttribute3 | ` Select DisplayName, samAccountName, DN, ClassName, extensionAttribute3 $ObjectsWithDupes | foreach { $_ | add-member noteproperty -Name "DupeEmailAddress" -Value $Email } $DupeOutput += $ObjectsWithDupes $DupesProcessed = ($DupeOutput | Select DN -Unique).Count $UsersProcessed = ($DupeOutput | ? {$_.Classname -eq "user"} | Select DN -Unique).Count $GroupsProcessed = ($DupeOutput | ? {$_.Classname -eq "group"} | Select DN -Unique).Count $ContactsProcessed = ($DupeOutput | ? {$_.Classname -eq "contact"} | Select DN -Unique).Count $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tProcessed " -noNewline -ForeGroundColor Yellow Write-Host "$DupesProcessed " -noNewLine -ForeGroundColor Green Write-Host "objects and " -noNewLine -ForeGroundColor Yellow Write-Host "$Count" -noNewLine -ForeGroundColor Green Write-Host " addresses" -ForeGroundColor Yellow } $DupeCount = $DupeOutput.count $DupeOutput = $DupeOutput | Sort displayname, ClassName, DupeEmailAddress #Open Excel Write-Host "`n`tGenerating spreadsheet" -ForeGroundColor Yellow $Excel = New-Object -comobject Excel.Application $Excel.Visible = $False $WB = $Excel.Workbooks.Add(1) #Create First Worksheet $EmailParseData = $WB.Worksheets.Item(1) [void]$EmailParseData.Activate() $EmailParseData.Name = "SMTP Data" #Make the top row pretty [void]$Excel.Cells.Item(2,1).Select() $Excel.ActiveWindow.FreezePanes = $True [void]$Excel.Range($Excel.Cells.item((1),(1)),$Excel.cells.item((1),(2))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 [void]$Excel.Range($Excel.Cells.item((1),(4)),$Excel.cells.item((1),(5))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 $Row = 1 #Populate Top row $EmailParseData.Cells.Item($Row,1) = "Domain" $Excel.Columns.item("A:A").ColumnWidth = 45 $EmailParseData.Cells.Item($Row,2) = "Number Of Occurances" $Excel.Columns.item("B:B").ColumnWidth = 23 $EmailParseData.Cells.Item($Row,4) = "Address Type" $Excel.Columns.item("D:D").ColumnWidth = 16 $EmailParseData.Cells.Item($Row,5) = "Number Of Occurances" $Excel.Columns.item("E:E").ColumnWidth = 23 $Row = 2 #Write to first worksheet Write-Host "`n`tWriting Email Domains" -ForeGroundColor Yellow $EmailDomains | Foreach { $EmailParseData.Cells.Item($Row,1) = $_.Key $EmailParseData.Cells.Item($Row,2) = $_.Value $Row++ } Write-Host "`n`tWriting Address Types" -ForeGroundColor Yellow $Row = 2 $EmailTypes | Foreach { $EmailParseData.Cells.Item($Row,4) = $_.Key $EmailParseData.Cells.Item($Row,5) = $_.Value $Row++ } #Add Second Worksheet Write-Host "`n`t`Creating Second Worksheet" -ForeGroundColor Yellow $DupeWS = $Excel.Worksheets.Add() [void]$DupeWS.Activate() $DupeWS.Name = "Duplicate Address Data" $Row = 1 #Make the top row pretty [void]$Excel.Cells.Item(2,1).Select() $Excel.ActiveWindow.FreezePanes = $True [void]$Excel.Range($Excel.Cells.item((1),(1)),$Excel.cells.item((1),(6))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 #Populate data in the top row $DupeWS.Cells.Item($row,1) = "DisplayName" $Excel.Columns.item("A:A").ColumnWidth = 35 $DupeWS.Cells.Item($row,2) = "samAccountName" $Excel.Columns.item("B:B").ColumnWidth = 25 $DupeWS.Cells.Item($row,3) = "DupeEmailAddress" $Excel.Columns.item("C:C").ColumnWidth = 60 $DupeWS.Cells.Item($row,4) = "ClassName" $Excel.Columns.item("D:D").ColumnWidth = 20 $DupeWS.Cells.Item($row,5) = "ExtensionAttribute3" $Excel.Columns.item("E:E").ColumnWidth = 35 $DupeWS.Cells.Item($row,6) = "DN" $Excel.Columns.item("F:F").ColumnWidth = 90 #Begin writing duplicate email address data $row++ Write-Host "`n`tWriting Duplicate Address Data" -ForeGroundColor Yellow $oldPos = $host.UI.RawUI.CursorPosition $DupeOutput | Foreach { $DupeWS.Cells.Item($row,1) = $_.Displayname $DupeWS.Cells.Item($row,2) = $_.Samaccountname $DupeWS.Cells.Item($row,3) = $_.DupeEmailAddress $DupeWS.Cells.Item($row,4) = $_.ClassName $DupeWS.Cells.Item($row,5) = $_.extensionAttribute3 $DupeWS.Cells.Item($row,6) = $_.DN $row++ If (($row % 5) -eq 0) { $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tOutput " -noNewline -ForeGroundColor Yellow Write-Host "$row " -noNewLine -ForeGroundColor Green Write-Host "lines to Excel`n" -ForeGroundColor Yellow } } $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tOutput " -noNewline -ForeGroundColor Yellow Write-Host "$row " -noNewLine -ForeGroundColor Green Write-Host "lines to Excel" -ForeGroundColor Yellow #Save the spreadsheet and exit Excel $Excel.DisplayAlerts = $False $saveAs = $ScriptPath + "DupeEmailReport." + (get-date).dayofyear + ".xls" write-host "`tSaving Report to: $saveAS`n`n`n" -ForegroundColor Cyan $WB.SaveAs($saveAs, 1) $WB.Close() $Excel.Quit() #Create the message $Body = "`<BR>" +` " Mail Enabled Objects Found`t`t $NumberMailobjects " +` "`<BR>" +` " Unique Email Addresses Found:`t`t $NumberAddresses " + ` "`<BR>" + ` " Duplicated Email Addresses:`t`t $NumberDuplicates " + ` "`<BR><BR>" + ` " Mail Objects Affected:`t`t $DupesProcessed " + ` "`<BR>" + ` " Users Affected:`t`t $UsersProcessed " + ` "`<BR>" + ` " Groups Affected:`t`t $GroupsProcessed " + ` "`<BR>" + ` " Contacts Affected:`t`t $ContactsProcessed " + ` "`<BR><BR>" +` " Number of Address Types:`t`t $NumberAddType " + ` "`<BR>" + ` " Number of Mail Domains:`t`t $NumberMailDomains" $Attachment = new-object System.Net.Mail.Attachment($saveAs) $objMail = new-object System.Net.Mail.MailMessage $objMail.From = $SenderAddress $objMail.Sender = $SenderAddress $objMail.To.Add($RecipientAddresses) $objMail.Subject = $Subject $objMail.Body = $Body $objMail.IsBodyHTML = $true $objMail.Attachments.Add($Attachment) #Send the message $objSMTP = New-Object System.Net.Mail.SmtpClient $objSMTP.Host = $SMTPServer $objSMTP.UseDefaultCredentials = $true $objSMTP.Send($objMail)
PowerShellCorpus/PoshCode/Invoke-MoveRequest_1.ps1
Invoke-MoveRequest_1.ps1
########################################################################### # # NAME: Invoke-MoveRequest.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jer@powershell.no # # COMMENT: Script to use when migrating mailboxes to Microsoft Exchange Server 2010 Cross-Forest. Prepares user objects already # moved to the target forest using Active Directory Migration Tool or other tools, and then invokes the mailbox move request. # For more information, see the following blog-post: http://blog.powershell.no/2010/04/23/exchange-server-2010-cross-forest-migration # # 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 23.04.2010 - Initial release # ########################################################################### #Adding Quest AD PowerShell Commands Snapin and Microsoft Exchange Server 2010 PowerShell Snapin Add-PSSnapin Quest.ActiveRoles.ADManagement Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 #Custom variables, edit this section $TargetDatabase = "Mailbox Database A" $TargetDeliveryDomain = "domain.com" $TargetForest="DomainA.local" $SourceForest="domainB.local" $SourceForestGlobalCatalog = "dc-01.domainB.local" $SourceForestCredential = Get-Credential -Credential "Domain\\SourceForestAdministrator" #Connect to source forest to collect users to migrate Connect-QADService -Service $SourceForest | Out-Null $SourceForestUsersToMigrate = Get-QADUser -SearchRoot "DomainA.local/Department A/Users" foreach ($user in $SourceForestUsersToMigrate) { Write-Host "Processing user $user" -ForegroundColor Yellow #Connect to source forest to collect source object attributes Connect-QADService -Service $SourceForest | Out-Null $TargetObject=$user.samaccountname $SourceObject=Get-QADUser $TargetObject -IncludeAllProperties $mail=$SourceObject.Mail $mailNickname=$SourceObject.mailNickname [byte[]]$msExchMailboxGUID=(Get-QADuser $SourceObject -IncludedProperties msExchMailboxGUID -DontConvertValuesToFriendlyRepresentation).msExchMailboxGUID $msExchRecipientDisplayType="-2147483642" $msExchRecipientTypeDetails="128" $msExchUserCulture=$SourceObject.msExchUserCulture $msExchVersion="44220983382016" $proxyAddresses=$SourceObject.proxyAddresses $targetAddress=$SourceObject.Mail $userAccountControl=514 #Connect to target forest to set target object attributes Connect-QADService -Service $TargetForest | Out-Null Set-QADUser -Identity $TargetObject -ObjectAttributes @{mail=$mail;mailNickname=$mailNickname;msExchMailboxGUID=$msExchMailboxGUID;msExchRecipientDisplayType=$msExchRecipientDisplayType;msExchRecipientTypeDetails=$msExchRecipientTypeDetails;msExchUserCulture=$msExchUserCulture;msExchVersion=$msExchVersion;proxyAddresses=$proxyAddresses;targetAddress=$targetAddress;userAccountControl=$userAccountControl} | Out-Null #Update Exchange-attributes (LegacyExchangeDN etc.) Get-MailUser $TargetObject | Update-Recipient #Invoking a new move-request New-MoveRequest -Identity $TargetObject -RemoteLegacy -TargetDatabase $TargetDatabase -RemoteGlobalCatalog $SourceForestGlobalCatalog -RemoteCredential $SourceForestCredential -TargetDeliveryDomain $TargetDeliveryDomain #Enable target object and unset "User must change password at next logon" Enable-QADUser -Identity $TargetObject | Out-Null Set-QADUser -Identity $TargetObject -UserMustChangePassword $false | Out-Null }
PowerShellCorpus/PoshCode/PS2WCF_1.ps1
PS2WCF_1.ps1
# Call WCF Services With PowerShell V1.0 22.12.2008 # # by Christian Glessner # Blog: http://www.iLoveSharePoint.com # Twitter: http://twitter.com/cglessner # Codeplex: http://codeplex.com/iLoveSharePoint # # requires .NET 3.5 # load WCF assemblies [void][System.Reflection.Assembly]::LoadWithPartialName("System.ServiceModel") [void][System.Reflection.Assembly]::LoadWithPartialName("System.Runtime.Serialization") # get metadata of a service function global:Get-WsdlImporter($wsdlUrl=$(throw "parameter -wsdlUrl is missing"), $httpGet) { if($httpGet -eq $true) { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet } else { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange } $mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient((New-Object System.Uri($wsdlUrl)),$mode) $mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue $metadataSet = $mexClient.GetMetadata() $wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet) return $wsdlImporter } # Generate wcf proxy types function global:Get-WcfProxy($wsdlImporter, $wsdlUrl, $proxyPath) { if($wsdlImporter -eq $null -and $wsdlUrl -eq $null) { throw "parameter -wsdlImporter or -wsdlUrl must be specified" } else { if($wsdlImporter -eq $null) { $script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl trap [Exception] { $script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl -httpGet $true continue } } } $generator = new-object System.ServiceModel.Description.ServiceContractGenerator foreach($contractDescription in $script:wsdlImporter.ImportAllContracts()) { [void]$generator.GenerateServiceContractType($contractDescription) } $parameters = New-Object System.CodeDom.Compiler.CompilerParameters if($proxyPath -eq $null) { [void]$parameters.GenerateInMemory = $true } else { $parameters.OutputAssembly = $proxyPath } $providerOptions = new-object "System.Collections.Generic.Dictionary``2[System.String,System.String]" [void]$providerOptions.Add("CompilerVersion","v3.5") $compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions) $result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit); if($result.Errors.Count -gt 0) { throw "Proxy generation failed" } foreach($type in $result.CompiledAssembly.GetTypes()) { if($type.BaseType.IsGenericType) { if($type.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" ) { $type } } } }
PowerShellCorpus/PoshCode/Add-SqlTable_5.ps1
Add-SqlTable_5.ps1
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"} ####################### function Get-SqlType { param([string]$TypeName) switch ($TypeName) { 'Boolean' {[Data.SqlDbType]::Bit} 'Byte[]' {[Data.SqlDbType]::VarBinary} 'Byte' {[Data.SQLDbType]::VarBinary} 'Datetime' {[Data.SQLDbType]::DateTime} 'Decimal' {[Data.SqlDbType]::Decimal} 'Double' {[Data.SqlDbType]::Float} 'Guid' {[Data.SqlDbType]::UniqueIdentifier} 'Int16' {[Data.SQLDbType]::SmallInt} 'Int32' {[Data.SQLDbType]::Int} 'Int64' {[Data.SqlDbType]::BigInt} default {[Data.SqlDbType]::VarChar} } } #Get-SqlType ####################### <# .SYNOPSIS Creates a SQL Server table from a DataTable .DESCRIPTION Creates a SQL Server table from a DataTable using SMO. .EXAMPLE $dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table .EXAMPLE $dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table. .NOTES Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52 Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Updated documentation v1.2 - Chad Miller - Add loading Microsoft.SqlServer.ConnectionInfo v1.3 - Chad Miller - Added error handling v1.4 - Chad Miller - Add VarCharMax and VarBinaryMax handling v1.5 - Chad Miller - Added AsScript switch to output script instead of creating table #> function Add-SqlTable { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [String]$TableName, [Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable, [Parameter(Position=4, Mandatory=$false)] [string]$Username, [Parameter(Position=5, Mandatory=$false)] [string]$Password, [ValidateRange(0,8000)] [Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000, [Parameter(Position=7, Mandatory=$false)] [switch]$AsScript ) try { if($Username) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance } $con.Connect() $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con $db = $server.Databases[$Database] $table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName foreach ($column in $DataTable.Columns) { $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)" if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') { if ($MaxLength -gt 0) {$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength} else { $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max" $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType } } else { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType } $col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType $col.Nullable = $column.AllowDBNull $table.Columns.Add($col) } if ($AsScript) { $table.Script() } else { $table.Create() } } catch { $message = $_.Exception.GetBaseException().Message Write-Error $message } } #Add-SqlTable
PowerShellCorpus/PoshCode/VMware Daily Report_2.ps1
VMware Daily Report_2.ps1
# vCheck - Daily Error Report # # Changes: # Version 1.12 - Added Hosts in Maintenance Mode and not responding + Bug Fixes # Version 1.11 - Simplified mail function. # Version 1.10 - Added How many days old the snapshots are # Version 1.9 - Added ability to change user account which makes the WMI calls # Version 1.8 - Added Real name resolution via AD and sorted disk space by PerfFree # Version 1.7 - Added Event Logs for VMware warnings and errors for past day # Version 1.6 - Add details to service state to see if it is expected or not # Version 1.5 - Check for objects to see if they exist before sending the email + add VMs with No VMTools param( [string] $VISRV) # You can change the following defaults by altering the below settings: # # Set the SMTP Server address $SMTPSRV = "myexchangeserver.mydomain.comk" # # Set the Email address to recieve from $EmailFrom = "reports@mydomain.com" # # Set the Email address to send the email to $EmailTo = "myemail@mydomain.com" #### Detail Settings #### # Set the username of the account with permissions to access the VI Server # for event logs and service details - you will be asked for the same username and password # only the first time this runs after setting the below username. # If it is left blank it will use the credentials of the user who runs the script $SetUsername = "" # Set the location to store the credentials in a secure manner $CredFile = ".\\mycred.crd" # Set the warning threshold for Datastore % Free Space $DatastoreSpace = "5" # Set the warning threshold for snapshots in days old $SnapshotAge = 14 # Set the number of days to show VMs created & removed for $VMsNewRemovedAge = 5 # Set the number of days of VC Events to check for errors $VCEventAge = 1 # Set tge bumber of days of VC Event Logs to check for warnings and errors $VCEvntlgAge = 1 ####################################### # Start of script if ($VISRV -eq ""){ Write-Host Write-Host "Please specify a VI Server name eg...." Write-Host " powershell.exe DailyReport.ps1 MYVISERVER" Write-Host Write-Host exit } function Send-SMTPmail($to, $from, $subject, $smtpserver, $body) { $mailer = new-object Net.Mail.SMTPclient($smtpserver) $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $msg.IsBodyHTML = $true $mailer.send($msg) } Function Get-CustomHTML ($Header){ $Report = @" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html><head><title>$($Header)</title> <META http-equiv=Content-Type content='text/html; charset=windows-1252'> <meta name="save" content="history"> <style type="text/css"> DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 10pt; RIGHT: 8px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline} TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%} *{margin:0} .dspcont { BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 95%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9} .filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative} .save{behavior:url(#default#savehistory);} .dspcont1{ display:none} a.dsphead0 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #cc0000} a.dsphead1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #7BA7C7} a.dsphead2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #A5A5A5} a.dsphead1 span.dspchar{font-family:monospace;font-weight:normal;} td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma} th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left} BODY {margin-left: 4pt} BODY {margin-right: 4pt} BODY {margin-top: 6pt} </style> </head> <body> <b><font face="Arial" size="5">$($Header)</font></b><hr size="8" color="#cc0000"> <font face="Arial" size="1"><b>Generated on $($ENV:Computername)</b></font><br> <font face="Arial" size="1">Report created on $(Get-Date)</font> <div class="filler"></div> <div class="filler"></div> <div class="filler"></div> <div class="save"> "@ Return $Report } Function Get-CustomHeader0 ($Title){ $Report = @" <h1><a class="dsphead0">$($Title)</a></h1> <div class="filler"></div> "@ Return $Report } Function Get-CustomHeader ($Num, $Title){ $Report = @" <h2><a class="dsphead$($Num)"> $($Title)</a></h2> <div class="dspcont"> "@ Return $Report } Function Get-CustomHeaderClose{ $Report = @" </DIV> <div class="filler"></div> "@ Return $Report } Function Get-CustomHeader0Close{ $Report = @" </DIV> "@ Return $Report } Function Get-CustomHTMLClose{ $Report = @" </div> </body> </html> "@ Return $Report } Function Get-HTMLTable { param([array]$Content) $HTMLTable = $Content | ConvertTo-Html $HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', "" $HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', "" $HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', "" $HTMLTable = $HTMLTable -replace '<html>', "" $HTMLTable = $HTMLTable -replace '<head>', "" $HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', "" $HTMLTable = $HTMLTable -replace '</head><body>', "" $HTMLTable = $HTMLTable -replace '</body></html>', "" Return $HTMLTable } Function Get-HTMLDetail ($Heading, $Detail){ $Report = @" <TABLE> <tr> <th width='25%'><b>$Heading</b></font></th> <td width='75%'>$($Detail)</td> </tr> </TABLE> "@ Return $Report } function Find-Username ($username){ if ($username -ne $null) { $root = [ADSI]"" $filter = ("(&(objectCategory=user)(samAccountName=$Username))") $ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter) $ds.PageSize = 1000 $ds.FindOne() } } function Get-VIServices { If ($SetUsername -ne ""){ $Services = get-wmiobject win32_service -Credential $creds -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" } } Else { $Services = get-wmiobject win32_service -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" } } $myCol = @() Foreach ($service in $Services){ $MyDetails = "" | select-Object Name, State, StartMode, Health If ($service.StartMode -eq "Auto") { if ($service.State -eq "Stopped") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "Unexpected State" } } If ($service.StartMode -eq "Auto") { if ($service.State -eq "Running") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "OK" } } If ($service.StartMode -eq "Disabled") { If ($service.State -eq "Running") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "Unexpected State" } } If ($service.StartMode -eq "Disabled") { if ($service.State -eq "Stopped") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "OK" } } $myCol += $MyDetails } Write-Output $myCol } function Get-DatastoreSummary { param( $InputObject = $null ) begin { } process { if ($InputObject -and $_) { throw 'The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.' return } $processObject = $(if ($InputObject) {$InputObject} else {$_}) if ($processObject) { $myCol = @() foreach ($ds in $_) { $MyDetails = "" | select-Object Name, Type, CapacityMB, FreeSpaceMB, PercFreeSpace $MyDetails.Name = $ds.Name $MyDetails.Type = $ds.Type $MyDetails.CapacityMB = $ds.CapacityMB $MyDetails.FreeSpaceMB = $ds.FreeSpaceMB $MyDetails.PercFreeSpace = [math]::Round(((100 * ($ds.FreeSpaceMB)) / ($ds.CapacityMB)),0) $myCol += $MyDetails } $myCol | Where { $_.PercFreeSpace -lt $DatastoreSpace } } } end { } } function Get-SnapshotSummary { param( $InputObject = $null ) BEGIN { } PROCESS { if ($InputObject -and $_) { throw 'ParameterBinderStrings\\AmbiguousParameterSet' break } elseif ($InputObject) { $InputObject } elseif ($_) { $mySnaps = @() foreach ($snap in $_){ $SnapshotInfo = Get-SnapshotExtra $snap $mySnaps += $SnapshotInfo } $mySnaps | Select VM, Name, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, @{N="Creator";E={(Find-Username (($_.Creator.split("\\"))[1])).Properties.displayname}}, Created, Description -ErrorAction SilentlyContinue | Sort DaysOld } else { throw 'ParameterBinderStrings\\InputObjectNotBound' } } END { } } function Get-SnapshotTree{ param($tree, $target) $found = $null foreach($elem in $tree){ if($elem.Snapshot.Value -eq $target.Value){ $found = $elem continue } } if($found -eq $null -and $elem.ChildSnapshotList -ne $null){ $found = Get-SnapshotTree $elem.ChildSnapshotList $target } return $found } function Get-SnapshotExtra ($snap){ $guestName = $snap.VM # The name of the guest $tasknumber = 999 # Windowsize of the Task collector $taskMgr = Get-View TaskManager # Create hash table. Each entry is a create snapshot task $report = @{} $filter = New-Object VMware.Vim.TaskFilterSpec $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime $filter.Time.beginTime = (($snap.Created).AddDays(-5)) $filter.Time.timeType = "startedTime" $collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter)) $dummy = $collectionImpl.RewindCollector $collection = $collectionImpl.ReadNextTasks($tasknumber) while($collection -ne $null){ $collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{ $row = New-Object PsObject $row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName $vm = Get-View $_.Entity if($vm -ne $null){ $snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result if($snapshot -ne $null){ $key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString()) $report[$key] = $row } } } $collection = $collectionImpl.ReadNextTasks($tasknumber) } $collectionImpl.DestroyCollector() # Get the guest's snapshots and add the user $snapshotsExtra = $snap | % { $key = $_.vm.Name + "&" + ($_.Created.ToString()) if($report.ContainsKey($key)){ $_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User } $_ } $snapshotsExtra } Function Set-Cred ($File) { $Credential = Get-Credential $credential.Password | ConvertFrom-SecureString | Set-Content $File } Function Get-Cred ($User,$File) { $password = Get-Content $File | ConvertTo-SecureString $credential = New-Object System.Management.Automation.PsCredential($user,$password) $credential } If ($SetUsername -ne ""){ if ((Test-Path -Path $CredFile) -eq $false) { Set-Cred $CredFile } $creds = Get-Cred $SetUsername $CredFile } $VIServer = Connect-VIServer $VISRV If ($VIServer.IsConnected -ne $true){ # Fix for scheduled tasks not running. $USER = $env:username $APPPATH = "C:\\Documents and Settings\\" + $USER + "\\Application Data" #SET THE APPDATA ENVIRONMENT WHEN NEEDED if ($env:appdata -eq $null -or $env:appdata -eq 0) { $env:appdata = $APPPATH } $VIServer = Connect-VIServer $VISRV If ($VIServer.IsConnected -ne $true){ send-SMTPmail -to $EmailTo -from $EmailFrom -subject "ERROR: $VISRV Daily Report" -smtpserver $SMTPSRV -body "The Connect-VISERVER Cmdlet did not work, please check you VI Server." exit } } $VM = Get-VM $VMH = Get-VMHost $Clusters = Get-Cluster $Datastores = Get-Datastore $FullVM = Get-View -ViewType VirtualMachine $MyReport = Get-CustomHTML "$VIServer Daily Report" $MyReport += Get-CustomHeader0 ($VIServer.Name) # ---- General Summary Info ---- $MyReport += Get-CustomHeader "1" "General Details" $MyReport += Get-HTMLDetail "Number of Hosts:" (($VMH).Count) $MyReport += Get-HTMLDetail "Number of VMs:" (($VM).Count) $MyReport += Get-HTMLDetail "Number of Clusters:" (($Clusters).Count) $MyReport += Get-HTMLDetail "Number of Datastores:" (($Datastores).Count) $MyReport += Get-CustomHeaderClose # ---- Snapshot Information ---- $Snapshots = $VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-$SnapshotAge))} | Get-SnapshotSummary If (($Snapshots | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Snapshots (Over $SnapshotAge Days Old)" $MyReport += Get-HTMLTable $Snapshots $MyReport += Get-CustomHeaderClose } # ---- Datastore Information ---- $OutputDatastores = $Datastores | Get-DatastoreSummary | Sort PercFreeSpace If (($OutputDatastores | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Datastores (Less than $DatastoreSpace% Free)" $MyReport += Get-HTMLTable $OutputDatastores $MyReport += Get-CustomHeaderClose } # ---- Hosts in Maintenance Mode ---- $MaintHosts = $VMH | where {$_.State -match "Maintenance"} | Select name,CustomFields If (($MaintHosts | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Hosts in Maintenance Mode" $MyReport += Get-HTMLTable $MaintHosts $MyReport += Get-CustomHeaderClose } # ---- Hosts Not responding ---- $RespondHosts = $VMH | where {$_.State -match "Not"} | Select name,CustomFields If (($RespondHosts | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Hosts not responding" $MyReport += Get-HTMLTable $RespondHosts $MyReport += Get-CustomHeaderClose } # ---- VMs created or Cloned ---- $VIEvent = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VMsNewRemovedAge) $OutputCreatedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmBeingClonedEvent" -or $_.Gettype().Name -eq "VmBeingDeployedEvent"} | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputCreatedVMs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VMs Created or Cloned (Last $VMsNewRemovedAge Day(s))" $MyReport += Get-HTMLTable $OutputCreatedVMs $MyReport += Get-CustomHeaderClose } # ---- VMs Removed ---- $OutputRemovedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmRemovedEvent"}| Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputRemovedVMs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VMs Removed (Last $VMsNewRemovedAge Day(s))" $MyReport += Get-HTMLTable $OutputRemovedVMs $MyReport += Get-CustomHeaderClose } # ---- VC Errors ---- $OutputErrors = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VCEventAge ) -Type Error | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputErrors | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Error Events (Last $VCEventAge Day(s))" $MyReport += Get-HTMLTable $OutputErrors $MyReport += Get-CustomHeaderClose } # ---- No VM Tools ---- $NoTools = $FullVM | Where { $_.Runtime.PowerState -eq "poweredOn" } | Select Name, @{N="ToolsVersion"; E={$_.Config.tools.toolsVersion}} | Where { $_.ToolsVersion -eq 0} | Select Name If (($NoTools | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "No VMTools" $MyReport += Get-HTMLTable $NoTools $MyReport += Get-CustomHeaderClose } # ---- CD-Roms Connected ---- $CDConn = $VM | Where { $_ | Get-CDDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host If (($CDConn | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VM: CD-ROM Connected - VMotion Violation" $MyReport += Get-HTMLTable $CDConn $MyReport += Get-CustomHeaderClose } # ---- Floppys Connected ---- $Floppy = $VM | Where { $_ | Get-FloppyDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host If (($Floppy | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VM:Floppy Drive Connected - VMotion Violation" $MyReport += Get-HTMLTable $Floppy $MyReport += Get-CustomHeaderClose } # ---- Virtual Center Details ---- $MyReport += Get-CustomHeader "1" "$VIServer Service Details" $MyReport += Get-HTMLTable (Get-VIServices) $MyReport += Get-CustomHeaderClose # ---- Virtual Center Event Logs - Error ---- $ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-$VCEvntlgAge)) If ($SetUsername -ne ""){ $ErrLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } Else { $ErrLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } If (($ErrLogs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Error" $MyReport += Get-HTMLTable ($ErrLogs) $MyReport += Get-CustomHeaderClose } # ---- Virtual Center Event Logs - Warning ---- $ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-1)) If ($SetUsername -ne ""){ $WarnLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } Else { $WarnLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } If (($WarnLogs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Warning" $MyReport += Get-HTMLTable ($WarnLogs) $MyReport += Get-CustomHeaderClose } $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose #Uncomment the following lines to save the htm file in a central location #$Date = Get-Date #$Filename = "C:\\Temp\\" + $VIServer + "DailyReport" + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm" #$MyReport | out-file -encoding ASCII -filepath $Filename #Invoke-Item $Filename send-SMTPmail $EmailTo $EmailFrom "$VISRV Daily Report" $SMTPSRV $MyReport $VIServer | Disconnect-VIServer -Confirm:$false
PowerShellCorpus/PoshCode/Invoke-AddTypeTypeDefini.ps1
Invoke-AddTypeTypeDefini.ps1
#############################################################################\n##\n## Invoke-AddTypeTypeDefinition\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\nDemonstrates the use of the -TypeDefinition parameter of the Add-Type\ncmdlet.\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Define the new C# class\n$newType = @'\nusing System;\n\nnamespace PowerShellCookbook\n{\n public class AddTypeTypeDefinitionDemo\n {\n public string SayHello(string name)\n {\n string result = String.Format("Hello {0}", name);\n return result;\n }\n }\n}\n\n'@\n\n## Add it to the Powershell session\nAdd-Type -TypeDefinition $newType\n\n## Show that we can access it like any other .NET type\n$greeter = New-Object PowerShellCookbook.AddTypeTypeDefinitionDemo\n$greeter.SayHello("World");
PowerShellCorpus/PoshCode/Add new smtp_set prmary_4.ps1
Add new smtp_set prmary_4.ps1
#alias,addnewemailaddress import-csv .\\source.csv | foreach { $user = Get-Mailbox $_.alias $user.emailAddresses+= $_.addnewemailaddress $user.primarysmtpaddress = $_.addnewemailaddress Set-Mailbox $user -emailAddresses $user.emailAddresses set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress }
PowerShellCorpus/PoshCode/Yet another hex2dec.ps1
Yet another hex2dec.ps1
@set @script=0 /* @echo off set @script= if "%1" neq "" cscript //nologo //e:jscript "%~dpnx0" %1 && goto:eof if "%1" equ "?" cscript //nologo //e:jscript "%~dpnx0" %1 && goto:eof setlocal echo Hex2dec v3.07 - converts hex to decimal and vice versa echo Copyright (C) 2012-2013 greg zakharov gregzakh@gmail.com echo. echo Use "clear" to erase history and "exit" to leave session echo. :begin set /p "ask=>>> " cscript //nologo //e:jscript "%~dpnx0" "%ask%" if "%ask%" equ "clear" cls if "%ask%" equ "exit" cls & goto:eof echo. goto:begin endlocal exit /b */ var num = { hex2dec : function(n) { return Number(n) ? '0x' + n.slice(2, n.length).toUpperCase() + ' = ' + Number(n) : '=>err'; }, dec2hex : function(n) { return Number(n) ? n + ' = 0x' + Number(n).toString(16).toUpperCase() : '=>err'; }, parseData : function(n) { if (n.slice(0, 2) == '0x') return this.hex2dec(n); else if (n.slice(0, 1) == 'x') return this.hex2dec('0' + n); else return this.dec2hex(n); }, getHelp : function() { var str = WScript.ScriptName + " v3.07 - converts hex to decimal and vice versa\\n" + "Copyright (C) 2012-2013 greg zakharov gregzakh@gmail.com\\n\\n" + "Usage: " + WScript.ScriptName + " [decimal | hexadecimal]"; return str; } }; try { var arg = WScript.Arguments.Unnamed(0); switch (arg) { case "?" : WScript.echo(num.getHelp()); break; default: WScript.echo(num.parseData(arg)); break; } } catch (e) { WScript.echo(e.message + '.'); }
PowerShellCorpus/PoshCode/Test-Certificate.ps1
Test-Certificate.ps1
##################################################################### # Test-Certificate.ps1 # Version 0.63 # # Tests specified certificate for certificate chain and revocation # # Vadims Podans (c) 2009 # http://www.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Test-Certificate { <# .Synopsis Tests specified certificate for certificate chain and revocation .Description Tests specified certificate for certificate chain and revocation status for each certificate in chain exluding Root certificates .Parameter Certificate Specifies the certificate to test certificate chain. This parameter may accept X509Certificate, X509Certificate2 objects or physical file path. this paramter accept pipeline input .Parameter Password Specifies PFX file password. Password must be passed as SecureString. .Parameter CRLMode Sets revocation check mode. May contain on of the following values: Online - perform revocation check downloading CRL from CDP extension ignoring cached CRLs. Default value Offline - perform revocation check using cached CRLs if they are already downloaded NoCheck - specified certificate will not checked for revocation status (not recommended) .Parameter CRLFlag Sets revocation flags for chain elements. May contain one of the following values: ExcludeRoot - perform revocation check for each certificate in chain exluding root. Default value EntireChain - perform revocation check for each certificate in chain including root. (not recommended) EndCertificateOnly - perform revocation check for specified certificate only. .Parameter VerificationFlags Sets verification checks that will bypassed performed during certificate chaining engine check. You may specify one of the following values: NoFlag - No flags pertaining to verification are included (default). IgnoreNotTimeValid - Ignore certificates in the chain that are not valid either because they have expired or they are not yet in effect when determining certificate validity. IgnoreCtlNotTimeValid - Ignore that the certificate trust list (CTL) is not valid, for reasons such as the CTL has expired, when determining certificate verification. IgnoreNotTimeNested - Ignore that the CA (certificate authority) certificate and the issued certificate have validity periods that are not nested when verifying the certificate. For example, the CA cert can be valid from January 1 to December 1 and the issued certificate from January 2 to December 2, which would mean the validity periods are not nested. IgnoreInvalidBasicConstraints - Ignore that the basic constraints are not valid when determining certificate verification. AllowUnknownCertificateAuthority - Ignore that the chain cannot be verified due to an unknown certificate authority (CA). IgnoreWrongUsage - Ignore that the certificate was not issued for the current use when determining certificate verification. IgnoreInvalidName - Ignore that the certificate has an invalid name when determining certificate verification. IgnoreInvalidPolicy - Ignore that the certificate has invalid policy when determining certificate verification. IgnoreEndRevocationUnknown - Ignore that the end certificate (the user certificate) revocation is unknown when determining certificate verification. IgnoreCtlSignerRevocationUnknown - Ignore that the certificate trust list (CTL) signer revocation is unknown when determining certificate verification. IgnoreCertificateAuthorityRevocationUnknown - Ignore that the certificate authority revocation is unknown when determining certificate verification. IgnoreRootRevocationUnknown - Ignore that the root revocation is unknown when determining certificate verification. AllFlags - All flags pertaining to verification are included. .Example Get-ChilItem cert:\\CurrentUser\\My | Test-Certificate -CRLMode "NoCheck" Will check certificate chain for each certificate in current user Personal container. Certificates will not checked for revocation status. .Example Test-Certificate C:\\Certs\\certificate.cer -CRLFlag "EndCertificateOnly" Will check certificate chain for certificate that is located in C:\\Certs and named as Certificate.cer and revocation checking will be performed for specified certificate only .Outputs This script return general info about certificate chain status #> [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] $Certificate, [System.Security.SecureString]$Password, [System.Security.Cryptography.X509Certificates.X509RevocationMode]$CRLMode = "Online", [System.Security.Cryptography.X509Certificates.X509RevocationFlag]$CRLFlag = "ExcludeRoot", [System.Security.Cryptography.X509Certificates.X509VerificationFlags]$VerificationFlags = "NoFlag" ) begin { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain $chain.ChainPolicy.RevocationFlag = $CRLFlag $chain.ChainPolicy.RevocationMode = $CRLMode $chain.ChainPolicy.VerificationFlags = $VerificationFlags function _getstatus_ ($status, $chain, $cert) { if ($status) { Write-Host Current certificate $cert.SerialNumber chain and revocation status is valid -ForegroundColor Green } else { Write-Warning "Current certificate $($cert.SerialNumber) chain is invalid due of the following errors:" $chain.ChainStatus | %{Write-Host $_.StatusInformation.trim() -ForegroundColor Red} } } } process { if ($_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $status = $chain.Build($_) _getstatus_ $status $chain $_ } else { if (!(Test-Path $Certificate)) {Write-Warning "Specified path is invalid"; return} else { if ((Resolve-Path $Certificate).Provider.Name -ne "FileSystem") { Write-Warning "Spicifed path is not recognized as filesystem path. Try again"; return } else { $Certificate = gi $(Resolve-Path $Certificate) switch -regex ($Certificate.Extension) { "\\.CER|\\.DER|\\.CRT" {$cert.Import($Certificate.FullName)} "\\.PFX" { if (!$Password) {$Password = Read-Host "Enter password for PFX file $certificate" -AsSecureString} $cert.Import($Certificate.FullName, $password, "UserKeySet") } "\\.P7B|\\.SST" { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $cert.Import([System.IO.File]::ReadAllBytes($Certificate.FullName)) } default {Write-Warning "Looks like your specified file is not a certificate file"; return} } $cert | %{ $status = $chain.Build($_) _getstatus_ $status $chain $_ } $cert.Reset() $chain.Reset() } } } } }
PowerShellCorpus/PoshCode/Send-XmppMessage.ps1
Send-XmppMessage.ps1
# Download XMPP SDK from http://www.ag-software.de/index.php?page=agsxmpp-sdk function Send-XmppMessage { param ( $From = $( Throw "You must specify a Jabber ID for the sender." ), $Password, # Leave blank to be prompted for password $To = $( Throw "You must specify a Jabber ID for the recipient." ), $Body = $( Throw "You must specify a body for the message." ) ) # This function reads a string from the host while masking with *'s. function Read-HostMasked( [string]$prompt="Password" ) { $password = Read-Host -AsSecureString $prompt; $BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password); $password = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR); [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR); return $password; } # Set path accordingly. $assemblyPath = $(resolve-path $profiledir\\Assemblies\\agsXMPP.dll) [void][reflection.assembly]::LoadFrom( $assemblyPath ) $jidSender = New-Object agsxmpp.jid( $From ) $jidReceiver = New-Object agsxmpp.jid ( $To ) $xmppClient = New-Object agsxmpp.XmppClientConnection( $jidSender.Server ) $Message = New-Object agsXMPP.protocol.client.Message( $jidReceiver, $Body ) # The following switches may assist in troubleshooting connection issues. # If SSL and StartTLS are disabled, then you can use a network sniffer to inspect the XML #$xmppClient.UseSSL = $FALSE #$xmppClient.UseStartTLS = $FALSE # Since this function is only used to send a message, we don't care about doing the # normal discovery and requesting a roster. Leave disabled to quicken the login period. $xmppClient.AutoAgents = $FALSE $xmppClient.AutoRoster = $FALSE # Use SRV lookups to determine correct XMPP server if different from the server # portion of your JID. e.g. user@gmail.com, the server is really talk.google.com $xmppClient.AutoResolveConnectServer = $TRUE if ( !$password ) { $password = Read-HostMasked } # Open connection, then wait for it to be authenticated $xmppClient.Open( $jidSender.User, $Password ) while ( !$xmppClient.Authenticated ) { Write-Verbose $xmppClient.XmppConnectionState Start-Sleep 1 } # If server disconnects you, try enabling this #$xmppClient.SendMyPresence() $xmppClient.Send( $Message ) # Send is asynchronous, so we must wait a second before closing the connection Start-Sleep 1 $xmppClient.Close() }
PowerShellCorpus/PoshCode/SqlProxy_6.psm1.ps1
SqlProxy_6.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 "Set-SqlLoginDefaultDatabase"=10 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" try { if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } catch { $message = $_.Exception.GetBaseException().Message write-error $message } } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } else { $server.Databases | where {$_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" try { $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase $login.LoginType = $logintype if ($logintype -eq 'SqlLogin') { if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } $login.Create($password) } else { $login.Create() } $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { if ($server.Information.Version.Major -eq '8') { $login.ChangePassword($password) } else { $login.ChangePassword($password,$true,$false) } $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLoginDefaultDatabase function changes a SQL Login default database. .INPUTS None You cannot pipe objects to Set-SqlLoginDefaultDatabase .OUTPUTS None This function does not generate any output. .EXAMPLE Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master' This command sets the default database for TestPSUnit login. .LINK Set-SqlLoginDefaultDatabase #> function Set-SqlLoginDefaultDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.DefaultDatabase = $DefaultDatabase $login.Alter() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLoginDefaultDatabase ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" try { $login = $server.Logins["$name"] if ($login) { $login.Rename("$newName") $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" try { $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login $loginObject = $sqlserver.Logins["$login"] if ($database.parent.Information.Version.Major -ne '8' -and $loginObject.LoginType -ne "WindowsGroup" ) { $user.DefaultSchema = $defaultschema } $user.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" try { $user = $database.Users[$name] if ($user) { $user.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "User $name does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.AddMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.DropMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.AddMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.DropMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog