full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/SVMotion-VM_1.ps1
SVMotion-VM_1.ps1
# author: Hal Rottenberg # Website/OpenID: http://halr9000.com # purpose: does "real" SVMotion of a VM # usage: get-vm | SVMotion-VM -destination (get-datastore foo) function SVMotion-VM { param( [VMware.VimAutomation.Client20.DatastoreImpl] $destination ) Begin { $datastoreView = get-view $destination $relocationSpec = new-object VMware.Vim.VirtualMachineRelocateSpec $relocationSpec.Datastore = $datastoreView.MoRef } Process { if ( $_ -isnot VMware.VimAutomation.Client20.VirtualMachineImpl ) { Write-Error "Expected VMware object on pipeline. skipping $_" continue } $vmView = Get-View $_ $vmView.RelocateVM_Task($relocationSpec) } }
PowerShellCorpus/PoshCode/Compare-Agents_1.ps1
Compare-Agents_1.ps1
#This scripts compares the agents that are installed in two zones and #gives the agents that are not common. #Usage: #Compare-Agents.ps1 -server1 RMSServer1.contoso.com -server2 RMSServer2.contoso.com -output c:\\Temp.txt #RMSServer1 is the one whose agents are to be moved. param([string] $Server1,$Server2,$output) Function Mainone { write-host $Server1 write-host $Server2 $Temp1 = $Server1 $Temp2 = $Server2 $outfilepath = $output New-Managementgroupconnection $Temp1 set-location monitoring:\\$Temp1 $AllServer1Agents = get-agent $RMSServer1 = get-RootManagementServer write-host "Got all the agents for the first group" $RMS1name = $RMSServer1.Computername $data1 = "All the agents on " + $RMS1name New-Managementgroupconnection $Temp2 set-location monitoring:\\$Temp2 $AllServer2Agents = get-agent $RMSServer2 = get-RootManagementServer write-host "Got all the agents for the second group" #Write-data $RMSServer.ManagementGroup.name $RMS2name = $RMSServer2.Computername $data2 = "All the agents on " + $RMS2name #write-data $data2 #foreach($Agent in $AllServer2Agents) { write-data $Agent.computername} write-host "Calling the function to compare Agents" CheckAgent $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name } Function CheckAgent($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name) { write-host "Calling function to get all agents in an array" Get-Agentnames $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name } Function Get-Agentnames($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name) { $Server1Agent = @() $Server2Agent = @() foreach($A in $AllServer1Agents) { $Server1Agent = $Server1Agent + $A.Computername } foreach($B in $AllServer2Agents) { $Server2Agent = $Server2Agent + $B.Computername } Compare-theAgents $Server1Agent $Server2Agent } function Compare-theAgents($Server1Agent,$Server2Agent) { $FoundAgent = @() $NotFoundAgent = @() for($i=0; $i -lt $Server1Agent.count; $i++) { $Temp1 = $Server1Agent[$i] $Data = "Comparing element " + $Server1Agent[$i] write-host $Data for($j=0; $j -lt $Server2Agent.count; $j++) { $Temp2 = $Server2Agent[$j] #write-host $Temp2 if($Temp1 -match $Temp2) { $FoundAgent = $FoundAgent + $Temp1 $Server1Agent[$i] = "Present" } } } for($k=0; $k -lt $Server1Agent.count; $k++) { if($Server1Agent[$k] -notmatch "Present") { $NotfoundAgent = $NotFoundAgent + $Server1Agent[$k] } } write-data "These are the agents that are found common" for($k=0;$k -lt $FoundAgent.count;$k++){write-data $FoundAgent[$k]} write-data "These are the agents that are not found" for($l=0;$l -lt $NotFoundAgent.count;$l++){write-data $NotFoundAgent[$l]} } function write-data($Writedata) { out-file -filepath $outfilepath -inputobject $Writedata -append -encoding ASCII } Mainone
PowerShellCorpus/PoshCode/ISE-Snippets.ps1
ISE-Snippets.ps1
#requires -version 2.0 ## ISE-Snippets module v 1.0 ## DEVELOPED FOR CTP3 ## See comments for each function for changes ... ############################################################################################################## ## As a shortcut for every snippet would be to much, I created Add-Snippet which presents a menu. ## Feel free to add your own snippets to function Add-Snippet but please contribute your changes here ############################################################################################################## ## Provides Code Snippets for working with ISE ## Add-Snippet - Presents menu for snippet selection ## Add-SnippetToEditor - Adds a snippet at caret position ############################################################################################################## ## Add-Snippet ############################################################################################################## ## Presents menu for snippet selection ############################################################################################################## function Add-Snippet { $snippets = @{ "region" = @( "#region", "#endregion" ) "function" = @( "function FUNCTION_NAME", "{", "}" ) "param" = @( "param ``", "(", ")" ) "if" = @( "if ( CONDITION )", "{", "}" ) "else" = @( "else", "{", "}" ) "elseif" = @( "elseif ( CONDITION )", "{", "}" ) "foreach" = @( "foreach ( ITEM in COLLECTION )", "{", "}" ) "for" = @( "foreach ( INIT; CONDITION; REPEAT )", "{", "}" ) "while" = @( "while ( CONDITION )", "{", "}" ) "do .. while" = @( "do" , "{", "}", "while ( CONDITION )" ) "do .. until" = @( "do" , "{", "}", "until ( CONDITION )" ) "try" = @( "try", "{", "}" ) "catch" = @( "catch", "{", "}" ) "catch [<error type>] " = @( "catch [ERROR_TYPE]", "{", "}" ) "finaly" = @( "finaly", "{", "}" ) } Write-Host "Select snippet:" Write-Host $i = 1 $snippetIndex = @() foreach ( $snippetName in $snippets.Keys | Sort ) { Write-Host ( "{0} - {1}" -f $i++, $snippetName) $snippetIndex += $snippetName } try { [int]$choice = Read-Host ("Select 1-{0}" -f $i) if ( ( $choice -gt 0 ) -and ( $choice -lt $i ) ) { $snippetName = $snippetIndex[$choice -1] Add-SnippetToEditor $snippets[$snippetName] } else { Throw "Choice not in range" } } catch { Write-Error "Choice was not in range or not even and integer" } } ## Add-SnippetToEditor ############################################################################################################## ## Adds a snippet at caret position ############################################################################################################## function Add-SnippetToEditor { param ` ( [string[]] $snippet ) $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") $newText = @() if ( $caretLine -gt 1 ) { $newText += $text[0..($caretLine -2)] } $curLine = $text[$caretLine -1] $indent = $curline -replace "[^\\t ]", "" foreach ( $snipLine in $snippet ) { $newText += $indent + $snipLine } if ( $caretLine -ne $text.Count ) { $newText += $text[$caretLine..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, $caretColumn) } Export-ModuleMember Add-Snippet ############################################################################################################## ## Inserts command Add Snippet to custom menu ############################################################################################################## if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "Snippet" } ) ) { $null = $psISE.CustomMenu.Submenus.Add("_Snippet", {Add-Snippet}, "Ctrl+Alt+S") }
PowerShellCorpus/PoshCode/Set-WebConfig.ps1
Set-WebConfig.ps1
function Set-WebConfigSqlConnectionString { param( [switch]$help, [string]$configfile = $(read-host "Please enter a web.config file to read"), [string]$connectionString = $(read-host "Please enter a connection string"), [switch]$backup = $TRUE ) $usage = "`$conString = `"Data Source=MyDBname;Initial Catalog=serverName;Integrated Security=True;User Instance=True`"`n" $usage += "`"Set-WebConfigSqlConnectionString -configfile `"C:\\Inetpub\\wwwroot\\myapp\\web.config`" -connectionString `$conString" if ($help) {Write-Host $usage} $webConfigPath = (Resolve-Path $configfile).Path $backup = $webConfigPath + ".bak" # Get the content of the config file and cast it to XML and save a backup copy labeled .bak $xml = [xml](get-content $webConfigPath) #save a backup copy if requested if ($backup) {$xml.Save($backup)} $root = $xml.get_DocumentElement(); $root.connectionStrings.add.connectionString = $connectionString # Save it $xml.Save($webConfigPath) }
PowerShellCorpus/PoshCode/Save-Credentials_1.ps1
Save-Credentials_1.ps1
<# .SYNOPSIS The script saves a username and password, encrypted with a custom key to to a file. .DESCRIPTION The script saves a username and password, encrypted with a custom key to to a file. The key is coded into the script but should be changed before use. The key allows the password to be decrypted by any user who has the key, on any machine. if the key parameter is omitted from ConvertFrom-SecureString, only the user who generated the file on the computer that generated the file can decrypt the password. see http://bsonposh.com/archives/254 for more info. To retrieve the password: $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 $VCCred = Import-Csv 'C:\\PATH\\FILE.TXT' $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) .NOTES File Name : SaveCredentials.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://poshcode.org/3485 .EXAMPLE Call the script with .\\SaveCredentials.ps1 no arguments or parameters are required #> $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 Write-Host "Key length is:" $key.length "The key length is acceptable if 16 or 32" Write-Host "This script saves a username and password into a file" Write-Host "Select an output file:" [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |Out-Null $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog $SaveFileDialog.initialDirectory = $initialDirectory $SaveFileDialog.filter = "All files (*.*)| *.*" $SaveFileDialog.ShowDialog() | Out-Null $OutFile = $SaveFileDialog.filename $null | Out-File -FilePath $Outfile $credential = Get-Credential #| ConvertFrom-SecureString -Key $key) $obj = New-Object -typename System.Object $obj | Add-Member -MemberType noteProperty -name Username -value $credential.UserName $obj | Add-Member -MemberType noteProperty -name Password -value ($credential.Password | ConvertFrom-SecureString -key $key) $obj | Export-Csv -Path $OutFile write-host "Username and password have been saved to $outfile"
PowerShellCorpus/PoshCode/Import-NmapXML.ps1
Import-NmapXML.ps1
#Requires -Version 2.0 function Import-NmapXML { #################################################################################### #.Synopsis # Parse XML output files of the nmap port scanner (www.nmap.org). # #.Description # Parse XML output files of the nmap port scanner (www.nmap.org) and # emit custom objects with properties containing the scan data. The # script can accept either piped or parameter input. The script can be # safely dot-sourced without error as is. # #.Parameter Path # Either 1) a string with or without wildcards to one or more XML output # files, or 2) one or more FileInfo objects representing XML output files. # #.Parameter OutputDelimiter # The delimiter for the strings in the OS, Ports and Services properties. # Default is a newline. Change it when you want single-line output. # #.Parameter RunStatsOnly # Only displays general scan information from each XML output file, such # as scan start/stop time, elapsed time, command-line arguments, etc. # #.Parameter ShowProgress # Prints progress information to StdErr while processing host entries. # #.Example # dir *.xml | Import-NMAPXML # #.Example # Import-NmapXML -path onefile.xml # Import-NmapXML -path *files.xml # #.Example # $files = dir *some.xml,others*.xml # Import-NmapXML -path $files # #.Example # Import-NmapXML -path scanfile.xml -runstatsonly # #.Example # Import-NmapXML scanfile.xml -OutputDelimiter " " # #Requires -Version 2.0 # #.Notes # Author: Jason Fossen (http://blogs.sans.org/windows-security/) # Edited: Justin Grote <justin+powershell NOSPAMAT grote NOSPAMDOT name> # Version: 3.6.1-JWG1 # Updated: 02.Feb.2011 # LEGAL: PUBLIC DOMAIN. SCRIPT PROVIDED "AS IS" WITH NO WARRANTIES OR GUARANTEES OF # ANY KIND, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY AND/OR FITNESS FOR # A PARTICULAR PURPOSE. ALL RISKS OF DAMAGE REMAINS WITH THE USER, EVEN IF # THE AUTHOR, SUPPLIER OR DISTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF # ANY SUCH DAMAGE. IF YOUR STATE DOES NOT PERMIT THE COMPLETE LIMITATION OF # LIABILITY, THEN DELETE THIS FILE SINCE YOU ARE NOW PROHIBITED TO HAVE IT. #################################################################################### [CmdletBinding()] param ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$Path, [String] $OutputDelimiter = "`n", [Switch] $RunStatsOnly, [Switch] $ShowProgress ) if ($Path -match "/\\?|/help|-h|-help|--h|--help") { "`nPurpose: Process nmap XML output files (www.nmap.org).`n" "Example: Import-NmapXML scanfile.xml" "Example: Import-NmapXML *.xml -runstatsonly `n" exit } if ($Path -eq $null) {$Path = @(); $input | foreach { $Path += $_ } } if (($Path -ne $null) -and ($Path.gettype().name -eq "String")) {$Path = dir $path} #To support wildcards in $path. $1970 = [DateTime] "01 Jan 1970 01:00:00 GMT" if ($RunStatsOnly) { ForEach ($file in $Path) { $xmldoc = new-object System.XML.XMLdocument $xmldoc.Load($file) $stat = ($stat = " " | select-object FilePath,FileName,Scanner,Profile,ProfileName,Hint,ScanName,Arguments,Options,NmapVersion,XmlOutputVersion,StartTime,FinishedTime,ElapsedSeconds,ScanTypes,TcpPorts,UdpPorts,IpProtocols,SctpPorts,VerboseLevel,DebuggingLevel,HostsUp,HostsDown,HostsTotal) $stat.FilePath = $file.fullname $stat.FileName = $file.name $stat.Scanner = $xmldoc.nmaprun.scanner $stat.Profile = $xmldoc.nmaprun.profile $stat.ProfileName = $xmldoc.nmaprun.profile_name $stat.Hint = $xmldoc.nmaprun.hint $stat.ScanName = $xmldoc.nmaprun.scan_name $stat.Arguments = $xmldoc.nmaprun.args $stat.Options = $xmldoc.nmaprun.options $stat.NmapVersion = $xmldoc.nmaprun.version $stat.XmlOutputVersion = $xmldoc.nmaprun.xmloutputversion $stat.StartTime = $1970.AddSeconds($xmldoc.nmaprun.start) $stat.FinishedTime = $1970.AddSeconds($xmldoc.nmaprun.runstats.finished.time) $stat.ElapsedSeconds = $xmldoc.nmaprun.runstats.finished.elapsed $xmldoc.nmaprun.scaninfo | foreach { $stat.ScanTypes += $_.type + " " $services = $_.services #Seems unnecessary, but solves a problem. if ($services.contains("-")) { #In the original XML, ranges of ports are summarized, e.g., "500-522", #but the script will list each port separately for easier searching. $array = $($services.replace("-","..")).Split(",") $temp = @($array | where { $_ -notlike "*..*" }) $array | where { $_ -like "*..*" } | foreach { invoke-expression "$_" } | foreach { $temp += $_ } $temp = [Int32[]] $temp | sort $services = [String]::Join(",",$temp) } switch ($_.protocol) { "tcp" { $stat.TcpPorts = $services ; break } "udp" { $stat.UdpPorts = $services ; break } "ip" { $stat.IpProtocols = $services ; break } "sctp" { $stat.SctpPorts = $services ; break } } } $stat.ScanTypes = $($stat.ScanTypes).Trim() $stat.VerboseLevel = $xmldoc.nmaprun.verbose.level $stat.DebuggingLevel = $xmldoc.nmaprun.debugging.level $stat.HostsUp = $xmldoc.nmaprun.runstats.hosts.up $stat.HostsDown = $xmldoc.nmaprun.runstats.hosts.down $stat.HostsTotal = $xmldoc.nmaprun.runstats.hosts.total $stat } return #Don't process hosts. } ForEach ($file in $Path) { If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Starting $file" ) } $xmldoc = new-object System.XML.XMLdocument $xmldoc.Load($file) # Process each of the <host> nodes from the nmap report. $i = 0 #Counter for <host> nodes processed. $xmldoc.nmaprun.host | foreach-object { $hostnode = $_ # $hostnode is a <host> node in the XML. # Init variables, with $entry being the custom object for each <host>. $service = " " #service needs to be a single space. $entry = ($entry = " " | select-object FQDN, HostName, Status, IPv4, IPv6, MAC, Ports, Services, OS, Script) # Extract state element of status: $entry.Status = $hostnode.status.state.Trim() if ($entry.Status.length -lt 2) { $entry.Status = "<no-status>" } # Extract fully-qualified domain name(s), removing any duplicates. $hostnode.hostnames.hostname | foreach-object { $entry.FQDN += $_.name + " " } $entry.FQDN = [System.String]::Join(" ",@($entry.FQDN.Trim().Split(" ") | sort-object -unique)) #Avoid -Join and -Split for now if ($entry.FQDN.Length -eq 0) { $entry.FQDN = "<no-fullname>" } # Note that this code cheats, it only gets the hostname of the first FQDN if there are multiple FQDNs. if ($entry.FQDN.Contains(".")) { $entry.HostName = $entry.FQDN.Substring(0,$entry.FQDN.IndexOf(".")) } elseif ($entry.FQDN -eq "<no-fullname>") { $entry.HostName = "<no-hostname>" } else { $entry.HostName = $entry.FQDN } # Process each of the <address> nodes, extracting by type. $hostnode.address | foreach-object { if ($_.addrtype -eq "ipv4") { $entry.IPv4 += $_.addr + " "} if ($_.addrtype -eq "ipv6") { $entry.IPv6 += $_.addr + " "} if ($_.addrtype -eq "mac") { $entry.MAC += $_.addr + " "} } if ($entry.IPv4 -eq $null) { $entry.IPv4 = "<no-ipv4>" } else { $entry.IPv4 = $entry.IPv4.Trim()} if ($entry.IPv6 -eq $null) { $entry.IPv6 = "<no-ipv6>" } else { $entry.IPv6 = $entry.IPv6.Trim()} if ($entry.MAC -eq $null) { $entry.MAC = "<no-mac>" } else { $entry.MAC = $entry.MAC.Trim() } # Process all ports from <ports><port>, and note that <port> does not contain an array if it only has one item in it. if ($hostnode.ports.port -eq $null) { $entry.Ports = "<no-ports>" ; $entry.Services = "<no-services>" } else { $hostnode.ports.port | foreach-object { if ($_.service.name -eq $null) { $service = "unknown" } else { $service = $_.service.name } $entry.Ports += $_.state.state + ":" + $_.protocol + ":" + $_.portid + ":" + $service + $OutputDelimiter # Build Services property. What a mess...but exclude non-open/non-open|filtered ports and blank service info, and exclude servicefp too for the sake of tidiness. if ($_.state.state -like "open*" -and ($_.service.tunnel.length -gt 2 -or $_.service.product.length -gt 2 -or $_.service.proto.length -gt 2)) { $entry.Services += $_.protocol + ":" + $_.portid + ":" + $service + ":" + ($_.service.product + " " + $_.service.version + " " + $_.service.tunnel + " " + $_.service.proto + " " + $_.service.rpcnum).Trim() + " <" + ([Int] $_.service.conf * 10) + "%-confidence>$OutputDelimiter" } } $entry.Ports = $entry.Ports.Trim() if ($entry.Services -eq $null) { $entry.Services = "<no-services>" } else { $entry.Services = $entry.Services.Trim() } } # Extract fingerprinted OS type and percent of accuracy. $hostnode.os.osmatch | foreach-object {$entry.OS += $_.name + " <" + ([String] $_.accuracy) + "%-accuracy>$OutputDelimiter"} $hostnode.os.osclass | foreach-object {$entry.OS += $_.type + " " + $_.vendor + " " + $_.osfamily + " " + $_.osgen + " <" + ([String] $_.accuracy) + "%-accuracy>$OutputDelimiter"} $entry.OS = $entry.OS.Replace(" "," ") $entry.OS = $entry.OS.Replace("<%-accuracy>","") #Sometimes no osmatch. $entry.OS = $entry.OS.Trim() if ($entry.OS.length -lt 16) { $entry.OS = "<no-os>" } # Extract script output, first for port scripts, then for host scripts. $hostnode.ports.port | foreach-object { if ($_.script -ne $null) { $entry.Script += "<PortScript id=""" + $_.script.id + """>$OutputDelimiter" + ($_.script.output -replace "`n","$OutputDelimiter") + "$OutputDelimiter</PortScript> $OutputDelimiter $OutputDelimiter" } } if ($hostnode.hostscript -ne $null) { $hostnode.hostscript.script | foreach-object { $entry.Script += '<HostScript id="' + $_.id + '">' + $OutputDelimiter + ($_.output.replace("`n","$OutputDelimiter")) + "$OutputDelimiter</HostScript> $OutputDelimiter $OutputDelimiter" } } if ($entry.Script -eq $null) { $entry.Script = "<no-script>" } # Emit custom object from script. $i++ #Progress counter... $entry } If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Finished $file, processed $i entries." ) } } }
PowerShellCorpus/PoshCode/LibrarySqlBackup_1.ps1
LibrarySqlBackup_1.ps1
# --------------------------------------------------------------------------- ### From the Apress book "Pro Windows PowerShell" p. 164 I found the following trap handler that will get to the InnerException.Message # --------------------------------------------------------------------------- trap { $exceptiontype = $_.Exception.gettype() $InnerExceptionType = "no inner exception" if($_.Exception.InnerException) { $InnerExceptionType = $_.Exception.InnerException.GetType() # RV - Added following line to display message $_.Exception.InnerException.Message } "FullyQualifiedErrorID: $($_.FullyQualifiedErrorID)" "Exception: $exceptionType" "InnerException: $innerExceptionType" continue }
PowerShellCorpus/PoshCode/Get-WebFile 4.1.ps1
Get-WebFile 4.1.ps1
function ConvertTo-Dictionary { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Hashtable")] [Hashtable[]]$Hashtable, [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="WebHeaders")] [System.Collections.Specialized.NameObjectCollectionBase]$Headers, [Parameter(Mandatory=$true,ParameterSetName="Hashtable")] [Type]$TKey, [Parameter(Mandatory=$true,ParameterSetName="Hashtable")] [Type]$Tvalue ) begin { switch($PSCmdlet.ParameterSetName) { "Hashtable" { $dictionary = New-Object "System.Collections.Generic.Dictionary[[$($TKey.FullName)],[$($TValue.FullName)]]" } "WebHeaders" { $dictionary = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" } } } process { switch($PSCmdlet.ParameterSetName) { "Hashtable" { foreach($ht in $Hashtable) { foreach($key in $ht.Keys) { $dictionary.Add( $key, $ht.$key ) } } } "WebHeaders" { foreach($key in $Headers.AllKeys) { $dictionary.Add($key, $Headers[$key]) } } } } end { return $dictionary } } function ConvertFrom-Dictionary { [CmdletBinding()] param($Dictionary, [Switch]$Encode) foreach($key in $Dictionary.Keys) { "{0} = {1}" -f $key, $( if($Encode) { [System.Net.WebUtility]::UrlEncode( $Dictionary.$key ) } else { $Dictionary.$key } ) } } ## Get-WebFile (aka wget for PowerShell) function Invoke-Web { #.Synopsis # Downloads a file or page from the web, or sends web API posts/requests #.Description # Creates an HttpWebRequest to download a web file or post data #.Example # Invoke-Web http://PoshCode.org/PoshCode.psm1 # # Downloads the latest version of the PoshCode module to the current directory #.Example # Invoke-Web http://PoshCode.org/PoshCode.psm1 ~\\Documents\\WindowsPowerShell\\Modules\\PoshCode\\ # # Downloads the latest version of the PoshCode module to the default PoshCode module directory... #.Example # $RssItems = @(([xml](Invoke-Web http://poshcode.org/api/ -passthru)).rss.channel.GetElementsByTagName("item")) # # Returns the most recent items from the PoshCode.org RSS feed #.Notes # History: # v4.1 - Reworked most of it with PowerShell 3's Invoke-WebRequest as inspiration # - Added a bunch of parameters, the ability to do PUTs etc., and session/cookie persistence # - Did NOT parse the return code and get you the FORMs the way PowerShell 3 does -- upgrade! ;) # v3.12 - Added full help # v3.9 - Fixed and replaced the Set-DownloadFlag # v3.7 - Removed the Set-DownloadFlag code because it was throwing on Windows 7: # "Attempted to read or write protected memory." # v3.6.6 Add UserAgent calculation and parameter # v3.6.5 Add file-name guessing and cleanup # 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) [CmdletBinding(DefaultParameterSetName="NoSession")] param( # The URL of the file/page to download [Parameter(Mandatory=$true,Position=0)] [System.Uri][Alias("Url")]$Uri # = (Read-Host "The URL to download") , # Specifies the body of the request. The body is the content of the request that follows the headers. # You can also pipe a request body to Invoke-WebRequest # Note that you should probably set the ContentType if you're setting the Body [Parameter(ValueFromPipeline=$true)] $Body , # Specifies the content type of the web request, such as "application/x-www-form-urlencoded" (defaults to "application/x-www-form-urlencoded" if the Body is set to a hashtable, dictionary, or other NameValueCollection) [String]$ContentType , # Specifies the client certificate that is used for a secure web request. Enter a variable that contains a certificate or a command or expression that gets the certificate. # To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have sufficient authority, the command fails. [System.Security.Cryptography.X509Certificates.X509Certificate[]] $Certificate , # Sends the results to the specified output file. Enter a path and file name. If you omit the path, the default is the current location. # By default, Invoke-WebRequest returns the results to the pipeline. To send the results to a file and to the pipeline, use the Passthru parameter. [string]$OutFile , # Leave the file unblocked instead of blocked [Switch]$Unblocked , # Rather than saving the downloaded content to a file, output it. # This is for text documents like web pages and rss feeds, and allows you to avoid temporarily caching the text in a file. [switch]$Passthru , # Supresses the Write-Progress during download [switch]$Quiet , # Specifies a name for the session variable. Enter a variable name without the dollar sign ($) symbol. # When you use the session variable in a web request, the variable is populated with a WebRequestSession object. # You cannot use the SessionVariable and WebSession parameters in the same command [Parameter(Mandatory=$true,ParameterSetName="CreateSession")] [String]$SessionVariable , # Specifies a web request session to store data for subsequent requests. # You cannot use the SessionVariable and WebSession parameters in the same command [Parameter(Mandatory=$true,ParameterSetName="UseSession")] $WebSession , # Pass the default credentials [switch]$UseDefaultCredentials , # Specifies a user account that has permission to send the request. The default is the current user. # Type a user name, such as "User01" or "Domain01\\User01", or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] [Alias("")]$Credential = [System.Management.Automation.PSCredential]::Empty , # Sets the KeepAlive value in the HTTP header to False. By default, KeepAlive is True. KeepAlive establishes a persistent connection to the server to facilitate subsequent requests. $DisableKeepAlive , # Specifies the headers for the web request. Enter a hash table or dictionary. [System.Collections.IDictionary]$Headers , # Determines how many times Windows PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. # Our default value is 5 (but .Net's default is 50). A value of 0 (zero) prevents all redirection. [int]$MaximumRedirection = 5 , # Specifies the method used for the web request. Valid values are Default, Delete, Get, Head, Options, Post, Put, and Trace. Default value is Get. [ValidateSet("Default", "Delete", "Get", "Head", "Options", "Post", "Put", "Trace")] [String]$Method = "Get" , # Uses a proxy server for the request, rather than connecting directly to the Internet resource. Enter the URI of a network proxy server. # Note: if you have a default proxy configured in your internet settings, there is no need to set it here. [Uri]$Proxy , # Pass the default credentials to the Proxy [switch]$ProxyUseDefaultCredentials , # Pass specific credentials to the Proxy [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $ProxyCredential= [System.Management.Automation.PSCredential]::Empty , # Text to include at the front of the UserAgent string [string]$UserAgent = "Mozilla/5.0 (Windows NT; Windows NT $([Environment]::OSVersion.Version.ToString(2)); $PSUICulture) WindowsPowerShell/$($PSVersionTable.PSVersion.ToString(2)); PoshCode/4.0; http://PoshCode.org" ) process { Write-Verbose "Downloading '$Uri'" $EAP,$ErrorActionPreference = $ErrorActionPreference, "Stop" $request = [System.Net.HttpWebRequest]::Create($Uri) if($DebugPreference -ne "SilentlyContinue") { Set-Variable WebRequest -Scope 2 -Value $request } $ErrorActionPreference = $EAP # Not everything is a GET request ... $request.Method = $Method.ToUpper() # Now that we have a web request, we'll use the session values first if we have any if($WebSession) { $request.CookieContainer = $WebSession.Cookies $request.Headers = $WebSession.Headers if($WebSession.UseDefaultCredentials) { $request.UseDefaultCredentials } elseif($WebSession.Credentials) { $request.Credentials = $WebSession.Credentials } $request.ClientCertificates = $WebSession.Certificates $request.UserAgent = $WebSession.UserAgent $request.Proxy = $WebSession.Proxy $request.MaximumAutomaticRedirections = $WebSession.MaximumRedirection } else { $request.CookieContainer = $Cookies = New-Object System.Net.CookieContainer } # And override session values with user values if they provided any $request.UserAgent = $UserAgent $request.MaximumAutomaticRedirections = $MaximumRedirection $request.KeepAlive = !$DisableKeepAlive # Authentication normally uses EITHER credentials or certificates, but what do I know ... if($Certificate) { $request.ClientCertificates.AddRange($Certificate) } if($UseDefaultCredentials) { $request.UseDefaultCredentials = $true } elseif($Credential -ne [System.Management.Automation.PSCredential]::Empty) { $request.Credentials = $Credential.GetNetworkCredential() } # You don't have to specify a proxy to specify proxy credentials (maybe your default proxy takes creds) if($Proxy) { $request.Proxy = New-Object System.Net.WebProxy $Proxy } if($request.Proxy -ne $null) { if($ProxyUseDefaultCredentials) { $request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials } elseif($ProxyCredentials -ne [System.Management.Automation.PSCredential]::Empty) { $request.Proxy.Credentials = $ProxyCredentials } } if($SessionVariable) { Set-Variable $SessionVariable -Scope 1 -Value $WebSession } if($Headers) { foreach($h in $Headers.Keys) { $request.Headers.Add($h, $Headers[$h]) } } if($Body) { $writer = $request.GetRequestStream(); if($Body -is [System.Collections.IDictionary] -or $Body -is [System.Collections.Specialized.NameObjectCollectionBase]) { if(!$ContentType) { $ContentType = "application/x-www-form-urlencoded" } [String]$Body = ConvertFrom-Dictionary $Body -Encode $($ContentType -eq "application/x-www-form-urlencoded") } else { $Body = $Body | Out-String } $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($Body); $request.ContentType = $ContentType $request.ContentLength = $bytes.Length $writer.Write($bytes, 0, $bytes.Length) $writer.Close() } try { $response = $request.GetResponse(); if($DebugPreference -ne "SilentlyContinue") { Set-Variable WebResponse -Scope 2 -Value $response } } catch [System.Net.WebException] { Write-Error $_.Exception -Category ResourceUnavailable return } catch { # Extra catch just in case, I can't remember what might fall here Write-Error $_.Exception -Category NotImplemented return } Write-Verbose "Retrieved $($Response.ResponseUri)" if((Test-Path variable:response) -and $response.StatusCode -eq 200) { # Magics to figure out a file location based on the response if($OutFile -and !(Split-Path $OutFile)) { $OutFile = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $OutFile } elseif((!$Passthru -and !$OutFile) -or ($OutFile -and (Test-Path -PathType "Container" $OutFile))) { [string]$OutFile = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value $OutFile = $OutFile.trim("\\/""'") $ofs = "" $OutFile = [Regex]::Replace($OutFile, "[$([Regex]::Escape(""$([System.IO.Path]::GetInvalidPathChars())$([IO.Path]::AltDirectorySeparatorChar)$([IO.Path]::DirectorySeparatorChar)""))]", "_") $ofs = " " if(!$OutFile) { $OutFile = $response.ResponseUri.Segments[-1] $OutFile = $OutFile.trim("\\/") if(!$OutFile) { $OutFile = Read-Host "Please provide a file name" } $OutFile = $OutFile.trim("\\/") if(!([IO.FileInfo]$OutFile).Extension) { $OutFile = $OutFile + "." + $response.ContentType.Split(";")[0].Split("/")[1] } } $OutFile = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $OutFile } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $response.CharacterSet ) [string]$output = "" } [int]$goal = $response.ContentLength $reader = $response.GetResponseStream() if($OutFile) { try { $writer = new-object System.IO.FileStream $OutFile, "Create" } catch { # Catch just in case, lots of things could go wrong ... Write-Error $_.Exception -Category WriteError return } } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); Write-Verbose "Read $count" if($OutFile) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $Uri" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $Uri" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($OutFile) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } if(Test-Path variable:response) { $response.Close(); } if($SessionVariable) { Set-Variable $SessionVariable -Scope 1 -Value ([PSCustomObject]@{ Headers = ConvertTo-Dictionary -Headers $request.Headers Cookies = $response.Cookies UseDefaultCredentials = $request.UseDefaultCredentials Credentials = $request.Credentials Certificates = $request.ClientCertificates UserAgent = $request.UserAgent Proxy = $request.Proxy MaximumRedirection = $request.MaximumAutomaticRedirections }) } if($WebSession) { $WebSession.Cookies = $response.Cookies } }}
PowerShellCorpus/PoshCode/Get-LocalGroups.ps1
Get-LocalGroups.ps1
function Add-NoteProperty { <# .Synopsis Adds a NoteProperty member to an object. .Description This function makes adding a property a lot easier than Add-Member, assuming you want to add a NoteProperty, which I find is true about 90% of the time. .Parameter object The object to add the property to. .Parameter name The name of the new property. .Parameter value The object to add as the property. .Example # Create a new custom object and add some properties. PS> $custom_obj = New-Object PSObject PS> Add-NoteProperty $custom_obj Name 'Custom' PS> Add-NoteProperty $custom_obj Value 42 .Example # Add a NoteProperty by passing the object to be modified down the pipeline. PS> $bunch_of_objects | Add-NoteProperty -name 'meaning_of_life' -value 42 .Notes NAME: Add-NoteProperty AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] $object, [Parameter(Mandatory = $true, Position = 1)] [string]$name, [Parameter(Mandatory = $true, Position = 2)] $value) BEGIN{} PROCESS{ $object | Add-Member -MemberType NoteProperty ` -Name $name ` -Value $property } END{} } function Get-COMProperty{ <# .Synopsis Gets a property of a __ComObject object. .Description This function calls the InvokeMember static method of the class to get properties that aren't directly exposed to PowerShell, such as local group members found by calling Members() on a DirectoryServices group object. .Parameter com_object The object to retrieve the property from. .Parameter property_name The name of the property. .Example # Get the names of all members of a group. PS> [adsi]$computer = 'WinNT://servername' PS> $groups = $groups = $computer.psbase.children | >> ?{$_.psbase.schemaclassname -eq 'group'} PS> $groups[0].Members() | %{Get-COMProperty $_ 'Name'} .Notes NAME: Get-COMProperty AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, Position = 1)] $com_object, [Parameter(Mandatory = $true, Position = 2)] [string]$property_name) [string]$property = $com_object.GetType().InvokeMember($property_name, 'GetProperty', $null, $com_object, $null) Write-Output $property } function Get-LocalGroups{ <# .Synopsis Gets a list of objects with information about local groups and their members. .Description This function returns a list of custom PSObjects that are a list of local groups on a computer. Each object has a property called Members that is a list of PSObjects representing each member, with Name, Domain, and ADSPath. .Parameter computername The object to retrieve the property from. .Example # Get a list of groups from a server. PS> Get-LocalGroups servername .Notes NAME: Get-LocalGroups AUTHOR: Tim Johnson <tojo2000@tojo200.com> FILE: LocalGroups.psm1 #> param([Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$computername = $env:computername) BEGIN{} PROCESS{ $output = @() [adsi]$computer = "WinNT://$computername" $groups = $computer.psbase.children | ?{$_.psbase.schemaclassname -eq 'group'} foreach ($group in $groups) { $members = @() $grp_obj = New-Object PSObject Add-NoteProperty $grp_obj 'Name' $group.Name.ToString() Add-NoteProperty $grp_obj 'aDSPath' $group.aDSPath.ToString() foreach ($user in $group.Members()){ $usr_obj = New-Object PSObject Add-NoteProperty $usr_obj 'aDSPath' (Get-COMProperty $user 'aDSPath') Add-NoteProperty $usr_obj 'Name' (Get-COMProperty $user 'Name') $path = $usr_obj.aDSPath.split('/') if ($path.Count -eq 4){ Add-NoteProperty $usr_obj 'Domain' $path[2] }elseif ($path.Count -eq 5) { Add-NoteProperty $usr_obj 'Domain' $path[3] }else{ Add-NoteProperty $usr_obj 'Domain' 'Unknown' } $members += $usr_obj } Add-NoteProperty $grp_obj 'Members' $members Write-Output $grp_obj } } END{} }
PowerShellCorpus/PoshCode/Binary Clock.ps1
Binary Clock.ps1
<# .SYNOPSIS This is a binary clock that lists the time in hours, minutes and seconds .DESCRIPTION This is a binary clock that lists the time in hours, minutes and seconds. Also available is the ability to display the time in a "human readable" format, display the date and display a helper display showoing how to read the binary numbers to determine the time. Tips: Use the "h" key show and hide the helper column to better understand what the binary values are. Use the "d" key to show and hide the current date. Use the "t" key to show the time in a more "human readable" format. .NOTES Name: BinaryClock/ps1 Author: Boe Prox DateCreated: 07/05/2011 Version 1.0 #> $rs = [RunspaceFactory]::CreateRunspace() $rs.ApartmentState = “STA” $rs.ThreadOptions = “ReuseThread” $rs.Open() $psCmd = {Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase}.GetPowerShell() $psCmd.Runspace = $rs $psCmd.Invoke() $psCmd.Commands.Clear() $psCmd.AddScript({ #Load Required Assemblies Add-Type –assemblyName PresentationFramework Add-Type –assemblyName PresentationCore Add-Type –assemblyName WindowsBase [xml]$xaml = @" <Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name='Window' Title='Binary Clock' WindowStartupLocation = 'CenterScreen' Width = '205' Height = '196' ShowInTaskbar = 'True' ResizeMode = 'NoResize' > <Window.Background> <LinearGradientBrush StartPoint='0,0' EndPoint='0,1'> <LinearGradientBrush.GradientStops> <GradientStop Color='#C4CBD8' Offset='0' /> <GradientStop Color='#E6EAF5' Offset='0.2' /> <GradientStop Color='#CFD7E2' Offset='0.9' /> <GradientStop Color='#C4CBD8' Offset='1' /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Window.Background> <Grid x:Name = 'Grid1' HorizontalAlignment="Stretch" ShowGridLines='False'> <Grid.ColumnDefinitions> <ColumnDefinition x:Name = 'Column1' Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition x:Name = 'helpcolumn' Width="0"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition x:Name = 'daterow' Height = '0'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> <RowDefinition x:Name = 'timerow' Height = '0'/> </Grid.RowDefinitions> <RadioButton x:Name = 'HourA0' IsChecked = 'False' GroupName = 'A' Grid.Row = '4' Grid.Column = '0' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'HourA1' IsChecked = 'False' GroupName = 'B' Grid.Row = '3' Grid.Column = '0' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'HourB0' IsChecked = 'False' GroupName = 'C' Grid.Row = '4' Grid.Column = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'HourB1' IsChecked = 'False' GroupName = 'D' Grid.Row = '3' Grid.Column = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'HourB2' IsChecked = 'False' GroupName = 'E' Grid.Row = '2' Grid.Column = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'HourB3' IsChecked = 'False' GroupName = 'F' Grid.Row = '1' Grid.Column = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteA0' IsChecked = 'False' GroupName = 'G' Grid.Row = '4' Grid.Column = '3' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteA1' IsChecked = 'False' GroupName = 'H' Grid.Row = '3' Grid.Column = '3' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteA2' IsChecked = 'False' GroupName = 'I' Grid.Row = '2' Grid.Column = '3' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteB0' IsChecked = 'False' GroupName = 'J' Grid.Row = '4' Grid.Column = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteB1' IsChecked = 'False' GroupName = 'K' Grid.Row = '3' Grid.Column = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteB2' IsChecked = 'False' GroupName = 'L' Grid.Row = '2' Grid.Column = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'MinuteB3' IsChecked = 'False' GroupName = 'M' Grid.Row = '1' Grid.Column = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondA0' IsChecked = 'False' GroupName = 'N' Grid.Row = '4' Grid.Column = '6' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondA1' IsChecked = 'False' GroupName = 'O' Grid.Row = '3' Grid.Column = '6' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondA2' IsChecked = 'False' GroupName = 'P' Grid.Row = '2' Grid.Column = '6' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondB0' IsChecked = 'False' GroupName = 'Q' Grid.Row = '4' Grid.Column = '7' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondB1' IsChecked = 'False' GroupName = 'R' Grid.Row = '3' Grid.Column = '7' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondB2' IsChecked = 'False' GroupName = 'S' Grid.Row = '2' Grid.Column = '7' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <RadioButton x:Name = 'SecondB3' IsChecked = 'False' GroupName = 'T' Grid.Row = '1' Grid.Column = '7' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '4' Grid.Column = '8' Content = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '3' Grid.Column = '8' Content = '2' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '2' Grid.Column = '8' Content = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '1' Grid.Column = '8' Content = '8' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' x:Name = 'H1Label' Grid.Row = '5' Grid.Column = '0' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' x:Name = 'H2Label' Grid.Row = '5' Grid.Column = '1' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '5' Grid.Column = '2' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' Content = ":" /> <Label FontWeight = 'Bold' x:Name = 'M1Label' Grid.Row = '5' Grid.Column = '3' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' x:Name = 'M2Label' Grid.Row = '5' Grid.Column = '4' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' Grid.Row = '5' Grid.Column = '5' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' Content = ":" /> <Label FontWeight = 'Bold' x:Name = 'S1Label' Grid.Row = '5' Grid.Column = '6' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' x:Name = 'S2Label' Grid.Row = '5' Grid.Column = '7' HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> <Label FontWeight = 'Bold' x:Name = 'datelabel' Grid.Row = '0' Grid.Column = '1' Grid.ColumnSpan = "6" HorizontalAlignment = 'Center' VerticalAlignment = 'Center' /> </Grid> </Window> "@ $reader=(New-Object System.Xml.XmlNodeReader $xaml) $Global:Window=[Windows.Markup.XamlReader]::Load( $reader ) $datelabel = $Global:window.FindName("datelabel") $H1Label = $Global:window.FindName("H1Label") $H2Label = $Global:window.FindName("H2Label") $M1Label = $Global:window.FindName("M1Label") $M2Label = $Global:window.FindName("M2Label") $S1Label = $Global:window.FindName("S1Label") $S2Label = $Global:window.FindName("S2Label") $timerow = $Global:window.FindName("timerow") $daterow = $Global:window.FindName("daterow") $helpcolumn = $Global:window.FindName("helpcolumn") $Global:Column1 = $Global:window.FindName("Column1") $Global:Grid = $column1.parent ##Events #Show helper column $Global:Window.Add_KeyDown({ If ($_.Key -eq "h") { Switch ($helpcolumn.width) { "*" {$helpcolumn.width = "0"} 0 {$helpcolumn.width = "*"} } } }) #Show time column $Global:Window.Add_KeyDown({ If ($_.Key -eq "t") { Switch ($timerow.height) { "*" {$timerow.height = "0"} 0 {$timerow.height = "*"} } } }) #Show date column $Global:Window.Add_KeyDown({ If ($_.Key -eq "d") { Switch ($daterow.height) { "*" {$daterow.height = "0"} 0 {$daterow.height = "*"} } } }) $update = { $datelabel.content = Get-Date -f D $hourA,$hourB = [string](Get-Date -f HH) -split "" | Where {$_} $minuteA,$minuteB = [string](Get-Date -f mm) -split "" | Where {$_} $secondA,$secondB = [string](Get-Date -f ss) -split "" | Where {$_} $hourAradio = $grid.children | Where {$_.Name -like "hourA*"} $minuteAradio = $grid.children | Where {$_.Name -like "minuteA*"} $secondAradio = $grid.children | Where {$_.Name -like "secondA*"} $hourBradio = $grid.children | Where {$_.Name -like "hourB*"} $minuteBradio = $grid.children | Where {$_.Name -like "minuteB*"} $secondBradio = $grid.children | Where {$_.Name -like "secondB*"} #hourA $H1Label.content = $hourA [array]$splittime = ([convert]::ToString($houra,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $hourAradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 #hourB $H2Label.content = $hourB [array]$splittime = ([convert]::ToString($hourb,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $hourBradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 #minuteA $M1Label.content = $minuteA [array]$splittime = ([convert]::ToString($minutea,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $minuteAradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 #minuteB $M2Label.content = $minuteB [array]$splittime = ([convert]::ToString($minuteb,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $minuteBradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 #secondA $S1Label.content = $secondA [array]$splittime = ([convert]::ToString($seconda,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $secondAradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 #secondB $S2Label.content = $secondB [array]$splittime = ([convert]::ToString($secondb,2)) -split"" | Where {$_} [array]::Reverse($splittime) $i = 0 ForEach ($hradio in $secondBradio) { Write-Verbose "i: $($i)" Write-Verbose "split: $($splittime[$i])" If ($splittime[$i] -eq "1") { $hradio.Ischecked = $True } Else { $hradio.Ischecked = $False } $i++ } $i = 0 } $Global:Window.Add_KeyDown({ If ($_.Key -eq "F5") { &$update } }) #Timer Event $Window.Add_SourceInitialized({ #Create Timer object Write-Verbose "Creating timer object" $Global:timer = new-object System.Windows.Threading.DispatcherTimer Write-Verbose "Adding interval to timer object" $timer.Interval = [TimeSpan]"0:0:.10" #Add event per tick Write-Verbose "Adding Tick Event to timer object" $timer.Add_Tick({ &$update Write-Verbose "Updating Window" }) #Start timer Write-Verbose "Starting Timer" $timer.Start() If (-NOT $timer.IsEnabled) { $Window.Close() } }) &$update $window.Showdialog() | Out-Null }).BeginInvoke() | out-null
PowerShellCorpus/PoshCode/Split-String_1.ps1
Split-String_1.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/Highlight syntax.ps1
Highlight syntax.ps1
#code which need highlight $code = @' #just example Get-Process | % { try { "{0, 7} {1}" -f $_.Id, $_.MainModule.ModuleName } catch [System.ComponentModel.Win32Exception] {} } '@ function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() #keywords $type = New-Object "Collections.Generic.Dictionary[String, [Drawing.Color]]" $type["Command"] = [Drawing.Color]::Cyan $type["Comment"] = [Drawing.Color]::Gray $type["GroupStart"] = [Drawing.Color]::Orange $type["GroupEnd"] = [Drawing.Color]::Orange $type["Keyword"] = [Drawing.Color]::FromArgb(0, 255, 0) $type["Member"] = [Drawing.Color]::Tomato $type["Operator"] = [Drawing.Color]::Linen $type["String"] = [Drawing.Color]::Yellow $type["Type"] = [Drawing.Color]::Silver $type["Variable"] = [Drawing.Color]::Crimson #main form $frmMain = New-Object Windows.Forms.Form $txtEdit = New-Object Windows.Forms.RichTextBox # #txtEdit # $txtEdit.BackColor = [Drawing.Color]::FromArgb(1, 36, 86) $txtEdit.Dock = "Fill" $txtEdit.Font = New-Object Drawing.Font("Courier New", 10, [Drawing.FontStyle]::Bold) $txtEdit.Text = $code # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(490, 190) $frmMain.Controls.Add($txtEdit) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.MaximizeBox = $false $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "gregzakh@gmail.com" #counter $i = 0 #highlight code [Management.Automation.PSParser]::Tokenize( $txtEdit.Text, [ref](New-Object "Collections.ObjectModel.Collection[Management.Automation.PSParseError]") ) | % { $txtEdit.SelectionStart = $_.Start - $i $txtEdit.SelectionLength = $_.Length #skip unnecessary types if ($_.Type -eq "LineContinuation" -or $_.Type -eq "NewLine") { $i++ } else { $txtEdit.SelectionColor = $type[$_.Type.ToString()] } } #when done $txtEdit.DeselectAll() #show form [void]$frmMain.ShowDialog() } frmMain_Show
PowerShellCorpus/PoshCode/IADsDNWithBinary Cmdlet_1.ps1
IADsDNWithBinary Cmdlet_1.ps1
//Adapted from code @ http://mow001.blogspot.com/2006/01/msh-snap-in-to-translate.html Thanks! using System; using System.ComponentModel; using System.Management.Automation; using System.Reflection; using System.Diagnostics; namespace space { // This class defines the properties of a snap-in [RunInstaller(true)] public class readIADsDNWithBinary : PSSnapIn { /// Creates instance of Snapin class. public readIADsDNWithBinary() : base() { } ///Snapin name is used for registration public override string Name { get { return "readIADsDNWithBinary"; } } /// Gets description of the snap-in. public override string Description { get { return "Reads a IADsDNWithBinary"; } } public override string Vendor { get { return "Andrew"; } } } /// Gets a IADsDNWithBinary ex: Read-IADsDNWithBinary $user.directoryentry."msRTCSIP-UserPolicy"[0] [Cmdlet("Read", "IADsDNWithBinary")] public class readIADsDNWithBinaryCommand : Cmdlet { [Parameter(Position = 0, Mandatory = true)] public object DNWithBinary { get { return DNWithBin; } set { DNWithBin = value; } } private object DNWithBin; protected override void EndProcessing() { ActiveDs.IADsDNWithBinary DNB = (ActiveDs.IADsDNWithBinary)DNWithBin; ActiveDs.DNWithBinary boink = new ActiveDs.DNWithBinaryClass(); boink.BinaryValue = (byte[])DNB.BinaryValue; boink.DNString = DNB.DNString; WriteObject(boink); } } /// Sets a IADsDNWithBinary [Cmdlet("Write", "IADsDNWithBinary")] public class writeIADsDNWithBinaryCommand : Cmdlet { [Parameter(Mandatory = true)] public byte[] Bin { get { return bin; } set { bin = value; } } private byte[] bin; [Parameter(Mandatory = true)] public string DN { get { return dn; } set { dn = value; } } private string dn; protected override void EndProcessing() { ActiveDs.DNWithBinary boink2 = new ActiveDs.DNWithBinaryClass(); boink2.BinaryValue = bin; boink2.DNString = dn; WriteObject(boink2); } } }
PowerShellCorpus/PoshCode/Colorize Subversion SVN_2.ps1
Colorize Subversion SVN_2.ps1
#draw output function drawlines($colors, $lines) { foreach ($line in $lines) { $color = $colors[[string]$line[0]] if ($color) { write-host $line -Fore $color } else { write-host $line } } } # svn stat function ss { drawlines @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } (svn stat) } # svn update function su { drawlines @{ "A"="Magenta"; "D"="Red"; "U"="Green"; "C"="Yellow"; "G"="Blue"; } (svn up) } # svn diff function sd { drawlines @{ "@"="Magenta"; "-"="Red"; "+"="Green"; "="="DarkGray"; } (svn diff) }
PowerShellCorpus/PoshCode/WriteFileName_4.ps1
WriteFileName_4.ps1
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate. # e.g. PS>.\\writefilename.ps1 c:\\ # call WriteFileName [string] # after done writing series of overwriting messages, call WriteFileNameEnd function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($Host.Name -match 'ise') { write-host $writestr; return } if ($global:wfnlastlen -eq $null) {$global:wfnlastlen=0} $ctop=[console]::cursortop $cleft=[console]::cursorleft $oldwritestrlen=$writestr.length $rem=$null $writelines = [math]::divrem($writestr.length+$cleft, [console]::bufferwidth, [ref]$rem) #if ($rem -ne 0) {$writelines+=1} $cwe = ($writelines-(([console]::bufferheight-1)-$ctop)) # calculate where text has scroll back to. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:wfnoldctop=[console]::cursortop $global:wfnoldcleft=[console]::cursorleft if ($global:wfnlastlen -gt $writestr.length) { write-host (" " * ($global:wfnlastlen-$writestr.length)) -nonewline # this only overwrites previously written text if needed, so no need to compute buffer movement on this } $global:wfnlastlen = $oldwritestrlen if ($ctop -lt 0) {$ctop=$cleft=0} [console]::cursortop=$ctop [console]::cursorleft=$cleft } function WriteFileNameEnd ( $switch=$true) # call this function when you are done overwriting messages on top of each other { # and before printing something else. Default switch=$true, which prints a newline, $false restores cursor position same line. if ($Host.Name -match 'ise') { return } if ($global:wfnoldctop -ne $null -and $global:wfnoldcleft -ne $null) { [console]::cursortop=$global:wfnoldctop [console]::cursorleft=$wfnoldcleft if ($global:wfnoldcleft -ne 0 -and $switch) { write-host "" } } $global:wfnoldctop=$null $global:wfnlastlen=$null $global:wfnoldcleft=$null } write-host "Checking: " -nonewline dir $args -recurse -ea 0 -force | %{WriteFileName ("$($_.fullname) ..."*(get-random -min 1 -max 100))} #WriteFileName "Final Test String." WriteFileNameEnd write-host "Done! exiting."
PowerShellCorpus/PoshCode/Make a phone call_4.ps1
Make a phone call_4.ps1
<# .NOTES AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com) WEBSITE: http://tekout.wordpress.com VERSION: 0.1 CREATED: 17th April, 2012 LASTEDIT: 17th April, 2012 Requires: PowerShell v2 or better .CHANGELOG 4/17/2012 Try passing powershell objects to PROTO API and pass the variables to .JS file Pass other system variables and check if text to speech can translate double or a double-to-char conversion is required. 4/18/2012 Changed get-diskusage to gwmi -class win32_logicaldisk .SYNOPSIS Make a phone call from Powershell. .DESCRIPTION The script demonstrates how you can collect state-data in powershell and pass it as an argument to a REST API call and alert a System Admin. For this example, TROPO REST API's were used. (www.tropo.com) The phone-number will receive a Call with the following text To speech Please check the server $this. The percent Free Space on C Drive is $inDecimals. This is a proof of concept. V 0.1 There are numerous areas of improvement. .IMPORTANT Please create a new account and setup your application in tropo. Its free for dev use. http://www.tropo.com Copy and replace the TOKEN in your application with the TOKEN below to initiate a call. .OTHER JAVASCRIPT (Hosted on Tropo) TropoTest.js call('+' + numToCall , { timeout:30, callerID:'19172688401', onAnswer: function() { say("Houston ! We have a problem "); say("Please check the server" + sourceServer ); say("The percent Free Space on C Drive is" + freeCDisk ); say("Goodbye."); log("Call logged Successfully"); }, onTimeout: function() { log("Call timed out"); }, onCallFailure: function() { log("Call could not be completed as dialed"); } }); #> # Proto API section. Please replace protoToken with your own Application Token, # I am posting my API token here so that someone can download and run the script by editing just the cell # field. $baseUrl = "https://api.tropo.com/1.0/sessions?action=create&" # Modify these variables. $protoToken = "10b0026696a79f448eb21d8dbc69d78acf12e2f1f62f291feecec8f2b8d1eac76da63d91dd317061a5a9eeb0" #US 10 Digit only for now. For Example 17327911234,19177911234 # Calls to Outside US are not allowed during the dev trials on Tropo. # You will receive a call from this number - 19172688401. That's the callerID $myCell = '11234567890' # Functions #4.18.12 -- Previous versoin used Get-DiskUsage and was erroring out if the cmldet is not installed. #modified it to use GWMI Function get-FreeDiskPercentForC { $disk = gwmi -class "win32_LogicalDisk" $free = $disk[0].FreeSpace / $disk[0].Size $freeDiskCPercent = [System.Math]::Round($free, 2) $freeDiskCPercent } # Get some more parameters here. $sourceServer =hostname $cDisk = get-FreeDiskPercentForC # Concatenate and form the Proto API string. I am sure someone can figure out a better way to do this than just adding. $callThis = $baseUrl+ 'token=' + $protoToken + '&numToCall=' + $myCell + '&sourceServer=' + $sourceServer + '&freeCDisk=' + $cDisk # Call the Proto API # I could have tested this with Invoke-RestMethod, but I didn't see the point. I am not receiving any data from the URL. $newClient = new-object System.Net.WebClient $newClient.DownloadString($callThis)
PowerShellCorpus/PoshCode/Invoke-AdvancedFunction..ps1
Invoke-AdvancedFunction..ps1
param(\n [Parameter(Mandatory = $true)]\n [ScriptBlock] $Scriptblock\n )\n\n## Invoke the scriptblock supplied by the user.\n& $scriptblock
PowerShellCorpus/PoshCode/UCS-ServiceProf-fromList.ps1
UCS-ServiceProf-fromList.ps1
<# ==================================================================== Author(s): Josh Atwell <josh.c.atwell@gmail.com> Link: www.vtesseract.com File: Get-UCSServiceProfileAssociations-FromList.ps1 Purpose: Gets Service Profile Associations for all UCS clusters provided in a list. If you want to view the Serivce Profile associations for a single UCSM you can use the following one-liner: Get-UcsServiceProfile | Select Ucs, Name, PnDn | Sort UCS,PnDn Date: 2012-10-01 Revision: 1 References: Written using UCSPowerTool 0.9.90 Requires Cisco UCSPowerTool ==================================================================== 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 ==================================================================== #> # Load UCSPowerTool Module if needed If ((Get-Module "CiscoUCSPS" -ErrorAction SilentlyContinue) -eq $null) { Write-Output "UCSPowerTool Module not loaded. Attempting to load UCSPowerTool" Import-Module "C:\\Program Files (x86)\\Cisco\\Cisco UCS PowerTool\\Modules\\CiscoUcsPS\\CiscoUcsPS.psd1" } # Prepopulated Data # Enter data and remote # comment character to use #$sourcelist = Get-Content "C:\\Josh\\Temp\\2012-09-29.txt" #$destinationfile = "C:\\Josh\\Temp\\ServiceProfiles_2012-09-29_b.csv" # User prompts if data is not prepopulated above If ($sourcelist -eq $null){ $sourcelist = Get-Content (Read-Host "Please enter path to file with list of UCSMs (.txt)") } If ($destinationfile -eq $null){ $destinationfile = Read-Host "Please enter file path and name for the output (.csv). If left blank no output file will be created." } # Prompts and stores user credentials $cred = Get-Credential Set-UcsPowerToolConfiguration -SupportMultipleDefaultUcs $true $AllUCS = $sourcelist Connect-UCS $AllUCS -Credential $cred $report = Get-UcsServiceProfile | Select Ucs, Name, PnDn | Sort UCS,PnDn Write-Output $report # Will export to CSV If ($destinationfile -ne $null){ $report | Export-CSV $destinationfile -NoTypeInformation } Disconnect-UCS # Clears the $cred variable for security purposes Clear-Variable cred If ((Read-Host "Do you want to disconnect the CiscoUCSPS module? (Y/N)") -eq "Y"){ Remove-Module "CiscoUCSPS" }Else{ Write-Output "Did not disconnect CiscoUCSPS module. You can do so manually with Remove-Module 'CiscoUCSPS'" }
PowerShellCorpus/PoshCode/Use-Culture.ps1
Use-Culture.ps1
#############################################################################\n##\n## Use-Culture\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n#############################################################################\n\n<#\n\n.SYNOPSIS\n\nInvoke a scriptblock under the given culture\n\n.EXAMPLE\n\nUse-Culture fr-FR { [DateTime]::Parse("25/12/2007") }\nmardi 25 decembre 2007 00:00:00\n\n#>\n\nparam(\n ## The culture in which to evaluate the given script block\n [Parameter(Mandatory = $true)]\n [System.Globalization.CultureInfo] $Culture,\n\n ## The code to invoke in the context of the given culture\n [Parameter(Mandatory = $true)]\n [ScriptBlock] $ScriptBlock\n)\n\nSet-StrictMode -Version Latest\n\n## A helper function to set the current culture\nfunction Set-Culture([System.Globalization.CultureInfo] $culture)\n{\n [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture\n [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture\n}\n\n## Remember the original culture information\n$oldCulture = [System.Threading.Thread]::CurrentThread.CurrentUICulture\n\n## Restore the original culture information if\n## the user's script encounters errors.\ntrap { Set-Culture $oldCulture }\n\n## Set the current culture to the user's provided\n## culture.\nSet-Culture $culture\n\n## Invoke the user's scriptblock\n& $ScriptBlock\n\n## Restore the original culture information.\nSet-Culture $oldCulture
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_1.ps1
Get Twitter RSS Feed_1.ps1
param ([String] $ScreenName) $client = New-Object System.Net.WebClient $idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName" $data = $client.DownloadString($idUrl) $start = 0 $findStr = '"id":' do { $start = $data.IndexOf($findStr, $start + 1) if ($start -gt 0) { $start += $findStr.Length $end = $data.IndexOf(',', $start) $userId = $data.SubString($start, $end-$start) } } while ($start -le $data.Length -and $start -gt 0) $feed = "http://twitter.com/statuses/user_timeline/$userId.rss" $feed
PowerShellCorpus/PoshCode/09af4d5a-52a6-4d61-89dd-7b9016c3d1d7.ps1
09af4d5a-52a6-4d61-89dd-7b9016c3d1d7.ps1
<%@ Page language="c#" AutoEventWireup="true" Debug="true" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Management.Automation.Runspaces" %> <%@ Import Namespace="System.Management.Automation" %> <%@ Import Namespace="System.Collections.ObjectModel" %> <script language="C#" runat="server"> // The previous lines use <%...%> to indicate script code, and they specify the namespaces to import. As mentioned earlier, the assemblies must be located in the \\Bin subdirectory of the application's starting point. // http://msdn.microsoft.com/en-us/library/aa309354(VS.71).aspx // // Description: // Run PowerShell Script from an ASP.Net web page // // Author: // Wayne Martin, 15/05/2008, http://waynes-world-it.blogspot.com/ // private void Button3_Click(object sender, System.EventArgs e) { String fp = Server.MapPath(".") + "\\\\" + tPowerShellScriptName.Text; StreamReader sr = new StreamReader(fp); tPowerShellScriptCode.Text = sr.ReadToEnd(); sr.Close(); } private void Button2_Click(object sender, System.EventArgs e) { tPowerShellScriptResult.Text = RunScript(tPowerShellScriptCode.Text); } // http://msdn.microsoft.com/en-us/library/ms714635(VS.85).aspx private string RunScript(string scriptText) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); // Create a new runspaces.command object of type script Command cmdScript = new Command(scriptText, true, false); cmdScript.Parameters.Add("-t", txtInput.Text); pipeline.Commands.Add(cmdScript); //You could also use: pipeline.Commands.AddScript(scriptText); // Re-format all output to strings pipeline.Commands.Add("Out-String"); // Invoke the pipeline Collection<PSObject> results = pipeline.Invoke(); //String sresults = pipeline.Output.Count.ToString(); //sresults = sresults + "," + results.Count.ToString(); String sresults = ""; foreach (PSObject obj in results) { sresults = sresults + obj.ToString(); } // close the runspace and set to null runspace.Close(); runspace = null; return sresults; } </script> <form id="Form1" method="post" runat="server"> <P> <asp:Label id="Label1" runat="server" Width="104px">Parameter:</asp:Label> <asp:TextBox id="txtInput" runat="server"></asp:TextBox></P> <P> <asp:Button id="Button3" runat="server" Text="Load" OnClick="Button3_Click"></asp:Button> </P> <P> <asp:Button id="Button2" runat="server" Text="Run" OnClick="Button2_Click"></asp:Button> </P> <P> <asp:Label id="Label2" runat="server" >Relative script name:</asp:Label> <asp:TextBox id="tPowerShellScriptName" Text="test.ps1" runat="server"></asp:TextBox></P> <P> <asp:TextBox rows="20" columns="120" TextMode="multiline" id="tPowerShellScriptCode" runat="server"></asp:TextBox></P> <P> <asp:TextBox rows="8" columns="120" TextMode="multiline" id="tPowerShellScriptResult" runat="server"></asp:TextBox></P> </form>
PowerShellCorpus/PoshCode/JSON _1.5.ps1
JSON _1.5.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 # v 1.1 - Changed ConvertFrom-Json to handle single item results # v 1.2 - CodeSigned to make a fellow geek happy # v 1.3 - Changed ConvertFrom-Json to handle zero item results (I hope) # v 1.4 - Added -File parmeter set to ConvertFrom-Json # - Cleaned up some error messages # v 1.5 - Corrected handling of arrays @@# v 1.6 - Corrected pipeline binding on ConvertFrom-Json # # There is no help (yet) because I keep forgetting that I haven't written help yet. # 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 # @@# However, you *can* use PSOjbect as your type when re-importing: @@# @@# > $Json = Get-Process | @@# >> Select PM, WS, CPU, ID, ProcessName, @{n="SnapshotTime";e={Get-Date}} | @@# >> ConvertTo-Json -NoType @@# @@# > $Json | ConvertFrom-json -Type PSObject 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 try { $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max) $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 | ConvertFrom-Xml } elseif(Get-Member -InputObject $xml -Name Objects) { return $xml.Objects | ConvertFrom-Xml } $propbag = @{} foreach($name in Get-Member -InputObject $xml -MemberType Properties | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) { Write-Verbose "$Name Type: $($xml.$Name.type)" $propbag."$Name" = Convert-Properties $xml."$name" } 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 Convert-Properties { param($InputObject) switch( $InputObject.type ) { "object" { return (ConvertFrom-Xml -Xml $InputObject) break } "string" { $MightBeADate = $InputObject.get_InnerText() -as [DateTime] ## Strings that are actually dates (*grumble* JSON is crap) if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) { return $MightBeADate } else { return $InputObject.get_InnerText() } break } "number" { $number = $InputObject.get_InnerText() if($number -eq ($number -as [int])) { return $number -as [int] } elseif($number -eq ($number -as [double])) { return $number -as [double] } else { return $number -as [decimal] } break } "boolean" { return [bool]::parse($InputObject.get_InnerText()) } "null" { return $null } "array" { [object[]]$Items = $( foreach( $item in $InputObject.GetEnumerator() ) { Convert-Properties $item } ) return $Items } default { return $InputObject break } } } Function ConvertFrom-Json { [CmdletBinding(DefaultParameterSetName="StringInput")] PARAM( [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="File")] [Alias("PSPath")] [string]$File , [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1,ParameterSetName="StringInput")] [string]$InputObject , [Parameter(Mandatory=$true)] [Type]$Type , [Switch]$ForceType ) BEGIN { [bool]$AsParameter = $PSBoundParameters.ContainsKey("File") -or $PSBoundParameters.ContainsKey("InputObject") } PROCESS { if($PSCmdlet.ParameterSetName -eq "File") { [string]$InputObject = @(Get-Content $File) -Join "`n" $null = $PSBoundParameters.Remove("File") } else { $null = $PSBoundParameters.Remove("InputObject") } [Xml.XmlElement]$xml = (Convert-JsonToXml $InputObject).Root if($xml) { if($xml.Objects) { $xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters }elseif($xml.Item -and $xml.Item -isnot [System.Management.Automation.PSParameterizedProperty]) { $xml.Item | ConvertFrom-Xml @PSBoundParameters }else { $xml | ConvertFrom-Xml @PSBoundParameters } } else { Write-Error "Failed to parse JSON with JsonReader" } } } ######### ### 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 * # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUVOSNLwCk5kgVZvSmrZS8eSHh # enegggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj # dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY # BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh # dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId # KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P # n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl # 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC # mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD # /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX # +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L # PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC # B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC # AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC # ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg # M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0 # LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv # bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G # CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee # zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4 # rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7 # bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb # 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA # T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow # gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl # IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY # aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0 # LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC # NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUEW0DtdE/ # JxK83G70qiWwclaBOkswDQYJKoZIhvcNAQEBBQAEggEAj4Uojbc96AZ7aKOLgkfP # E+qkrMWAuGijIacClwgOcUGOzdkNDQAdbvvLJTWafE7uBDFdEuxL7MZDvPDLFPJ0 # U95AjfVwhf7FTEMHL3UOGJS5Lo/JAsnIz6Fza4faLv4kilXyRRME1iBqH/vxllNj # mGV8Rm0Yg8EZ4ClYLonHuGFT2+XqOA1wbjncZbUfqg/8ybD+TVh/19BJoqSRNoL9 # /TKQTgBoOVSB3pJmvoFfKjxPrS/1fPiVOGi0HfP4JhzAYRy9PDHCmxat0IE+ev9w # LAjR2YUQ0xJRYIa1rQfJaohi45wMyIoeur3Z3zHL9sk+MbkQvyMO2Qsmi5fU309e # 1g== # SIG # End signature block
PowerShellCorpus/PoshCode/Out-DataTable_1.ps1
Out-DataTable_1.ps1
####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-Alias | Out-DataTable This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties .LINK http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx #> function Out-DataTable { [CmdletBinding()] param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) Begin { $dt = new-object Data.datatable $First = $true } Process { foreach ($object in $InputObject) { $DR = $DT.NewRow() foreach($property in $object.PsObject.get_properties()) { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $property.Name.ToString() $DT.Columns.Add($Col) } if ($property.IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/VerifyCategoryRule_3.ps1
VerifyCategoryRule_3.ps1
## From Windows PowerShell Cookbook (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) Set-StrictMode -Version Latest if($message.Body -match "book") { [Console]::WriteLine("This is a message about the book.") } else { [Console]::WriteLine("This is an unknown message.") }
PowerShellCorpus/PoshCode/ShowUI Clock _1.ps1
ShowUI Clock _1.ps1
New-UIWidget -AsJob -Content { $shadow = DropShadowEffect -Color Black -Shadow 0 -Blur 8 $now = Get-Date; StackPanel { TextBlock -Name "Time" ('{0:h:mm tt}' -f $now) -FontSize 108 -LineHeight 100 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Effect $shadow -FontFamily "Century Gothic" StackPanel -Orientation Horizontal { TextBlock -Name "Day" ('{0:dd}' -f $now) -FontSize 80 -LineHeight 80 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Opacity 0.6 -Effect $shadow -FontFamily "Century Gothic" StackPanel { TextBlock -Name "Month" ('{0:MMMM}' -f $now).ToUpper() -fontsize 40 -LineHeight 40 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -FontFamily "Century Gothic" TextBlock -Name "Weekday" ('{0:dddd}' -f $now).ToUpper() -fontsize 28 -LineHeight 28 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Effect $shadow -FontFamily "Century Gothic" } -Margin 0 } -Margin 0 } -Margin 0 } -Interval "0:0:0.2" -UpdateBlock { $now = Get-Date $Time.Text = '{0:h:mm tt}' -f $now $Day.Text = '{0:dd}' -f $now $Month.Text = ('{0:MMMM}' -f $now).ToUpper() $Weekday.Text = ('{0:dddd}' -f $now).ToUpper() }
PowerShellCorpus/PoshCode/WriteFileName_1.ps1
WriteFileName_1.ps1
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate. # e.g. PS>.\\writefilename.ps1 c:\\ # call WriteFileName [string] # after done writing series of overwriting messages, call WriteFileNameEnd function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. # Features the ability to deal with end of console buffer overflows. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length $spaces = "" if ($global:lastlen -gt $writestr.length) { $spaces = " " * ($global:lastlen-$writestr.length) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to. if ($cwe -gt 0) { if (($ctop-$cwe0) -gt 0) { $ctop-=$cwe } else {$ctop=0} } write-host "$writestr" -nonewline $global:oldctop=[console]::cursortop if ([console]::cursorleft -ne 0) {$global:oldctop+=1} write-host "$spaces" -nonewline $global:lastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=0 } function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other { # and before printing something else if ($global:oldctop -ne $null) { [console]::cursortop=$global:oldctop [console]::cursorleft=0 } $global:oldctop=$null $global:lastlen=$null } dir $args -recurse -ea 0 -force | %{$string="Test String. "*(get-random(100));$string+="Checking $($_.fullname) ..."; WriteFileName $string;sleep -seconds 1} #WriteFileName "Final Test String." WriteFileNameEnd write-host "Done! exiting."
PowerShellCorpus/PoshCode/New-Wrapper.ps1
New-Wrapper.ps1
function New-Wrapper { <# .Synopsis Encrypt a secret script to run from a new ps1 wrapper script. .Description Encrypt a secret script to run from a new ps1 wrapper script. A block diagram of how password is protected. http://bit.ly/jE1N7n The original template used http://bit.ly/lFE2IO if required. Important - Flatten Original Script first: Original script must be prepared because when it is decrypted, it's converted into a big "one liner"....so, -Remove # comments. -Place a semicolon ; at the end of each line. -Remove unnecessary white space. The password is embedded in the new script's file-name for convenience, so rename before you run it for the first time. If savePass option is used, it will not prompt for a password again unless script is altered, renamed, moved or executed from a different host like the ISE. Optionally: Script can be locked to a specific user (most secure mode) Forced to be run from UNC - to thwart debugging Save encoded password in registry - so you only need to enter it once. Obfuscate wrapper script code - easy to read variable names are replaced with hard to read names. No, it is not 100% secure, but with the option to use perUser it is secure as the user's account, and if password is not even saved, then it is as secure as AES. Basically if anything, when the password is saved, the script is signed. i.e. If a single character in the script is altered, then the script will cease to run and will prompt for the original password again. MD5 hash is used instead of SHA1 because it conveniently makes a compatible 128 bit key length key for the 128 bit AES. The known MD5 vulnerabilities are not an issue in this implementation. .parameter inputScript Script you want to encrypt and wrap. .parameter password Password to encrypt and decrypt script .parameter perUser Each user that wants to run script will have to have to enter the password. Used with savePass option, the user's identity is hashed with the password as extra protection. Only the owner of this user account can possibly reverse engineer the password making it more secure. .parameter forceUnC Script will only run from UNC, thus thwarting debugger from extracting decrypted script and password. Also if script is saved on a secure network share, separare from password then that could be desirable. .parameter savePass XOR Hash of hardware finger print and password is saved in registry - to decode password, script must XOR again with hashes of the script's path, script's contents, system serial number, PS host that the script is running under and the identity of user (if specified). .parameter test Quickly allows you to test script runs from encrypted block before wrapping. If original script has not been properly prepared, ie. flattened as per instructions in description above, then it will fail. .parameter newTemplate Use this switch to build a new wrapper template. Input Script is output to Hex so you can use this block to replace the $template variable. (Note, if copied from console, remove carriage returns) .parameter obfuscate Easy to read variable names are replaced with hard to read names. Note Security through obscurity is bad so if the script has to be really secure then use peruser mode or don't save the password. The wrapper script is very hard to understand when obfuscated but an experienced attacker with time could unravel and then attempt to manually build the hardware hash. .Example New-Wrapper "C:\\scripts\\secret.ps1" Description ----------- Encrypts secret.ps1 and places it in a PowerShell wrapper script using: Default password "Password1" Current folder and default file name .Example New-Wrapper -inputScript "C:\\scripts\\secret.ps1" -password 43rH3489Dv -savePass -perUser -obfuscate Description ----------- Script wrapper variables are obfuscated, a complex password is used and encoded password is saved in registry. Only the user that saved the password can decode it as it is hashed with their logon identity. .Inputs None .Outputs none #> [CmdletBinding(SupportsShouldProcess = $false)] param( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline=$false)] [string]$inputScript, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline=$false)] [string]$password="Password1", [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$perUser, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$forceUnC, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$savePass, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$test, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$newTemplate, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [switch]$obfuscate, [Parameter( Mandatory=$false, ValueFromPipeline=$false)] [string]$outputScript ) BEGIN { $template = "5B5265666C656374696F6E2E417373656D626C795D3A3A4C6F6164576974685061727469616C4E616D65282253797374656D2E536563757269747922297C6F75742D6E756C6C3B202066756E6374696F6E204D4435486173687B20706172616D285B737472696E675D24696E537472696E672C5B7377697463685D2468617368293B2024696E537472696E672B3D285B737472696E675D5B6D6174685D3A3A5049292E737562737472696E6728302C3136293B20246148423D286E65772D4F626A6563742053656375726974792E43727970746F6772617068792E4D443543727970746F5365727669636550726F7669646572292E436F6D70757465486173682824285B436861725B5D5D24696E537472696E6729293B206966282468617368297B666F726561636828246279746520696E2024614842297B2474656D703D227B303A587D22202D662024627974653B6966282474656D702E6C656E6774682D657131297B2474656D703D22302474656D70227D3B24726573756C742B3D2474656D707D3B2D6A6F696E2024726573756C743B7D656C73657B246148427D20207D202066756E6374696F6E204465637279707442797465737B20706172616D282453796D416C672C24696E42797465732C24526567486578293B20247866726D3D2453796D416C672E437265617465446563727970746F7228293B207472797B246F7574426C6F636B3D247866726D2E5472616E73666F726D46696E616C426C6F636B2824696E42797465732C20302C2024696E42797465732E4C656E677468297D2063617463687B77726974652D686F7374202257726F6E67205057223B476574526567202D6B65792024526567486578202D56616C756520246E756C6C202D7365743B627265616B7D2072657475726E205B53797374656D2E546578742E556E69636F6465456E636F64696E675D3A3A556E69636F64652E476574537472696E6728246F7574426C6F636B29207D202066756E6374696F6E204857486173687B20706172616D2824536372506174682C5B7377697463685D2450657255736572293B2024617A3D4D443548617368202453637250617468202D686173683B2024627A3D4D443548617368202867776D6920285B53797374656D2E546578742E456E636F64696E675D3A3A555446382E476574537472696E67285B53797374656D2E436F6E766572745D3A3A46726F6D426173653634537472696E67282256326C754D7A4A6655336C7A644756745257356A6247397A64584A6C222929297C257B245F2E285B53797374656D2E546578742E456E636F64696E675D3A3A555446382E476574537472696E67285B53797374656D2E436F6E766572745D3A3A46726F6D426173653634537472696E6728225532567961574673546E5674596D5679222929297D29202D686173683B2024637A3D4D4435486173682028676320245363725061746829202D686173683B2024647A3D4D443548617368202824686F73742E6E616D6529202D686173683B2024657A3D584F52486173682028584F52486173682024617A2024627A292028584F52486173682024637A2024647A293B206966282450657255736572297B24647A3D4D4435486173682028436F6E7665727446726F6D2D536563757265537472696E67202D536563757265537472696E672028436F6E76657274546F2D536563757265537472696E67202D737472696E672024657A202D6173706C61696E74657874202D666F72636529292D686173683B584F52486173682024657A2024647A7D656C73657B24657A7D207D202066756E6374696F6E2072756E5363726970747B20706172616D285B737472696E675D24746578746F66736372697074626C6F636B293B2024657865637574696F6E636F6E746578742E496E766F6B65436F6D6D616E642E4E6577536372697074426C6F636B2824746578746F66736372697074626C6F636B29207D202066756E6374696F6E20584F52486173687B20706172616D285B737472696E675D24696E707574312C205B737472696E675D24696E70757432293B2024636F6D62696E656442797465733D4028293B20666F722824636F756E743D303B24636F756E742D6C7424696E707574312E6C656E6774683B24636F756E742B2B297B2024686578313D24696E707574312E737562737472696E672824636F756E742C31293B24686578323D24696E707574322E737562737472696E672824636F756E742C31293B2024626974313D5B436F6E766572745D3A3A546F537472696E67282230782468657831222C32293B24626974313D222428223022202A28342D2824626974312E6C656E6774682929292462697431223B2024626974323D5B436F6E766572745D3A3A546F537472696E67282230782468657832222C32293B24626974323D222428223022202A28342D2824626974322E6C656E6774682929292462697432223B2024636F6D62696E6564426974733D4028293B20666F722824636F756E74323D303B24636F756E74322D6C74343B24636F756E74322B2B297B20202478313D24626974312E737562737472696E672824636F756E74322C31293B2478323D24626974322E737562737472696E672824636F756E74322C31293B2024636F6D62696E6564426974732B3D247831202D62786F72202478323B202466696E616C3D5B436F6E766572745D3A3A546F496E74363428282D6A6F696E2024636F6D62696E656442697473292C203229207D20246865783D227B303A587D22202D66282466696E616C293B2024636F6D62696E656442797465732B3D24686578207D202D6A6F696E2024636F6D62696E65644279746573207D202066756E6374696F6E2048657841736369697B20706172616D2824646279746573292024636F756E743D303B2473746F703D246462797465732E6C656E6774683B246465637279707465643D22223B20646F7B246865783D246462797465732E737562737472696E672824636F756E742C32293B20246465637279707465642B3D5B436861725D5B436F6E766572745D3A3A546F496E74333228246865782C3136293B2024636F756E743D24636F756E742B327D7768696C652824636F756E742D6C742473746F70293B20262872756E53637269707420282D6A6F696E20246465637279707465642929207D202046756E6374696F6E204C6963656E63657B20706172616D28245265674865782C247073772C24536372506174682C2450657255736572293B2069662824707377297B476574526567202D6B65792024526567486578202D56616C75652028584F52486173682848574861736820245363725061746820245065725573657229202470737729202D5365747D20656C73657B247265673D476574526567202D6B657920245265674865783B69662824726567297B584F5248617368284857486173682024536372506174682024506572557365722920247265677D7D207D202046756E6374696F6E204765745265677B20706172616D285B737472696E675D246B65792C5B737472696E675D2476616C75652C5B7377697463685D247365742C5B737472696E675D247265673D285B53797374656D2E546578742E456E636F64696E675D3A3A555446382E476574537472696E67285B53797374656D2E436F6E766572745D3A3A46726F6D426173653634537472696E67282253457444565470635532396D64486468636D56635256425422292929293B206966282128746573742D70617468202452656729297B4E49202D706174682024526567202D666F7263657C6F75742D6E756C6C3B53502024526567202D6E20246B6579202D766120246E756C6C7D2069662824736574297B53502024526567202D6E20246B6579202D7661202476616C75657D656C73657B7472797B72657475726E2847502024526567202D6E20244B6579202D4541202773746F7027292E246B65797D63617463687B7D7D207D20205B737472696E675D24536372506174683D222428244D79496E766F636174696F6E2E4D79436F6D6D616E642E446566696E6974696F6E29223B2069662824666F726365556E63297B696628212824536372506174682E737562737472696E6728302C32292D6571225C5C2229297B224E6F742052756E2046726F6D20554E43223B627265616B7D7D20245265674865783D584F524861736820284D443548617368202824656E634865782E737562737472696E6728312C33322929202D68617368292028485748617368202453637250617468202450657255736572293B2020696628247361766550617373297B24706173733D4C6963656E6365202452656748657820246E756C6C2024536372506174682024506572557365723B6966282128247061737329297B24706173733D4D44354861736828526561642D486F73742022456E7465722050617373776F72642229202D686173683B6C6963656E636520245265674865782024706173732024536372506174682024506572557365727D7D20656C73657B24706173733D4D44354861736828526561642D486F73742022456E7465722050617373776F72642229202D686173687D2020244165734353503D4E65772D4F626A6563742053797374656D2E53656375726974792E43727970746F6772617068792E41657343727970746F5365727669636550726F76696465723B20244165734353502E6B65793D4D4435486173682024706173733B20244165734353502E69763D4D443548617368284D443548617368202470617373202D68617368293B202024636F756E743D303B2473746F703D24456E634865782E6C656E6774683B24456E6342797465733D4028293B20646F7B246865783D24456E634865782E737562737472696E672824636F756E742C32293B20247A7A3D5B436F6E766572745D3A3A546F496E74333228246865782C3136293B2024456E6342797465732B3D5B53797374656D2E436F6E766572745D3A3A546F4279746528247A7A293B2024636F756E743D24636F756E742B327D7768696C652824636F756E742D6C742473746F70293B20204865784173636969202844656372797074427974657320244165734353502024456E6342797465732024526567486578292020202020202020"; [Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null; function new-scriptblock { param([string]$textofscriptblock); $executioncontext.InvokeCommand.NewScriptBlock($textofscriptblock) } function MD5-Hash { param ([string]$inString,[switch]$hash); $inString+=([string][math]::PI).substring(0,16); $aHB=(new-Object Security.Cryptography.MD5CryptoServiceProvider).ComputeHash($([Char[]]$inString)); if ($hash){foreach ($byte in $aHB){$temp="{0:X}" -f $byte;if ($temp.length-eq1){$temp="0$temp"};$result+=$temp};-join $result;}else{$aHB}; } function Encrypt-String { param($SymAlg, [string]$inString) $inBlock = [System.Text.UnicodeEncoding]::Unicode.getbytes($instring) $xfrm = $symAlg.CreateEncryptor() $outBlock = $xfrm.TransformFinalBlock($inBlock, 0, $inBlock.Length); return $outBlock; } function Decrypt-Bytes { param($SymAlg, $inBytes) $xfrm = $symAlg.CreateDecryptor(); $outBlock = $xfrm.TransformFinalBlock($inBytes, 0, $inBytes.Length) return [System.Text.UnicodeEncoding]::Unicode.GetString($outBlock) } function HexToAscii { param($dHex); $count=0;$stop=$dHex.length;$dAscii=@(); do{ $hex=$dHex.substring($count,2); $dAscii+=[Char][Convert]::ToInt32($hex,16); $count=$count+2; }while($count-lt$stop); [string]$result = -join $dAscii $result } } PROCESS { # Create hash of password $pass = MD5-Hash $password -hash # get-content of ps1 script file to encrypt if (Test-Path $inputScript){[string]$inputScriptContent = get-content $inputScript} else {"Can't read $inputScript"; break} # Ascii to Hex $hex2=$inputScriptContent.ToCharArray() | % {"{0:X}" -f ([int][char]$_)} | % {if ($_.length -eq 1){"0"+$_}else{$_}} $strHex = -join $hex2 # Capture hex for new template if ($newTemplate){$strhex; break} # Generate CSP, Key and IV $AesCSP = New-Object System.Security.Cryptography.AesCryptoServiceProvider $AesCSP.key = MD5-Hash $pass $AesCSP.iv = MD5-Hash (MD5-Hash $pass -hash) # Encrypt PlainText $EncBytes = Encrypt-String $aesCSP $strHex # Encrypted Bytes to Encrypted Hex $EncHex = [System.Convert]::ToBase64String($EncBytes) $EncHex = -join ($EncBytes | % {$hh="{0:X}" -f $_; if ($hh.length-eq1){"0$hh"}else{$hh}}) # Encrypted Hex to Encrypted Bytes $count=0;$stop=$EncHex.length;$EncBytes2=@() do{ $hex=$EncHex.substring($count,2); $zz=[Convert]::ToInt32($hex,16); $EncBytes2+=[System.Convert]::ToByte($zz); $count=$count+2; }while($count-lt$stop); # Encrypted Bytes to Decrypted Hex $dHex = Decrypt-Bytes $AesCSP $EncBytes2; # Decrypted Hex to Ascii $sb=HexToAscii $dHex # Test/Build Template if ($test) { &(new-scriptblock $sb) } else { # OutputScript if (!($outputScript)){$outputScript="$($EncHex.substring(0,15))-$password.ps1"} $tb="`$encHex=`"$encHex`";$(HexToAscii $template)" if($peruser){$tb="`$peruser=`$true;"+$tb}else{$tb="`$peruser=`$false;"+$tb} if($forceUnC){$tb="`$forceUnC=`$true;"+$tb}else{$tb="`$forceUnC=`$false;"+$tb} if($savePass){$tb="`$savePass=`$true;"+$tb}else{$tb="`$savePass=`$false;"+$tb} if ($obfuscate) { $sub = 'FFF,MD5Hash,$FFE,$inString,$FFD,$hash,-FFD,-hash,$FFC,$aHB,$FFB,$byte,$FFA,$temp,$FF9,$result,FF8,DecryptBytes,$FF7,$SymAlg,$FF6,$inBytes,$FF5,$RegHex,$FF4,$xfrm,$xxx,$xxx,` $xxx,$xxx,$FF3,$outBlock,FF2,HWHash,$FF1,$ScrPath,$FF0,$PerUser,$FF0,$peruser,$FEF,$az,$FEE,$bz,$FED,$cz,$FEC,$dz,$FEB,$ez,FEA,runScript,$FE9,$textofscriptblock,FE8,XORHash,$xxx,$xxx,` $xxx,$xxx,$FE7,$input1,$FE6,$input2,$FE5,$combinedBytes,$FE4,$count2,$FE3,$hex1,$FE2,$hex2,$FE1,$bit1,$FE0,$bit2,$FDF,$combinedBits,$FDE,$count,$FDD,$x1,$FDC,$x2,$xxx,$xxx,` $xxx,$xxx,$FDB,$final,FD4,HexAscii,$FD3,$dbytes,$FD2,$stop,$FD1,$decrypted,FD0,Licence,FD0,licence,$FCF,$RegHex,$FCE,$psw,$FCD,$ScrPath,FCB,GetReg,$xxx,$xxx,` $xxx,$xxx,FC7,GetReg,$FC6,$forceUnc,$FC6,$forceUnC,$FC5,$encHex,$FC5,$EncHex,$FC4,$savePass,$FC3,$pass,$FC2,$AesCSP,$FC1,$hex,$FC0,$EncBytes,$xxx,$xxx,` $xxx,$xxx,FBF,value,$FBF,$value,FBF,Value,$FBD,$Reg,$FBD,$reg,$FBC,$key,$FBC,$Key,-FBC,-key,$FBB,$Set,$FBB,$set,-FBB,-Set,-FBB,-set,$FBA,$zz,$xxx,$xxx,` $FB9,$xxx,` $FB8,$xxx,` $FB7,$xxx,` $FB6,$xxx,` $FB5,$xxx,` $FB4,$xxx,` $FB3,$xxx,` $FB2,$xxx,` $FB1,$xxx,` $FB0,$xxx,` $FAF,$xxx,` $FAE,$xxx,` $FAD,$xxx,` $FAC,$xxx,` $FAB,$xxx,` $FAA,$xxx,` $FA9,$xxx,` $FA8,$xxx,` $FA7,$xxx,` $FA6,$xxx,` $FA5,$xxx,` $FA4,$xxx,` $FA3,$xxx,` $FA2,$xxx,` $FA1,$xxx,` $FA0,$xxx,` $F9F,$xxx,` $F9E,$xxx,` $F9D,$xxx,` $F9C,$xxx,` $F9B,$xxx,` $F9A,$xxx,' #spares $subArray = $sub.Split(',') for($x=0;$X-le$subArray.length-2; $x=$x+2){$tb=$tb.replace($subArray[$x+1],$subArray[$x])} } $tb | out-file $outputScript ii $outputScript } } } <# Challenge1 Create a new encrypted script, just use -savePass option. Run script (using console), thus saving password in registry. Then without using original password or modification to script, obtain plain text of encrypted script. Use debuger tracer or any other idea or external tool to achieve this goal. Full points for explaining how you succeeded. Skip to Challenge 4 Challenge2 Create a new encrypted script, just use -savePass option. Run script (using console), thus saving password in registry. Move or rename script and then Manually build the hardware hash by analysing code and original environment extract password hash from registry key using your hacked hardware hash and then use that to obtain plain text of encrypted script. Re-entering password "Password1" at any time is a fail. (A true attacker would not know it) Challenge3 Same as Challenge2 but also use -perUser option Instead of moving script, log onto computer using another account and attempt to retrieve plain text of decrypted script. Re-entering password "Password1" at any time is a fail. (A true attacker would not know it) Simulating original user's password being reset by logging on as them to get the hash of their identity is a half pass. Explain how you obtained the user specific part of the hash without compromising users account for full points Challenge4 Move to the next level by modifying the script to make it more secure. Explain the steps or provide code for full points. Challenge5 You are obviously interested in the concept of this script to have got this far, add another feature, correct a bug, make it more robust and/or repost to another forum to see if others can take the idea further. Thanks. #>
PowerShellCorpus/PoshCode/0ba8cce5-b168-4f3d-a2e5-9c04920fb80e.ps1
0ba8cce5-b168-4f3d-a2e5-9c04920fb80e.ps1
# The $test variable can be pretty much whatever you want it to be, or with a little adjustment it isn't even necessary. # I just wanted to set it up like this for the $match variable later on $test=(get-folder testing|get-vm) #$data and the csv is where all the information lies that this script/s pulls $data=import-csv book1.csv $hostcredential=Get-Credential "Host Credentials" $guestcredential=Get-Credential "Guest Credentials" #Line row, row line, same thing in a spreadsheet. I just wish I knew more of those basic understood variables such as $line. # If anyone knows a good listing please let me know foreach ($line in $data) { #For each of the VMs in $test it checks to see if there is a listing for that vm name in the excel spreadsheet. $match=$test|?{$line.guestname -eq $_.name} IF($match) { #Oh invoke-vmscript how I both love and hate you. This calls for the execution of the script works2.ps1 script locally on the remote computer invoke-vmscript -vm $match.name -scripttext '&"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" "C:\\Power\\works2.ps1"' -scripttype "powershell" -hostcredential $hostcredential -guestcredential $guestcredential -confirm } }
PowerShellCorpus/PoshCode/Find Local Group Members_8.ps1
Find Local Group Members_8.ps1
# Author: Hal Rottenberg # Purpose: Find matching members in a local group # Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx # Change these two to suit your needs $ChildGroups = "Domain Admins", "Group Two" $LocalGroup = "Administrators" $MemberNames = @() # uncomment this line to grab list of computers from a file # $Servers = Get-Content serverlist.txt $Servers = $env:computername # for testing on local computer foreach ( $Server in $Servers ) { $Group= [ADSI]"WinNT://$Server/$LocalGroup,group" $Members = @($Group.psbase.Invoke("Members")) $Members | ForEach-Object { $MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) } $ChildGroups | ForEach-Object { $output = "" | Select-Object Server, Group, InLocalAdmin $output.Server = $Server $output.Group = $_ $output.InLocalAdmin = $MemberNames -contains $_ Write-Output $output } }
PowerShellCorpus/PoshCode/Added_Deleted AD Objects_2.ps1
Added_Deleted AD Objects_2.ps1
#REQUIRES -pssnapin quest.activeroles.admanagement #REQUIRES -pssnapin Pscx begin { # Build variables $strSMTPServer = "xx.xx.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/Out-Html.ps1
Out-Html.ps1
################################################################################ # Out-HTML - converts cmdlets help to HTML format # Based on Out-wiki by Dimitry Sotnikov (http://dmitrysotnikov.wordpress.com/2008/08/18/out-wiki-convert-powershell-help-to-wiki-format/) # # Modify the invocation line at the bottom of the script if you want to document # fewer command, subsets or snapins # Open default.htm to view in frameset or index.htm for index page with links. ################################################################################ # Created By: Vegard Hamar ################################################################################ param($outputDir = "./help") function FixString { param($in = "") if ($in -eq $null) { $in = "" } return $in.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;") } function Out-HTML { param($commands = $null, $outputDir = "./help") $commandsHelp = $commands | sort-object PSSnapIn, noun | get-help -full #create an output directory if ( -not (Test-Path $outputDir)) { md $outputDir | Out-Null } #Generate frame page $indexFileName = $outputDir + "/index.htm" #Generate frameset @' <html> <head> <title>PowerShell Help</title> </head> <frameset cols="250,*"> <frame src="./index.htm" /> <frame src="" name="display"/> </frameset> </html> '@ | Out-File "$outputDir/default.htm" #Generate index @' <html> <head> <title>PowerShell Help</title> </head> <body> '@ | out-file $indexFileName $SnapIn = "" foreach ($c in $commandsHelp) { if ($SnapIn -ne $c.PSSnapIn.Name) { "<a href='#" + $c.PSSnapIn.name + "'>* " + $c.PSSnapIn.Name.Replace(".", " ") + "</a></br>" | out-file $indexFileName -Append $SnapIn = $c.PSSnapIn.Name } } $SnapIn = "" foreach ($c in $commandsHelp) { if ($SnapIn -ne $c.PSSnapIn.Name) { "<h3><a name='$($c.PSSnapIn.Name)'>" +$c.PSSnapIn.Name.Replace(".", " ") + "</a></h3>" | Out-File $indexFileName -Append $SnapIn = $c.PSSnapIn.Name } "<a href='" + $c.name + ".htm' target='display'>* $($c.Name)</a></br>" | out-file $indexFileName -Append } #Generate all single help files $outputText = $null foreach ($c in $commandsHelp) { $fileName = ( $outputDir + "/" + $c.Name + ".htm" ) @" <html> <head> <title>$($c.Name)</title> </head> <body> <h1>$($c.Name)</h1> <div>$($c.synopsis)</div> <h2> Syntax </h2> <code>$(FixString($c.syntax | out-string -width 2000).Trim())</code> <h2> Detailed Description </h2> <div>$(FixString($c.Description | out-string -width 2000))</div> <h2> Related Commands </h2> <div> "@ | out-file $fileName foreach ($relatedLink in $c.relatedLinks.navigationLink) { if($relatedLink.linkText -ne $null -and $relatedLink.linkText.StartsWith("about") -eq $false){ " * <a href='$($relatedLink.linkText).htm'>$($relatedLink.linkText)</a><br/>" | out-file $fileName -Append } } @" </div> <h2> Parameters </h2> <table border='1'> <tr> <th>Name</th> <th>Description</th> <th>Required?</th> <th>Pipeline Input</th> <th>Default Value</th> </tr> "@ | out-file $fileName -Append $paramNum = 0 foreach ($param in $c.parameters.parameter ) { @" <tr valign='top'> <td>$($param.Name)&nbsp;</td> <td>$(FixString(($param.Description | out-string -width 2000).Trim()))&nbsp;</td> <td>$(FixString($param.Required))&nbsp;</td> <td>$(FixString($param.PipelineInput))&nbsp;</td> <td>$(FixString($param.DefaultValue))&nbsp;</td> </tr> "@ | out-file $fileName -Append } " </table>}" | out-file $fileName -Append # Input Type if (($c.inputTypes | Out-String ).Trim().Length -gt 0) { @" <h2> Input Type </h2> <div>$(FixString($c.inputTypes | out-string -width 2000).Trim())</div> "@ | out-file $fileName -Append } # Return Type if (($c.returnValues | Out-String ).Trim().Length -gt 0) { @" <h2> Return Values </h2> <div>$(FixString($c.returnValues | out-string -width 2000).Trim())</div> "@ | out-file $fileName -Append } # Notes if (($c.alertSet | Out-String).Trim().Length -gt 0) { @" <h2> Notes </h2> "<div>$(FixString($c.alertSet | out-string -Width 2000).Trim())</div> "@ | out-file $fileName -Append } # Examples if (($c.examples | Out-String).Trim().Length -gt 0) { " <h2> Examples </h2>" | out-file $fileName -Append foreach ($example in $c.examples.example) { @" <h3> $(FixString($example.title.Trim(('-',' '))))</h3> <pre>$(FixString($example.code | out-string ).Trim())</pre> <div>$(FixString($example.remarks | out-string -Width 2000).Trim())</div> "@ | out-file $fileName -Append } } @" </body> </html> "@ | out-file $fileName -Append } @" </body> </html> "@ | out-file $indexFileName -Append } Out-HTML (Get-Command ) $outputDir
PowerShellCorpus/PoshCode/Get Exchange DB Stats_1.ps1
Get Exchange DB Stats_1.ps1
# requires -version 2.0 # # get-sgstats2010.ps1 # # returns various info about storage groups # # Author: rfoust@duke.edu # Modified: May 20, 2012 # # This has only been tested with Exchange 2010 # Use -nomountpoint if you don't use mountpoints in your environment param([string]$server=$env:computername.tolower(), [string]$database="NotSpecified", [switch]$all, [switch]$noemail, [switch]$nologcheck, [switch]$nomountpoint) #Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin if (!(get-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlycontinue)) { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 } # found this really cool function here: http://www.olavaukan.com/tag/powershell/ function Util-Convert-FileSizeToString { param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [int64]$sizeInBytes ) switch ($sizeInBytes) { {$sizeInBytes -ge 1TB} {"{0:n$sigDigits}" -f ($sizeInBytes/1TB) + " TB" ; break} {$sizeInBytes -ge 1GB} {"{0:n$sigDigits}" -f ($sizeInBytes/1GB) + " GB" ; break} {$sizeInBytes -ge 1MB} {"{0:n$sigDigits}" -f ($sizeInBytes/1MB) + " MB" ; break} {$sizeInBytes -ge 1KB} {"{0:n$sigDigits}" -f ($sizeInBytes/1KB) + " KB" ; break} Default { "{0:n$sigDigits}" -f $sizeInBytes + " Bytes" } } } # specifying only a single database using -database makes the script run faster for testing if ($database -eq "NotSpecified") { # $dbs = get-mailboxdatabase -status | ? { $_.replicationtype -eq "Remote" } | select-object servername,name,databasesize,mounted | sort servername,name $dbs = get-mailboxdatabase -status | ? { $_.replicationtype -eq "Remote" } | sort servername,name } else { $dbs = get-mailboxdatabase $database -status | sort servername,name } $fragments = @() # array to hold html fragments $data = @() # array to hold the psobjects $prettydata = @() # array to hold pretty data (strings, not raw bytes) foreach ($db in $dbs) { write-host "Processing $db." $raw = new-object psobject $pretty = new-object psobject write-host "Gathering count of mailboxes on $db." $mailboxes = (get-mailbox -database $db.name -resultsize unlimited).count #get copy status $copystatus = (get-mailboxdatabasecopystatus $db.name | ? { $_.activecopy -eq $false }).status if (-not $nologcheck) { #figure out how much space the logs are consuming # $drive will probably end up being D$ in all cases, but might as well do the logic to figure it out write-host "Finding out how much disk space the log files are using for $db ..." $drive = $db.logfolderpath.tostring().substring(0,1) + "$" $substring = $db.logfolderpath.tostring().substring(0,2) $uncpath = "\\\\$($db.server)\\" + $drive + ($db.logfolderpath.tostring().replace($substring,"")) + "\\*.log" $logsize = (ls $uncpath | measure-object -property length -sum).sum $logsizetotal += $logsize $logsize = util-convert-filesizetostring $logsize } #calculate average mailbox size Write-Host "Calculating average mailbox size ..." $avg = get-mailboxstatistics -database $db | % { $_.totalitemsize.value.tobytes() } $avg = ($avg | Measure-Object -Average).average $avgTotal += $avg if ($avg) { $avgPretty = util-convert-filesizetostring $avg } #calculate deleted mailbox size Write-Host "Calculating deleted mailbox size ..." $deletedMBsize = get-mailboxstatistics -database $db | ? { $_.DisconnectDate -ne $null } | % { $_.totalitemsize.value.tobytes() } $deletedMBsize = ($deletedMBsize | Measure-Object -Sum).sum $deletedMBsizeTotal += $deletedMBsize if ($deletedMBsize) { $deletedMBsizePretty = util-convert-filesizetostring $deletedMBsize } #calculate dumpster size Write-Host "Calculating dumpster size ..." $dumpster = get-mailboxstatistics -database $db | % { $_.totaldeleteditemsize.value.tobytes() } $dumpster = ($dumpster | Measure-Object -Sum).sum $dumpsterTotal += $dumpster if ($dumpster) { $dumpsterPretty = util-convert-filesizetostring $dumpster } #get a shorter db size $dbsize = $db.databasesize.tobytes() $dbsizetotal += $dbsize if ($dbsize) { $dbsizePretty = util-convert-filesizetostring $dbsize } #get free space on the mountpoint volume if ($nomountpoint) { $freespace = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.drivename + "\\") }).freespace } else { $freespace = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.tostring() + "\\") }).freespace } $freespacetotal += $freespace if ($freespace) { $freespacePretty = util-convert-filesizetostring $freespace } #get capacity on the mountpoint volume if ($nomountpoint) { $capacity = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.drivename + "\\") }).capacity } else { $capacity = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.tostring() + "\\") }).capacity } $capacitytotal += $capacity if ($capacity) { $capacityPretty = util-convert-filesizetostring $capacity } #get a shorter whitespace size $whitespace = $db.availablenewmailboxspace.tobytes() $whitespacetotal += $whitespace if ($whitespace) { $whitespacePretty = util-convert-filesizetostring $whitespace } # create psobject with raw bytes $raw | add-member NoteProperty "ServerName" $db.servername $raw | add-member NoteProperty "Database" $db.name $raw | add-member NoteProperty "Mailboxes" $mailboxes $raw | add-member NoteProperty "CopyStatus" $copystatus $raw | add-member NoteProperty "DBSize" $dbsize # $raw | add-member NoteProperty "Mounted" $db.mounted $raw | add-member NoteProperty "LogSize" $logsize $raw | add-member NoteProperty "FreeSpace" $freespace $raw | add-member NoteProperty "TotalSpace" $capacity $raw | add-member NoteProperty "Whitespace" $whitespace $raw | add-member NoteProperty "Deleted Mbox" $deletedMBsize $raw | add-member NoteProperty "Dumpster" $dumpster $raw | add-member NoteProperty "Avg Mbox" $avgPretty $raw | add-member NoteProperty "Last Full Backup" $db.lastfullbackup $raw | add-member NoteProperty "Last Incr Backup" $db.lastincrementalbackup $data += $raw # create psobject with pretty display sizes (MB, GB, etc) $pretty | add-member NoteProperty "ServerName" $db.servername $pretty | add-member NoteProperty "Database" $db.name $pretty | add-member NoteProperty "Mailboxes" $mailboxes $pretty | add-member NoteProperty "CopyStatus" $copystatus $pretty | add-member NoteProperty "DBSize" $dbsizePretty # $pretty | add-member NoteProperty "Mounted" $db.mounted $pretty | add-member NoteProperty "LogSize" $logsize $pretty | add-member NoteProperty "FreeSpace" $freespacePretty $pretty | add-member NoteProperty "TotalSpace" $capacityPretty $pretty | add-member NoteProperty "Whitespace" $whitespacePretty $pretty | add-member NoteProperty "Deleted Mbox" $deletedMBsizePretty $pretty | add-member NoteProperty "Dumpster" $dumpsterPretty $pretty | add-member NoteProperty "Avg Mbox" $avgPretty $pretty | add-member NoteProperty "Last Full Backup" $db.lastfullbackup $pretty | add-member NoteProperty "Last Incr Backup" $db.lastincrementalbackup $prettydata += $pretty } # add a "total" row $thingy = new-object psobject write-host; write-host "Calculating totals ..." $mailboxes = ($data | measure-object mailboxes -sum).sum $deletedMBsizetotal = ($deletedMBsizetotal | Measure-Object -Sum).sum $thingy | add-member NoteProperty "ServerName" "Total" $thingy | add-member NoteProperty "Database" $data.count $thingy | add-member NoteProperty "DBSize" (util-convert-filesizetostring $dbsizetotal) $thingy | add-member NoteProperty "Mailboxes" $mailboxes if (-not $nologcheck) { $thingy | add-member NoteProperty "LogSize" (util-convert-filesizetostring $logsizetotal) } $thingy | add-member NoteProperty "FreeSpace" (util-convert-filesizetostring $freespacetotal) $thingy | add-member NoteProperty "TotalSpace" (util-convert-filesizetostring $capacitytotal) $thingy | add-member NoteProperty "Whitespace" (util-convert-filesizetostring $whitespacetotal) $thingy | Add-Member NoteProperty "Deleted Mbox" (util-convert-filesizetostring $deletedMBsizeTotal) $thingy | Add-Member NoteProperty "Dumpster" (util-convert-filesizetostring $dumpsterTotal) #$thingy | Add-Member NoteProperty "Avg Mbox" (util-convert-filesizetostring $avgTotal) $prettyData += $thingy # add raw data total row $thingy = new-object psobject $mailboxes = ($data | measure-object mailboxes -sum).sum $deletedMBsizetotal = ($deletedMBsizetotal | Measure-Object -Sum).sum $thingy | add-member NoteProperty "ServerName" "Total" $thingy | add-member NoteProperty "Database" $data.count $thingy | add-member NoteProperty "DBSize" $dbsizetotal $thingy | add-member NoteProperty "Mailboxes" $mailboxes if (-not $nologcheck) { $thingy | add-member NoteProperty "LogSize" $logsizetotal } $thingy | add-member NoteProperty "FreeSpace" $freespacetotal $thingy | add-member NoteProperty "TotalSpace" $capacitytotal $thingy | add-member NoteProperty "Whitespace" $whitespacetotal $thingy | Add-Member NoteProperty "Deleted Mbox" $deletedMBsizeTotal $thingy | Add-Member NoteProperty "Dumpster" $dumpsterTotal #$thingy | Add-Member NoteProperty "Avg Mbox" $avgTotal $data += $thingy # dump pretty data out to screen $prettyData # bullet graph idea came from here: http://www.usrecordings.com/test-lab/bullet-graph.htm # powershell html chart was inspired by: http://jdhitsolutions.com/blog/2012/02/create-html-bar-charts-from-powershell/ $style = "<style type=`"text/css`"> html * { margin: 0; padding: 0; border: 0; } body { text-align: left; font: 10pt Arial, sans-serif; } TH { border-width: 1px; padding: 0px; border-style: solid; border-color: black; background-color: thistle } h1 { font: 30pt Arial, sans-serif; padding: 10px 0 5px 0; width: 540px; margin: 0 auto 10px auto; border-bottom: 1px solid #8f8f8f; text-align: left; } h2 { font: 20pt Arial, sans-serif; } p#contact { font: 10pt Arial, sans-serif; width: 398px; margin: 0 auto; padding-top: 7px; text-align: left; line-height: 140%; } a:link, a:visited, a:hover { color: rgb(32,108,223); font-weight: bold; text-decoration: none; } a:hover { color: #cc0000; font-weight: bold; } div#container { position: relative; margin: 0px 50px; padding: 0; text-align: left; top: 80px; width: 250px; } /* BULLET GRAPH */ div.box-wrap { position: relative; width: 200px; height: 21px; top: 0; left: 0; margin: 0; padding: 0; } /* CHANGE THE WIDTH AND BACKGROUND COLORS AS NEEDED */ div.box1 { position: absolute; height: 20px; width: 30%; left: 0; background-color: #eeeeee; z-index: 1; font-size: 0; } div.box2 { position: absolute; height: 20px; width: 30%; left: 30%; background-color: #dddddd; z-index: 1; font-size: 0; } div.box3 { position: absolute; height: 20px; width: 30%; left: 60%; background-color: #bbbbbb; z-index: 1; font-size: 0; } div.box4 { position: absolute; height: 20px; width: 10%; left: 90%; background-color: #bbbbbb; z-index: 1; font-size: 0; } /* RED LINE */ div.target { position: absolute; height: 20px; width: 1px; left: 32px; top: 0; background-color: #cc0000; z-index: 7; font-size: 0; } /* ONE SEGMENT ONLY */ div.actual { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #000000; font-size: 0; z-index: 5; font-size: 0; } /* TWO SEGMENTS */ div.actualWhitespace { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #b580fe; font-size: 0; z-index: 5; font-size: 0; } div.actualDeleted { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #2d006b; font-size: 0; z-index: 5; font-size: 0; } div.actualDumpster { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #dabffe; font-size: 0; z-index: 5; font-size: 0; } div.actualData { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #400099; font-size: 0; z-index: 5; font-size: 0; } div.mylabel { position: relative; height: 20px; width: 145px; left: -155px; top: 2px; background-color: #fff; z-index: 7; font-size: 0; color: #000000; font: 10pt Arial, sans-serif; text-align: right; } div.scale-tb1 { padding: 0; margin: 0; font-size: 0; width: 200px; border: 0; position: relative; top: 10px; left: 0px; border-top: 1px solid #8f8f8f; } div.scale-tb2 { padding: 0; margin: 0; font-size: 0; width: 200px; border: 0; position: relative; top: 0px; left: 0px; } /* SCALE MARKS */ div.sc21 { position: absolute; height: 7px; width: 1px; left: 0px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc22 { position: absolute; height: 7px; width: 1px; left: 39px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc23 { position: absolute; height: 7px; width: 1px; left: 79px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc24 { position: absolute; height: 7px; width: 1px; left: 119px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc25 { position: absolute; height: 7px; width: 1px; left: 159px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc26 { position: absolute; height: 7px; width: 1px; left: 199px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc31 { position: absolute; height: 7px; width: 1px; left: 0px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc32 { position: absolute; height: 7px; width: 1px; left: 39px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc33 { position: absolute; height: 7px; width: 1px; left: 79px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc34 { position: absolute; height: 7px; width: 1px; left: 119px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc35 { position: absolute; height: 7px; width: 1px; left: 159px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc36 { position: absolute; height: 7px; width: 1px; left: 199px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } /* SCALE TEXT */ div.cap21 { position: absolute; top: 40px; left: -2px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap22 { position: absolute; top: 40px; left: 35px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap23 { position: absolute; top: 40px; left: 71px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap24 { position: absolute; top: 40px; left: 112px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap25 { position: absolute; top: 40px; left: 152px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap26 { position: absolute; top: 40px; left: 191px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap31 { position: absolute; top: 29px; left: -2px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap32 { position: absolute; top: 29px; left: 35px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap33 { position: absolute; top: 29px; left: 71px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap34 { position: absolute; top: 29px; left: 112px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap35 { position: absolute; top: 29px; left: 152px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap36 { position: absolute; top: 29px; left: 191px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } </style>" $fragments += "<H2>Exchange 2010 Statistics</H2>" $fragments += $prettyData | ConvertTo-Html -fragment # $fragments += "<br>" $html = @() $html += "<div id=`"container`">" $html += "Database Size Graph" foreach ($db in $data) { if ($db.servername -ne "Total") { $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: $([math]::round((($db.totalspace - $db.freespace) / $db.totalspace) * 100))%`"></div> <div class=`"actualWhitespace`" style=`"width: $([math]::round((($db.dbsize) / $db.totalspace)*100))%`"></div> <div class=`"actualDeleted`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"actualDumpster`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace - $db.'deleted mbox') / $db.totalspace)*100))%`"></div> <div class=`"actualData`" style=`"width: $([math]::round((($db.dbsize - $db.dumpster - $db.'deleted mbox' - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"mylabel`">$($db.database)</div> <div class=`"cap31`">0%</div> <div class=`"cap32`">20%</div> <div class=`"cap33`">40%</div> <div class=`"cap34`">60%</div> <div class=`"cap35`">80%</div> <div class=`"cap36`">100%</div> <div class=`"scale-tb2`"> <div class=`"sc31`"></div> <div class=`"sc32`"></div> <div class=`"sc33`"></div> <div class=`"sc34`"></div> <div class=`"sc35`"></div> <div class=`"sc36`"></div> </div> </div> <p style=`"height: 30px;`"></p>" } else # total row { $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: $([math]::round((($db.totalspace - $db.freespace) / $db.totalspace) * 100))%`"></div> <div class=`"actualWhitespace`" style=`"width: $([math]::round((($db.dbsize) / $db.totalspace)*100))%`"></div> <div class=`"actualDeleted`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"actualDumpster`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace - $db.'deleted mbox') / $db.totalspace)*100))%`"></div> <div class=`"actualData`" style=`"width: $([math]::round((($db.dbsize - $db.dumpster - $db.'deleted mbox' - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"mylabel`">Total</div> <div class=`"cap31`">0%</div> <div class=`"cap32`">20%</div> <div class=`"cap33`">40%</div> <div class=`"cap34`">60%</div> <div class=`"cap35`">80%</div> <div class=`"cap36`">100%</div> <div class=`"scale-tb2`"> <div class=`"sc31`"></div> <div class=`"sc32`"></div> <div class=`"sc33`"></div> <div class=`"sc34`"></div> <div class=`"sc35`"></div> <div class=`"sc36`"></div> </div> </div> <p style=`"height: 30px;`"></p>" } } # show a graph key $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: 90%`"></div> <div class=`"actualWhitespace`" style=`"width: 100%`"></div> <div class=`"actualDeleted`" style=`"width: 75%`"></div> <div class=`"actualDumpster`" style=`"width: 50%`"></div> <div class=`"actualData`" style=`"width: 25%`"></div> <div class=`"mylabel`">Key:</div> </div> MBs - Dumpster - Del MB - Whitespace<br> Red Line: Used Disk Space </div> <p style=`"height: 30px;`"></p>" $html += "</div><!-- container -->" $fragments += $html $emailbody = convertto-html -head $style -Body $fragments $date = get-date -uformat "%Y-%m-%d" if (-not $noemail) { $smtpServer = "your.smtpserver.com" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "somebody@somewhere.com" $msg.To.Add("you@somewhere.com") $msg.Subject = "Exchange 2010 Daily Statistics" $msg.Body = $emailbody $msg.IsBodyHtml = $true $smtp.Send($msg) }
PowerShellCorpus/PoshCode/Import-Iis-Log_2.ps1
Import-Iis-Log_2.ps1
param ( [Parameter( Mandatory=$true, Position = 0, ValueFromPipeline=$true, HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log." )] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter( Position = 1, HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar." )] [ValidateNotNullOrEmpty()] [string] $Delimiter = " ", [Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8 ) begin { $fieldNames = @() $output = New-Object Object Add-Member -InputObject $output -MemberType NoteProperty -Name "DateTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ClientHost" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserName" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Service" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Machine" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerIp" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerPort" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Method" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ScriptPath" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "QueryString" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceSubStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Win32Status" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesSent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesRecived" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProcessingTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProtocolVersion" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Host" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserAgent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Cookie" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Referer" -Value $null ##### ##fix by dezaron. ##### [Reflection.Assembly]::LoadFile( ` 'C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\System.Web.dll')` | out-null <# Unable to find type [System.Web.HttpUtility]: make sure that the assembly containing this type is loaded. #> } process { foreach($line in Get-Content -Path $Path -Encoding $Encoding) { if($line.StartsWith("#Fields: ")) { $fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter)); } elseif(-not $line.StartsWith("#")) { $fieldValues = @($line.Split($Delimiter)); for($i = 0; $i -lt $fieldValues.Length; $i++) { $name = $fieldNames[$i] $value = $fieldValues[$i] switch($name) { "date" { $output.DateTime = [DateTime]::Parse($value) } "time" { $output.DateTime += [TimeSpan]::Parse($value) } "c-ip" { $output.ClientHost = [System.Net.IPAddress]::Parse($value) } "cs-username" { $output.UserName = if($value -eq '-') { $null } else { $value } } "s-sitename" { $output.Service = $value } "s-computername" { $output.Machine = $value } "s-ip" { $output.ServerIp = [System.Net.IPAddress]::Parse($value) } "s-port" { $output.ServerPort = [int]$value } "cs-method" { $output.Method = $value } "cs-uri-stem" { $output.ScriptPath = [System.Web.HttpUtility]::UrlDecode($value) } "cs-uri-query" { $output.QueryString = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } "sc-status" { $output.ServiceStatus = [int]$value } "sc-substatus" { $output.ServiceSubStatus = [int]$value } "sc-win32-status" { $output.Win32Status = [BitConverter]::ToInt32([BitConverter]::GetBytes([UInt32]($value)), 0) } "sc-bytes" { $output.BytesSent = [UInt64]$value } "cs-bytes" { $output.BytesRecived = [UInt64]$value } "time-taken" { $output.ProcessingTime = [int]$value } "cs-version" { $output.ProtocolVersion = $value } "cs-host" { $output.Host = if($value -eq '-') { $null } else { $value } } "cs(User-Agent)" { $output.UserAgent = if($value -eq '-') { $null } else { $value } } "cs(Cookie)" { $output.Cookie = if($value -eq '-') { $null } else { $value } } "cs(Referer)" { $output.Referer = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } } } Write-Output $output } } }
PowerShellCorpus/PoshCode/Add-SqlClientAlias.ps1
Add-SqlClientAlias.ps1
####################### <# .SYNOPSIS Adds a SQL Server Client Alias by setting registry key. .DESCRIPTION Provides same functionality as cliconfg.exe GUI. Although there is a WMI provider to add client network aliases, the differences between SQL version make it diffult to use. This method creates the registry key. .EXAMPLE ./add-sqlclientalias.ps1 -ServerAlias Z001\\sql2 -ServerName Z001XA\\sql2 -Protocol TCP -Port 5658 This command add a SQL client alias .NOTES Version History v1.0 - Chad Miller - 9/24/2012 - Initial release .LINK http://social.msdn.microsoft.com/Forums/sa/sqldataaccess/thread/39fe3b15-96a1-454f-b3bd-da6b1f74700a #> param( [Parameter(Position=0, Mandatory=$true)] [string] $ServerAlias, [Parameter(Position=1, Mandatory=$true)] [string] $ServerName, [ValidateSet("NP", "TCP")] [Parameter(Position=2, Mandatory=$true)] [string] $Protocol="TCP", [Parameter(Position=3, Mandatory=$false)] [int] $PortNumber ) if ($Protocol="TCP") { if ($PortNumber) { $value = "DBMSSOCN,{0},{1}" -f $ServerName,$PortNumber } else { $value = "DBMSSOCN,{0}" -f $ServerName } } else { $value = "DBNMPNTW,\\\\{0}\\pipe\\sql\\query" -f $ServerName } Set-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo' -Name $ServerAlias -Value $value
PowerShellCorpus/PoshCode/Test-WebDAV_3.ps1
Test-WebDAV_3.ps1
function Test-WebDav () { param ( $Url = "$( throw 'URL parameter is required.')" ) $xhttp = New-Object -ComObject msxml2.xmlhttp $xhttp.open("OPTIONS", $url, $false) $xhttp.send() if ( $xhttp.getResponseHeader("DAV") ) { $true } else { $false } }
PowerShellCorpus/PoshCode/Force WSUS Check.ps1
Force WSUS Check.ps1
# Powershell Script to force clients check into WSUS server # Import Active Directory PS Modules CMDLETS Import-Module ActiveDirectory $comps = Get-ADComputer -Filter {operatingsystem -like "*server*"} $cred = Get-Credential Foreach ($comp in $comps) { Invoke-Command -computername $comp.Name -credential $cred { wuauclt.exe /detectnow } Write-Host Forced WSUS Check-In on $comp.Name }
PowerShellCorpus/PoshCode/357ba246-f3a1-4446-97ea-d22781827866.ps1
357ba246-f3a1-4446-97ea-d22781827866.ps1
function Write-ProgressForm { <# .SYNOPSIS Write-ProgressForm V1.0 GUI Replacement for PowerShell's Write-Progress command .DESCRIPTION GUI Replacement for PowerShell's Write-Progress command Uses same named parameters for drop-in replacement CAVEATS: You can't close the Form by clicking on it, must call Write-ProgressForm -Completed Therefore decided to hide Close button (why tease people?) .INPUTS Same as Write-Progress command BONUS: -ICOpath <path to your ICO> -FormTitle <Title of the Write-progress form> (Only needs to be mentioned when 1st called then it sticks around) .OUTPUTS Nothing but a GUI .NOTES Uses Global variables extensively License: GPL v3.0 or greater / BSD (Latest version) Form Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 Generated On: 30/01/2013 12:38 PM Generated By: Denis St-Pierre, Ottawa, Canada #> param( #parameters with default values assigned [String]$Activity="Activity", [String]$CurrentOperation="CurrentOperation", [String]$status="Status", [Int]$PercentComplete=0, [switch]$Completed=$false, [int]$FontSize = 10, [String]$ICOpath="", #yes, you can use your *OWN* icon file in the form [String]$FormTitle="" ) $HideUselessCloseButton=$true #Change to false if you can fix it, pls $UselessAutoSize=$false #Useless because it doesn't work as expected #If WriteProgressForm variable exists, use it. If ( Get-Variable -Name WriteProgressForm -Scope Global -ErrorAction SilentlyContinue ) { If ( $Completed){ #If asked to close, do it $progressBar1.Value=100 $StatusLabel.Text = "Complete" Start-Sleep -Seconds 1 $WriteProgressForm.close() Return } else { #otherwise, Update it $progressBar1.Value = $PercentComplete #To update Progress bar position $ActivityLabel.Text = "$Activity" $CurrentOperationLabel.Text = "$CurrentOperation" $StatusLabel.Text = "$status" Return } } #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $global:WriteProgressForm = New-Object System.Windows.Forms.Form $global:StatusLabel = New-Object System.Windows.Forms.Label $CloseButton = New-Object System.Windows.Forms.Button $global:progressBar1 = New-Object System.Windows.Forms.ProgressBar $global:CurrentOperationLabel = New-Object System.Windows.Forms.Label $global:ActivityLabel = New-Object System.Windows.Forms.Label $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. # $WriteProgressForm.close()= # { #TODO: Place custom script here # } $CloseButton_OnClick= { #TODO: Place custom script here } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $WriteProgressForm.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $WriteProgressForm.AccessibleDescription = "WriteProgressFormDesc" $WriteProgressForm.AccessibleName = "WriteProgressForm" $WriteProgressForm.AccessibleRole = 48 $WriteProgressForm.AutoSize = $true #works on forms, labels not so much $WriteProgressForm.AutoSizeMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 170 # $System_Drawing_Size.Width = 505 # $WriteProgressForm.ClientSize = $System_Drawing_Size $WriteProgressForm.DataBindings.DefaultDataSourceUpdateMode = 0 $WriteProgressForm.StartPosition = 1 #Center of the Screen #add Icon to dialog, if possible If ( ($ICOpath -ne "") -and (Test-Path "$ICOpath") ) { Try { #If the ICO file is NFG, ignore and move on $WriteProgressForm.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon("$ICOpath") } catch { } #use default ICO } $WriteProgressForm.Name = "WriteProgressForm" $WriteProgressForm.Text = "$FormTitle" # $WriteProgressForm.add_FormClosing($WriteProgressForm.close()) #failed attempt to make CloseButton work w/o PS code # ** $StatusLabel $StatusLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 33 $StatusLabel.Location = $System_Drawing_Point $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 475 $StatusLabel.MinimumSize = $System_Drawing_Size $StatusLabel.AutoSize = $UselessAutoSize $StatusLabel.Name = "StatusLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $StatusLabel.Padding = $System_Windows_Forms_Padding # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 475 # $StatusLabel.Size = $System_Drawing_Size $StatusLabel.TabIndex = 4 $StatusLabel.Text = "$status" $WriteProgressForm.Controls.Add($StatusLabel) # ** $CloseButton $CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 400 $System_Drawing_Point.Y = 134 $CloseButton.Location = $System_Drawing_Point $CloseButton.Name = "CloseButton" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 25 $System_Drawing_Size.Width = 90 $CloseButton.Size = $System_Drawing_Size $CloseButton.TabIndex = 3 $CloseButton.Text = "Close" $CloseButton.UseVisualStyleBackColor = $True $CloseButton.add_Click($CloseButton_OnClick) # $CloseButton.add_MouseClick($WriteProgressForm.close()) #failed attempt #2 to make CloseButton work w/o PS code If ($HideUselessCloseButton) { #dont add button to form } else { $WriteProgressForm.Controls.Add($CloseButton) } # ** $progressBar1 $progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 10 $System_Drawing_Point.Y = 57 $progressBar1.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 5 $System_Windows_Forms_Padding.Bottom = 5 $System_Windows_Forms_Padding.Left = 5 $System_Windows_Forms_Padding.Right = 5 $System_Windows_Forms_Padding.Top = 5 $progressBar1.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 30 $System_Drawing_Size.Width = 480 $progressBar1.MinimumSize = $System_Drawing_Size $progressBar1.AutoSize = $UselessAutoSize #doesn't work, stays the same size $progressBar1.Name = "progressBar1" # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 30 # $System_Drawing_Size.Width = 480 # $progressBar1.Size = $System_Drawing_Size $progressBar1.Step = 1 $progressBar1.Style = 1 $progressBar1.TabIndex = 2 $progressBar1.Value = $PercentComplete #Progress bar position $WriteProgressForm.Controls.Add($progressBar1) # ** $CurrentOperationLabel $CurrentOperationLabel.AccessibleDescription = "CurrentOperationDesc" $CurrentOperationLabel.AccessibleName = "CurrentOperation" $CurrentOperationLabel.AccessibleRole = 0 $CurrentOperationLabel.CausesValidation = $False $CurrentOperationLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 100 $CurrentOperationLabel.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $CurrentOperationLabel.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 475 $CurrentOperationLabel.MinimumSize = $System_Drawing_Size $CurrentOperationLabel.AutoSize = $UselessAutoSize $CurrentOperationLabel.Name = "CurrentOperationLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $CurrentOperationLabel.Padding = $System_Windows_Forms_Padding # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 475 # $CurrentOperationLabel.Size = $System_Drawing_Size $CurrentOperationLabel.TabIndex = 1 $CurrentOperationLabel.Text = "$CurrentOperation" $WriteProgressForm.Controls.Add($CurrentOperationLabel) # ** $ActivityLabel # $ActivityLabel.CausesValidation = $False $ActivityLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 10 $System_Drawing_Point.Y = 10 $ActivityLabel.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $ActivityLabel.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 480 $ActivityLabel.MinimumSize = $System_Drawing_Size $ActivityLabel.Name = "ActivityLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $ActivityLabel.Padding = $System_Windows_Forms_Padding $ActivityLabel.AutoSize = $UselessAutoSize # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 480 # $ActivityLabel.Size = $System_Drawing_Size $ActivityLabel.TabIndex = 0 $ActivityLabel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",$FontSize,1,3,1) $ActivityLabel.Text = "$Activity" $WriteProgressForm.Controls.Add($ActivityLabel) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $WriteProgressForm.WindowState #Init the OnLoad event to correct the initial state of the form $WriteProgressForm.add_Load($OnLoadForm_StateCorrection) #Show the Form # $WriteProgressForm.ShowDialog()| Out-Null #ShowDialog waits until it is closed $WriteProgressForm.Show() #show form and keep on going $WriteProgressForm.activate() #Make sure its on top Start-sleep -Milliseconds 500 #was needed to give time for form to fully draw itself } #End Function #Clean up global WriteProgressForm variables before try { $WriteProgressForm.close() Remove-Variable StatusLabel | Out-Null Remove-Variable CurrentOperationLabel | Out-Null Remove-Variable progressBar1 | Out-Null Remove-Variable ActivityLabel | Out-Null Remove-Variable WriteProgressForm } catch { #go on } $ScopeNum=0 $Scope=0 $TotalNumScopes=100 #Foreach ($DHCPScope in $ObjDHCPscopes){ for ($PCcomplete=1; $PCcomplete -lt 100; $PCcomplete++) { $ScopeName="ScopeName" $Scope=$Scope+1 #increment $CurrentOperation="*CurOp*Getting Leases from scope $ScopeName" $Status="*Status*$PCcomplete% complete. ($Scope of $TotalNumScopes)" # Write-Progress -Activity "*Act*Building list from DHCP server ..." -status $status -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" Write-ProgressForm -Activity "*Act*Building list from DHCP server ... Building list from DHCP server... Building list from DHCP server ..." -status $status -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" Start-sleep -Milliseconds 050 } $PCcomplete=100 $CurrentOperation="complete" #Write-Progress -Activity "Building list from DHCP server ..." -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" -Status "$PCcomplete% complete." Write-ProgressForm -Activity "Building list from DHCP server ..." -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" -Status "$PCcomplete% complete." Start-sleep -seconds 1 #Write-Progress -Activity "Complete" -Completed -Status "Complete" Write-ProgressForm -Activity "Complete" -Completed -Status "Complete"
PowerShellCorpus/PoshCode/Export top n SQLPlans_1.ps1
Export top n SQLPlans_1.ps1
<# ALZDBA SQLServer_Export_SQLPlans_SMO.ps1 Export top n consuming sqlplans via avg_worker_time (=cpu) for all databases of a given SQLServer (SQL2005+) Instance results in a number of .SQLPlan files and the consumption overview .CSV file #> #requires -version 2 #SQLServer instance $SQLInstance = 'uabe0db97\\uabe0db97' #What number of plans to export per db ? [int]$nTop = 50 trap { # Handle all errors not handled by try\\catch $err = $_.Exception write-verbose "Trapped error: $err.Message" while( $err.InnerException ) { $err = $err.InnerException write-host $err.Message -ForegroundColor Black -BackgroundColor Red }; # End the script. break } Clear-Host # databases of which we do not want sqlplans [string[]]$ExcludedDb = 'tempdb' , 'model' #recipient $AllDbSQLPlan = $null $SampleTime = Get-Date -Format 'yyyyMMdd_HHmm' #Load SQLServer SMO libraries [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null $serverInstance = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $SQLInstance #Oh please put some application info in your connection metadata ! $serverInstance.ConnectionContext.ApplicationName = "DBA_Export_SQLPlans" $serverInstance.ConnectionContext.WorkstationId = $env:COMPUTERNAME # connecting should take less than 5 seconds ! $serverInstance.ConnectionContext.ConnectTimeout = 5 #connect before processing $serverInstance.ConnectionContext.Connect() $Query = '' if ( $serverInstance.VersionMajor -lt 9 ) { write-host $('{0} is of a Non-supported SQLServer version [{1}].' -f $SQLInstance, $serverInstance.VersionString) -ForegroundColor Black -BackgroundColor Red # End the script. break } elseif ( $serverInstance.VersionMajor -lt 10 ) { # SQL2005 $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(qp.objectid ) as [Schema] , Object_name(qp.objectid ) AS [Object_Name] , ISNULL(qs.total_elapsed_time / qs.execution_count, 0) AS [Avg_Elapsed_Time] , qs.execution_count AS [Execution_Count] , qs.total_worker_time AS [Total_Worker_Time] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , ISNULL(qs.execution_count / DATEDIFF(SS, qs.creation_time, GETDATE()), 0) AS [Calls_per_Second] , qs.max_logical_reads , qs.max_logical_writes , qs.creation_time as cached_time , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , DATEDIFF( SS, qs.creation_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.dm_exec_query_stats AS qs WITH ( NOLOCK ) CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qp.dbid = DB_ID() and qs.execution_count > 5 and Object_name(qp.objectid ) not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50 /* in microseconds */ ORDER BY Avg_Elapsed_Time DESC OPTION ( RECOMPILE ) ; ' -f $nTop ) } elseif ( $serverInstance.VersionMajor -eq 10 -and $serverInstance.VersionMinor -lt 50 ) { # SQL2008 $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(qp.objectid ) as [Schema] , Object_name(qp.objectid ) AS [Object_Name] , ISNULL(qs.total_elapsed_time / qs.execution_count, 0) AS [Avg_Elapsed_Time] , qs.execution_count AS [Execution_Count] , qs.total_worker_time AS [Total_Worker_Time] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , ISNULL(qs.execution_count / DATEDIFF(SS, qs.creation_time, GETDATE()), 0) AS [Calls_per_Second] , qs.max_logical_reads , qs.max_logical_writes , qs.creation_time as cached_time , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , DATEDIFF( SS, qs.cached_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.dm_exec_query_stats AS qs WITH ( NOLOCK ) CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qp.dbid = DB_ID() and qs.execution_count > 5 and Object_name(qp.objectid ) not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50000 /* in microseconds */ ORDER BY Avg_Elapsed_Time DESC OPTION ( RECOMPILE ) ; ' -f $nTop ) } else { # SQL2008R2 and up $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(p.object_id ) as [Schema] , p.name AS [Object_Name] , qs.total_elapsed_time / qs.execution_count AS [avg_elapsed_time] , qs.total_elapsed_time , qs.execution_count , cast(ISNULL(qs.execution_count * 1.00 / DATEDIFF(SS, qs.cached_time, GETDATE()), 0) as decimal(9,3)) AS [CallsPerSecond] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , qs.total_worker_time AS [Total_Worker_Time] , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , qs.cached_time , DATEDIFF( SS, qs.cached_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.procedures AS p WITH ( NOLOCK ) INNER JOIN sys.dm_exec_procedure_stats AS qs WITH ( NOLOCK ) ON p.[object_id] = qs.[object_id] CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qs.database_id = DB_ID() and qs.execution_count > 5 /* only non-ms sprocs */ and p.is_ms_shipped = 0 and p.name not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50000 /* in microseconds */ ORDER BY avg_elapsed_time DESC OPTION ( RECOMPILE ) ;' -f $nTop ) } $i = 0 foreach($db in $serverInstance.Databases){ if ( $ExcludedDb -notcontains $db.Name ) { $i += 1 $pct = 100 * $i / $serverInstance.Databases.Count Write-progress -Status "Processing DBs - $($db.Name)" -Activity "Collection SQLPlans $SQLInstance" -PercentComplete $pct try { $DbSQLPlans = $db.ExecuteWithResults("$Query").Tables[0] if ( !( $AllDbSQLPlan )) { $AllDbSQLPlan = $DbSQLPlans.clone() } if ( $DbSQLPlans.rows.count -gt 0 ) { $AllDbSQLPlan += $DbSQLPlans } } catch { #just neglect this error Write-Verbose $_.Exception.Message } } else { Write-Verbose "Excluded Db $db.name" } } #Take control: do it yourself ! $serverInstance.ConnectionContext.Disconnect() if ( $AllDbSQLPlan -and $AllDbSQLPlan.Count -gt 0 ) { $TargetPath = "c:\\tempo\\Powershell" if ( !(Test-Path $TargetPath) ) { md $TargetPath | Out-Null } Write-progress -Status "Exporting Consumption Data" -Activity "Exporting SQLPlans $SQLInstance" -PercentComplete 15 $TargetFile = $('{0}-{1}_AllDbSQLPlan.csv' -f $SampleTime, $($SQLInstance -replace '\\\\', '_') ) $AllDbSQLPlan | Select Db_Name, Row_Number, Schema, Object_Name, avg_elapsed_time, total_elapsed_time, execution_count, Calls_Per_Second, Avg_Worker_Time, Total_Worker_Time, Missing_Indexes, cached_time, Time_In_Cache_SS | sort Db_Name, Row_Number | Export-Csv -Path $( Join-Path -Path $TargetPath -ChildPath $TargetFile ) -Delimiter ';' -NoTypeInformation $i = 0 foreach ( $p in $AllDbSQLPlan ) { $i += 1 $pct = 100 * $i / $AllDbSQLPlan.Count Write-progress -Status "Exporting SQLPlan - $($p.Object_Name)" -Activity "Exporting SQLPlans $SQLInstance" -PercentComplete $pct $TargetFileName = $('{0}-{1}-{2}-{3}-{4}-{5}.SQLPlan' -f $SampleTime, $($SQLInstance.Replace('\\','_')) , $p.Db_Name, $p.Row_Number, $p.Schema , $p.Object_Name ) Write-verbose $TargetFileName Out-File -FilePath $( Join-Path -Path $TargetPath -ChildPath $TargetFileName ) -InputObject $p.query_plan } #open explorer at target path Invoke-Item "$TargetPath" } else { Write-Host "No SQLPlans to be exported ! " -ForegroundColor Black -BackgroundColor Yellow }
PowerShellCorpus/PoshCode/Run-Query (SharePoint)_2.ps1
Run-Query (SharePoint)_2.ps1
function Run-Query($siteUrl, $queryText) { [reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null [reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null [reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null $s = [microsoft.sharepoint.spsite]$siteUrl $q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s $q.querytext = $queryText $q.RowLimit = 100 $q.ResultTypes = "RelevantResults" $dt = $q.Execute() $r = $dt["RelevantResults"] $output = @() while ($r.Read()) { $o = new-object PSObject 0..($r.FieldCount-1) | foreach { add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r[$_].ToString() } $output += $o } return $output } @@ @@ @@#Sample usage: @@#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM S" @@# @@#
PowerShellCorpus/PoshCode/elevate-process (sudo).ps1
elevate-process (sudo).ps1
function elevate-process { $file, [string]$arguments = $args; $psi = new-object System.Diagnostics.ProcessStartInfo $file; $psi.Arguments = $arguments; $psi.Verb = "runas"; $psi.WorkingDirectory = get-location; [System.Diagnostics.Process]::Start($psi); } set-alias sudo elevate-process;
PowerShellCorpus/PoshCode/PerformanceHistory 2.52.ps1
PerformanceHistory 2.52.ps1
##requires -version 2.0 ## Get-PerformanceHistory.ps1 ############################################################################################################## ## Lets you see the amount of time recent commands in your history have taken ## History: ## v2.52 - added regex-based iteration counting to calculate averages ## v2.51 - removed PsParser features to make it v1 compatible ## v2.5 - added "average" calculation if the first thing in your command line is a range: 1..x ## v2 - added measuring the scripts involved in the command, (uses Tokenizer) ## - adds a ton of parsing to make the output pretty ############################################################################################################## # function Get-PerformanceHistory { param( [int]$count=1, [int[]]$id=@((Get-History -count 1| Select Id).Id) ) ## Removed to make this v1 compatible ## $Parser = [System.Management.Automation.PsParser] function FormatTimeSpan($ts) { if($ts.Minutes) { if($ts.Hours) { if($ts.Days) { return "{0:##}d {1:00}:{2:00}:{3:00}.{4:00000}" -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:##}:{1:00}:{2:00}.{3:00000}" -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:##}:{1:00}.{2:00000}" -f $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } return "{0:#0}.{1:00000}" -f $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds))) } # if there's only one id, then the count counts, otherwise we just use the ids # ... basically: { 1..$count | % { $id += $id[-1]-1 } } if($id.Count -eq 1) { $id = ($id[0])..($id[0]-($count-1)) } # so we can call it with just the IDs Get-History -id $id | ForEach { $msr = $null $cmd = $_ # default formatting values $avg = 7; $len = 8; $count = 1 ## Removed to make this v1 compatible ## $tok = $Parser::Tokenize( $cmd.CommandLine, [ref]$null ) ## if( ($tok[0].Type -eq "Number") -and ## ($tok[0].Content -le 1) -and ## ($tok[2].Type -eq "Number") -and ## ($tok[1].Content -eq "..") ) ## { ## $count = ([int]$tok[2].Content) - ([int]$tok[0].Content) + 1 ## } ## ## $com = @( $tok | where {$_.Type -eq "Command"} | ## foreach { ## $Local:ErrorActionPreference = "SilentlyContinue" ## get-command $_.Content ## $Local:ErrorActionPreference = $Script:ErrorActionPreference ## } | ## where { $_.CommandType -eq "ExternalScript" } | ## foreach { $_.Path } ) ## ## # If we actually got a script, measure it out ## if($com.Count -gt 0){ ## $msr = Get-Content -path $com | Measure-Object -Line -Word -Char ## } else { $msr = Measure-Object -in $cmd.CommandLine -Line -Word -Char ## } ## V1 Averages: $min, $max = ([regex]"^\\s*(?:(?<min>\\d+)\\.\\.(?<max>\\d+)\\s+\\||for\\s*\\([^=]+=\\s*(?<min>\\d+)\\s*;[^;]+\\-lt\\s*(?<max>\\d+)\\s*;[^;)]+\\)\\s*{)").match( $cmd.CommandLine ).Groups[1,2] | % { [int]$_.Value } $count = $max - $min if($count -le 0 ) { $count = 1 } "" | Select @{n="Id"; e={$cmd.Id}}, @{n="Duration"; e={FormatTimeSpan ($cmd.EndExecutionTime - $cmd.StartExecutionTime)}}, @{n="Average"; e={FormatTimeSpan ([TimeSpan]::FromTicks( (($cmd.EndExecutionTime - $cmd.StartExecutionTime).Ticks / $count) ))}}, # @{n="Lines"; e={$msr.Lines}}, # @{n="Words"; e={$msr.Words}}, # @{n="Chars"; e={$msr.Characters}}, # @{n="Type"; e={if($com.Count -gt 0){"Script"}else{"Command"}}}, @{n="Commmand"; e={$cmd.CommandLine}} } | # I have to figure out what the longest time string is to make it look its best Foreach { $avg = [Math]::Max($avg,$_.Average.Length); $len = [Math]::Max($len,$_.Duration.Length); $_ } | Sort Id | Format-Table @{l="Duration";e={"{0,$len}" -f $_.Duration}},@{l="Average";e={"{0,$avg}" -f $_.Average}},Commmand -auto #Lines,Words,Chars,Type, #}
PowerShellCorpus/PoshCode/ADFS troubleshooting_1.ps1
ADFS troubleshooting_1.ps1
<# This Script will check the MSOnline Office 365 setup. It will prompt the user running it to specify the credentials. It will then check compare the onsite information with the online information and inform the user if it is out of sync. #> $PSAdmin = Read-host "This script needs to be run as Administrator, have you done this? Y or N..." If($PSAdmin -eq 'Y' -or 'y'){ Add-PSSnapin Microsoft.Adfs.Powershell Import-Module MSOnline $cred = Get-Credential Connect-MsolService -credential:$cred Write-host "Below are the URLs Office 365 uses to connect, these URLs MUST be the same (if they are not then see article http://support.microsoft.com/kb/2647020)..." -foreground "Green" Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'FederationMetadataUrl' Write-Host "Below is the certificate information for ADFS, the top section is the onsite information showing the current certificate with serial number. The bottom section shows the Office 365 online certificate details. The serial number MUST be the same. If they are not see article http://support.microsoft.com/kb/2647020..." -foreground 'Green' Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'TokenSigningCertificate' | fl | Out-Default } Else{ Write-host "Please close Powershell and re-run it as adminstrator" -foreground "Red" Break}
PowerShellCorpus/PoshCode/SearchZIP_4.psm1 .ps1
SearchZIP_4.psm1 .ps1
function SearchZIPfiles { <# .SYNOPSIS Search for (filename) strings inside compressed ZIP or RAR files (V2.8). .DESCRIPTION In any directory containing a large number of ZIP/RAR compressed Web Page files this procedure will search each individual file name for simple text strings, listing both the source RAR/ZIP file and the individual file name containing the string. The relevant RAR/ZIP can then be subsequently opened in the usual way. Using the '-Table' (or alias '-GridView') switch will show the results with the Out-GridView display. .EXAMPLE extract -find 'library' -path d:\\scripts Searching for 'library' - please wait... (Use CTRL+C to quit) [Editor.zip] Windows 7 Library Procedures.mht [Editor.rar] My Library collection from 1974 Idi Amin.html [Test2.rar] Playlists from library - Windows 7 Forums.mht [Test3.rar] Module library functions UserGroup.pdf Folder 'D:\\Scripts' contains 4 matches for 'library' in 4 file(s). .EXAMPLE extract -find 'backup' -path doc Searching for 'backup' - please wait... (Use CTRL+C to quit) [Web.zip] How To Backup User and System Files.mht [Pages.rar] Create an Image Backup.pdf Folder 'C:\\Users\\Sam\\Documents' contains 2 matches for 'backup' in 2 file(s). .EXAMPLE extract pdf desk Searching for 'pdf' - please wait... (Use CTRL+C to quit) [Test1.rar] VirtualBox_ Guest Additions package.pdf [Test2.rar] W8 How to Install Windows 8 in VirtualBox.pdf [Test2.rar] W8 Install Windows 8 As a VM with VirtualBox.pdf Folder 'C:\\Users\\Sam\\Desktop' contains 3 matches for 'pdf' in 2 file(s). This example uses the 'extract' alias to find all 'pdf' files on the desktop. .NOTES The first step will find any lines containing the selected pattern (which can be anywhere in the line). Each of these lines will then be split into 2 headings: Source and Filename. Note that there may be the odd occasion where a 'non-readable' character in the returned string slips through the net! .LINK Web Address Http://www.SeaStarDevelopment.BraveHost.com #> [CmdletBinding()] param([string][string][Parameter(Mandatory=$true)]$Find, [string][ValidateNotNullOrEmpty()]$path = $pwd, [switch][alias("GRIDVIEW")]$table) Set-StrictMode -Version 2 switch -wildcard ($path) { 'desk*' { $path = Join-Path $home 'desktop\\*' ; break } 'doc*' { $docs = [environment]::GetFolderPath("mydocuments") $path = Join-Path $docs '*'; break } default { $xpath = Join-Path $path '*' -ea 0 if (!($?) -or !(Test-Path $path)) { Write-Warning "Path '$path' is invalid - resubmit" return } $path = $xpath } } Get-ChildItem $path -include '*.rar','*.zip' | Select-String -SimpleMatch -Pattern $find | foreach-Object ` -begin { [int]$count = 0 $container = @{} $folder = $path.Replace('*','') $lines = @{} $regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*(\\\\|/)(?<file>.*\\.(mht|html?|pdf))(.*)$' Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)" } ` -process { if ( $_ -match $regex ) { $container[$matches.zip] +=1 #Record the number in each. $source = $matches.zip -replace [regex]::Escape($folder) $file = $matches.file $file = $file -replace '\\p{S}|\\p{Cc}',' ' #Some 'Dingbats'. $file = $file -replace '\\s+',' ' #Single space words. if ($table) { $key = "{0:D4}" -f $count $lines["$key $source"] = $file #Create a unique key. } else { Write-Host "[$source] $file" } $count++ } } ` -end { $total = "in $($container.count) file(s)." $title = "Folder '$($path.Replace('\\*',''))' contains $($count) matches for '$find' $total" if ($table -and $count -gt 0) { $lines.GetEnumerator() | Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}}, @{name = 'Match' ;expression = {$_.Value}} | Sort-Object Match | Out-GridView -Title $title } else { if ($count -eq 0) { $title = "Folder '$($path.Replace('\\*',''))' contains no matches for '$find'." } Write-Host $title } } } #End function. New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR' Export-ModuleMember -Function SearchZIPfiles -Alias Extract
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_4.ps1
Send-HTMLFormattedEmail_4.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/New-ISEMenu_4.ps1
New-ISEMenu_4.ps1
Import-Module ShowUI Function New-ISEMenu { New-Grid -AllowDrop:$true -Name "ISEAddonCreator" -columns Auto, * -rows Auto,Auto,Auto,*,Auto,Auto -Margin 5 { New-Label -Name Warning -Foreground Red -FontWeight Bold -Column 1 ($target = New-TextBox -Name txtName -Column 1 -Row ($Row=1)) New-Label "Addon Menu _Name" -Target $target -Row $Row ($target = New-TextBox -Name txtShortcut -Column 1 -Row ($Row+=1)) New-Label "Shortcut _Key" -Row $Row -Target $target ($target = New-TextBox -Name txtScriptBlock -Column 1 -Row ($Row+=1) -MinHeight 141 -MinWidth 336 -AcceptsReturn:$true -HorizontalScrollBarVisibility Auto -VerticalScrollBarVisibility Auto) New-Label "Script _Block" -Row $Row -Target $target New-CheckBox "_Add to ISE Profile" -Name chkProfile -Row ($Row+=1) New-StackPanel -Orientation Horizontal -Column 1 -Row ($Row+=1) -HorizontalAlignment Right { New-Button "_Save" -Name btnSave -Width 75 -Margin "0,0,5,0" -IsDefault -On_Click { if ($txtName.Text.Trim() -eq "" -or $txtShortcut.text.Trim() -eq "" -or $txtScriptBlock.text.Trim() -eq "") { $Warning.Content = "You must supply all parameters" } else { $menuItems = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | Select -ExpandProperty DisplayName if ($menuItems -Contains $txtName.Text) { $Warning.Content = "Select another Name for the menu" return } try { $ScriptBlock = [ScriptBlock]::Create($txtScriptBlock.Text) $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add($txtName.Text,$ScriptBlock,$txtShortcut.Text) | Out-Null } catch { $Warning.Content = "Fatal Error Creating MenuItem:`n$_" return } if ($chkProfile.IsChecked) { $profileText = "`n`#Added by ISE Menu Creator Addon if (`$psISE) { `$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(`"$($txtName.Text)`",`{$ScriptBlock`},`"$($txtShortcut.Text)`") | Out-Null } " Add-Content -Path $profile -Value $profileText } $window.Close() } } New-Button "Cancel" -Name btnCancel -Width 75 -IsCancel } } -show -On_Load { $txtName.Focus() } } # this will add a the "New ISE menu" menu item and load it every time you run this script! $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New ISE menu",{New-ISEMenu},"ALT+M") | Out-Null
PowerShellCorpus/PoshCode/ShowUI Weather Widget.ps1
ShowUI Weather Widget.ps1
## And a slick weather widget using Yahoo's forecast and images New-UIWidget -AsJob { Grid { Rectangle -RadiusX 10 -RadiusY 10 -StrokeThickness 0 -Width 170 -Height 80 -HorizontalAlignment Left -VerticalAlignment Top -Margin "60,40,0,0" -Fill { LinearGradientBrush -Start "0.5,0" -End "0.5,1" -Gradient { GradientStop -Color "#FF007bff" -Offset 0 GradientStop -Color "#FF40d6ff" -Offset 1 } } Image -Name Image -Stretch Uniform -Width 250.0 -Height 180.0 -Source "http://l.yimg.com/a/i/us/nws/weather/gr/31d.png" TextBlock -Name Temp -Text "99°" -FontSize 80 -Foreground White -Margin "130,0,0,0" -Effect { DropShadowEffect -Color Black -Shadow 0 -Blur 8 } TextBlock -Name Forecast -Text "Forecast" -FontSize 12 -Foreground White -Margin "120,95,0,0" } } -Refresh "00:10" { # To find your WOEID, browse or search for your city from the Weather home page. # The WOEID is the LAST PART OF the URL for the forecast page for that city. $woEID = 14586 $channel = ([xml](New-Object Net.WebClient).DownloadString("http://weather.yahooapis.com/forecastrss?p=$woEID")).rss.channel $h = ([int](Get-Date -f hh)) if($h -gt ([DateTime]$channel.astronomy.sunrise).Hour -and $h -lt ([DateTime]$channel.astronomy.sunset).Hour) { $dayOrNight = 'd' } else { $dayOrNight = 'n' } $source = "http`://l.yimg.com/a/i/us/nws/weather/gr/{0}{1}.png" -f $channel.item.condition.code, $dayOrNight $Image.Source = $source $Temp.Text = $channel.item.condition.temp + [char]176 $Forecast.Text = "High: {0}{2} Low: {1}{2}" -f $channel.item.forecast[0].high, $channel.item.forecast[0].low, [char]176 }
PowerShellCorpus/PoshCode/Get-Computer.ps1
Get-Computer.ps1
function Get-Computer { <# .Synopsis Retrieves basic information about a computer. .Description The Get-Computer cmdlet retrieves basic information such as computer name, domain or workgroup name, and whether or not the computer is on a workgroup or a domain for the local computer. .Example Get-Computer Returns comptuer name, domain or workgroup name, and isDomainName .Example Get-Computer Returns comptuer name, domain or workgroup name, and isDomainName .OutPuts [PSObject] .Notes NAME: Get-Computer AUTHOR: Tome Tanasovski LASTEDIT: 2/13/2010 KEYWORDS: .Link Http://powertoe.wordpress.com #Requires -Version 2.0 #> $sig = @" [DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] public static extern int NetGetJoinInformation(string server,out IntPtr domain,out int status); "@ $type = Add-Type -MemberDefinition $sig -Name Win32Utils -Namespace NetGetJoinInformation -PassThru $ptr = [IntPtr]::Zero $status = 0 $type::NetGetJoinInformation($null, [ref] $ptr, [ref]$status) |Out-Null $returnobj = New-Object PSObject $workdomainname = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr) $returnobj |Add-Member NoteProperty ComputerName ([System.Windows.Forms.SystemInformation]::Computername) switch ($status) { 0 { Write-Warning "NetJoin status is type is Unknown. Cannot determine whether or not this computer is on a domain or workgroup" $returnobj |Add-Member Noteproperty isDomain $null } 1 { Write-Warning "NetJoin status is type is Unjoined. Cannot determine whether or not this computer is on a domain or workgroup" $returnobj |Add-Member Noteproperty isDomain $null } 2 { $returnobj |Add-Member Noteproperty isDomain $false $returnobj |Add-Member Noteproperty WorkgroupName $workdomainname } 3 { $returnobj |Add-Member Noteproperty isDomain $true $returnobj |Add-Member Noteproperty DomainName $workdomainname } } return $returnobj }
PowerShellCorpus/PoshCode/chkhash_20.ps1
chkhash_20.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false "ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, " "in order to detect corrupt or hacked files." "" ".\\chkhash.ps1 -h for usage." "" for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]" " [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml" " or create it and store hashes there if not present]" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" " [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude " " c:\\users\\eve\\hashes directory and subdirs]" " PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u" " [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to" " existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]" " PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml" " [Load hashes.xml and check hashes of all files contained within.]" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { while (($i+1) -lt $args2.count) { $i++ if ($args2[$i] -like "-*") {break} $exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories. } continue } $args3+=@($args2[$i]) # Add files/dirs } if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es)." $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Send-Growl 1.0.ps1
Send-Growl 1.0.ps1
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0) ## Initially it only supports a very simple notice, and I haven't gotten callbacks working yet ## Coming soon: ## * Send notices to other PCs directly ## * Wrap the registration of new messages ## * Figure out the stupid ## Change these to whatever you like, at least the first one, since it should point at a real ico file $defaultIcon = "$PSScriptRoot\\PowerGrowl.ico" $appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Script:PowerGrowler)) { $script:GrowlApp = New-Object "Growl.Connector.Application" $appName $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::AES [Growl.Connector.NotificationType[]]$global:PowerGrowlerNotices = @("Default") ## You should change this $global:PowerGrowlerNotices[0].Icon = $defaultIcon } ## I was going to store these ON the PowerGrowler object, but ... ## I wanted to make the notices editable, without making it editable ## So instead, I add them to it only after you register them.... # Add-Member -InputObject $script:PowerGrowler -MemberType NoteProperty -Name Notices -Value $PowerGrowlerNotices ## Should only (have to) do this once. $script:PowerGrowler.Register($script:GrowlApp, $global:PowerGrowlerNotices ) ## This is test code, it doesn't work -- as far as I can tell, the notification never gets called ... $script:PowerGrowler.Add_NotificationCallback( { Write-Host "The object $this" -fore Cyan Write-Host $("Response Type: {0}\\r\\nNotification ID: {1}\\r\\nCallback Data: {2}\\r\\nCallback Data Type: {3}\\r\\n" -f $_.Result, $_.NotificationID, $_.Data, $_.Type) -fore Yellow } ) function Send-Growl { #.Synopsis # Send a growl notice #.Description # Send a growl notice with the scpecified values #.Parameter Caption # The short caption to display #.Parameter Message # The message to send (most displays will resize to accomodate) #.Parameter NoticeType # The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur. # For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities. #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Send-Growl "Greetings" "Hello World!" # # The Hello World of Growl. #.Example # Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png # # Displays a message with a couple of movie quotes and a mail icon. # PARAM ( [Parameter(Mandatory=$true, Position=0)] [string]$Caption=$(Read-Host "A SHORT caption") , [Parameter(Mandatory=$true, Position=1)] [string]$Message=$(Read-Host "The detailed message") #, [string]$CallbackData #, [string]$CallbackType , [Parameter(Mandatory=$false)][Alias("Type")] [string]$NoticeType=$global:PowerGrowlerNotices[0].Name , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } if( $CallbackData -and $CallbackType ) { $context = new-object Growl.Connector.CallbackContext $context.Data = $CallbackData $context.Type = $CallbackType $script:PowerGrowler.Notify($notice, $context) } else { $script:PowerGrowler.Notify($notice) } } Export-ModuleMember -Function Send-Growl
PowerShellCorpus/PoshCode/New-Zip_1.ps1
New-Zip_1.ps1
Function New-Zip { <# .SYNOPSIS Create a Zip File from any files piped in. .DESCRIPTION Requires that you have the SharpZipLib installed, which is available from http://www.icsharpcode.net/OpenSource/SharpZipLib/ .NOTES File Name : PowerZip.psm1 Author : Christophe CREMON (uxone) - http://powershell.codeplex.com Requires : PowerShell V2 .PARAMETER Source Set the name of the source to zip (file or directory) .PARAMETER ZipFile Set the name of the zip file to create .PARAMETER Recurse Browse the source recursively .PARAMETER Include Include only items you specify .PARAMETER Exclude Exclude items you specify .PARAMETER AbsolutePaths Preserve the absolute path name of each item in the zip container .PARAMETER DeleteAfterZip Delete source items after successful zip .EXAMPLE New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP #> param ( [ValidateNotNullOrEmpty()] [Parameter( Mandatory = $true) ] [string] $Source, [Parameter( Mandatory = $true) ] [string] $ZipFile, [switch] $Recurse, [array] $Include, [array] $Exclude, [switch] $AbsolutePaths, [switch] $DeleteAfterZip ) [int] $ExitCode = 1 $LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib") if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" } if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" } if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" } if ( $AbsolutePaths -eq $true ) { $AbsolutePathsArgument = "-AbsolutePaths" } if ( $DeleteAfterZip -eq $true ) { $DeleteAfterZipArgument = "-DeleteAfterZip" } if ( $Include ) { $Include = $Include -join "," $IncludeArgument = "-Include $Include" } if ( $Exclude ) { $Exclude = $Exclude -join "," $ExcludeArgument = "-Exclude $Exclude" } $RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path if ( -not $RootPath ) { throw "! Source not found {$Source}" } if ( $Include ) { $Source = $Source+"\\*" } $GetCommand = "Get-ChildItem -Path '$Source' $RecurseArgument $IncludeArgument $ExcludeArgument -Force" $ItemsToZip = Invoke-Expression -Command $GetCommand $SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum $SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } if ( -not $SizeBeforeZip ) { Write-Output "NOTHING TO ZIP" break } $StartTime = Get-Date Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n" Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n" Write-Output "Initializing ZIP File {$ZipFile} ...`n" $CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue if ( -not $CreateZIPContainer ) { throw "! Unable to create ZIP container {$ZipFile}" } $oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile)) [byte[]] $Buffer = New-Object Byte[] 4096 foreach ( $Item in $ItemsToZip ) { if ( $Item.FullName -ne $ZipFile ) { if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue ) { $ZipEntry = $Item.FullName if ( -not $AbsolutePaths ) { $ReplacePath = [Regex]::Escape( $RootPath+"\\" ) $ZipEntry = $Item.FullName -replace $ReplacePath,"" } if ( $Item.psIsContainer -eq $true ) { if ( $Recurse -eq $true ) { Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..." $OldErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/") $oZipOutputStream.PutNextEntry($oZipEntry) if ( $? -ne $true ) { $ItemsNotZipped += @($Item.FullName) $ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}") } $ErrorActionPreference = $OldErrorActionPreference } } else { Write-Output "Processing ZIP of File {$($Item.FullName)} ..." $OldErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $FileStream = [IO.File]::OpenRead($Item.FullName) $oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry") $oZipOutputStream.PutNextEntry($oZipEntry) [ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer) if ( $? -ne $true ) { $ItemsNotZipped += @($Item.FullName) $ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}") } $FileStream.Close() } } } } $oZipOutputStream.Finish() $oZipOutputStream.Close() if ( $? -eq $true ) { $ErrorActionPreference = $OldErrorActionPreference if ( $DeleteAfterZip ) { $ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object { if ( $_.psIsContainer -ne $true ) { if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue ) { Write-Output "Processing Delete of File {$($_.FullName)} ..." $RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue if ( $? -ne $true ) { $ErrorsArray += @("! Unable to Delete File {$($_.FullName)}") } } } } if ( $Recurse ) { $ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object { if ( $_.psIsContainer -eq $true ) { if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue ) { Write-Output "Processing Delete of Directory {$($_.FullName)} ..." $RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue if ( $? -ne $true ) { $ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}") } } } } } } Write-Output "`nZIP File Created {$ZipFile} ...`n" $ExitCode = 0 } else { $ErrorActionPreference = $OldErrorActionPreference $ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n") } if ( $ErrorsArray ) { Write-Output "`n[ ERRORS OCCURED ]" $ErrorsArray $ExitCode = 1 } else { $SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum $SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n" $Gain = ( $SizeBeforeZip - $SizeAfterZip ) $GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) } if ( $Gain -gt 0 ) { $GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ } Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n" } } $EndTime = Get-Date $ExecutionTime = ($EndTime-$StartTime) Write-Output "`nExecution Time : $ExecutionTime`n" Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n" exit $ExitCode } Export-ModuleMember -Function New-Zip
PowerShellCorpus/PoshCode/Route.psm1.ps1
Route.psm1.ps1
None
PowerShellCorpus/PoshCode/Get-SqlSpn.ps1
Get-SqlSpn.ps1
####################### <# .SYNOPSIS Gets MSQLSvc service principal names (spn) from Active Directory. .DESCRIPTION The Get-SqlSpn function gets SPNs for MSQLSvc services attached to account and computer objects .EXAMPLE Get-SqlSpn This command gets MSSQLSvc SPNs for the current domain .NOTES Adapted from http://www.itadmintools.com/2011/08/list-spns-in-active-directory-using.html Version History v1.0 - Chad Miller - Initial release #> function Get-SqlSpn { $serviceType="MSSQLSvc" $filter = "(servicePrincipalName=$serviceType/*)" $domain = New-Object System.DirectoryServices.DirectoryEntry $searcher = New-Object System.DirectoryServices.DirectorySearcher $searcher.SearchRoot = $domain $searcher.PageSize = 1000 $searcher.Filter = $filter $results = $searcher.FindAll() foreach ($result in $results) { $account = $result.GetDirectoryEntry() foreach ($spn in $account.servicePrincipalName.Value) { if($spn -match "^MSSQLSvc\\/(?<computer>[^\\.|^:]+)[^:]*(:{1}(?<port>\\w+))?$") { new-object psobject -property @{ComputerName=$matches.computer;Port=$matches.port;AccountName=$($account.Name);SPN=$spn} } } } } #Get-SqlSpn
PowerShellCorpus/PoshCode/Get-NestedGroups v_3.ps1
Get-NestedGroups v_3.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/NTFS ACLs Folder Tree_2.ps1
NTFS ACLs Folder Tree_2.ps1
####################################### # TITLE: listACL.ps1 # # AUTHOR: Santiago Fernandez Mu±oz # # # # DESC: This script generate a HTML # # report show all ACLs asociated with # # a Folder tree structure starting in # # root specified by the user # ####################################### param ([string] $computer = 'localhost', [string] $path = $(if ($help -eq $false) {Throw "A path is needed."}), [int] $level = 0, [string] $scope = 'administrator', [switch] $help = $false, [switch] $debug = $false ) #region Initializations and previous checkings #region Initialization $allowedLevels = 10 $Stamp = get-date -uformat "%Y%m%d" $report = "$PWD\\$computer.html" $comparison = "" $UNCPath = "\\\\" + $computer + "\\" + $path + "\\" #endregion #region Previous chekings #require -version 2.0 if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."} if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path } switch ($scope) { micro { $comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")' } user { $comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")' } } #endregion #endregion #region Function definitions function drawDirectory([ref] $directory) { $dirHTML = ' <div class="' if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level } $dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div> <div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div> <div class="container"> <div class="heACL"> <table class="info3" cellpadding="0" cellspacing="0"> <thead> <th scope="col"><b>Owner</b></th> <th scope="col"><b>Privileges</b></th> </thead> <tbody>' foreach ($itemACL in $directory.value.ACL) { $acls = $null if ($itemACL.AccessToString -ne $null) { $acls = $itemACL.AccessToString.split("`n") } $dirHTML += '<tr><td>' + $itemACL.Owner + '</td> <td> <table> <thead> <th>User</th> <th>Control</th> <th>Privilege</th> </thead> <tbody>' foreach ($acl in $acls) { $temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}") if ($debug) { write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp } if ($temp.count -eq 1) { continue } if ($scope -ne 'administrator') { if ( Invoke-Expression $comparison ) { $dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>" } } else { $dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>" } } $dirHTML += '</tbody> </table> </td> </tr>' } $dirHTML += ' </tbody> </table> </div> </div> </div>' return $dirHTML } #endregion #region Printing help message if ($help) { Write-Host @" /ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ\\ Ę Script gather access control lists per directory Ę \\ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ/ USAGE: ./listACL -computer <machine or IP> -path <path> -level <0-10> -help:[$false] PARAMETERS: computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost) path [REQUIRED] - Folder's path to query. level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels. 0 show that there's no limit in the going down (Default: 0) scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are: Ę user, show important information to the user. Ę micro, show user scope information plus important information for the IT Department. Ę administrator, show all information. help [OPTIONAL] - This help. "@ exit 0 } #endregion if (Test-Path $report) { Remove-item $report } #To normalize I check if last character in the path is the folder separator character if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) } #region Header, style and javascript functions needed by the html report @" <html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-16" /> <title>Access Control List for $path in $computer</title> <!-- Styles --> <style type="text/css"> body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; } table{ font-size:100%; table-layout:fixed; width:100%; } td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; } .title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; } .he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; } .he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; } .he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; } .he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } .heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; } DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; } .he0 .expando{ font-size:100%; } .info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; } .disalign TD{ padding-bottom:5px; padding-right:10px; } .info TD{ padding-right:10px; width:50%; } .info3 TD{ padding-right:10px; width:33%; } .info4 TD, .info4 TH{ padding-right:10px; width:25%; } .info5 TD, .info5 TH{ padding-right:0px; width:20%; } .info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; } .subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; } .subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; } .subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; } .subtable .footnote{ border-top:1px solid #CCCCCC; } .subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; } .subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; } .subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; } .subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; } .subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; } .explainlink{ color:#000000; text-decoration:none; cursor:pointer; } .explainlink:hover{ color:#0000FF; text-decoration:underline; } .spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; } .filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; } .container{ display:block; position:relative; } .rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; } .rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; } .gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; } .gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; } #uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; } #dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; } #objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; } #gposummary { display:block; } #gpoinformation { display:block; } </style> </head> <body> <table class="title" cellpadding="0" cellspacing="0"> <tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr> <tr> <td id="dtstamp">Data obtained on: $(Get-Date)</td> <td><div id="objshowhide" tabindex="0"></div></td> </tr> </table> <div class="filler"></div> "@ | Set-Content $report #endregion #region Information gathering $colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName $colACLs = @() #We start going through the path pointed out by the user foreach($file in $colFiles) { #To control the current level in the tree we are in it's needed to count the number of separator characters #contained in the path. However in order to make the count correctly it's needed to delete the path #provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be #string used to do the level count. #It's needed to use a REGEX object to get ALL separator character matches. $matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count if ($level -ne 0 -and ($matches - 1) -gt $level) { continue } if ($debug) { Write-Host $file.FullName "->" $file.Mode } if ($file.Mode -notlike "d*") { continue } $myobj = "" | Select-Object Folder,ACL,level $myobj.Folder = $file $myobj.ACL = Get-Acl $file.FullName $myobj.level = $matches - 1 $colACLs += $myobj } #endregion #region Setting up the report '<div class="gposummary">' | Add-Content $report for ($i = 0; $i -lt $colACLs.count; $i++) { drawDirectory ([ref] $colACLs[$i]) | Add-Content $report } '</div></body></html>' | Add-Content $report #endregion
PowerShellCorpus/PoshCode/Get-RecurseMember_1.ps1
Get-RecurseMember_1.ps1
function Get-RecurseMember { <# .Synopsis Does a recursive search for unique users that are members of an AD group. .Description Recursively gets a list of unique users that are members of the specified group, expanding any groups that are members out into their member users. Note: Requires the Quest AD Cmdlets http://www.quest.com/powershell/activeroles-server.aspx .Parameter group The name of the group. .Example PS> Get-RecurseMember 'My Domain Group' .Notes NAME: Get-RecurseMember AUTHOR: tojo2000 #Requires -Version 2.0 #> param([Parameter(Position = 0, Mandatory = $true] [string]$group) $users = @{} try { $members = Get-QADGroupMember $group } catch [ArgumentException] { Write-Host "`n`n'$group' not found!`n" return $null } foreach ($member in $members) { if ($member.Type -eq 'user') { $users.$($member.Name.ToLower()) = $member } elseif ($member.Type -eq 'group') { foreach ($user in (Get-RecurseMember $member.Name)) { $users.$($user.Name.ToLower()) = $user } } } foreach ($user in $users.Keys | sort) { Write-Output $users.$user } }
PowerShellCorpus/PoshCode/SQL-Select.ps1
SQL-Select.ps1
<# .SYNOPSIS Author:...Vidrine Date:.....2012/04/08 .DESCRIPTION Function uses the Microsoft SQL cmdlets 'Invoke-SQLcmd' to connect to a SQL database and run a SELECT statement. Results of the query are returned. Store returned results in a variable to be able to interact with them as an object. .PARAM server Hostname/IP of the server hosting the SQL database. .PARAM database Name of the SQL database to connect to. .PARAM table Name of the table within the specified SQL database. .PARAM selectWhat [String] Select string. This will specify the SELECT value to use in the SQL statement. Default value is '*'. .PARAM where [String] Where string. This will specify the WHERE clause to use in the SQL statement. ie. "id='64'" .EXAMPLE $results = SQL-Select -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -selectWhat '*' .EXAMPLE $results = SQL-Select -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -selectWhat '*' -where "id='64'" #> function SQL-Select { param( [string]$server, [string]$database, [string]$table, [string]$selectWhat = '*', [string]$where ) ## SELECT statement with a WHERE clause if ($where){ $sqlQuery = @" SELECT $selectWhat FROM $table WHERE $where "@ } ## General SELECT statement else { $sqlQuery = @" SELECT $selectWhat FROM $table "@ } try { $results = Invoke-SQLcmd -ServerInstance $server -Database $database -Query $sqlQuery return $results } catch{} }
PowerShellCorpus/PoshCode/ConvertFrom-Hashtable_1.ps1
ConvertFrom-Hashtable_1.ps1
# function ConvertFrom-Hashtable { PARAM([HashTable]$hashtable,[switch]$combine) BEGIN { $output = New-Object PSObject } PROCESS { if($_) { $hashtable = $_; if(!$combine) { $output = New-Object PSObject } } $hashtable.GetEnumerator() | ForEach-Object { Add-Member -inputObject $object ` -memberType NoteProperty -name $_.Name -value $_.Value } $object } #}
PowerShellCorpus/PoshCode/Get-Netstat 1,_2.ps1
Get-Netstat 1,_2.ps1
$null, $null, $null, $null, $netstat = netstat -a -n -o [regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)' foreach ($net in $netstat) { [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName switch -regex ($net.Trim()) { $regexTCP { $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 = ( Get-Process -Id $matches.PID ).ProcessName } $regexUDP { $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 = ( Get-Process -Id $matches.PID ).ProcessName } } $Process.LocalPort = ' ' + $Process.LocalPort $Process.LocalPort = $Process.LocalPort.Substring($Process.LocalPort.length-6,6) $process }
PowerShellCorpus/PoshCode/Get-Netstat 1,0.ps1
Get-Netstat 1,0.ps1
$null, $null, $null, $null, $netstat = netstat -a -n -o [regex]$regexTCP = '(?<Protocol>\\S+)\\s+(?<LocalAddress>\\S+)\\s+(?<RemoteAddress>\\S+)\\s+(?<State>\\S+)\\s+(?<PID>\\S+)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+(?<LocalAddress>\\S+)\\s+(?<RemoteAddress>\\S+)\\s+(?<PID>\\S+)' foreach ($net in $netstat) { switch -regex ($net.Trim()) { $regexTCP { $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LocalAddress $process.RemoteAddress = $matches.RemoteAddress $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName $process continue } $regexUDP { $process = "" | Select-Object Protocol, LocalAddress, RemoteAddress, State, PID, ProcessName $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LocalAddress $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName $process continue } } }
PowerShellCorpus/PoshCode/Import-Delimited 2.ps1
Import-Delimited 2.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 ################################################################################ ## Version History ## Version 1.0 ## First working version ## Version 2.0 ## Fixed bug in final call to Write-Output ################################################################################ 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-Delimited $delimiter $script:tmp) } } }
PowerShellCorpus/PoshCode/Autoload Module _1.2.ps1
Autoload Module _1.2.ps1
#Requires -Version 2.0 ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time. ## Provides significant memory benefits over pre-loading all your functions, and significant performance benefits over using plain scripts. Can also *inject* functions into Modules so they inherit the module scope instead of the current local scope. ## Please see the use example in the script below ## Version History ## v 1.2 - 2011.05.02 ## - Exposed the LoadNow alias and the Resolve-Autoloaded function ## v 1.1 - 2011.02.09 ## Added support for autoloading scripts (files that don't have a "function" in them) ## v 1.0 - 2010.10.20 ## Officially out of beta -- this is working for me without problems on a daily basis. ## Renamed functions to respect the Verb-Noun expectations, and added Export-ModuleMember ## beta 8 - 2010.09.20 ## Finally fixed the problem with aliases that point at Invoke-Autoloaded functions! ## beta 7 - 2010.06.03 ## Added some help, and a function to force loading "now" ## Added a function to load AND show the help... ## beta 6 - 2010.05.18 ## Fixed a bug in output when multiple outputs happen in the END block ## beta 5 - 2010.05.10 ## Fixed non-pipeline use using $MyInvocation.ExpectingInput ## beta 4 - 2010.05.10 ## I made a few tweaks and bug fixes while testing it's use with PowerBoots. ## beta 3 - 2010.05.10 ## fix for signed scripts (strip signature) ## beta 2 - 2010.05.09 ## implement module support ## beta 1 - 2010.04.14 ## Initial Release ## To use: ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments ## For example: <# function Skip-Object { param( [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $InputObject ) begin { if($Last) { $Queue = new-object System.Collections.Queue $Last } $e = $every; $UpTo++; $u = 0 } process { $InputObject | where { --$First -lt 0 } | foreach { if($Last) { $Queue.EnQueue($_) if($Queue.Count -gt $Last) { $Queue.DeQueue() } } else { $_ } } | foreach { if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo } } | foreach { if($every -and (--$e -le 0)) { $e = $every } else { $_ } } } } #> ## 2) Put the function into a script (for our example: C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 ) ## 3) Import the Autoload Module ## 5) Run this command (or add it to your profile): <# New-Autoload C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 Skip-Object #> ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it. ## Now, you can just use the function: ## 1..10 | Skip-Object -first 2 -upto 2 function Invoke-Autoloaded { #.Synopsis # This function was autoloaded, but it has not been parsed yet. # Use Get-AutoloadHelp to force parsing and get the correct help (or just invoke the function once). #.Description # You are seeing this help because the command you typed was imported via the New-Autoload command from the Autoload module. The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the Get-AutoloadHelp function. # # For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: Get-AutoloadHelp Get-PerformanceHistory [CmdletBinding()]Param() DYNAMICPARAM { $CommandName = $MyInvocation.InvocationName return Resolve-Autoloaded $CommandName }#DynamicParam begin { Write-Verbose "Command: $CommandName" if(!$Script:AutoloadHash[$CommandName]) { do { $Alias = $CommandName $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName" } while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue)) } else { Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])" } if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" } $ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName] Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName -> $FunctionName" #Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta $global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function ) Write-Verbose "Autoloaded Command: $($Command|Out-String)" $scriptCmd = {& $command @PSBoundParameters | Write-Output } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($myInvocation.ExpectingInput) } process { Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)" try { if($_) { $steppablePipeline.Process($_) } else { $steppablePipeline.Process() } } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } Write-Verbose "Invoke-Autoloaded End: $CommandName" } }#Invoke-Autoloaded function Get-AutoloadHelp { [CmdletBinding()] Param([Parameter(Mandatory=$true)][String]$CommandName) $null = Resolve-Autoloaded $CommandName Get-Help $CommandName } function Resolve-Autoloaded { [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Name")] [String]$CommandName ) $OriginalCommandName = "($CommandName)" Write-Verbose "Command: $CommandName" if(!$Script:AutoloadHash[$CommandName]) { do { $Alias = $CommandName $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition $OriginalCommandName += "($CommandName)" Write-Verbose "Resolve-Autoloaded Begin: $Alias -> $CommandName" } while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue)) } else { Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])" } if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command $OriginalCommandName!" } Write-Verbose "Resolve-Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])" $ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName] Write-Verbose "Autoloading:`nScriptName: $ScriptName `nModuleName: $ModuleName `nFunctionName: $FunctionName" if(!$ScriptName){ $ScriptName = $CommandName } if(!$FunctionName){ $FunctionName = $CommandName } if($ModuleName) { $Module = Get-Module $ModuleName } else { $Module = $null } ## Determine the command name based on the alias used to invoke us ## Store the parameter set for use in the function later... $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary #$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript ) $externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1 Write-Verbose "Processing Script: $($externalScript |Out-String)" $parserrors = $null $prev = $null $script = $externalScript.ScriptContents [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]::Reverse($tokens) $function = $false ForEach($token in $tokens) { if($prev -and $token.Content -eq "# SIG # Begin signature block") { $script = $script.SubString(0, $token.Start ) } if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) { $script = $script.Insert( $prev.Start, "global:" ) $function = $true Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')" } $prev = $token } if(!$function) { $script = "function global:$Functionname { $script }" } if($Module) { $script = Invoke-Expression "{ $Script }" Write-Verbose "Importing Function into $($Module) module." &$Module $Script | Out-Null $command = Get-Command $FunctionName -Type Function Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)" } else { Write-Verbose "Importing Function without module." Invoke-Expression $script | out-null $command = Get-Command $FunctionName -Type Function Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)" } if(!$command) { throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)" } if($CommandName -eq $FunctionName) { Remove-Item Alias::$($CommandName) Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)" } else { Set-Alias $CommandName $FunctionName -Scope Global Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)" } foreach( $pkv in $command.Parameters.GetEnumerator() ){ $parameter = $pkv.Value if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue } $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes) $paramdictionary.Add($pkv.Key, $param) } return $paramdictionary } function New-Autoload { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Name , [Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)] [Alias("BaseName")] $Alias = $Name , [Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)] $Function = $Alias , [Parameter(Position=3,Mandatory=$false)] [String]$Module , [Parameter(Mandatory=$false)] [String]$Scope = '2' ) begin { $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") if(!$xlr8r::Get["PSParser"]) { if($xlr8r::AddReplace) { $xlr8r::AddReplace( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } else { $null = $xlr8r::Remove( "PSParser" ) $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } } } process { for($i=0;$i -lt $Name.Count;$i++){ if($Alias -is [Scriptblock]) { $a = $Name[$i] | &$Alias } elseif($Alias -is [Array]) { $a = $Alias[$i] } else { $a = $Alias } if($Function -is [Scriptblock]) { $f = $Name[$i] | &$Function } elseif($Function -is [Array]) { $f = $Function[$i] } else { $f = $Function } Write-Verbose "Set-Alias $Module\\$a Invoke-Autoloaded -Scope $Scope" Set-Alias $a Invoke-Autoloaded -Scope $Scope $Script:AutoloadHash[$a] = $Name[$i],$Module,$f Write-Verbose "$($Script:AutoloadHash.Count) `$AutoloadHash[$a] = $($Script:AutoloadHash[$a])" } } } Set-Alias Autoload New-Autoload Set-Alias LoadNow Resolve-Autoloaded New-Variable -Name AutoloadHash -Value @{} -Scope Script -Description "The Autoload alias-to-script cache" -Option ReadOnly -ErrorAction SilentlyContinue Export-ModuleMember -Function New-Autoload, Invoke-Autoloaded, Get-AutoloadHelp, Resolve-Autoloaded -Alias *
PowerShellCorpus/PoshCode/Import-GmailFilterXml.ps1
Import-GmailFilterXml.ps1
param ( $Path ) [xml]$flt = Get-Content -Path $Path $title = $flt.feed.title $author = $flt.feed.author.name $output = @() foreach ( $entry in $flt.feed.entry ) { foreach ( $property in $entry.property ) { foreach ($item in $property) { $process = "" | select Id, Updated, Name, Value $process.Id = $entry.Id $process.Updated = [datetime]$entry.Updated $process.Name = $item.Name $process.Value = $item.Value $output += $process } } } $output
PowerShellCorpus/PoshCode/ScriptingAgentConfig.xml.ps1
ScriptingAgentConfig.xml.ps1
<?xml version="1.0" encoding="UTF-8" ?> <Configuration version="1.0"> <Feature Name="MailboxProvisioningDatabase" Cmdlets="new-mailbox"> <ApiCall Name="ProvisionDefaultProperties"> #Regex switch to decide mailboxdatabase based on the user specified Name-attribute switch -regex (($provisioningHandler.UserSpecifiedParameters["Name"]).substring(0,1)) { "[A-F]" {$databasename = "MDB A-F"} "[G-L]" {$databasename = "MDB G-L"} "[M-R]" {$databasename = "MDB M-R"} "[S-X]" {$databasename = "MDB S-X" } "[Y-Z]" {$databasename = "MDB Y-Z" } default {$databasename = "MDB Y-Z" } } #New template recipient $user = new-object -type Microsoft.Exchange.Data.Directory.Recipient.ADUser; #The template recipient are provided a database based on the result of the regex switch $user.database = "CN=$databasename,CN=Databases,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN="Exchange organization name",CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=local"; #The template recipient are provided as an argument to a new template mailbox which will be used by the New-Mailbox cmdlet new-object -type Microsoft.Exchange.Data.Directory.Management.Mailbox -argumentlist $user </ApiCall> </Feature> </Configuration>
PowerShellCorpus/PoshCode/get-smtpconnections.ps1
get-smtpconnections.ps1
param ( $logpath = "C:\\WINDOWS\\system32\\LogFiles\\SMTPSVC1" # can also be fed by "gci $logpath | select basename" but then all logfiles would be read $logfiles = @("ex130213.log","ex130214.log") $regex = "(?:[0-9]{1,3}\\.){3}[0-9]{1,3}" ) $smtphosts = @() foreach ($logFile in $logfiles){ # can also be iterated thru "gci $logpath" if all logfiles need parsing $logfilepath = Join-Path $logpath $logfile write-host "getting smtp connections from $logfile" -foregroundcolor green $smtphosts += select-string -Path $logfilepath -Pattern $regex -AllMatches | %{ $_.Matches } | % { $_.Value } | sort -Unique } $smtphosts | sort -Unique # can be followed by "| nslookup" for automated reverse lookup
PowerShellCorpus/PoshCode/2311f39b-7495-4f1a-9a8b-bc425f057624.ps1
2311f39b-7495-4f1a-9a8b-bc425f057624.ps1
function Get-EasterWestern { Param( [Parameter(Mandatory=$true)] [int] $Year ) $a = $Year % 19 $b = [Math]::Floor($Year / 100) $c = $Year % 100 $d = [Math]::Floor($b / 4) $e = $b % 4 $f = [Math]::Floor(($b + 8) / 25) $g = [Math]::Floor((($b - $f + 1) / 3)) $h = ((19 * $a) + $b + (-$d) + (-$g) + 15) % 30 $i = [Math]::Floor($c / 4) $k = $c % 4 $L1 = -($h + $k) #here because powershell is picking up - (subtraction operator) as incorrect toekn $L = (32 + (2 * $e) + (2 * $i) + $L1) % 7 $m = [Math]::Floor(($a + (11 * $h) + (22 * $L)) / 451) $v1 = -(7 * $m) #here because powershell is picking up - (subtraction operator) as incorrect toekn $month = [Math]::Floor(($h + $L + $v1 + 114) / 31) $day = (($h + $L + $v1 + 114) % 31) + 1 [System.DateTime]$date = "$Year/$month/$day" $date <# .SYNOPSIS Calculates the Gregorian Easter date for a given year. .DESCRIPTION Calculates the Gregorian Easter date for a given year greater than 1751. Algorithm sourced from http://en.wikipedia.org/wiki/Computus, Anonymous Gregorian algorithm. .PARAMETER Year The year to calculate easter for. .EXAMPLE PS C:\\> Get-EasterWestern 2017 .INPUTS System.Int32 .OUTPUTS System.DateTime #> }
PowerShellCorpus/PoshCode/Get-Netstat 1,_1.ps1
Get-Netstat 1,_1.ps1
$null, $null, $null, $null, $netstat = netstat -a -n -o [regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)' foreach ($net in $netstat) { [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName switch -regex ($net.Trim()) { $regexTCP { $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 = ( Get-Process -Id $matches.PID ).ProcessName } $regexUDP { $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 = ( Get-Process -Id $matches.PID ).ProcessName } } $Process.LocalPort = ' ' + $Process.LocalPort $Process.LocalPort = $Process.LocalPort.Substring($Process.LocalPort.length-6,6) $process }
PowerShellCorpus/PoshCode/PS2WCF_3.ps1
PS2WCF_3.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=$null, $wsdlUrl, $proxyPath) { if($wsdlImporter -eq $null -and $wsdlUrl -eq $null) { throw "parameter -wsdlImporter or -wsdlUrl must be specified" } else { if($wsdlImporter -eq $null) { $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 $wsdlImporter.ImportAllContracts()) { [void]$generator.GenerateServiceContractType($contractDescription) } $parameters = New-Object System.CodeDom.Compiler.CompilerParameters if($proxyPath -eq $null) { $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/336b281d-5018-4ca9-a92e-baf5152f59a3.ps1
336b281d-5018-4ca9-a92e-baf5152f59a3.ps1
function Get-Installed { <# .SYNOPSIS This function lists data found in the registry associated with installed programs. .DESCRIPTION Describe the function in more detail Author: Stan Miller .EXAMPLE Get all apps whose display names start with a specific string and display all valuenames get-installed -re "^microsoft xna" -valuenameRE ".*" The "^" above means starts with the following string. The ".*" means match all including the empty string .EXAMPLE get-installed -re "^microsoft xna game studio platform tool$" Display the default set of valuenames for apps whose displayname starts (^) and ends ($) with "microsoft xna game studio platform tool" displayname=microsoft xna game studio platform tools displayversion=1.1.0.0 installdate=20100204 installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\ localpackage=C:\\Windows\\Installer\\2d09d3a5.msi madeup-gname={BED4CEEC-863F-4AB3-BA23-541764E2D2CE} madeup-loginid=System madeup-wow=1 uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE} windowsinstaller=1 .EXAMPLE get-installed -re "^microsoft xna game studio platform tool" -compress $False Display the default set of valuenames for apps whose displayname starts with "^microsoft xna" only this time show all registry sources. In this case the products and uninstall areas displayname=microsoft xna game studio platform tools keypath=software\\microsoft\\windows\\currentversion\\installer\\userdata\\s-1-5-18\\products\\ceec4debf3683ba4ab324571462e2dec\\installproperties displayversion=1.1.0.0 installdate=20100204 installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\ localpackage=C:\\Windows\\Installer\\2d09d3a5.msi madeup-loginid=System uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE} windowsinstaller=1 keypath=software\\wow6432node\\microsoft\\windows\\currentversion\\uninstall\\{bed4ceec-863f-4ab3-ba23-541764e2d2ce} displayversion=1.1.0.0 installdate=20100204 installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\ madeup-gname={BED4CEEC-863F-4AB3-BA23-541764E2D2CE} madeup-wow=1 uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE} windowsinstaller=1 .EXAMPLE get-installed -namesummary $true Display the frequency of valuenames for all apps in all registry location only this time show all registry sources in reverse order of occurrence. UninstallString,616 DisplayName,616 Publisher,600 DisplayVersion,525 VersionMajor,490 InstallDate,474 EstimatedSize,474 InstallSource,470 Version,469 ModifyPath,461 WindowsInstaller,457 Language,396 madeup-gname,391 NoModify,366 HelpLink,323 madeup-wow,308 NoRepair,256 SystemComponent,235 LocalPackage,225 URLInfoAbout,171 VersionMinor,167 InstallLocation,159 ParentDisplayName,91 ParentKeyName,91 madeup-native,83 DisplayIcon,79 Comments,78 URLUpdateInfo,71 RegOwner,69 MoreInfoURL,66 ProductID,62 RegCompany,59 NoRemove,53 Readme,35 Contact,33 ReleaseType,26 IsMinorUpgrade,26 RegistryLocation,25 HelpTelephone,21 UninstallPath,16 LogFile,9 MajorVersion,7 APPName,6 MinorVersion,6 Size,6 QuietUninstallString,5 NoElevateOnModify,4 Inno Setup: User,3 SkuComponents,3 ShellUITransformLanguage,3 ProductGuid,3 NVI2_Package,3 Inno Setup: App Path,3 Inno Setup: Icon Group,3 CacheLocation,3 ProductCodes,3 NVI2_Timestamp,3 Inno Setup: Deselected Tasks,3 NVI2_Setup,3 Inno Setup: Setup Version,3 LogMode,3 PackageIds,3 Inno Setup: Language,2 RequiresIESysFile,2 InstanceId,2 UninstDataVerified,1 BundleVersion,1 BundleProviderKey,1 Inno Setup: Selected Components,1 FCLAppName,1 Inno Setup: Selected Tasks,1 Integrated,1 BundleUpgradeCode,1 Installed,1 SQLProductFamilyCode,1 FCLGUID,1 UninstallerCommonDir,1 BundleDetectCode,1 InstallerType,1 DisplayName_Localized,1 Inno Setup: Setup Type,1 EngineVersion,1 BundleCachePath,1 Resume,1 .EXAMPLE get-installed -re "^microsoft xna game studio platform tools$" -makeobjects $true Instead of displaying the valuenames create an object for further use displayname : microsoft xna game studio platform tools DisplayVersion : 1.1.0.0 InstallDate : 20100204 InstallLocation : InstallSource : C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\ LocalPackage : C:\\Windows\\Installer\\2d09d3a5.msi madeup-gname : {BED4CEEC-863F-4AB3-BA23-541764E2D2CE} madeup-native : madeup-wow : 1 QuietUninstallString : UninstallString : MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE} WindowsInstaller : 1 .EXAMPLE get-installed -re "^microsoft xna game studio" -makeobjects $true|format-table Instead of displaying the valuenames create an object for further use displayname DisplayVersion InstallDate InstallLocation InstallSource LocalPackage madeup-gname madeup-native madeup-wow QuietUninstallStrin g ----------- -------------- ----------- --------------- ------------- ------------ ------------ ------------- ---------- ------------------- microsoft xna ga... 3.1.10527.0 XNA Game Studio 3.1 1 microsoft xna ga... 3.1.10527.0 20100204 c:\\c3aa2d4649aa0... c:\\Windows\\Insta... {E1D78366-91DA-4... 1 microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {007BECB0-17DD-4... 1 microsoft xna ga... 3.1.10527.0 20100204 c:\\c3aa2d4649aa0... c:\\Windows\\Insta... {0DC16794-7E69-4... 1 microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {AF9BDE67-11A5-4... 1 microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {3BA37E38-B53D-4... 1 microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {DFB81F19-ED3A-4... 1 microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {7FD30AE7-281D-4... 1 microsoft xna ga... 1.1.0.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {BED4CEEC-863F-4... 1 .PARAMETER computername The computer name to query. Just one. .PARAMETER re regular expression used to select software displayname .PARAMETER compress defaults to true. Merges values by valuename from many sources of installed data. The merge means if it finds a valuename more than once it shows only the first one found. This is true except for madeup-loginid. Instead a string is created with comma separated values where the values are the loginids of sids found in the product sections. Set to false the program will separate the values by registry keypath. data from products installed by the system takes precedence over software...uninstall .PARAMETER namesummary displays a list of valuenames found in registry in descending order of frequency no other data shown if this is set to $true .PARAMETER valuenameRE regular expression to specify which valuenames to display defaults to "displayversion|windowsinstaller|uninstallstring|localpackage|installsource|installdate|madeup-|gp_" specify .* to display all valuenames valuename not in registry but madeup in this program start with madeup- madeup-wow was set for uninstall key in the software wow6432node portion of the registry madeup-native was set for uninstall key in the software native portion of the key madeup-guid was set from the uninstall subkey containing the value names madeup-loginid was set from the registry product section valuename from group policy is prepended with "gp_" .PARAMETER makeobjects Create objects whose properties are the merged valuenames defined by the value name defaults. #> [CmdletBinding()] param ( [Parameter(Mandatory=$False)] [Alias('computer')] [string]$computername=$env:computername, [string]$re = ".*", [boolean]$compress=$true, [boolean]$namesummary=$false, [boolean]$makeobjects=$false, [string]$valuenameRE="displayversion|windowsinstaller|uninstallstring|installlocation|localpackage|installsource|installdate|madeup-|gp_", [string]$makeobjectsRE="displayversion|windowsinstaller|uninstallstring|installlocation|localpackage|installsource|installdate|madeup-|gp_" ) begin { try { $regbase=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$computername) } catch [Exception] { # see if remote registry is stopped Write-Host "Failed to open registry due to " $_.Exception.Message if ($_.Exception.HResult -eq 53) { # The network path was not found exit } Write-Host "Checking if registry service started on " $computername try { Get-Service remoteregistry -ComputerName $computername|gm $remoteregistry=(Get-Service remoteregistry -ComputerName $computername).status } catch [Exception] { Write-Host "cannot reach service manager on " $computername exit } "Remote Registry status is " + $remoteregistry if ($remoteregistry -ieq "stopped") { Set-Service remoteregistry -Status Running -Computername $computername sleep 5 try { $regbase=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$computername) } catch [Exception] { return $_.Exception.Message } } else { write-Host "could not open registry for " $computername exit } } $software=@{} # Keep hash of software displaynames -> hash of keypaths -> hash of valuename->values $valuenamesfound=@{} # keep count of valuenames found $pg2displayname=@{} # set in getproductdata and used in getgrouppolicydata $sid2logid=@{} # Set it $installedbywho=@{} # track who has installed a product Function load_sid2logid { # Set $sid2logid using registry profilelist $ProfileListKey=$regbase.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",$False) if ($ProfileListKey -eq $null) {return "Yuck"} foreach ($guid in $ProfileListKey.GetSubKeyNames()) { if ($guid -imatch "^s-") { switch($guid.ToUpper()) { "S-1-5-18" {$sid2logid.Add("S-1-5-18","System")} "S-1-5-19" {$sid2logid.Add("S-1-5-19","Service")} "S-1-5-20" {$sid2logid.Add("S-1-5-20","Network")} default { [string]$ProfileImagePath=$ProfileListKey.OpenSubKey($guid).GetValue("ProfileImagePath") $logid=$ProfileImagePath.Split("\\")[-1] $sid2logid.Add($guid.ToUpper(),$logid) } } } } } load_sid2logid } process { Function upvaluenamesfound { param([string]$valuename) if ($valuenamesfound.ContainsKey($valuename)) { $valuenamesfound.$valuename++ } else { $valuenamesfound.Add($valuename,1) } } Function getuninstalldata { param([STRING] $subkeyname) $uninstallkey=$regbase.OpenSubKey($subkeyname,$False) foreach ($gname in $uninstallkey.GetSubKeyNames()) { $prodkey=$uninstallkey.OpenSubKey($gname) $displayname=$prodkey.GetValue("displayname") $uninstallstring=$prodkey.GetValue("uninstallstring") if ($displayname -ine "" -and $displayname -ne $null -and $uninstallstring -ine "" -and $uninstallstring -ine $null ) { $KeyPath=$subkeyname+"\\"+$gname $valuehash= @{} #"KeyPath=" + $KeyPath #"displayname='" + $displayname + "'" $valuehash.Add("madeup-gname",$gname) upvaluenamesfound("madeup-gname") if ($subkeyname -imatch "wow6432node") { $valuehash.Add("madeup-wow",1) upvaluenamesfound("madeup-wow") } else { $valuehash.Add("madeup-native",1) upvaluenamesfound("madeup-native") } foreach ($valuename in $prodkey.GetValueNames()) { $value=$prodkey.GetValue($valuename) if ($value -ine "" -and $value -ine $null) { $valuehash.Add($valuename.tolower(),$prodkey.GetValue($valuename)) upvaluenamesfound($valuename) #"added " + $valuename + "=" + $valuehash.$valuename } } $guidformat="no" if ($gname.StartsWith("{") -and $gname.EndsWith("}") -and $gname.Length -eq 38 ) {$guidformat="yes"} $tolower=$displayname.ToLower() if ($software.ContainsKey($tolower)) { $software.$tolower.Add($KeyPath.ToLower(),$valuehash) } else { $subhash=@{} $subhash.Add($KeyPath.ToLower(),$valuehash) $software.Add($tolower,$subhash) } } } } Function getproductdatabysid { param([string]$sid) $subkeyname="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\"+$sid+"\\Products" $productkey=$regbase.OpenSubKey($subkeyname,$False) foreach ($gname in $productkey.GetSubKeyNames()) { $prodkey=$productkey.OpenSubKey($gname).OpenSubKey("InstallProperties") try { $displayname=$prodkey.GetValue("displayname") $uninstallstring=$prodkey.GetValue("uninstallstring") $pg2displayname.Add($gname.ToLower(),$displayname) # remember packed guid } catch { $uninstallstring="" $displayname="" } if ($displayname -ine "" -and $displayname -ne $null -and $uninstallstring -ine "" -and $uninstallstring -ine $null ) { $KeyPath=$subkeyname+"\\"+$gname + "\\InstallProperties" #"KeyPath=" + $KeyPath #"displayname='" + $displayname + "'" $valuehash= @{} $valuehash.Add("madeup-loginid",$sid2logid.$sid) foreach ($valuename in $prodkey.GetValueNames()) { $value=$prodkey.GetValue($valuename) if ($value -ine "" -and $value -ine $null) { $valuehash.Add($valuename.tolower(),$prodkey.GetValue($valuename)) upvaluenamesfound($valuename) #"added " + $valuename + "=" + $valuehash.$valuename } } $tolower=$displayname.ToLower() if ($software.ContainsKey($tolower)) { $software.$tolower.Add($KeyPath.ToLower(),$valuehash) } else { $subhash=@{} $subhash.Add($KeyPath.ToLower(),$valuehash) $software.Add($tolower,$subhash) } } } } Function getproductdata { $subkeyname="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData" $userdatakey=$regbase.OpenSubKey($subkeyname,$False) foreach ($sid in $userdatakey.GetSubKeyNames()) { getproductdatabysid($sid) } } Function getgrouppolicydata { $subkeyname="SOFTWARE/Microsoft/Windows/CurrentVersion/Group Policy/AppMgmt" $gpkey=$regbase.OpenSubKey($subkeyname,$False) if ($gpkey -eq $null) { return } foreach ($gname in $gpkey.GetSubKeyNames()) { $prodkey=$gpkey.OpenSubKey($gname) $displayname=$pg2displayname.($gname.ToLower()) if ($displayname -ine "" -and $displayname -ine $null) { $keypath=$subkeyname+ "\\" + $gname $valuehash=@{} foreach ($valuename in $prodkey.GetValueNames()) { $value=$prodkey.GetValue($valuename) if ($value -ine "" -and $value -ine $null) { $valuehash.Add("gp_"+$valuename.tolower(),$prodkey.GetValue($valuename)) upvaluenamesfound($valuename) #"added " + $valuename + "=" + $valuehash.$valuename } } $tolower=$displayname.ToLower() if ($software.ContainsKey($tolower)) { $software.$tolower.Add($KeyPath.ToLower(),$valuehash) } else { $subhash=@{} $subhash.Add($KeyPath.ToLower(),$valuehash) $software.Add($tolower,$subhash) } } } } getuninstalldata("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall") getuninstalldata("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall") getproductdata getgrouppolicydata #HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products\\00002109610090400000000000F01FEC\\InstallProperties if ($namesummary) { $mykeys=$valuenamesfound.keys|sort-object -Property @{Expression={[int]$valuenamesfound.$_}; Ascending=$false} foreach ($valuename in ($mykeys)) { if ($valuename -ne "" -and $valuename -ne $null) {$valuename + "," + $valuenamesfound.$valuename} } } elseif ($makeobjects) { foreach ($displayname in ($software.Keys|Sort-Object)) { if ($displayname -imatch $re) { #" " #"displayname=" + $displayname $compressedhash=@{}; foreach ($keypath in ($software.$displayname.Keys|Sort-Object)) { foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object)) { if (-not $compressedhash.ContainsKey($valuename)) { $compressedhash.Add($valuename,$software.$displayname.$keypath.$valuename) } elseif ($valuename -ieq "madeup-loginid") { $compressedhash.$valuename += ("," + $software.$displayname.$keypath.$valuename) } } } $obj=New-Object object $obj|Add-Member -MemberType NoteProperty "displayname" $displayname foreach ($valuename in ($valuenamesfound.keys|Sort-Object)) { if ($valuename -imatch $makeobjectsRE) { if ($compressedhash.ContainsKey($valuename)) { $obj|Add-Member -MemberType NoteProperty $valuename $compressedhash.$valuename } else { $obj|Add-Member -MemberType NoteProperty $valuename "" } } } Write-Output $obj } } } elseif ($compress) { foreach ($displayname in ($software.Keys|Sort-Object)) { if ($displayname -imatch $re) { " " "displayname=" + $displayname $compressedhash=@{}; foreach ($keypath in ($software.$displayname.Keys|Sort-Object)) { foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object)) { if (-not $compressedhash.ContainsKey($valuename)) { $compressedhash.Add($valuename,$software.$displayname.$keypath.$valuename) } elseif ($valuename -ieq "madeup-loginid") { $compressedhash.$valuename += ("," + $software.$displayname.$keypath.$valuename) } } } foreach ($valuename in ($compressedhash.Keys|Sort-Object)) { if ($valuename -imatch $valuenameRE) { " " + $valuename + "=" + $compressedhash.$valuename } } } } } else { foreach ($displayname in ($software.Keys|Sort-Object)) { if ($displayname -imatch $re) { " " "displayname=" + $displayname foreach ($keypath in ($software.$displayname.Keys|Sort-Object)) { " keypath=" + $keypath foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object)) { if ($valuename -imatch $valuenameRE) { " " + $valuename + "=" + $software.$displayname.$keypath.$valuename } } } } } } } }
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_5.ps1
TabExpansion for V2CTP_5.ps1
## Tab-Completion ################# ## For V2CTP3. ## This won't work on V1 and V2CTP and V2CTP2. ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion (this also support default help function and man alias) ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion (this also support default help function and man alias) ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Errora s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" } ## $data = Get-Process ## $data[2,4,5] | % { $_.<tab> ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion by -Property parameter ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ## #Parameter expansion for function, filter and script ## man -f<tab> ## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1 ## .\\foobar.ps1 -<tab> -b<tab> ## #Enum expansion for function, filter and scripts ## # this can do continuous enum expansion with comma and no spaces ## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab> ## #Enum expansion for assignment expression ## #needs space(s) after '=' and comma ## #strongly-typed with -as operator and space(s) ## $ErrorActionPreference =<space><tab> ## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3 ## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab> ## #Path expansion with variable and '\\' or '/' ## $PWD\\../../<tab>\\<tab> ## "$env:SystemDrive/pro<tab>/<tab> ## #Operator expansion which starts with '-' ## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2' ## 1..9 -co<tab> 5 ## #Keyword expansion ## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } } ## #Variable name expansion (only global scope) ## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab> ## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab> ## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab> ## Tee-Object -Variable <tab> ## gv pro<tab>,<tab> ## Remove-Variable -Name out<tab>,<tab>,ps<tab> ## ... | ... | tee -v <tab> ## #Alias name expansion ## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab> ## Export-Alias -Name <tab> ## Get-Alias i<tab>,e<tab>,a<tab> ## epal -n for<tab> ## #Property name expansion with -groupBy parameter ## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab> ## ps | ft -g <tab> ## gcm | Format-Wide -GroupBy Par<tab> ## #Type accelerators expansion with no charactors ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ## #Switch syntax option expansion ## switch -w<tab> -f<tab> ## #Better powershell.exe option expansion with '-' ## powershell -no<tab> -<tab> -en<tab> ## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* ) ## [par<tab> ## [cmd<tab> ## #Member expansion for CmdletBinding and Parameter attributes ## [Parameter(man<tab>,<tab>1,val<tab>$true)] ## [CmdletBinding( <tab>"foo", su<tab>$true)] ## #Several current date/time formats with Ctrl+D ## <Ctrl+D><tab><tab><tab><tab><tab>... ## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,') ## <command>;<tab> # push command ## <Ctrl+D><tab> # pop ## #Paste clipboard with Ctrl+V ## <Ctrl+V><tab> ## # Cut current line with Ctrl+X ## <command><Ctrl+X><tab> ## # Cut words with a charactor after Ctrl+X until the charactor ## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-' ## 2: PS > dir - ## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now ## # Cut last word in current line with Ctrl+Z ## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line ## 2: PS > Get-ChildItem ## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0 } else { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") $_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID.Add($_i.GetValue("")) } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose } ### Generate TypeNames list... if ( Test-Path $PSHOME\\TypeNames.txt ) { $_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0 } else { $_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames.Add($_type.FullName) } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose } if ( Test-Path $PSHOME\\TypeNames_System.txt ) { $_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0 } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0 } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort iex (@' function prompt { if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member 'NoteProperty' CommandType $f.CommandType -P | Add-Member 'NoteProperty' Definition $a.Definition -P | Add-Member 'NoteProperty' Description $a.Description -P | Add-Member 'NoteProperty' Key $e.Key -P | Add-Member 'NoteProperty' Location $c.Location -P | Add-Member 'NoteProperty' LocationName $c.LocationName -P | Add-Member 'NoteProperty' Options $a.Options -P | Add-Member 'NoteProperty' ReferencedCommand $a.ReferencedCommand -P | Add-Member 'NoteProperty' ResolvedCommand $a.ResolvedCommand -P | Add-Member 'NoteProperty' ScriptBlock $f.ScriptBlock -P | Add-Member 'NoteProperty' StoreNames $c.StoreNames -P | Add-Member 'NoteProperty' SubKeyCount $h.SubKeyCount -P | Add-Member 'NoteProperty' Value $e.Value -P | Add-Member 'NoteProperty' ValueCount $h.ValueCount -P | Add-Member 'NoteProperty' Visibility $a.Visibility -P | Add-Member 'NoteProperty' Property $h.Property -P | Add-Member 'NoteProperty' ResolvedCommandName $a.ResolvedCommandName -P | Add-Member 'ScriptMethod' Close {} -P | Add-Member 'ScriptMethod' CreateSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKeyTree {} -P | Add-Member 'ScriptMethod' DeleteValue {} -P | Add-Member 'ScriptMethod' Flush {} -P | Add-Member 'ScriptMethod' GetSubKeyNames {} -P | Add-Member 'ScriptMethod' GetValue {} -P | Add-Member 'ScriptMethod' GetValueKind {} -P | Add-Member 'ScriptMethod' GetValueNames {} -P | Add-Member 'ScriptMethod' IsValidValue {} -P | Add-Member 'ScriptMethod' OpenSubKey {} -P | Add-Member 'ScriptMethod' SetValue {} -P } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Mode $f.Mode -P | Add-Member 'NoteProperty' Assembly $t.Assembly -P | Add-Member 'NoteProperty' AssemblyQualifiedName $t.AssemblyQualifiedName -P | Add-Member 'NoteProperty' Attributes $f.Attributes -P | Add-Member 'NoteProperty' BaseType $t.BaseType -P | Add-Member 'NoteProperty' ContainsGenericParameters $t.ContainsGenericParameters -P | Add-Member 'NoteProperty' CreationTime $f.CreationTime -P | Add-Member 'NoteProperty' CreationTimeUtc $f.CreationTimeUtc -P | Add-Member 'NoteProperty' DeclaringMethod $t.DeclaringMethod -P | Add-Member 'NoteProperty' DeclaringType $t.DeclaringType -P | Add-Member 'NoteProperty' Exists $f.Exists -P | Add-Member 'NoteProperty' Extension $f.Extension -P | Add-Member 'NoteProperty' FullName $f.FullName -P | Add-Member 'NoteProperty' GenericParameterAttributes $t.GenericParameterAttributes -P | Add-Member 'NoteProperty' GenericParameterPosition $t.GenericParameterPosition -P | Add-Member 'NoteProperty' GUID $t.GUID -P | Add-Member 'NoteProperty' HasElementType $t.HasElementType -P | Add-Member 'NoteProperty' IsAbstract $t.IsAbstract -P | Add-Member 'NoteProperty' IsAnsiClass $t.IsAnsiClass -P | Add-Member 'NoteProperty' IsArray $t.IsArray -P | Add-Member 'NoteProperty' IsAutoClass $t.IsAutoClass -P | Add-Member 'NoteProperty' IsAutoLayout $t.IsAutoLayout -P | Add-Member 'NoteProperty' IsByRef $t.IsByRef -P | Add-Member 'NoteProperty' IsClass $t.IsClass -P | Add-Member 'NoteProperty' IsCOMObject $t.IsCOMObject -P | Add-Member 'NoteProperty' IsContextful $t.IsContextful -P | Add-Member 'NoteProperty' IsEnum $t.IsEnum -P | Add-Member 'NoteProperty' IsExplicitLayout $t.IsExplicitLayout -P | Add-Member 'NoteProperty' IsGenericParameter $t.IsGenericParameter -P | Add-Member 'NoteProperty' IsGenericType $t.IsGenericType -P | Add-Member 'NoteProperty' IsGenericTypeDefinition $t.IsGenericTypeDefinition -P | Add-Member 'NoteProperty' IsImport $t.IsImport -P | Add-Member 'NoteProperty' IsInterface $t.IsInterface -P | Add-Member 'NoteProperty' IsLayoutSequential $t.IsLayoutSequential -P | Add-Member 'NoteProperty' IsMarshalByRef $t.IsMarshalByRef -P | Add-Member 'NoteProperty' IsNested $t.IsNested -P | Add-Member 'NoteProperty' IsNestedAssembly $t.IsNestedAssembly -P | Add-Member 'NoteProperty' IsNestedFamANDAssem $t.IsNestedFamANDAssem -P | Add-Member 'NoteProperty' IsNestedFamily $t.IsNestedFamily -P | Add-Member 'NoteProperty' IsNestedFamORAssem $t.IsNestedFamORAssem -P | Add-Member 'NoteProperty' IsNestedPrivate $t.IsNestedPrivate -P | Add-Member 'NoteProperty' IsNestedPublic $t.IsNestedPublic -P | Add-Member 'NoteProperty' IsNotPublic $t.IsNotPublic -P | Add-Member 'NoteProperty' IsPointer $t.IsPointer -P | Add-Member 'NoteProperty' IsPrimitive $t.IsPrimitive -P | Add-Member 'NoteProperty' IsPublic $t.IsPublic -P | Add-Member 'NoteProperty' IsSealed $t.IsSealed -P | Add-Member 'NoteProperty' IsSerializable $t.IsSerializable -P | Add-Member 'NoteProperty' IsSpecialName $t.IsSpecialName -P | Add-Member 'NoteProperty' IsUnicodeClass $t.IsUnicodeClass -P | Add-Member 'NoteProperty' IsValueType $t.IsValueType -P | Add-Member 'NoteProperty' IsVisible $t.IsVisible -P | Add-Member 'NoteProperty' LastAccessTime $f.LastAccessTime -P | Add-Member 'NoteProperty' LastAccessTimeUtc $f.LastAccessTimeUtc -P | Add-Member 'NoteProperty' LastWriteTime $f.LastWriteTime -P | Add-Member 'NoteProperty' LastWriteTimeUtc $f.LastWriteTimeUtc -P | Add-Member 'NoteProperty' MemberType $t.MemberType -P | Add-Member 'NoteProperty' MetadataToken $t.MetadataToken -P | Add-Member 'NoteProperty' Module $t.Module -P | Add-Member 'NoteProperty' Name $t.Name -P | Add-Member 'NoteProperty' Namespace $t.Namespace -P | Add-Member 'NoteProperty' Parent $f.Parent -P | Add-Member 'NoteProperty' ReflectedType $t.ReflectedType -P | Add-Member 'NoteProperty' Root $f.Root -P | Add-Member 'NoteProperty' StructLayoutAttribute $t.StructLayoutAttribute -P | Add-Member 'NoteProperty' TypeHandle $t.TypeHandle -P | Add-Member 'NoteProperty' TypeInitializer $t.TypeInitializer -P | Add-Member 'NoteProperty' UnderlyingSystemType $t.UnderlyingSystemType -P | Add-Member 'NoteProperty' PSChildName $f.PSChildName -P | Add-Member 'NoteProperty' PSDrive $f.PSDrive -P | Add-Member 'NoteProperty' PSIsContainer $f.PSIsContainer -P | Add-Member 'NoteProperty' PSParentPath $f.PSParentPath -P | Add-Member 'NoteProperty' PSPath $f.PSPath -P | Add-Member 'NoteProperty' PSProvider $f.PSProvider -P | Add-Member 'NoteProperty' BaseName $f.BaseName -P | Add-Member 'ScriptMethod' Clone {} -P | Add-Member 'ScriptMethod' CompareTo {} -P | Add-Member 'ScriptMethod' Contains {} -P | Add-Member 'ScriptMethod' CopyTo {} -P | Add-Member 'ScriptMethod' Create {} -P | Add-Member 'ScriptMethod' CreateObjRef {} -P | Add-Member 'ScriptMethod' CreateSubdirectory {} -P | Add-Member 'ScriptMethod' Delete {} -P | Add-Member 'ScriptMethod' EndsWith {} -P | Add-Member 'ScriptMethod' FindInterfaces {} -P | Add-Member 'ScriptMethod' FindMembers {} -P | Add-Member 'ScriptMethod' GetAccessControl {} -P | Add-Member 'ScriptMethod' GetArrayRank {} -P | Add-Member 'ScriptMethod' GetConstructor {} -P | Add-Member 'ScriptMethod' GetConstructors {} -P | Add-Member 'ScriptMethod' GetCustomAttributes {} -P | Add-Member 'ScriptMethod' GetDefaultMembers {} -P | Add-Member 'ScriptMethod' GetDirectories {} -P | Add-Member 'ScriptMethod' GetElementType {} -P | Add-Member 'ScriptMethod' GetEnumerator {} -P | Add-Member 'ScriptMethod' GetEvent {} -P | Add-Member 'ScriptMethod' GetEvents {} -P | Add-Member 'ScriptMethod' GetField {} -P | Add-Member 'ScriptMethod' GetFields {} -P | Add-Member 'ScriptMethod' GetFiles {} -P | Add-Member 'ScriptMethod' GetFileSystemInfos {} -P | Add-Member 'ScriptMethod' GetGenericArguments {} -P | Add-Member 'ScriptMethod' GetGenericParameterConstraints {} -P | Add-Member 'ScriptMethod' GetGenericTypeDefinition {} -P | Add-Member 'ScriptMethod' GetInterface {} -P | Add-Member 'ScriptMethod' GetInterfaceMap {} -P | Add-Member 'ScriptMethod' GetInterfaces {} -P | Add-Member 'ScriptMethod' GetLifetimeService {} -P | Add-Member 'ScriptMethod' GetMember {} -P | Add-Member 'ScriptMethod' GetMembers {} -P | Add-Member 'ScriptMethod' GetMethod {} -P | Add-Member 'ScriptMethod' GetMethods {} -P | Add-Member 'ScriptMethod' GetNestedType {} -P | Add-Member 'ScriptMethod' GetNestedTypes {} -P | Add-Member 'ScriptMethod' GetObjectData {} -P | Add-Member 'ScriptMethod' GetProperties {} -P | Add-Member 'ScriptMethod' GetProperty {} -P | Add-Member 'ScriptMethod' GetTypeCode {} -P | Add-Member 'ScriptMethod' IndexOf {} -P | Add-Member 'ScriptMethod' IndexOfAny {} -P | Add-Member 'ScriptMethod' InitializeLifetimeService {} -P | Add-Member 'ScriptMethod' Insert {} -P | Add-Member 'ScriptMethod' InvokeMember {} -P | Add-Member 'ScriptMethod' IsAssignableFrom {} -P | Add-Member 'ScriptMethod' IsDefined {} -P | Add-Member 'ScriptMethod' IsInstanceOfType {} -P | Add-Member 'ScriptMethod' IsNormalized {} -P | Add-Member 'ScriptMethod' IsSubclassOf {} -P | Add-Member 'ScriptMethod' LastIndexOf {} -P | Add-Member 'ScriptMethod' LastIndexOfAny {} -P | Add-Member 'ScriptMethod' MakeArrayType {} -P | Add-Member 'ScriptMethod' MakeByRefType {} -P | Add-Member 'ScriptMethod' MakeGenericType {} -P | Add-Member 'ScriptMethod' MakePointerType {} -P | Add-Member 'ScriptMethod' MoveTo {} -P | Add-Member 'ScriptMethod' Normalize {} -P | Add-Member 'ScriptMethod' PadLeft {} -P | Add-Member 'ScriptMethod' PadRight {} -P | Add-Member 'ScriptMethod' Refresh {} -P | Add-Member 'ScriptMethod' Remove {} -P | Add-Member 'ScriptMethod' Replace {} -P | Add-Member 'ScriptMethod' SetAccessControl {} -P | Add-Member 'ScriptMethod' Split {} -P | Add-Member 'ScriptMethod' StartsWith {} -P | Add-Member 'ScriptMethod' Substring {} -P | Add-Member 'ScriptMethod' ToCharArray {} -P | Add-Member 'ScriptMethod' ToLower {} -P | Add-Member 'ScriptMethod' ToLowerInvariant {} -P | Add-Member 'ScriptMethod' ToUpper {} -P | Add-Member 'ScriptMethod' ToUpperInvariant {} -P | Add-Member 'ScriptMethod' Trim {} -P | Add-Member 'ScriptMethod' TrimEnd {} -P | Add-Member 'ScriptMethod' TrimStart {} -P | Add-Member 'NoteProperty' Chars $s.Chars -P } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Action '' -P | Add-Member 'NoteProperty' Command '' -P | Add-Member 'NoteProperty' Enabled '' -P | Add-Member 'NoteProperty' HitCount '' -P | Add-Member 'NoteProperty' Id '' -P | Add-Member 'NoteProperty' Script '' -P } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function TabExpansion { # This is the default function to use for tab expansion. It handles simple # member expansion on variables, variable name expansion and parameter completion # on commands. It doesn't understand strings so strings containing ; | ( or { may # cause expansion to fail. param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $params = @{view = 'extended','adapted','base'} } else { $params = @{static=$true} } if ( $_val -is [Hashtable] ) { [Object[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } } if ( $_keys -ne $null ) { $_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat}) } else { $_members = (Get-Member @params -InputObject $_val $_pat) } foreach ($_m in $_members | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } switch ([int]$line[-1]) { # Ctrl+D several date/time formats 4 { "[DateTime]::Now" [DateTime]::Now [DateTime]::Now.ToString("yyyyMMdd") [DateTime]::Now.ToString("MMddyyyy") [DateTime]::Now.ToString("yyyyMMddHHmmss") [DateTime]::Now.ToString("MMddyyyyHHmmss") 'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) } break; } # Ctrl+P hand-operated pop from command buffer stack 16 { $_base = $lastword.SubString(0, $lastword.Length-1) $_base + $global:_cmdstack.Pop() break; } # Ctrl+R $Host.UI.RawUI. 18 { '$Host.UI.RawUI.' '$Host.UI.RawUI' break; } # Ctrl+V paste clipboard 22 { $_base = $lastword.SubString(0, $lastword.Length-1) $_clip = New-Object System.Windows.Forms.TextBox $_clip.Multiline = $true $_clip.Paste() $_base + $_clip.Text break; } # Ctrl+X cut current line 24 { $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $line.SubString(0, $line.Length-1) $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") break; } # Ctrl+Z cut last word in current line 26 { $line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break; } } switch ( [int]$line[-2] ) { # Ctrl+X cut words with a charactor after Ctrl+X until the charactor 24 { $line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break; } } switch -regex ($lastWord) { # Handle property and method expansion at '$_' '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[(\\w+(\\.\\w*)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' "CmdletBinding", "Parameter", "Alias", "ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength", "ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange", "ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" ` -like $_opt -replace '^(.*)$', '[$1(' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ("'`$0'") $fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'") $fse = $fse -replace "''", "'" $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_base + $global:_cmdstack.Pop() } else { ""; break; } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") ""; break; } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_command = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_command -match '\\{([^\\{\\}]*)$') { $_command = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_command -match '\\(([^()]*)$') { $_command = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_command = $_command.Trim().Split()[0] # now get the info object for it... $_command = @(Get-Command -type 'All' $_command)[0] # loop resolving aliases... while ($_command.CommandType -eq 'alias') { $_command = @(Get-Command -type 'All' $_command.Definition)[0] } if ( $_command.name -eq "powershell.exe" ) { if ( $global:_PSexeOption ) { $global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } else { ($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } break; } if ( $_command -ne $null ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_command.Parameters.Keys | sort) { if ($_n -like $_pat) { '-' + $_n } } } elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$') { $_pat = $Matches[2] + '*' "regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1' break; } else { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # Tab complete against history either #<pattern> or #<id> '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } # try to find a matching command... default { # parse the script... $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null) if ( $_tokens ) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Member') { $_pat = $_lastToken.Content + '*' $i=$_tokens.count; do { $i-- } until ( $_tokens[$i].Type -eq "Attribute") if ( $lastWord -match "^(.*)([\\(,])\\w*$" ) { $_base = $matches[1] + $matches[2] } switch ( $_tokens[$i].Content ) { 'Parameter' { [System.Management.Automation.ParameterAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" } } 'CmdletBinding' { [System.Management.Automation.CmdletBindingAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" } } } break; } if ( $_tokens[1].Type -eq "Attribute") { if ( $line.Split("(").Count -gt $line.Split(")").Count ) { if ( $lastWord -match "^(.*)([\\(,])\\w*$" ) { $_base = $matches[1] + $matches[2] } switch ( $_tokens[1].Content ) { 'Parameter' { [System.Management.Automation.ParameterAttribute].GetProperties() | % { $_base + $_.Name + "=" } } 'CmdletBinding' { [System.Management.Automation.CmdletBindingAttribute].GetProperties() | % { $_base + $_.Name + "=" } } } } break; } } $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,function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | gm -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { $_cmdlet = [regex]::Split($line, '[|;=]')[-1] if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { 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,Function,Filter,ExternalScript' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { 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; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ($_tokens) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Command') { $_cmd = $_lastToken.Content # don't look for paths... if ($_cmd.IndexOfAny('/\\') -eq -1) { # handle parsing errors - the last token string should be the last # string in the line... if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) { $_pat = $_cmd + '*' $_base = $lastword.substring(0, $lastword.length-$_cmd.length) "begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (", "end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ", "param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" ` -like $_pat | % {'{0}{1}' -f $_base,$_ } $ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) | Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ } } } } } } } } }
PowerShellCorpus/PoshCode/Set-Domain_5.ps1
Set-Domain_5.ps1
function Set-Domain { param( [switch]$help, [string]$domain=$(read-host "Please specify the domain to join"), [System.Management.Automation.PSCredential]$credential = $(Get-Credential) ) $usage = "`$cred = get-credential `n" $usage += "Set-Domain -domain MyDomain -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/Xml Module 5.0.ps1
Xml Module 5.0.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 $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } filter Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Path # The path to an xml document (on disc or any other content provider). #.Parameter Indent # The indent level (defaults to 2 spaces) #.Example # [xml]$xml = get-content Data.xml # C:\\PS>Format-Xml $xml #.Example # get-content Data.xml | Format-Xml #.Example # Format-Xml C:\\PS\\Data.xml #.Example # ls *.xml | Format-Xml # [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 ) ## Load from file, if necessary if($Path) { [xml]$xml = Get-Content $Path } $StringWriter = New-Object System.IO.StringWriter $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter $xmlWriter.Formatting = "indented" $xmlWriter.Indentation = $Indent $xml.WriteContentTo($XmlWriter) $XmlWriter.Flush() $StringWriter.Flush() Write-Output $StringWriter.ToString() } Set-Alias fxml Format-Xml -EA 0 function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( # Specifies the path and file names of the XML files to search. Wildcards are permitted. [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , # Specifies one or more XML nodes to search. [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [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. [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $nsManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace -Xml $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { [Xml]$node = Remove-XmlNamespace -Xml $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace -Xml $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml 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="Xml")] param( # 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 string that contains the XML to search. You can also pipe strings to Select-XML. [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , # The Attribute name (or "#text") for which the value is going to be replaced. Providing no value or an empty string results in replacing the InnerXml. [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [String[]]$Attribute , # The value toreplace in the specified Attribute name [Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [String]$Value , # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [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. [Switch]$RemoveNamespace ) begin { $null = $PSBoundParameters.Remove("Attribute") $null = $PSBoundParameters.Remove("Value") $command = $ExecutionContext.InvokeCommand.GetCommand( "Select-Xml", [System.Management.Automation.CommandTypes]::Function ) $steppablePipeline = {& $command @PSBoundParameters | Write-Output }.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($myInvocation.ExpectingInput) } process { Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)" try { foreach($node in $(if($_) { $steppablePipeline.Process($_) } else { $steppablePipeline.Process() })){ if($Attribute) { $node.$Attribute = $Value } else { $node.Set_InnerXml($Value) } } } catch { throw } } end { try { foreach($node in $steppablePipeline.End()) { if($Attribute) { $node.$Attribute = $Value } else { $node.Set_InnerXml($Value) } } } catch { throw } Write-Verbose "Invoke-Autoloaded End: $CommandName" } } 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 #.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 , [Alias("Parameters")] [hashtable]$Arguments ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { $OFS = "`n" Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader "$Xslt" )) )) } [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 $Arguments } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Node $Xml $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="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content #, # [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] # [ValidateNotNullOrEmpty()] # [Alias("StyleSheet")] # [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Node $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Node $Xml $StyleSheet } } } Set-Alias rmns 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 = [type]::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 $string: $_" } } $xr.Close() $sr.Dispose() } } function ConvertTo-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [PSObject[]]$InputObject ) begin { $type = [type]::gettype("System.Management.Automation.Serializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null) $sw = new-object System.IO.StringWriter $xw = new-object System.Xml.XmlTextWriter $sw $serializer = $ctor.invoke($xw) $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null) $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") } process { try { [void]$method.invoke($serializer, $InputObject) } catch { write-warning "Could not serialize $($InputObject.gettype()): $_" } } end { [void]$done.invoke($serializer, @()) $sw.ToString() $xw.Close() $sw.Dispose() } } ######## 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 ) # BEGIN { # if([string]::IsNullOrEmpty( $tag.NamespaceName )) { # $tag = $($script:NameSpaceStack.Peek()) + $tag # if( $script:NameSpaceStack.Count -gt 0 ) { # $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() ) # } else { # $script:NameSpaceStack.Push( $null ) # } # } else { # $script:NameSpaceStack.Push( $tag.Namespace ) # } # } PROCESS { New-Object XElement $( $tag while($args) { $attrib, $value, $args = $args if($attrib -is [ScriptBlock]) { # then it's content &$attrib } elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value $script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value) } elseif($value -match "-(?!\\d)\\w") { $args = @($value)+@($args) } elseif($value -ne $null) { New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value } } ) } # END { # $null = $script:NameSpaceStack.Pop() # } } Set-Alias xe New-XElement Set-Alias New-XmlElement New-XElement function ConvertFrom-XmlDsl { Param([ScriptBlock]$script) $parserrors = $null $global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) } [Array]::Reverse( $duds ) [string[]]$ScriptText = "$script" -split "`n" ForEach($token in $duds ) { # replace : notation with namespace notation if( $token.Content.Contains(":") ) { $key, $localname = $token.Content -split ":" $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" ) } else { $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" ) } # insert 'xe' before everything (unless it's a valid command) $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " ) } Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") )) } ######## 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, Convert-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU+W/LVKaLu6n+Wgl15WXeZ6ul # qS2ggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp # Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy # dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw # MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp # BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV # BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 # IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J # 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj # Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR # ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU # TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC # pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV # uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD # VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk # QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0 # YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl # IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y # aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo # dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg # KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG # IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3 # BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv # bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj # b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG # SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl # IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA # UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF # pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q # qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h # fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B # UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5 # 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1 # pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4 # npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV # 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki # 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp # 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR # MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD # b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln # bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk # aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB # qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0 # IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh # dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW # GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP # ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC # rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD # dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0 # U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2 # R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU # Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC # MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE # AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ # yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq # t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw # KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD # VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud # IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC # AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg # c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g # Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG # JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0 # dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB # BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j # bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j # b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A # 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb # E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27 # zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n # FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j # RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D # dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT # DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj # YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ # bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3 # AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBSg2DWYYgWq # 6pyxukc314L3m5t3ITANBgkqhkiG9w0BAQEFAASCAQCpGT09SsMDF6YhBqX8bBah # Y16E/29IvPFYmtpmrvvj4PkMS6rBO8vYWAhOwzUZntv56y2e0r9f6WwRHRvL20ya # Do6I2Rtv+wCJBjE3Mzjhb5WPO54a463ZaSHoE2KAPxlVHq1IN91OA1YMSbb3zy4p # xQGrNFHUe4Y4r3Buy8utnKkrJ9NR7deYXY30aowIYbRqaPlKKpiNkdqHvlNZjgVV # O0r8FEgk85KIhSNlwtMyiDffWi2OoQ9jADSSOQyvayqhGNpeg5GcDyWUC3DFqJgt # SzZ3wtECmjSUNABUornTKCHwNGOs67b3kkIz49sP273xQDaydYghe24JcDpmets7 # SIG # End signature block
PowerShellCorpus/PoshCode/Get-Arguments.ps1
Get-Arguments.ps1
##############################################################################\n##\n## Get-Arguments\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\nUses command-line arguments\n\n#>\n\nparam(\n ## The first named argument\n $FirstNamedArgument,\n\n ## The second named argument\n [int] $SecondNamedArgument = 0\n)\n\nSet-StrictMode -Version Latest\n\n## Display the arguments by name\n"First named argument is: $firstNamedArgument"\n"Second named argument is: $secondNamedArgument"\n\nfunction GetArgumentsFunction\n{\n ## We could use a param statement here, as well\n ## param($firstNamedArgument, [int] $secondNamedArgument = 0)\n\n ## Display the arguments by position\n "First positional function argument is: " + $args[0]\n "Second positional function argument is: " + $args[1]\n}\n\nGetArgumentsFunction One Two\n\n$scriptBlock =\n{\n param($firstNamedArgument, [int] $secondNamedArgument = 0)\n\n ## We could use $args here, as well\n "First named scriptblock argument is: $firstNamedArgument"\n "Second named scriptblock argument is: $secondNamedArgument"\n}\n\n& $scriptBlock -First One -Second 4.5
PowerShellCorpus/PoshCode/20498039475807687.ps1
20498039475807687.ps1
# Requires a connection to Exchange Server, or Exchange Management Shell $s = New-PSSession -ConfigurationName Microsoft.Exchange -Name ExchMgmt -ConnectionUri http://ex14.domain.local/PowerShell/ -Authentication Kerberos Import-PSSession $s # Get all Client Access Server properties for all mailboxes with an ActiveSync Device Partnership $Mailboxes = Get-CASMailbox -Filter {HasActivesyncDevicePartnership -eq $true} -ResultSize Unlimited # Get DeviceID for all mailboxes $EASMailboxes = $Mailboxes | Select-Object PrimarySmtpAddress,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}} # Set the ActiveSyncAllowedDeviceIDs attribute of all Mailboxes $EASMailboxes | foreach {Set-CASMailbox $_.PrimarySmtpAddress -ActiveSyncAllowedDeviceIDs $_.DeviceID}
PowerShellCorpus/PoshCode/Sort-ISE.ps1
Sort-ISE.ps1
function Sort-ISE () { <# .SYNOPSIS ISE Extension sort text starting at column $start comparing the next $length characters .DESCRIPTION ISE Extension sort text starting at column $start comparing the next $length characters Leftmost column is column 1 .NOTES File Name : Sort_ISE.ps1 Author : Bernd Kriszio - http://pauerschell.blogspot.com/ Requires : PowerShell V2 CTP3 .LINK Script posted to: .EXAMPLE Sort-ISE 1 10 #> #requires -version 2.0 param ( [Parameter(Position = 0, Mandatory=$false)] [int]$start = 1, [Parameter(Position = 1, Mandatory=$false)] [int]$length = -1 ) $newlines = @{} $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") foreach ($line in $text){ $key = [string]::join("", $line[($start - 1)..($start - 1 + $length)]) if ( $newlines[$key] -ne $null) { $newlines[$key] = $newlines[$key] + $line } else { $newlines[$key] = $line } } $Sortedkeys = $newlines.keys | sort $newtext = '' foreach ($key in $Sortedkeys){ $newtext += $newlines[$key] } $editor.Text = $newtext }
PowerShellCorpus/PoshCode/Import-CSV.ps1
Import-CSV.ps1
Param($file,$headers) # Check for Input and fill $data if($input){$data = @();$input | foreach-Object{$data += $_}} # Check for File and Test the Path if($file) { if(Test-Path $file) { # Check for Headers... if none use import-csv if(!$headers) { import-Csv $data return } else { $data = Get-Content $file } } else{Write-Host "Invalid File Passed";return $false} } # Creating Object foreach($entry in $data) { $values = $entry.Split(",") if($values.Count -gt $headers.Count) { Write-Host "Value Count [$($values.Count)] and Headers [$($Headers.Count)] do not match" return $false } $myobj = "" | Select-Object -prop $headers $i = 0 foreach($value in $values) { $header = $headers[$i] $myobj.$header = $value $i++ } $myobj }
PowerShellCorpus/PoshCode/Test-SqlConnection_1.ps1
Test-SqlConnection_1.ps1
####################### <# Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed issues, added colorized HTML output #> Add-Type -AssemblyName System.Xml.Linq $Script:CMServer = 'MyServer' ####################### function Test-Ping { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { $ComputerName | foreach {$result=Test-Connection -ComputerName $_ -Count 1 -Quiet; new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args=$_;Result=$result;Message=$null}} } } #Test-Ping ####################### function Test-Wmi { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach {$name=$_; Get-WmiObject -ComputerName $name -Class Win32_ComputerSystem -ErrorAction 'Stop' | out-null; new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null}} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-Wmi ####################### function Test-Port { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName ,[Parameter(Mandatory=$true)] [int32]$Port) Process { try { $Computername | foreach { $sock = new-object System.Net.Sockets.Socket -ArgumentList $([System.Net.Sockets.AddressFamily]::InterNetwork),$([System.Net.Sockets.SocketType]::Stream),$([System.Net.Sockets.ProtocolType]::Tcp); $name=$_; ` $sock.Connect($name,$Port) new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} $sock.Close()} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-Port ####################### function Test-SMB { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { Test-Port $ComputerName 445 } } #Test-SMB ####################### function Test-SSIS { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName ,[Parameter(Mandatory=$true)] [ValidateSet("2005", "2008")] [string]$Version ) #Note: Unlike the database engine and replication SSIS is not backwards compatible # Once an assembly is loaded, you can unload it. This means you need to fire up a powershell.exe process # and mixing between 2005 and 2008 SSIS connections are not permitted in same powershell process. # You'll need to test 2005 and 2008 SSIS in separate powershell.exe processes Begin { $ErrorAction = 'Stop' if ($Version -eq 2008) { add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" } else { add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" } } process { $ComputerName | foreach { $name=$_; ` if ((test-SSISService -ComputerName $name).Result) { try { $app = new-object ("Microsoft.SqlServer.Dts.Runtime.Application") $out = $null $app.GetServerInfo($name,[ref]$out) | out-null new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"}} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message='SSIS Not Running'} } } } } #Test-SSIS ####################### function Test-SQL { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ServerInstance) process { $ServerInstance | foreach { $name = $_; ` if ((test-Ping $(ConvertTo-ComputerName $name)).Result) { $connectionString = "Data Source={0};Integrated Security=true;Initial Catalog=master;Connect Timeout=3;" -f $name $sqlConn = new-object ("Data.SqlClient.SqlConnection") $connectionString try { $sqlConn.Open() new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } finally { $sqlConn.Dispose() } } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message='Host Unreachable'} } } } } #Test-SQL ####################### function Test-AgentService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -Class Win32_Service -ComputerName $name -Filter {Name Like 'SQLAgent%' and State='Stopped'} -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-AgentService ####################### function Test-SqlService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -ComputerName $name ` -query "select Name,State from Win32_Service where (NOT Name Like 'MSSQLServerADHelper%') AND (Name Like 'MSSQL%' OR Name Like 'SQLServer%') And State='Stopped'" ` -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-SqlService ####################### function Test-SSISService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -Class Win32_Service -ComputerName $ComputerName -Filter {Name Like 'MsDtsServer%' And State='Stopped'} -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-SSISService ####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile, [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() switch ($As) { 'DataSet' { Write-Output ($ds) } 'DataTable' { Write-Output ($ds.Tables) } 'DataRow' { Write-Output ($ds.Tables[0]) } } } #Invoke-Sqlcmd2 ####################### function Test-DatabaseOnline { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ServerInstance) begin { $query = @" SELECT name FROM sysdatabases WHERE DATABASEPROPERTYEX(name,'Status') <> 'ONLINE' "@ } process { try { $ServerInstance | foreach { $name=$_; ` $out = Invoke-Sqlcmd2 -ServerInstance $name -Database master -Query $query -ConnectionTimeout 5 | foreach {$_.name} if ($out) {$out = $out -join ","; new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$out} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-DatabaseOnline ####################### filter ConvertTo-ComputerName { param ($ServerInstance) if ($_) { $ServerInstance = $_ } $ServerInstance -replace "\\\\.*|,.*" } #ConvertTo-ComputerName ####################### filter ConvertTo-NamePortNumber { param ($ServerInstance) if ($_) { $ServerInstance = $_ } $work = $ServerInstance -split "," if ($work[1]) { new-object psobject -Property @{ComputerName=$work[0];PortNumber=$work[1]} } } #ConvertTo-NamePortNumber ####################### function Get-CMServer { param($ServerInstance,$GroupName,[switch]$UsePort) $query = @" FROM msdb.dbo.sysmanagement_shared_registered_servers s JOIN msdb.dbo.sysmanagement_shared_server_groups g ON s.server_group_id = g.server_group_id WHERE 1 = 1 "@ if ($UsePort) { $query = "SELECT DISTINCT s.server_name AS 'name'`n" + $query + "`nAND PATINDEX('%,%', s.server_name) <> 0" } else { $query = "SELECT DISTINCT s.name`n" + $query } if ($GroupName) { $query = $query + "`nAND g.name = '$GroupName'" } #Write-Host $query Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database msdb -Query $query | foreach {$_.name} } #Get-CMServer ####################### filter Get-SqlVersion2 { param($ServerInstance) $query = @" select CAST(SERVERPROPERTY('ServerName') AS varchar(128)) AS 'server_name', CASE CONVERT(int, LEFT(CONVERT(varchar(10),SERVERPROPERTY('ProductVersion')),1)) WHEN 1 THEN '2008' WHEN 9 THEN '2005' WHEN 8 THEN '2000' END AS 'version' "@ if ($_) { $ServerInstance = $_ } Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database master -Query $query -ConnectionTimeout 5 } #Get-SqlVersion2 ####################### function Test-Main { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [ValidateSet("Ping","WMI","SMB","Port","SQL","Database","SSIS","Agent")] [string]$Test, [Parameter(Position=1, Mandatory=$false)] [string]$GroupName, [Parameter(Position=2, Mandatory=$false)] [string]$SqlVersion='2008' ) #HTML colorize code adapted from post by Joel Bennet #http://stackoverflow.com/questions/4559233/technique-for-selectively-formatting-data-in-a-powershell-pipeline-and-output-as switch ($test) { 'Ping' { $html = Get-CMServer $Script:CMServer $GroupName | ConvertTo-ComputerName | Test-Ping | ConvertTo-Html } 'WMI' { $html = Get-CMServer $Script:CMServer $GroupName | ConvertTo-ComputerName | Test-WMI | ConvertTo-Html } 'SMB' { $html = Get-CMServer $Script:CMServer $GroupName | ConvertTo-ComputerName | Test-SMB | ConvertTo-Html } 'Port' { $html = Get-CMServer $Script:CMServer $GroupName -UsePort | ConvertTo-NamePortNumber | foreach {Test-Port $_.ComputerName $_.PortNumber} | ConvertTo-Html } 'SQL' { $html = Get-CMServer $Script:CMServer $GroupName | Test-SQL | ConvertTo-Html } 'Database' { $html = Get-CMServer $Script:CMServer $GroupName | Test-DatabaseOnline | ConvertTo-Html } 'SSIS' { $html = Get-CMServer $Script:CMServer $GroupName | Get-SqlVersion2 | where {$_.version -eq $SqlVersion } | foreach {$_.server_name} | ConvertTo-ComputerName | Test-SSIS -Version $SqlVersion | ConvertTo-Html } 'Agent' { $html = Get-CMServer $Script:CMServer $GroupName | ConvertTo-ComputerName | Test-AgentService | ConvertTo-Html } } $xml = [System.Xml.Linq.XDocument]::Parse("$html") # Find the index of the column you want to format: $index = (($xml.Descendants("{http://www.w3.org/1999/xhtml}th") | Where-Object { $_.Value -eq "Result" }).NodesBeforeSelf() | Measure-Object).Count # Format the column based on whatever rules you have: switch($xml.Descendants("{http://www.w3.org/1999/xhtml}td") | Where { ($_.NodesBeforeSelf() | Measure).Count -eq $index } ) { {'True' -eq $_.Value } { $_.SetAttributeValue( "style", "background: green;"); continue } {'False' -eq $_.Value } { $_.SetAttributeValue( "style", "background: red;"); continue } } # Save the html out to a file $xml.Save("$pwd/$test.html") # Open the thing in your browser to see what we've wrought ii .\\$test.html } #Test-Main
PowerShellCorpus/PoshCode/Get-WindowsExperience_1.ps1
Get-WindowsExperience_1.ps1
function Get-WindowsExperienceRating { #.Synopsis # Gets the Windows Experience Ratings #.Parameter ComputerName # The name(s) of the computer(s) to get the Windows Experience (WinSat) numbers for. [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName='localhost' ) process { Get-WmiObject -ComputerName $ComputerName Win32_WinSAT | ForEach-Object { if($_.WinSatAssessmentState -ne 1) { Write-Warning "WinSAT data for '$($_.__SERVER)' is out of date ($($_.WinSatAssessmentState))" } $_ } | Select-Object -Property @{name="Computer";expression={$_.__SERVER}}, *Score #, WinSPRLevel } }
PowerShellCorpus/PoshCode/Get-MWSOrder_2.ps1
Get-MWSOrder_2.ps1
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GetOrderCmdlet.cs" company="Huddled Masses"> // Copyright (c) 2011 Joel Bennett // </copyright> // <summary> // Defines the Get-Order Cmdlet for Amazon Marketplace Orders WebService. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace PoshOrders { using System; using System.Management.Automation; // I'm using Amazon's MarketplaceWebServiceOrders Apache-licensed web-service access code. using MarketplaceWebServiceOrders; using MarketplaceWebServiceOrders.Model; /// <summary> /// Get Amazon Marketplace Orders from the WebService /// </summary> [Cmdlet(VerbsCommon.Get, "Order")] public class GetOrderCmdlet : Cmdlet { // Access Key ID and Secret Access Key ID for the Amazon MWS /// <summary>The Amazon Access Key ID</summary> private const string AccessKeyId = "INSERT YOUR MWS ACCESS KEY HERE"; /// <summary>The Amazon Secret Key</summary> private const string SecretAccessKey = "INSERT YOUR MWS SECRET ACCESS KEY HERE"; /// <summary>The Application Name is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationName = "INSERT YOUR APPLICATION NAME HERE"; /// <summary>The Application Version is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationVersion = "1.0"; /// <summary>Default value for the service URL is for the USA</summary> private string serviceUrl = "https://mws.amazonservices.com/Orders/2011-01-01"; /// <summary>The web service client</summary> private MarketplaceWebServiceOrdersClient marketplaceWebServiceOrdersClient; /// <summary>Default value for "Created After" is 1 day ago.</summary> private DateTime createdAfter = DateTime.MinValue; /// <summary>Default value for "Created Before" is infinitely in the future</summary> private DateTime createdBefore = DateTime.MaxValue; /// <summary>The Default order status is Unshipped or PartiallyShipped</summary> private OrderStatusEnum[] orderStatus = new[] { OrderStatusEnum.Unshipped, OrderStatusEnum.PartiallyShipped }; /// <summary> /// Gets or sets the merchant id. /// </summary> /// <value> /// The merchant id. /// </value> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] public string MerchantId { get; set; } /// <summary> /// Gets or sets the marketplace id. /// </summary> /// <value> /// The marketplace id. /// </value> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Marketplace { get; set; } /// <summary> /// Gets or sets the service URL. /// Defaults to the USA service URL. /// </summary> /// <value> /// The service URL. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string ServiceUrl { get { return this.serviceUrl; } set { this.serviceUrl = value; } } /// <summary> /// Gets or sets a date orders must prescede. /// </summary> /// <value> /// The date. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedBefore { get { return this.createdBefore; } set { this.createdBefore = value; } } /// <summary> /// Gets or sets a date the orders must come aftercreated after. /// </summary> /// <value> /// The created after. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedAfter { get { return this.createdAfter; } set { this.createdAfter = value; } } /// <summary> /// Gets or sets the order status. /// </summary> /// <value> /// The order status. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public OrderStatusEnum[] OrderStatus { get { return orderStatus; } set { orderStatus = value; } } /// <summary> /// Gets or sets the buyer email. /// </summary> /// <value> /// The buyer email. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string BuyerEmail { get; set; } /// <summary> /// Gets or sets the seller order id. /// </summary> /// <value> /// The seller order id. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SellerOrderId { get; set; } /// <summary> /// Gets or sets whether to include the Order Items /// </summary> /// <value> /// True to included the Order Items /// </value> [Parameter(Mandatory = false)] public SwitchParameter IncludeItems { get; set; } /// <summary> /// Implement the Begin step for PowerShell Cmdlets /// </summary> protected override void BeginProcessing() { base.BeginProcessing(); var config = new MarketplaceWebServiceOrdersConfig { ServiceURL = "https://mws.amazonservices.com/Orders/2011-01-01" }; this.marketplaceWebServiceOrdersClient = new MarketplaceWebServiceOrdersClient( ApplicationName, ApplicationVersion, AccessKeyId, SecretAccessKey, config); } /// <summary> /// Implement the Process step for PowerShell Cmdlets /// </summary> protected override void ProcessRecord() { base.ProcessRecord(); /* // If no dates are specificied, start a day ago ... if (CreatedBefore == DateTime.MaxValue && CreatedAfter == DateTime.MinValue) { CreatedAfter = DateTime.UtcNow.AddDays(-1); } */ // Amazon's policy doesn't allow calling with a CreatedBefore after two minutes before the request time if (CreatedBefore == DateTime.MaxValue) { CreatedBefore = DateTime.Now.AddMinutes(-2); } var orderRequest = new ListOrdersRequest { MarketplaceId = new MarketplaceIdList(), OrderStatus = new OrderStatusList(), BuyerEmail = this.BuyerEmail, SellerId = this.MerchantId, SellerOrderId = this.SellerOrderId, CreatedAfter = this.CreatedAfter, CreatedBefore = this.CreatedBefore }; orderRequest.OrderStatus.Status.AddRange(OrderStatus); orderRequest.MarketplaceId.Id.AddRange(Marketplace); var response = marketplaceWebServiceOrdersClient.ListOrders(orderRequest); foreach (var order in response.ListOrdersResult.Orders.Order) { var output = new PSObject(order); if (IncludeItems.ToBool()) { var itemRequest = new ListOrderItemsRequest { AmazonOrderId = order.AmazonOrderId, SellerId = this.MerchantId, }; var items = marketplaceWebServiceOrdersClient.ListOrderItems(itemRequest); output.Properties.Add(new PSNoteProperty("Items", items.ListOrderItemsResult.OrderItems.OrderItem)); } WriteObject(output); } } } }
PowerShellCorpus/PoshCode/Move-LockedFile.ps1
Move-LockedFile.ps1
##############################################################################\n##\n## Move-LockedFile\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\nRegisters a locked file to be moved at the next system restart.\n\n.EXAMPLE\n\nMove-LockedFile c:\\temp\\locked.txt c:\\temp\\locked.txt.bak\n\n#>\n\nparam(\n ## The current location of the file to move\n $Path,\n\n ## The target location of the file\n $Destination\n)\n\nSet-StrictMode -Version Latest\n\n## Convert the the path and destination to fully qualified paths\n$path = (Resolve-Path $path).Path\n$destination = $executionContext.SessionState.`\n Path.GetUnresolvedProviderPathFromPSPath($destination)\n\n## Define a new .NET type that calls into the Windows API to\n## move a locked file.\n$MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004\n$memberDefinition = @'\n[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]\npublic static extern bool MoveFileEx(\n string lpExistingFileName, string lpNewFileName, int dwFlags);\n'@\n$type = Add-Type -Name MoveFileUtils `\n -MemberDefinition $memberDefinition -PassThru\n\n## Move the file\n$type::MoveFileEx($path, $destination, $MOVEFILE_DELAY_UNTIL_REBOOT)
PowerShellCorpus/PoshCode/PurgeFile script..ps1
PurgeFile script..ps1
<# .SYNOPSIS Purgefiles - recursively remove files with given extension and maximum age from a given path. .DESCRIPTION Read the synopsis Example PurgeFiles.psq -path C:\\temp -ext .tmp -max 24 .EXAMPLE PurgeFiles.psq -path C:\\temp -ext .tmp -max 24 #> # HISTORY # 2010/01/29 # rluiten Created param( [Parameter(Mandatory=$true)][string] $path ,[Parameter(Mandatory=$true)][string] $extension ,[Parameter(Mandatory=$true)][int] $maxHours ,[switch] $deleteMode = $false ,[switch] $listMode = $false ) function delete-file([string]$path, [string]$extension, [datetime]$oldestAllowed, [bool] $deleteMode, [bool] $listMode) { $filesToRemove = Get-Childitem $path -recurse | ?{ !$_.PSIsContainer -and $($_.LastWriteTime -lt $oldestAllowed) -and ($_.Extension -eq $extension) } if ($listMode -and $filesToRemove) { $filesToRemove | %{write-host "FILE: $($_.LastWriteTime) ""$($_.FullName)""`r`n"} } if ($deleteMode -and $filesToRemove) { write-host "Removing Files...`r`n" $filesToRemove | remove-item -force } } $oldestAllowed = (get-date).AddHours(-$maxHours) if (-not $deleteMode) { write-host "Running in trial mode, no files will be deleted.`r`n" } delete-file $path $extension $oldestAllowed $deleteMode $listMode
PowerShellCorpus/PoshCode/5e6d3b3f-4cf8-4c50-95a0-a300d6f0b630.ps1
5e6d3b3f-4cf8-4c50-95a0-a300d6f0b630.ps1
# to load c:\\powershellscripts\\cluster_utils.ps1 if it isn't already loaded @@. require cluster_utils Here are the functions: $global:loaded_scripts=@{} function require([string]$filename){ if (!$loaded_scripts[$filename]){ . c:\\powershellscripts\\$filename $loaded_scripts[$filename]=get-date } } function reload($filename){ . c:\\powershellscripts\\$filename.ps1 $loaded_scripts[$filename]=get-date }
PowerShellCorpus/PoshCode/Paraimpu.ps1
Paraimpu.ps1
# This requires JSON 1.7 ( http://poshcode.org/2930 ) and the HttpRest ( http://poshcode.org/2097 ) modules # It's a first draft at Paraimpu cmdlets # I'm not sure yet that using Paraimpu with my Chumby gets me what I want, since it only shows one item and can't go back to old ones. # # YOU SHOULD SET THE $Token DEFAULT VALUES TO YOUR "Thing"'s Token! ipmo json, httprest function Send-Paraimpu { #.Synopsis # Send data to paraimpu! #.Description # Send JSON data to Paraimpu (don't forget JSON is case sensitive) #.Example # Send-Paraimpu @{ # text = "This is a test message for my chumby, so I'm sending an image and sound too!" # image = "http://www.blogsdna.com/wp-content/uploads/2009/12/PowerShell-Logo.png" # sound = "http://www.frogstar.com/audio/download/14250/gong.mp3" # } #.Notes # Remember javascript is case sensitive! param( # The data you want to send to Paraimpu [Hashtable]$Data, # The token of the paraimpu "Generic Sensor" to send the data to [Guid]$Token = "a9988bbd-cb35-4b2d-ba23-69198d36977b" ) $json = New-JSON @{ token = $Token 'content-type' = "application/json" data = $Data } http post http://paraimpu.crs4.it/data/new -content $json } function Send-ParaChumby { #.Synopsis # Send data to paraimpu with an image and sound for Chumby #.Description # Send JSON data to Paraimpu ... #.Example # Send-Paraimpu "This is a test message for my chumby, and has default image and sound." param( [Parameter(Position=0,ValueFromPipeline=$true,Mandatory=$true)] $InputObject, [Parameter(Position=1)] $Image, [Parameter(Position=2)] $Sound = "http://www.frogstar.com/audio/download/14250/gong.mp3", [Switch]$Collect, [Int]$Width = 30, [Guid]$Token = "a9988bbd-cb35-4b2d-ba23-69198d36977b" ) begin { if($Collect) { $output = New-Object System.Collections.ArrayList } } process { if(!$Collect) { Send-Paraimpu @{ text = ($InputObject | Out-String -Width $Width | Tee -var dbug) -replace "`r`n","`n"; image = $Image; sound = $Sound } -Token:$Token Write-Verbose $dbug } else { $null = $Output.Add($InputObject) } } end { if($Collect) { Send-Paraimpu @{ text = ($Output | Out-String -Width $Width | Tee -var dbug) -replace "`r`n","`n"; image = $Image; sound = $Sound } -Token:$Token Write-Verbose $dbug } }}
PowerShellCorpus/PoshCode/Manage ASP_5.NET Providers.ps1
Manage ASP_5.NET Providers.ps1
# Manage_ASP_NET_Providers.ps1 # by Chistian Glessner # http://iLoveSharePoint.com # If you want to change the app config you have to restart PowerShell param($appConfigPath=$null) # App config path have to be set before loading System.Web.dll [System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $appConfigPath ) [void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") function global:Get-MembershipProvider($providerName=$null, [switch]$all) { if($all) { return [System.Web.Security.Membership]::Providers } if($providerName -eq $null) { return [System.Web.Security.Membership]::Provider } else { return [System.Web.Security.Membership]::Providers[$providerName] } } function global:Add-MembershipUser($login=$(throw "-login is required"), $password=$(throw "$password is required"), $mail=$(throw "-mail is required"),$question, $answer, $approved=$true) { $provider = $input | select -First 1 if($provider -isnot [System.Web.Security.MembershipProvider]) { $provider = Get-MembershipProvider } $status = 0 $provider.CreateUser($login, $password, $mail, $question, $answer, $approved, $null, [ref]$status) return [System.Web.Security.MembershipCreateStatus]$status } function global:Get-MembershipUser($identifier, $maxResult=100) { $provider = $input | select -First 1 if($provider -isnot [System.Web.Security.MembershipProvider]) { $provider = Get-MembershipProvider } if($identifier -ne $null) { $name = $provider.GetUserNameByEmail($identifier) if($name -ne $null){$identifier = $name} return $provider.GetUser($identifier,$false) } $totalUsers = 0 $users = $provider.GetAllUsers(0,$maxResult,[ref]$totalUsers) $users if($totalUsers -gt $maxResult) { throw "-maxResult limit exceeded" } } function global:Reset-MembershipUserPassword($identifier=$(throw "-identifier is required"), $questionAnswer) { $provider = $input | select -First 1 if($provider -isnot [System.Web.Security.MembershipProvider]) { $provider = Get-MembershipProvider } $name = $provider.GetUserNameByEmail($identifier) if($name -ne $null){$identifier = $name} return $provider.ResetPassword($identifier, $questionAnswer) } function global:Get-RoleProvider($providerName=$null, [switch]$all) { if($all) { return [System.Web.Security.Roles]::Providers } if($providerName -eq $null) { return [System.Web.Security.Roles]::Provider } else { return [System.Web.Security.Roles]::Providers[$providerName] } } function global:Get-ProfileProvider($providerName=$null) { if($all) { return [System.Web.Security.ProfileManager]::Providers } if($providerName -eq $null) { return [System.Web.Profile.ProfileManager]::Provider } else { return [System.Web.Profile.ProfileManager]::Providers[$providerName] } }
PowerShellCorpus/PoshCode/New-ISEMenu_5.ps1
New-ISEMenu_5.ps1
Import-Module ShowUI Function New-ISEMenu { New-Grid -AllowDrop:$true -Name "ISEAddonCreator" -columns Auto, * -rows Auto,Auto,Auto,*,Auto,Auto -Margin 5 { New-Label -Name Warning -Foreground Red -FontWeight Bold -Column 1 ($target = New-TextBox -Name txtName -Column 1 -Row ($Row=1)) New-Label "Addon Menu _Name" -Target $target -Row $Row ($target = New-TextBox -Name txtShortcut -Column 1 -Row ($Row+=1)) New-Label "Shortcut _Key" -Row $Row -Target $target ($target = New-TextBox -Name txtScriptBlock -Column 1 -Row ($Row+=1) -MinHeight 141 -MinWidth 336 -AcceptsReturn:$true -HorizontalScrollBarVisibility Auto -VerticalScrollBarVisibility Auto) New-Label "Script _Block" -Row $Row -Target $target New-CheckBox "_Add to ISE Profile" -Name chkProfile -Row ($Row+=1) New-StackPanel -Orientation Horizontal -Column 1 -Row ($Row+=1) -HorizontalAlignment Right { New-Button "_Save" -Name btnSave -Width 75 -Margin "0,0,5,0" -IsDefault -On_Click { if ($txtName.Text.Trim() -eq "" -or $txtShortcut.text.Trim() -eq "" -or $txtScriptBlock.text.Trim() -eq "") { $Warning.Content = "You must supply all parameters" } else { $menuItems = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | Select -ExpandProperty DisplayName if ($menuItems -Contains $txtName.Text) { $Warning.Content = "Select another Name for the menu" return } try { $ScriptBlock = [ScriptBlock]::Create($txtScriptBlock.Text) $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add($txtName.Text,$ScriptBlock,$txtShortcut.Text) | Out-Null } catch { $Warning.Content = "Fatal Error Creating MenuItem:`n$_" return } if ($chkProfile.IsChecked) { $profileText = "`n`#Added by ISE Menu Creator Addon if (`$psISE) { `$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(`"$($txtName.Text)`",`{$ScriptBlock`},`"$($txtShortcut.Text)`") | Out-Null } " Add-Content -Path $profile -Value $profileText } $window.Close() } } New-Button "Cancel" -Name btnCancel -Width 75 -IsCancel } } -show -On_Load { $txtName.Focus() } } # this will add a the "New ISE menu" menu item and load it every time you run this script! $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New ISE menu",{New-ISEMenu},"ALT+M") | Out-Null
PowerShellCorpus/PoshCode/0dbcab33-47ec-4c68-98cd-b9e906786e5a.ps1
0dbcab33-47ec-4c68-98cd-b9e906786e5a.ps1
$WarningPreference = "SilentlyContinue" $password = Get-Content C:\\securestring.txt | convertto-securestring $username = "PROD\\administrator" $credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password $uucenter = "uuoresund.dk" $totalSize = 0 $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://prod-exch1.prod.local/PowerShell/ -Credential $credentials Import-PSSession $session -DisableNameChecking | out-null foreach ($mbx in Get-Mailbox) { if($mbx.PrimarySMTPAddress -like '*uuoresund.dk*') { $size = (Get-MailboxStatistics $mbx.Identity).TotalItemSize $position = $size.IndexOf("(") $size = $size.Substring($position+1) $position = $size.IndexOf(" ") $size = $size.Substring(0, $position) $totalSize = [long]$totalSize + [long]$size } } $totalSize = $totalSize/1000000 Write-Host "<prtg>" Write-Host " <result>" Write-Host " <channel>$uucenter</channel>" Write-Host " <value>$totalSize</value>" Write-Host " <float>1</float>" Write-Host " </result>" Write-Host "</prtg>" Remove-PSSession $session Exit 0
PowerShellCorpus/PoshCode/WpfBindingHelper.ps1
WpfBindingHelper.ps1
using System; using System.Windows; using System.ComponentModel; using System.Windows.Markup; using System.Windows.Data; using System.Globalization; namespace PoshWpf { public class BindingConverter : ExpressionConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(MarkupExtension)) ? true : false; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(MarkupExtension)) { var bindingExpression = value as BindingExpression; if (bindingExpression == null) throw new Exception(); return bindingExpression.ParentBinding; } return base.ConvertTo(context, culture, value, destinationType); } } public static class XamlHelper { static XamlHelper() { Register(typeof(System.Windows.Data.BindingExpression), typeof(PoshWpf.BindingConverter)); } internal static void Register(Type T, Type TC) { var attr = new Attribute[] { new TypeConverterAttribute(TC) }; TypeDescriptor.AddAttributes(T, attr); } public static string ConvertToXaml(object ui) { var outstr = new System.Text.StringBuilder(); //this code need for right XML fomating var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var writer = System.Xml.XmlWriter.Create(outstr, settings); var dsm = new System.Windows.Markup.XamlDesignerSerializationManager(writer); //this string need for turning on expression saving mode dsm.XamlWriterMode = System.Windows.Markup.XamlWriterMode.Expression; System.Windows.Markup.XamlWriter.Save(ui, dsm); return outstr.ToString(); } } }
PowerShellCorpus/PoshCode/825cfd12-39f8-4fa2-9843-880b0ab0e880.ps1
825cfd12-39f8-4fa2-9843-880b0ab0e880.ps1
$Raw = Whoami /groups $Groups = $Raw | ?{ $_ -match "Enabled Group" } | %{$_.Split(" ,")[0] } | ?{ $_ -like "*\\*" }| Sort $Groups
PowerShellCorpus/PoshCode/Connect-AccessDB_3.ps1
Connect-AccessDB_3.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 Write-Output $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/Get-Answer.ps1
Get-Answer.ps1
##############################################################################\n##\n## Get-Answer\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\nUses Bing Answers to answer your question\n\n.EXAMPLE\n\nGet-Answer "(5 + e) * sqrt(x) = Pi"\nCalculation\n(5+e )*sqrt ( x)=pi : x=0.165676\n\n.EXAMPLE\n\nGet-Answer msft stock\nMicrosoft Corp (US:MSFT) NASDAQ\n29.66 -0.35 (-1.17%)\nAfter Hours: 30.02 +0.36 (1.21%)\nOpen: 30.09 Day's Range: 29.59 - 30.20\nVolume: 55.60 M 52 Week Range: 17.27 - 31.50\nP/E Ratio: 16.30 Market Cap: 260.13 B\n\n#>\n\nSet-StrictMode -Version Latest\n\n$question = $args -join " "\n\nfunction Main\n{\n ## Load the System.Web.HttpUtility DLL, to let us URLEncode\n Add-Type -Assembly System.Web\n\n ## Get the web page into a single string with newlines between\n ## the lines.\n $encoded = [System.Web.HttpUtility]::UrlEncode($question)\n $url = "http://www.bing.com/search?q=$encoded"\n $text = (new-object System.Net.WebClient).DownloadString($url)\n\n ## Find the start of the answers section\n $startIndex = $text.IndexOf('<div class="ans">')\n\n ## The end is either defined by an "attribution" div\n ## or the start of a "results" div\n $endIndex = $text.IndexOf('<div class="sn_att2">')\n if($endIndex -lt 0) { $endIndex = $text.IndexOf('<div id="results">') }\n\n ## If we found a result, then filter the result\n if(($startIndex -ge 0) -and ($endIndex -ge 0))\n {\n ## Pull out the text between the start and end portions\n $partialText = $text.Substring($startIndex, $endIndex - $startIndex)\n\n ## Very fragile screen scraping here. Replace a bunch of\n ## tags that get placed on new lines with the newline\n ## character, and a few others with spaces.\n $partialText = $partialText -replace '<div[^>]*>',"`n"\n $partialText = $partialText -replace '<tr[^>]*>',"`n"\n $partialText = $partialText -replace '<li[^>]*>',"`n"\n $partialText = $partialText -replace '<br[^>]*>',"`n"\n $partialText = $partialText -replace '<span[^>]*>'," "\n $partialText = $partialText -replace '<td[^>]*>'," "\n\n $partialText = CleanHtml $partialText\n\n ## Now split the results on newlines, trim each line, and then\n ## join them back.\n $partialText = $partialText -split "`n" |\n Foreach-Object { $_.Trim() } | Where-Object { $_ }\n $partialText = $partialText -join "`n"\n\n [System.Web.HttpUtility]::HtmlDecode($partialText.Trim())\n }\n else\n {\n "`nNo answer found."\n }\n}\n\n## Clean HTML from a text chunk\nfunction CleanHtml ($htmlInput)\n{\n $tempString = [Regex]::Replace($htmlInput, "(?s)<[^>]*>", "")\n $tempString.Replace("&nbsp&nbsp", "")\n}\n\n. Main
PowerShellCorpus/PoshCode/Add-ByteFormat.ps1
Add-ByteFormat.ps1
function Add-ByteFormat { <# .Synopsis Function to make display of custom properties more human-readable. .Description With help of this function you will be able to force nice display of numeric data. It's using best possible unit of measure for *bytes sizes. If input object is PSCustomObject it will just modify it's ToString() method If it's any other type - it will try to remove property, re-add and modify ToString() method. Tested both on v2 and v3, works fine in both cases. .Example Get-ChildItem | Add-ByteFormat -Property Length Output: Directory: C:\\temp\\PowerShell\\vug\\ShowUI Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 26/04/2012 09:36 534.00 B 0_GetProxy.ps1 -a--- 26/04/2012 11:12 266.00 B 1_StackPanel.ps1 -a--- 25/04/2012 19:44 752.00 B 2_SimpleUI.ps1 -a--- 25/04/2012 19:43 913.00 B 3_Przezroczyste.ps1 -a--- 25/04/2012 19:41 1.28 KB 4_ADLastName.ps1 -a--- 25/04/2012 19:42 1.38 KB 5_ADLastName.ps1 -a--- 25/04/2012 19:41 343.00 B 6_RandomFont.ps1 -a--- 25/04/2012 19:54 1.42 KB 7_ADLastName.ps1 -a--- 26/04/2012 11:17 624.00 B 8_Show-Command.ps1 -a--- 26/04/2012 10:28 8.01 KB 9_Show-Picture.ps1 -a--- 25/04/2012 19:27 21.29 KB logo.png -a--- 15/10/2011 10:34 1.14 MB Normal.png -a--- 25/05/2011 11:28 222.93 KB Powershell-V2-1280x1024.jpg -a--- 25/05/2011 11:26 232.69 KB PowerShell1024x768[1].jpg -a--- 09/01/2011 21:59 80.36 KB powershellpl.png -a--- 26/04/2012 07:18 5.27 KB Sm-.csv -a--- 26/04/2012 11:18 8.08 KB WAR.csv Changes format of the Length property for files in current directory. As a side effect in v3 it will show folders as having 1B size. .Example Get-WmiObject -Class Win32_LogicalDisk | Add-ByteFormat -Property Size, FreeSpace -DecimalPoint 0 Output: DeviceID : C: DriveType : 3 ProviderName : FreeSpace : 9 GB Size : 298 GB VolumeName : PXL Will display disk information using WMI in N0 format. .Example Import-Csv Foo.csv | Add-ByteFormat -Property HDSize, RAM | Format-Table -AutoSize Output: Name HDSize RAM ---- ------ --- One 120.50 GB 1.47 GB Two 58.10 GB 3.47 GB Three 88.01 GB 1.21 GB This command is wash & go for data imported from CSV that contains numeric: -- numeric are no longer strings -- numeric are displayed in nice(r) fasion. .Link http://becomelotr.wordpress.com/2012/05/03/more-on-output/ #> [CmdletBinding()] param ( # Properties that will get ToString() method modified to allow better display. [Parameter( Mandatory = $true )] [string[]]$Property, # Number of decimal points used. [Alias('DP')] [int]$DecimalPoint = 2, # Object, that has properties that will be modified. [Parameter( ValueFromPipeline = $true, Mandatory = $true )] [Object]$InputObject ) begin { $MethodOptions = @{ Name = 'ToString' MemberType = 'ScriptMethod' PassThru = $true Force = $true Value = [ScriptBlock]::Create(@" "{0:N$DecimalPoint} {1}" -f @( switch -Regex ([math]::Log(`$this,1024)) { ^0 { (`$this / 1), ' B' } ^1 { (`$this / 1KB), 'KB' } ^2 { (`$this / 1MB), 'MB' } ^3 { (`$this / 1GB), 'GB' } ^4 { (`$this / 1TB), 'TB' } default { (`$this / 1PB), 'PB' } } ) "@ ) } } process { foreach ($Prop in $Property) { $SelectedProperty = $InputObject.$Prop if (!$SelectedProperty) { Write-Verbose "No such property: $Prop" continue } if ( ! ([double]$InputObject.$Prop) ) { Write-Verbose "Can't be casted into double: $Prop" continue } if ($SelectedProperty -is [System.String]) { # Need to change property type to make sure we get .ToString() to run... ;) [Int64]$InputObject.$Prop = $SelectedProperty } if (!$InputObject.PSTypeNames.Contains('System.Management.Automation.PSCustomObject')) { try { $Member = @{ MemberType = 'NoteProperty' Name = $Prop Force = $true Value = $SelectedProperty } $InputObject | Add-Member @Member } catch { Write-Verbose "Not able to replace property on this type: $($InputObject.GetType().FullName)" continue } } $InputObject.$Prop = $InputObject.$Prop | Add-Member @MethodOptions } $InputObject } } @@# Function in action. ;) ([PSCustomObject]@{ Name = 'Anna' HDSize = 21313123 RAM = 123GB Foo = '12313213123' }),([PSCustomObject]@{ Name = 'Ewa' HDSize = 213112313123 RAM = 1234MB Foo = '12313213123' }),([PSCustomObject]@{ Name = 'Adam' HDSize = 21313 RAM = 530PB Foo = '1231321113123' }) | Add-ByteFormat -Property HDSize, RAM, Foo -Verbose @' Name,HDSize,RAM,Foo Anna,21313123,12313213123,12313213123123 Ewa,123123123,123123123123,0 Adam,1231312312313,1231313213123123,12313123123123 '@ | ConvertFrom-Csv | Add-ByteFormat -Property HDSize, RAM, Foo -Verbose
PowerShellCorpus/PoshCode/Ping-Host_1.ps1
Ping-Host_1.ps1
function Ping-Host {param( [string]$HostName, [int32]$Requests = 3) for ($i = 1; $i -le $Requests; $i++) { $Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'" Start-Sleep -Seconds 1 if ($Result.StatusCode -ne 0) {return $FALSE} } return $TRUE }
PowerShellCorpus/PoshCode/Get-MSDNInfo.ps1
Get-MSDNInfo.ps1
function Get-MSDNInfo { <# .SYNOPSIS Opens the MSDN web page of an object member: type, method or property. .DESCRIPTION The Get-MSDNInfo function enables you to quickly open a web browser to the MSDN web page of any given instance of a .NET object. You can also refer to Get-MSDNInfo by its alias: 'msdn'. .PARAMETER InputObject Specifies an instance of a .NET object. .PARAMETER Name Specifies one member name (type, property or method name). .PARAMETER MemberType Specifies the type of the object member. Possible values are: 'Type','Property','Method' or their shortcuts: 'T','M','P'. The default value is 'Type'. .PARAMETER Culture If MSDN has localized versions then you can use this parameter with a value of the localized version culture string. The default value is 'en-US'. The full list of cultures can be found by executing the following command: PS > [System.Globalization.CultureInfo]::GetCultures('AllCultures') .PARAMETER List The List parameter orders the function to print a list of the incoming object's methods and properties. You can use the List parameter to get a view of the object members that the function support. .EXAMPLE PS> $ps = Get-Process -Id $pid PS> $ps | Get-MSDNInfo -List TypeName: System.Diagnostics.Process MemberType Name ---------- ---- Method BeginErrorReadLine Method BeginOutputReadLine Method CancelErrorRead Method CancelOutputRead Method Close Method CloseMainWindow Method CreateObjRef Method Dispose Method EnterDebugMode Method Equals Method GetCurrentProcess Method GetHashCode Method GetLifetimeService Method GetProcessById Method GetProcesses (...) Property BasePriority Property Container Property EnableRaisingEvents Property ExitCode Property ExitTime Property Handle Property HandleCount Property HasExited Property Id Property MachineName Property MainModule (...) Description ----------- The first command store the current session process object in a variable named $ps. The variable is piped to Get-MSDNInfo which specifies the List parameter. The result is a list of the process object members. .EXAMPLE PS> $date = Get-Date PS> Get-MSDNInfo -InputObject $date -MemberType Property TypeName: System.DateTime 1. Date 2. Day 3. DayOfWeek 4. DayOfYear 5. Hour 6. Kind 7. Millisecond 8. Minute 9. Month 10. Now 11. Second 12. Ticks 13. TimeOfDay 14. Today 15. UtcNow 16. Year Enter the Property item number ( Between 1 and 16. Press CTRL+C to cancel): Description ----------- The command gets all the properties of the date object and prints a numbered menu. You are asked to supply the property item number. Once you type the number and press the Enter key, the function invokes the given property web page in the default browser. .EXAMPLE PS> $date = Get-Date PS> Get-MSDNInfo -InputObject $date Description ----------- Opens the web page of the object type name. .EXAMPLE Get-Date | Get-MSDNInfo -Name DayOfWeek -MemberType Property Description ----------- If you know the exact property name and you don't want the function to print the numbered menu then you can pass the property name as an argument to the MemberType parameter. This will open the MSDN web page of the DayOfWeek property of the DateTime structure. .EXAMPLE PS> $winrm = Get-Service -Name WinRM PS> $winrm | msdn -mt Method TypeName: System.ServiceProcess.ServiceController 1. Close 2. Continue 3. CreateObjRef 4. Dispose 5. Equals 6. ExecuteCommand 7. GetDevices 8. GetHashCode 9. GetLifetimeService 10. GetServices 11. GetType 12. InitializeLifetimeService 13. Pause 14. Refresh 15. Start 16. Stop 17. ToString 18. WaitForStatus Enter the Method item number ( Between 1 and 18. Press CTRL+C to cancel): Description ----------- The command prints a numbered menu of the WinRM service object methods. You are asked to supply the method item number. Once you type the number and press the Enter key, the function invokes the given method web page in the default browser. The command also uses the 'msdn' alias of the function Get-MSDNInfo and the alias 'mt' of the MemberType parameter. .EXAMPLE $date | Get-MSDNInfo -Name AddDays -MemberType Method Description ----------- Opens the page of the AddDays DateTime method. .NOTES Author: Shay Levy Blog : http://blogs.microsoft.co.il/blogs/ScriptFanatic/ .LINK http://blogs.microsoft.co.il/blogs/ScriptFanatic/ #> [CmdletBinding(DefaultParameterSetName='Type')] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [System.Object]$InputObject, [Parameter(ParameterSetName='Type')] [ValidateNotNullOrEmpty()] [System.String]$Name, [Parameter(ParameterSetName='Type')] [ValidateNotNullOrEmpty()] [ValidateSet('Type','Method','Property','t','m','p')] [Alias('mt')] [System.String]$MemberType='Type', [Parameter(ParameterSetName='Type')] [ValidateNotNullOrEmpty()] [System.String]$Culture='en-US', [Parameter(ParameterSetName='List')] [switch]$List ) begin { $baseUrl = "http://msdn.microsoft.com/$Culture/library/" # exclude special name members $SpecialName = [System.Reflection.MethodAttributes]::SpecialName switch -regex($MemberType) { '^(Type|t)$' {$MemberType='Type'; break} '^(Method|m)$' {$MemberType='Method'; break} '^(Property|p)$' {$MemberType='Property'; break} default {$MemberType='Type'} } } process { if($MemberType -eq 'Type' -AND $Name) { Throw "Invalid 'MemberType' value. Please enter another value: 'Property' or 'Method'." } if($PSCmdlet.ParameterSetName -eq 'List') { Write-Host "`n`t TypeName: $($InputObject.GetType().FullName)" $InputObject.GetType().GetMembers() | Where-Object {$_.MemberType -match '^(method|property)$' -AND !($_.Attributes -band $SpecialName)} | Sort-Object MemberType,Name -Unique | Format-Table MemberType,Name -Auto } else { $member = $InputObject.GetType().GetMembers() | Where-Object {$_.MemberType -eq $MemberType -AND !($_.Attributes -band $SpecialName)} | Select-Object Name,MemberType,DeclaringType -Unique | Sort-Object Name if($MemberType -eq 'Type') { Start-Process -FilePath ("$baseUrl{0}.aspx" -f $InputObject.GetType().FullName) break } if($Name) { $m = $member | Where-Object {$_.MemberType -eq $MemberType -AND $_.Name -eq $Name} if($m) { Start-Process -FilePath ("$baseUrl{0}.{1}.aspx" -f $m.DeclaringType,$m.Name) } else { Write-Error "'$Name' is not a $MemberType of '$($InputObject.GetType().FullName)'. Check the Name and try again." } } else { # display numbered members menu Write-Host "`n TypeName: $($InputObject.GetType().FullName)`n" for($i=0;$i -lt $member.count; $i++) { Write-Host "$($i+1). $($member[$i].name)" } do{ [int]$num = Read-Host -Prompt "`nEnter the $membertype item number ( Between 1 and $($member.count). Press CTRL+C to cancel)" } while ( $num -lt 1 -or $num -gt $member.count) Start-Process -FilePath ("$baseUrl{0}.{1}.aspx" -f $member[$num-1].DeclaringType,$member[$num-1].Name) } } } } Set-Alias -Name msdn -Value Get-MSDNInfo
PowerShellCorpus/PoshCode/WakeOnLan.ps1
WakeOnLan.ps1
#wakeonlan $computer function WakeOnLan($computer) { $select=$select |where-object {$_.computername -eq $computer} |Select-Object mac if ($select.mac -eq $null) { echo "workstation not found.epic fail. use all to wake'em all" } else { $select.mac -match "(..)(..)(..)(..)(..)(..)" | out-null $mac= [byte[]]($matches[1..6] |% {[int]"0x$_"}) $UDPclient = new-Object System.Net.Sockets.UdpClient $UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000) $packet = [byte[]](,0xFF * 102) 6..101 |% { $packet[$_] = $mac[($_%6)]} $UDPclient.Send($packet, $packet.Length) echo "workstation $computer is booting up..." } } #wakeonlan all the computers function WakeOnLanAll { $computers=$select | Select-Object computername foreach ($computer in $computers) { $target = $computer.computername WakeOnLan($target) #delay to be powergrid friendly Start-Sleep -seconds 5 } } #shutdown $computer function ShutDown($computer) { if ($computer.ToLower() -eq "all") { $select=$select|Select-Object computername foreach ($computername in $select) { $target=$computername.computername get-wmiobject win32_operatingsystem -computer $target | foreach {$_.shutdown()} } } else { $select=$select |where-object {$_.computername -eq $computer} |Select-Object computername if ($select.computername -eq $null) { echo "workstation $computer not found.epic fail. use all to kill'em all" } else { get-wmiobject win32_operatingsystem -computer $computer | foreach {$_.Shutdown()} } } } ####reboot $computer function Reboot($computer) { #reboot all if ($computer.ToLower() -eq "all") { $select=$select|Select-Object computername foreach ($computername in $select) { $target=$computername.computername get-wmiobject win32_operatingsystem -computer $target | foreach {$_.reboot()} } } else { $select=$select |where-object {$_.computername -eq $computer} |Select-Object computername #check input if ($select.computername -eq $null) { echo "workstation $computer not found.epic fail. use all to kill'em all" } #reboot else { get-wmiobject win32_operatingsystem -computer $computer | foreach {$_.reboot()} #delay to be powergrid friendly Start-Sleep -seconds 5 } } } ################### $option=read-host "Enter option" $select=Import-Csv workstations.csv switch ($option) { "wol" { $computer=read-host "Enter Workstation to wake..." if ($computer -eq "all") { WakeOnLanAll } else { WakeOnLan($computer) ping -4 -n 25 $computer } } "reboot" { $computer=read-host "Enter Workstation to reboot..." Reboot($computer) } "shutdown" { $computer=read-host "Enter Workstation to kill..." Shutdown($computer) } default {echo "error!options are : wol, reboot, shutdown"} }
PowerShellCorpus/PoshCode/Execute-RunspaceJob.ps1
Execute-RunspaceJob.ps1
<# .SYNOPSIS Executes a set of parameterized script blocks asynchronously using runspaces, and returns the resulting data. .DESCRIPTION Encapsulates generic logic for using Powershell background runspaces to execute parameterized script blocks in an efficient, multi-threaded fashion. For detailed examples of how to use the function, see http://awanderingmind.com/tag/execute-runspacejob/. .PARAMETER ScriptBlock The script block to execute. Should contain one or more parameters. .PARAMETER ArgumentList A hashtable containing data about the entity to be processed. The key should be a unique string to identify the entity to be processed, such as a server name. The value should be another hashtable of arguments to be passed into the script block. .PARAMETER ThrottleLimit The maximum number of concurrent threads to use. Defaults to 10. .PARAMETER RunAsync If specified, the function will not wait for all the background runspaces to complete. Instead, it will return an array of runspace objects that can be used to further process the results at a later time. .NOTES Author: Josh Feierman Date: 7/15/2012 Version: 1.1 #> function Execute-RunspaceJob { [Cmdletbinding()] param ( [parameter(mandatory=$true)] [System.Management.Automation.ScriptBlock]$ScriptBlock, [parameter(mandatory=$true,ValueFromPipeline=$true)] [System.Collections.Hashtable]$ArgumentList, [parameter(mandatory=$false)] [int]$ThrottleLimit = 10, [parameter(mandatory=$false)] [switch]$RunAsync ) begin { try { #Instantiate runspace pool $runspacePool = [runspacefactory]::CreateRunspacePool(1,$ThrottleLimit) $runspacePool.Open() #Array to hold runspace data $runspaces = @() #Array to hold return data $data = @() } catch { Write-Warning "Error occurred initializing function setup." Write-Warning $_.Exception.Message break } } process { # Queue all sets of parameters for execution foreach ($Argument in $ArgumentList.Keys) { try { $rowIdentifier = $Argument Write-Verbose "Queuing item $rowIdentifier for processing." $runspaceRow = "" | Select-Object @{n="Key";e={$rowIdentifier}}, @{n="Runspace";e={}}, @{n="InvokeHandle";e={}} $powershell = [powershell]::Create() $powershell.RunspacePool = $runspacePool $powershell.AddScript($scriptBlock).AddParameters($ArgumentList[$rowIdentifier]) | Out-Null $runspaceRow.Runspace = $powershell $runspaceRow.InvokeHandle = $powershell.BeginInvoke() $runspaces += $runspaceRow } catch { Write-Warning "Error occurred queuing item '$Argument'." Write-Warning $_.Exception.Message } } } end { try { if ($RunAsync) { Write-Output $runspaces } else { $totalCount = $runspaces.Count # Wait for all runspaces to complete while (($runspaces | Where-Object {$_.InvokeHandle.IsCompleted -eq $false}).Count -gt 0) { $completedCount = ($runspaces | Where-Object {$_.InvokeHandle.IsCompleted -eq $true}).Count Write-Verbose "Completed $completedCount of $totalCount" Start-Sleep -Seconds 1 } # Retrieve returned data and handle any threads that had errors foreach ($runspaceRow in $runspaces) { try { Write-Verbose "Retrieving data for item $($runspaceRow.Key)." if ($runspaceRow.Runspace.InvocationStateInfo.State -eq "Failed") { $errorMessage = $runspaceRow.Runspace.InvocationStateInfo.Reason.Message Write-Warning "Processing of item $($runspaceRow.Key) failed with error: $errorMessage" } else { $data += $runspaceRow.Runspace.EndInvoke($runspaceRow.InvokeHandle) } } catch { Write-Warning "Error occurred processing result of runspace for set '$($runspaceRow.Key)'." Write-Warning $_.Exception.Message } finally { $runspaceRow.Runspace.dispose() } } $runspacePool.Close() Write-Output $data } } catch { Write-Warning "Error occurred processing returns of runspaces." Write-Warning $_.Exception.Message } } }
PowerShellCorpus/PoshCode/Move-Mailbox _1.ps1
Move-Mailbox _1.ps1
param( #distribution group holding usermailbox(es) [string] $DistGroup = "XC2010Move", #move requests per batch/script run [int] $BatchCount = 5 ) #remove user(s) without mailbox Get-DistributionGroupMember $DistGroup | get-user -Filter {Recipienttype -eq "User"} -EA SilentlyContinue | Remove-DistributionGroupMember -Identity $DistGroup -Confirm:$False #remove mailbox(es) already moved to 2010 (by previous script run) Get-DistributionGroupMember $DistGroup | Get-Mailbox -EA SilentlyContinue -RecipientTypeDetails "UserMailbox" | Remove-DistributionGroupMember -Identity $DistGroup -Confirm:$False #get pre-2010 mailbox(es) not yet moved $MB2Move = Get-DistributionGroupMember $DistGroup | Get-Mailbox -EA SilentlyContinue | Where {($_.RecipientTypeDetails -eq "LegacyMailbox") -and ($_.MailboxMoveStatus -eq ‘None’) -and ($_.ExchangeUserAccountControl -ne "AccountDisabled")} | Get-Random -Count $BatchCount #create batch label as reference $batch = "$($env:computername)_MoveMB_{0:ddMMM_yyyy}" -f (Get-Date) #move pre-2010 mailbox(es) ForEach ($SingleMailbox in $MB2Move) {New-MoveRequest –Identity $SingleMailbox -BadItemLimit 100 -AcceptLargeDataLoss -Batchname $batch} #set quotas on moved mailbox(es) Get-DistributionGroupMember $DistGroup | Get-Mailbox -RecipientTypeDetails "UserMailbox" -EA SilentlyContinue | Where {($_.MailboxMoveStatus -eq ‘Completed’)} | Set-Mailbox -Identity $_ -IssueWarningQuota "1920MB" -ProhibitSendQuota "1984MB" -ProhibitSendReceiveQuota "2048MB"} #remove move request(s) upon completion Get-MoveRequest -MoveStatus Completed | Remove-MoveRequest -Confirm:$False
PowerShellCorpus/PoshCode/Get-Parameter_7.ps1
Get-Parameter_7.ps1
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) { foreach ($paramset in (Get-Command $Cmdlet).ParameterSets){ $Output = @() foreach ($param in $paramset.Parameters) { if ( !$ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue } } $process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory, Pipeline, PipelineByPropertyName $process.Name = $param.Name $process.Type = $param.ParameterType.Name if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases if ( $param.Position -lt 0 ) { $process.Position = $null } else { $process.Position = $param.Position } $process.IsMandatory = $param.IsMandatory $process.Pipeline = $param.ValueFromPipeline $process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName $output += $process } if ( !$Full ) { $Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline } else { Write-Output $Output } } } function gpm ($Cmdlet) { Get-Parameter $Cmdlet | ft name,type,is*,pipe* -GroupBy parameterset -AutoSize }
PowerShellCorpus/PoshCode/Get-MIX10Video.ps1
Get-MIX10Video.ps1
#requires -version 2.0 PARAM ( [Parameter(Position=1, Mandatory=$true)] [ValidateSet("wmv","wmvhigh","ppt", "mp4")] [String]$MediaType, [string]$Destination = $PWD ) if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and -not ( # Vista and ... new-object Security.Principal.WindowsPrincipal ( [Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { Write-Warning @" On VISTA and above, BITS limits the number of jobs in the queue to 300 jobs and the number of jobs that a non-administrator user can create to 60 jobs. You MUST run this script from an elevated host if you're on Vista, Windows 7, or Server 2008 "@ } Import-Module BitsTransfer Push-Location $Destination $Extension = $(switch -wildcard($MediaType){"wmv*"{"wmv"} "mp4"{"mp4"} "ppt"{"pptx"}}) $BaseUrl = "http://ecn.channel9.msdn.com/o9/mix/10/{0}/{2}.{1}" "CL01", "CL02", "CL03", "CL06", "CL07", "CL08", "CL09", "CL10", "CL13", "CL14", "CL15", "CL16", "CL17", "CL18", "CL19", "CL20", "CL21", "CL22", "CL23", "CL24", "CL25", "CL26", "CL27", "CL28", "CL29", "CL30", "CL50", "CL51", "CL52", "CL53", "CL54", "CL55", "CL56", "CL58", "CL59", "CL60", "DS01", "DS02", "DS03", "DS04", "DS05", "DS06", "DS07", "DS08", "DS09", "DS10", "DS11", "DS12", "DS13", "DS14", "DS15", "DS16", "EX01", "EX02", "EX03", "EX04", "EX06", "EX07", "EX10", "EX11", "EX12", "EX13", "EX14", "EX15", "EX16", "EX17", "EX18", "EX19", "EX20", "EX21", "EX22", "EX23", "EX25", "EX26", "EX27", "EX28", "EX29", "EX30", "EX31", "EX32", "EX33", "EX34", "EX35", "EX36", "EX37", "EX38", "EX39", "EX50", "EX51", "EX52", "EX53", "EX55", "EX56", "FTL01", "FTL02", "FTL03", "FTL50", "FTL51", "KEY01", "KEY02", "PR01", "PR02", "SVC01", "SVC02", "SVC03", "SVC04", "SVC05", "SVC06", "SVC07", "SVC08", "SVC09", "SVC10", "SVC12", "SVC50" | ForEach { Start-BitsTransfer -Source $($BaseUrl -f $MediaType, $Extension, $_) -Async } Pop-Location Write-Host "You may now use Get-BitsTransfer to check on the status of the downloads. By default, failed transfers will be retried every 10 minutes for two weeks." # SIG # Begin signature block # MIIQpAYJKoZIhvcNAQcCoIIQlTCCEJECAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUmuwkLIvcY4HgxR1/UfjBbLhG # vJ+ggg3ZMIIGyzCCBbOgAwIBAgICAIMwDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNV # BAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUg # RGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMTgwNgYDVQQDEy9TdGFydENvbSBD # bGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVjdCBDQTAeFw0wOTEyMjIw # NjAwMTlaFw0xMTEyMjMxMTE2NTdaMIHIMSAwHgYDVQQNExcxMTc2NjEtcTdtZGI4 # Y28zaGhBbXAxMjELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCVdpc2NvbnNpbjESMBAG # A1UEBxMJR3JlZW5kYWxlMS0wKwYDVQQLEyRTdGFydENvbSBWZXJpZmllZCBDZXJ0 # aWZpY2F0ZSBNZW1iZXIxGDAWBgNVBAMTD1N0ZXZlbiBNdXJhd3NraTEmMCQGCSqG # SIb3DQEJARYXc3RldmVAdXNlcG93ZXJzaGVsbC5jb20wggEiMA0GCSqGSIb3DQEB # AQUAA4IBDwAwggEKAoIBAQC94TIYIjVOhj2zKhUQngQ5nxqPCCH6/nsKe49FNqgE # SPG2PRX9WBNdYIg1QXhpkw16bw+1PItHJi6vjZ7OiYyrS1Sui6iUnQ3Nt40I1H7N # Hn4i5yn7AcFgUUCBpQgUXEc+10pZUnJ7mY1BqJJGXrDve8I2NxkDPiPwNnm6xqwO # XkeaWSYpxKv/QXI6J+wnSSvrcMZegMxZ8TbMT7ihNCt8Y+UVlKF7g4jcRjnGzn5h # F5qJodmgIIuQGkuKspTzqDrIMelJHqZTyvHWBjtA09zkDpMpDlhMP6A4Lu2vpIrc # 8Ztb9FAFD/+oTLo1cz80QjY2I7rM3oxAWwsdGrCkIn09AgMBAAGjggL3MIIC8zAJ # BgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDA6BgNVHSUBAf8EMDAuBggrBgEFBQcD # AwYKKwYBBAGCNwIBFQYKKwYBBAGCNwIBFgYKKwYBBAGCNwoDDTAdBgNVHQ4EFgQU # nU30uCjZk+GBJq9f25DWwbMRxhQwHwYDVR0jBBgwFoAU0E4PQJlsuEsZbzsouODj # iAc0qrcwggFCBgNVHSAEggE5MIIBNTCCATEGCysGAQQBgbU3AQIBMIIBIDAuBggr # BgEFBQcCARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjA0Bggr # BgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50ZXJtZWRpYXRlLnBk # ZjCBtwYIKwYBBQUHAgIwgaowFBYNU3RhcnRDb20gTHRkLjADAgEBGoGRTGltaXRl # ZCBMaWFiaWxpdHksIHNlZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg # dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp # bGFibGUgYXQgaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjBjBgNV # HR8EXDBaMCugKaAnhiVodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9jcnRjMi1jcmwu # Y3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0c3NsLmNvbS9jcnRjMi1jcmwuY3Js # MIGJBggrBgEFBQcBAQR9MHswNwYIKwYBBQUHMAGGK2h0dHA6Ly9vY3NwLnN0YXJ0 # c3NsLmNvbS9zdWIvY2xhc3MyL2NvZGUvY2EwQAYIKwYBBQUHMAKGNGh0dHA6Ly93 # d3cuc3RhcnRzc2wuY29tL2NlcnRzL3N1Yi5jbGFzczIuY29kZS5jYS5jcnQwIwYD # VR0SBBwwGoYYaHR0cDovL3d3dy5zdGFydHNzbC5jb20vMA0GCSqGSIb3DQEBBQUA # A4IBAQDAKxouOZbRGXHT2avNItDoYlnhoLXypJnLUiRX9LXoOSh5Tlj6EQPJuXyG # pqVDzPfN3YdqmqTSSVay7r7ndOa+VvyPppIc4xE7nMuSPT8HUej96sDJI0QBbQM2 # +OoEVl/ZXcsPbaIGKVKkPFS3nTJ54UNxPKfHUK71IimVyhMQY/KaucD0BuU9Guqi # 8rh2eYqm2BKkD8RHJxSbTCoMY1g83B/pvaGs2bI7OCwL+sfICFQhoRzY7RLE2Rvy # maIr9CzN7EBTNYWSr56j/0vuvNFCn0htw2rspyN8ZS+pa3lc/MiWoLVJ09HwJ1pK # C1soqH5vqdPHHDkw1E5qY8uraRCRMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0B # AQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkG # A1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UE # AxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIw # MTQ1WhcNMTIxMDI0MjIwMTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0 # YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl # IFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRl # cm1lZGlhdGUgT2JqZWN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC # AQEAyiOLIjUemqAbPJ1J0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzw # FQNKJCdU5ftKoM5N4YSjId6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3 # HaV3/z9159nnvyxQEckRZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaN # rsLc9pboUoYIC3oyzWoUTZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9Y # aQpGtW/h/W/FkbQRT3sCpttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8A # a8hQ+M1qGdQjAye8OzbVuUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zAL # BgNVHQ8EBAMCAQYwHQYDVR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNV # HSMEgaAwgZ2AFE4L7xqkQFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMC # SUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdp # dGFsIENlcnRpZmljYXRlIFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRp # ZmljYXRpb24gQXV0aG9yaXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAv # MC0GCCsGAQUFBzAChiFodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQw # YAYDVR0fBFkwVzAsoCqgKIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2Nh # LWNybC5jcmwwJ6AloCOGIWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNy # bDCBggYDVR0gBHsweTB3BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRw # Oi8vY2VydC5zdGFydGNvbS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0 # cDovL2NlcnQuc3RhcnRjb20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4 # QgEBBAQDAgABMFAGCWCGSAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1h # cnkgSW50ZXJtZWRpYXRlIE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkq # hkiG9w0BAQUFAAOCAgEAUKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+ # IwIsT75Q1kLsnnfUQfbFpl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9t # uA8Ohu3eY1cPl7eOaY4QqvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPv # KLRS0CqKgsH2nweovk4hfXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw # 6M6yGJAGG3GnzbwadF9BUW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5Ux # hCpA+wr+l+NbHP5x5XZ58xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9 # y94+leAYqr8bbBNAFTX1pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7 # d6UXUSn5bw2+usvhdkW4npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaII # sIAxclf25FwssWjieMwV0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1 # 094X38OvMO/++H5S45Ki3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnq # GBfqiOnzxxRVNOw2hSQp0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0x # ggI1MIICMQIBATCBkzCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29t # IEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25p # bmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlh # dGUgT2JqZWN0IENBAgIAgzAJBgUrDgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAig # AoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgEL # MQ4wDAYKKwYBBAGCNwIBFjAjBgkqhkiG9w0BCQQxFgQUqXZyhT3gPb/yztv37JLm # MK4u2YUwDQYJKoZIhvcNAQEBBQAEggEAr3pUvFrxGYAyWsVPDHQXkEry1vupa04M # 0DJqCEb7lFFzDc56MKtOxr2L59+wOLN6go1KV7njbaQ5FbVC2CX8bIgeoiCXIKp0 # bsClIXTkViqS1BDcOxGM6RaQOzqFCy+8e5ahimkR+jxYGNTM2MnqEeHw8mY582ZU # WOVnMYeF5pV+UQFsV/ri+jLk0BVHqkpMFy4F3BqeBH5U0jQ8Ai9Vh4OAfoDEdkAD # aV+A5IVZmhUEuTG0v8MFeQM8XDU70NeusQleY3o98RlRT7/UW/MbOFxeM8Ogzyl2 # aIkAqJBpca3PlnaVVWWoNlTb3pjKkByLmEMkMMAnamBS2PJmauWlQg== # SIG # End signature block
PowerShellCorpus/PoshCode/Sort-ISE_Boots.ps1
Sort-ISE_Boots.ps1
function Sort-ISE () { <# .SYNOPSIS ISE Extension sort text starting at column $start comparing the next $length characters .DESCRIPTION ISE Extension sort text starting at column $start comparing the next $length characters Leftmost column is column 1 .NOTES File Name : Sort-ISE_Boots.ps1 Author : Bernd Kriszio - http://pauerschell.blogspot.com/ Requires : PowerShell V2 CTP3 .LINK Script posted to: http://poshcode.org/ .EXAMPLE Sort-ISE 1 10 #> #requires -version 2.0 param ( [Parameter(Position = 0, Mandatory=$false)] [int]$start = 1, [Parameter(Position = 1, Mandatory=$false)] [int]$length = -1 ) "`$start = $Start `$length = $length" $newlines = @{} $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $text -replace "`r", "-" $text = $editor.Text.Split("`n") '----------' foreach ($i in 0..$($text.length -1 )){ "$i $($text[$i])" } foreach ($line in $text){ $key = [string]::join("", $line[($start - 1)..($start - 1 + $length)]) if ( $newlines[$key] -ne $null) { $newlines[$key] = $newlines[$key] + "`n" + $line } else { $newlines[$key] = $line } } $Sortedkeys = $newlines.keys | sort $newtext = '' foreach ($key in $Sortedkeys){ if ($newtext -ne '') { $newtext += "`n" + $newlines[$key] } else { $newtext = $newlines[$key] } } ' =======' Write-host $newtext ' .......' $text = $newtext.Split("`n") foreach ($i in 0..$($text.length -1 )){ "$i $($text[$i])" } #$newtext = $newtext -replace "`n", "`r`n" $editor.Text = $newtext } function Show-Sort_ISE_DLG { <# .SYNOPSIS ISE Extension sort text starting at column $start comparing the next $length characters .DESCRIPTION ISE Extension sort text starting at column $start comparing the next $length characters Leftmost column is column 1. Querry parameters by dialog. .NOTES File Name : Sort-ISE_Boots.ps1 Author : Bernd Kriszio - http://pauerschell.blogspot.com/ Requires : PowerShell V2 CTP3 .LINK Script posted to: http://poshcode.org/ .EXAMPLE Sort-ISE 1 10 #> #requires -version 2.0 Param([string]$Prompt = "Please enter start and length:") Remove-Variable textBox -ErrorAction SilentlyContinue Border -BorderThickness 4 -BorderBrush "#BE8" -Background "#EFC" ( StackPanel -Margin 10 $( Label $Prompt StackPanel -Orientation Horizontal $( TextBox -OutVariable global:textbox -Width 150 -On_KeyDown { if($_.Key -eq "Return") { #Write-Output $textbox[0].Text #Write-Output $textbox2[0].Text Sort-ISE $textbox[0].Text $textbox2[0].Text $BootsWindow.Close() } } TextBox -OutVariable global:textbox2 -Width 150 -On_KeyDown { if($_.Key -eq "Return") { #Write-Output $textbox[0].Text #Write-Output $textbox2[0].Text Sort-ISE $textbox[0].Text $textbox2[0].Text $BootsWindow.Close() } } Button "Ok" -On_Click { #Write-Output $textbox[0].Text #Write-Output $textbox2[0].Text Sort-ISE $textbox[0].Text $textbox2[0].Text $BootsWindow.Close() } ) ) ) | Boots -On_Load { $textbox[0].Focus() } ` -WindowStyle None -AllowsTransparency $true ` -On_PreviewMouseLeftButtonDown { if($_.Source -notmatch ".*\\.(TextBox|Button)") { $BootsWindow.DragMove() } } } if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "_Sort" } ) ) { $null = $psISE.CustomMenu.Submenus.Add("_Sort", {Show-Sort_ISE_DLG}, "Ctrl+Alt+S") }
PowerShellCorpus/PoshCode/Folder inheritance.ps1
Folder inheritance.ps1
# setup the test folders md c:\\grandfather\\father\\son md c:\\grandmother\\mother\\daughter # By default the folders will inherit ACLs from the C: drive # To toggle it or change it to the desired setting # Will force the inheritance from parent $inheritance = get-acl c:\\grandmother $inheritance.SetAccessRuleProtection($false,$false) set-acl c:\\grandmother -aclobject $inheritance #Display the new state (Get-Acl c:\\grandmother).AreAccessRulesProtected ############################################################# # Second script to go the other way ############################################################# # Will remove the inheritance from parent $inheritance = get-acl c:\\grandfather $inheritance.SetAccessRuleProtection($true,$true) set-acl c:\\grandfather -aclobject $inheritance #Display the new state (Get-Acl c:\\grandfather).AreAccessRulesProtected # As you can see changing the ($false,$false) to ($true,$true) is the only difference in the 2 scripts
PowerShellCorpus/PoshCode/Combine-CSV Function.ps1
Combine-CSV Function.ps1
function Combine-CSV{ <# .Synopsis Combines similar CSV files into a single CSV File .Description Function will combine common .CSV files into one large file. CSV files should have same header. This script is intended to aid when doing large reports across a large environment. .Parameter SourceFolder Specifies the folder location for the .CSV files. If no filter is applied it will combine all .CSV files in that directory. .Parameter Filter Specifies any filtering used for Get-ChildItem when grabbing the list of files to be combined. .Parameter ExportFileName Specifies the file to have the combined .CSV files exported. The combined file will be placed into the same directory as the SourceFolder .Example Combine-CSV -SourceFolder "C:\\Temp\\" -Filter "vcm*.csv" -ExportFileName "All-VCM.csv" This will combine all .CSV files in directory C:\\Temp\\ that begin with "vcm" and export those files to file All-VCM.csv in the same directory. .Example Combine-CSV -SourceFolder "C:\\Temp\\" -Filter "vcm*.csv" This will combine all .CSVs that start with "vcm" and output results to screen only since the -ExportFileName parameter is not used. .Link http://www.vtesseract.com .Notes ==================================================================== Author(s): Josh Atwell <josh.c.atwell@gmail.com> http://www.vtesseract.com/ Date: 2012-10-02 Revision: 1.0 ==================================================================== 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( [Parameter(Position=0,Mandatory=$true,HelpMessage="Please provide the folder which contains your .CSV files.")] $SourceFolder, [Parameter(Position=1,Mandatory=$false,HelpMessage="Please provide any Get-ChildItem filter you would like to apply")] [String]$Filter, [Parameter(Position=2,Mandatory=$false,HelpMessage="Please provide exported CSV filename")] [String]$ExportFileName ) Begin{ If ($SourceFolder.EndsWith("\\") -eq $false){ $SourceFolder = $SourceFolder + "\\" } Write-Verbose "Source Folder is $SourceFolder" If ((Test-Path $SourceFolder) -eq $True){ $files = Get-childitem -Path $SourceFolder -Filter $Filter | Sort $count = ($files).Count Write-Verbose "Combining $count .CSV files" $FullText = Get-Content ($files | Select -First 1).FullName }Else{ Write-Output "Path $SourceFolder does not exist" } } Process{ foreach($file in ($files | Select -Skip 1)){ $FullText = $FullText + (Get-Content $file.FullName | Select -Skip 1) } } End{ If($ExportFileName -ne ""){ $DestinationFullPath = $SourceFolder + $ExportFileName Write-Verbose "Writing output to file $DestinationFullPath" Set-Content -Path $DestinationFullPath -Value ($FullText) } Else { return $FullText } } }