full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Get-ADGroupModifications_1.ps1
Get-ADGroupModifications_1.ps1
###########################################################################" # # NAME: Get-ADGroupModificationsReport.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: Generates a HTML-report of Active Directory group membership modifications (addings and deletions). # Specify a valid path on line 211 to store the report. # For more details, see the following blog-post: # http://blog.powershell.no/2009/10/11/active-directory-group-membership-modifications-report # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 11.10.2009 - Initial release # 1.1 29.04.2010 - Enhanced the script performance by storing each domain controllers security eventlog in a variable # ###########################################################################" #Requires -Version 2.0 function Get-CustomHTML ($Header){ $Report = @" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http`://www.w3.org/TR/html4/frameset.dtd"> <html><head><title>$($Header)</title> <META http-equiv=Content-Type content='text/html; charset=windows-1252'> <meta name="save" content="history"> <style type="text/css"> DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 10pt; RIGHT: 8px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline} TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%} *{margin:0} .dspcont { BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 95%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9} .filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative} .save{behavior:url(#default#savehistory);} .dspcont1{ display:none} a.dsphead0 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #cc0000} a.dsphead1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #7BA7C7} a.dsphead2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #A5A5A5} a.dsphead1 span.dspchar{font-family:monospace;font-weight:normal;} td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma} th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left} BODY {margin-left: 4pt} BODY {margin-right: 4pt} BODY {margin-top: 6pt} </style> </head> <body> <b><font face="Arial" size="5">$($Header)</font></b><hr size="8" color="#cc0000"> <font face="Arial" size="1"><b>Generated on $($ENV:Computername)</b></font><br> <font face="Arial" size="1">Report created on $(Get-Date)</font> <div class="filler"></div> <div class="filler"></div> <div class="filler"></div> <div class="save"> "@ return $Report } function Get-CustomHeader0 ($Title){ $Report = @" <h1><a class="dsphead0">$($Title)</a></h1> <div class="filler"></div> "@ return $Report } function Get-CustomHeader ($Num, $Title){ $Report = @" <h2><a class="dsphead$($Num)"> $($Title)</a></h2> <div class="dspcont"> "@ return $Report } function Get-CustomHeaderClose{ $Report = @" </DIV> <div class="filler"></div> "@ return $Report } function Get-CustomHeader0Close{ $Report = @" </DIV> "@ return $Report } function Get-CustomHTMLClose{ $Report = @" </div> </body> </html> "@ return $Report } function Get-HTMLTable { param([array]$Content) $HTMLTable = $Content | ConvertTo-Html $HTMLTable = $HTMLTable -replace "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http`://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">", "" $HTMLTable = $HTMLTable -replace "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http`://www.w3.org/TR/html4/strict.dtd"">", "" $HTMLTable = $HTMLTable -replace "<html xmlns=""http`://www.w3.org/1999/xhtml"">", "" $HTMLTable = $HTMLTable -replace '<html>', "" $HTMLTable = $HTMLTable -replace '<head>', "" $HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', "" $HTMLTable = $HTMLTable -replace '</head><body>', "" $HTMLTable = $HTMLTable -replace '</body></html>', "" return $HTMLTable } function Get-HTMLDetail ($Heading, $Detail){ $Report = @" <TABLE> <tr> <th width='25%'><b>$Heading</b></font></th> <td width='75%'>$($Detail)</td> </tr> </TABLE> "@ return $Report } #Initialize array for domain controllers in the current domain $domaincontrollers = @() #Get current domain $dom = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain() #Get domain controllers in the current domain and add them to the $domain controllers array $dom.DomainControllers | select Name | ForEach-Object {$domaincontrollers += $_.name} $MyReport = Get-CustomHTML "Active Directory Group Modifications - Daily Report" $MyReport += Get-CustomHeader0 ("$domaincontroller") # ---- General Summary Info ---- $MyReport += Get-CustomHeader "1" "General Details" $MyReport += Get-HTMLDetail "Domain name:" $dom $MyReport += Get-HTMLDetail "Number of Domain Controllers:" $domaincontrollers.count $MyReport += Get-CustomHeaderClose foreach ($domaincontroller in $domaincontrollers){ $eventlog = Get-EventLog -LogName ‘Security’ -ComputerName $domaincontroller -After ((Get-Date).AddDays(-1)) # ---- Members added to Domain Local Groups ---- $MyReport += Get-CustomHeader "1" "Members added to Domain Local Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "636" -or $_.EventID -eq "4732"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose # ---- Members removed from Domain Local Groups ---- $MyReport += Get-CustomHeader "1" "Members removed from Domain Local Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "637" -or $_.EventID -eq "4733"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose # ---- Members added to Global Groups ---- $MyReport += Get-CustomHeader "1" "Members added to Global Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "632" -or $_.EventID -eq "4728"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose # ---- Members removed from Global Groups ---- $MyReport += Get-CustomHeader "1" "Members removed from Global Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "633" -or $_.EventID -eq "4729"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose # ---- Members added to Universal Groups ---- $MyReport += Get-CustomHeader "1" "Members added to Universal Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "660" -or $_.EventID -eq "4756"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose # ---- Members removed from Universal Groups ---- $MyReport += Get-CustomHeader "1" "Members removed from Universal Groups on domaincontroller $domaincontroller" $MyReport += Get-HTMLTable ($eventlog | Where-Object {$_.EventID -eq "661" -or $_.EventID -eq "4757"} | select TimeGenerated,Message ) $MyReport += Get-CustomHeaderClose $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose } $Date = Get-Date $Filename = "C:\\Temp\\" + "DailyReport" + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm" $MyReport | out-file -encoding ASCII -filepath $Filename
PowerShellCorpus/PoshCode/Invoke-LocalizedScript.p.ps1
Invoke-LocalizedScript.p.ps1
Set-StrictMode -Version Latest\n\n## Create some default messages for English cultures, and\n## when culture-specific messages are not available.\n$messages = DATA {\n @{\n Greeting = "Hello, {0}"\n Goodbye = "So long."\n }\n}\n\n## Import localized messages for the current culture.\nImport-LocalizedData messages -ErrorAction SilentlyContinue\n\n## Output the localized messages\n$messages.Greeting -f "World"\n$messages.Goodbye
PowerShellCorpus/PoshCode/Convert-BounceToX_3.ps1
Convert-BounceToX_3.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/9efa67c2-1147-4c7c-92f8-98b63b15cebd.ps1
9efa67c2-1147-4c7c-92f8-98b63b15cebd.ps1
Function Get-VMHostNetworks { <# .SYNOPSIS Return a list of networks from a given host .DESCRIPTION After connecting to your VI server, we get a list of virtual switches on the datacenter and from that we pull out the VHostID that matches the server we passed in at the command-line. Using the VHostID we return a list of networks objects on that server. .PARAMETER VMHost The name of the VMWare Host Server to pull networks from .PARAMETER VIServer The name of your VSPhere Server .EXAMPLE Get-VMHostNetworks -VMHost v1.copmany.com -VIServer vc.company.com Name Key VLanId PortBinding NumPorts ---- --- ------ ----------- -------- Management Network key-vim.host.PortGroup-Mana... 0 DMZ Network key-vim.host.PortGroup-DMZ ... 100 Admin Network key-vim.host.PortGroup-Admi... 101 Description ----------- This shows the output from the command using all parameters. .NOTES This script requires the VMware vSphere PowerCLI to be downloaded and installed, please see the second link for the download. .LINK http://scripts.patton-tech.com/wiki/PowerShell/VMWareManagement#Get-VMHostNetworks .LINK http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Connect-VIServer.html .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualSwitch.html .LINK http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualPortGroup.html #> Param ( [string]$VMHost, [string]$VIServer ) Begin { Try { Connect-VIServer -Server $VIServer $VSwitches = Get-VirtualSwitch } Catch { Return $Error[0] } } Process { foreach ($Vswitch in $VSwitches) { If ($VSwitch.VMHost.Name -like "$($VMhost)*") { $VHostID = $VSwitch.VMHost.Id } } $VMNetworks = Get-VirtualPortGroup |Where-Object {$_.VMhostID -eq $VhostID} } End { Return $VMNetworks } }
PowerShellCorpus/PoshCode/Xml Module 4.6.ps1
Xml Module 4.6.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. $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } filter Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Path # The path to an xml document (on disc or any other content provider). #.Parameter Indent # The indent level (defaults to 2 spaces) #.Example # [xml]$xml = get-content Data.xml # C:\\PS>Format-Xml $xml #.Example # get-content Data.xml | Format-Xml #.Example # Format-Xml C:\\PS\\Data.xml #.Example # ls *.xml | Format-Xml # [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. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets [CmdletBinding()] param( [Parameter(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 { $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 -Xml $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 -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace -EA 0 function New-XDocument { #.Synopsis # Creates a new XDocument (the new xml document type) #.Description # This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML # It creates a new XDocument, and takes scritpblock(s) to define it's contents #.Parameter root # The root node name #.Parameter version # Optional: the XML version. Defaults to 1.0 #.Parameter encoding # Optional: the Encoding. Defaults to UTF-8 #.Parameter standalone # Optional: whether to specify standalone in the xml declaration. Defaults to "yes" #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) # #.Example # [string]$xml = New-XDocument rss -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # item { # title {"The First Item"} # link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # description {"Ema Lazarus' Poem"} # pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"} # } # } # } # # C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # C:\\PS>$xml.ToString() # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss version="2.0"> # <channel> # <title>Test RSS Feed</title> # <link>http ://HuddledMasses.org</link> # <description>An RSS Feed generated simply to demonstrate my XML DSL</description> # <item> # <title>The First Item</title> # <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link> # <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid> # <description>Ema Lazarus' Poem</description> # <pubDate>2003-10-31T00:00:00Z</pubDate> # </item> # </channel> # </rss> # # # Description # ----------- # This example shows the creation of a complete RSS feed with a single item in it. # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output. # # #.Example # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc { # title {"Test First Entry"} # link {"http`://HuddledMasses.org"} # updated {(Get-Date -f u) -replace " ","T"} # author { # name {"Joel Bennett"} # uri {"http`://HuddledMasses.org"} # } # id {"http`://huddledmasses.org/" } # # entry { # title {"Test First Entry"} # link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" } # id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" } # updated {(Get-Date 10/31/2003 -f u) -replace " ","T"} # summary {"Ema Lazarus' Poem"} # link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution" # dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" } # category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses" # } # } | % { $_.Declaration.ToString(); $_.ToString() } # # <?xml version="1.0" encoding="UTF-16" standalone="yes"?> # <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom"> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org</link> # <updated>2009-07-29T17:25:49Z</updated> # <author> # <name>Joel Bennett</name> # <uri>http ://HuddledMasses.org</uri> # </author> # <id>http ://huddledmasses.org/</id> # <entry> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link> # <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id> # <updated>2003-10-31T00:00:00Z</updated> # <summary>Ema Lazarus' Poem</summary> # <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" /> # <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights> # <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" /> # </entry> # </feed> # # # Description # ----------- # This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString(). # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.# # [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") )) } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUgCBQLQ8Wt+HKMRoDZyZDej8R # Mm2gggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj # dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY # BgNVBAoMEVhlcm94IENvcnBvcmF0aW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ShellCorpus/PoshCode/Test-IPMask_1.ps1
Test-IPMask_1.ps1
<# .SYNOPSIS Tests for a valid IP mask. .DESCRIPTION The Test-IPMask script validates the input string against all CIDR subnet masks and returns a boolean value. .PARAMETER IPMask The IP mask to be evaluated. .EXAMPLE Test-IPMask 255.255.255.0 Description ----------- Tests if the IP mask "255.255.255.0" is a valid CIDR subnet mask. .INPUTS System.String .OUTPUTS System.String System.Boolean .NOTES Name: Test-IPMask.ps1 Author: Rich Kusak (rkusak@cbcag.edu) Created: 2011-01-03 LastEdit: 2011-01-05 00:49 Version 1.0.0 #Requires -Version 2.0 .LINK http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing .LINK about_regular_expressions #> [CmdletBinding()] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [string]$IPMask ) begin { # Common subnet mask values $common = '0|128|192|224|240|248|252|254|255' # Build a regular expression to represent all possible mask strings $masks = @( "(^($common)\\.0\\.0\\.0$)" "(^255\\.($common)\\.0\\.0$)" "(^255\\.255\\.($common)\\.0$)" "(^255\\.255\\.255\\.($common)$)" ) # Join all possible strings with the regex "or" operator $regex = [string]::Join('|', $masks) } process { # Evaluate the IPMask input and output the result [regex]::Match($IPMask, $regex) | Select @{name='IPMask' ; expression={$IPMask}}, @{name='Valid' ; expression={$_.Success}} }
PowerShellCorpus/PoshCode/New-ObjectRecursive.ps1
New-ObjectRecursive.ps1
<# .Synopsis Creates new object based on hashtable definition .Description Function is wrapper for New-Object that allows user to create nested objects using nested hashtable as definition. If you want to take advantage of type use 'Type' key within hashtable that defines object. .Example $obj = New-ObjectRecursive @{Test = @{ InnerTest = 'Value'; AnotherInner = 'Another'; InnerwithInner = @{ Deepest = 'It is very deep'}}; Flat = 'SomeValue'} $obj.Test.InnerwithInner.Deepest It is very deep Create simpe custom object with several inner psobjects, depending of hashtable structure. .Example (New-ObjectRecursive @{ Type = 'Windows.Forms.Form'; Size = @{ Type = 'Drawing.Size'; width = 400; Height = 400}; Text = 'Title of window'}).ShowDialog() Display windows form of size 400 x 400 and title 'Title of window', assuming Windows.Forms are loaded. #> param( $Property ) if ($Property -is [hashtable]) { if ($Type = $Property.Type) { $Property.Remove('Type') } else { $Type = 'PSObject' } $PropertyHash = @{} foreach ($key in $Property.keys) { $PropertyHash.Add($key, $(New-ObjectRecursive $Property[$key])) } Try { New-Object $Type -Property $PropertyHash -ErrorAction SilentlyContinue if (!$?) { Write-Host -ForegroundColor Red $Error[0].Exception.Message } } catch { Write-Host -ForegroundColor Red "Problems with creating object of type: $Type. Try to use PSObject instead . . ." New-Object PSObject -Property $PropertyHash -ErrorAction SilentlyContinue Write-Host -ForegroundColor Red "Error message:" $_.Exception.Message } } else { $Property }
PowerShellCorpus/PoshCode/Get-Credential 2.4.ps1
Get-Credential 2.4.ps1
## Get-Credential ## An improvement over the default cmdlet which has no options ... ################################################################################################### ## History ## v 2.4 Fix a bug in -Store when the UserName isn't passed in as a parameter ## v 2.3 Add -Store switch and support putting credentials into the file system ## v 2.1 Fix the comment help and parameter names to agree with each other (whoops) ## v 2.0 Rewrite for v2 to replace the default Get-Credential ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit ## v 1.1 Add -Console switch and set registry values accordingly (ouch) ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet ################################################################################################### function Get-Credential { ## .Synopsis ## Gets a credential object based on a user name and password. ## .Description ## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations. ## ## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically. [CmdletBinding(DefaultParameterSetName="Prompted")] PARAM( # A default user name for the credential prompt, or a pre-existing credential (would skip all prompting) [Parameter(ParameterSetName="Prompted",Position=1,Mandatory=$false)] [Parameter(ParameterSetName="Promptless",Position=1,Mandatory=$true)] [Parameter(ParameterSetName="StoreCreds",Position=1,Mandatory=$true)] [Parameter(ParameterSetName="Flush",Position=1,Mandatory=$true)] [Alias("Credential")] [PSObject]$UserName=$null , # Allows you to override the default window title of the credential dialog/prompt # # You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it. [Parameter(ParameterSetName="Prompted",Position=2,Mandatory=$false)] [string]$Title=$null , # Allows you to override the text displayed inside the credential dialog/prompt. # # You can use this for things like presenting an explanation of what you need the credentials for. [Parameter(ParameterSetName="Prompted",Position=3,Mandatory=$false)] [string]$Message=$null , # Specifies the default domain to use if the user doesn't provide one (by default, this is null) [Parameter(ParameterSetName="Prompted",Position=4,Mandatory=$false)] [string]$Domain=$null , # The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\". [Parameter(ParameterSetName="Prompted",Mandatory=$false)] [switch]$GenericCredentials , # Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE) [Parameter(ParameterSetName="Prompted",Mandatory=$false)] [switch]$Inline , # Store the credential in the file system (and overwrite them) [Parameter(ParameterSetName="Prompted",Mandatory=$false)] [Parameter(ParameterSetName="Promptless",Mandatory=$false)] [Parameter(ParameterSetName="StoreCreds",Mandatory=$true)] [switch]$Store , # Remove stored credentials from the file system [Parameter(ParameterSetName="Flush",Mandatory=$true)] [switch]$Flush , # Allows you to override the path to store credentials in [Parameter(ParameterSetName="Prompted",Mandatory=$false)] [Parameter(ParameterSetName="Promptless",Mandatory=$false)] [Parameter(ParameterSetName="StoreCreds",Mandatory=$false)] $CredentialFolder = $(Join-Path ${Env:APPDATA} Credentials) , # The password [Parameter(ParameterSetName="Promptless",Position=5,Mandatory=$true)] $Password = $( if($UserName -and (Test-Path "$(Join-Path $CredentialFolder $UserName).cred")) { if($Flush) { Remove-Item "$(Join-Path $CredentialFolder $UserName).cred" } else { Get-Content "$(Join-Path $CredentialFolder $UserName).cred" | ConvertTo-SecureString } }) ) process { [PSCredential]$Credential = $null if( $UserName -is [System.Management.Automation.PSCredential]) { $Credential = $UserName } elseif($UserName -ne $null) { $UserName = $UserName.ToString() } if($Password) { if($Password -isnot [System.Security.SecureString]) { [char[]]$Chars = $Password.ToString().ToCharArray() $Password = New-Object System.Security.SecureString foreach($c in $chars) { $Password.AppendChar($c) } } $Credential = New-Object System.Management.Automation.PSCredential $UserName, $Password } if(!$Credential) { if($Inline) { if($Title) { Write-Host $Title } if($Message) { Write-Host $Message } if($Domain) { if($UserName -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } if(!$UserName) { $UserName = Read-Host "User" if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } $Credential = New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString) } if($GenericCredentials) { $Type = "Generic" } else { $Type = "Domain" } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. ## BugBug? PowerShell.exe disregards the last parameter $Credential = $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Type, "Default") } if($Store) { $CredentialFile = "$(Join-Path $CredentialFolder $Credential.UserName).cred" if(!(Test-Path $CredentialFolder)) { mkdir $CredentialFolder | out-null } $Credential.Password | ConvertFrom-SecureString | Set-Content $CredentialFile } return $Credential } }
PowerShellCorpus/PoshCode/Get-VMStorageAdapters.ps1
Get-VMStorageAdapters.ps1
<# .SYNOPSIS Reports on Fibre Channel Adapters in the ESX hosts for a vCenter environment. .DESCRIPTION This script iterates through each Datacenter,Cluster, and Host in a vCenter environment and then lists the Fibre Channel HBAs that are present. .LINK .EXAMPLE PS> Get-VMStorageAdapters.ps1 -FileName hba.txt This example runs the script and directs output to be saved to hba.txt in addition to the console. .PARAMETER Server Connect to the specified vCenter server for the environment you wish to collect information from. .PARAMETER Credential Credential to connect to the vCenter server. If no credentials are specified script will prompt for them. .PARAMETER FileName Name of text file to save script output in addition to the console .NOTES Name: Get-VMStorageAdapters Author: Mark E. Schill Date Created: 10/01/2009 Date Revised: 10/01/2009 Version: 1.0 History: 1.0 10/01/2009 - Initial Revision #requires –Version 2.0 #requires -PsSnapIn VMware.VimAutomation.Core -Version 2 #> [CmdletBinding()] param( [Parameter(Position=1,Mandatory=$false)] [Alias("VIServer")] $Server , [Parameter(Position=2,Mandatory=$false)] [Alias("PSCredential")] [System.Management.Automation.PSCredential]$Credential , [Parameter(Position=3,Mandatory=$False)] $FileName ) Begin { # Were credentials specified? If not then prompt for them. if(!$Credential) { $Credential = Get-Credential } # Are we outputing to file? If so then set filename and create. if ($FileName) { $ScriptPath = Split-Path $MyInvocation.MyCommand.Definition -Parent $FileName = "$ScriptPath\\$FileName" Set-Content -Path $FileName -Value "" -force } #Connect to vCenter Server Connect-VIServer -Server $VIServer -Credential $Credential #Iterate Datacenters Get-Datacenter | % { Write-Host $([string]::Format( "{0}",$_.Name)) -ForegroundColor Cyan if ($FileName) {Add-Content -Path $FileName -Value $([string]::Format( "{0}",$_.Name))} #Iterate Clusters Get-Cluster -Location $_ | % { Write-Host $([string]::Format( "`t{0}",$_.Name)) -ForegroundColor Cyan if ($FileName) {Add-Content -Path $FileName -Value $([string]::Format( "`t{0}",$_.Name))} #Iterate ESX Hosts Get-VMHost -Location $_ | % { Write-Host $([string]::Format( "`t`t{0}",$_.Name)) -ForegroundColor Cyan if ($FileName) {Add-Content -Path $FileName -Value $([string]::Format( "`t`t{0}",$_.Name))} #Iterate through storage adapters on server and filter out Fibre Channel Adapters. $StorageView = Get-VMHostStorage -VMHost $_ | Get-View $StorageAdapter = $StorageView.StorageDeviceInfo.HostBusAdapter $StorageAdapter | % { if ( $_.key -match "FibreChannelHba" ) { # Output the Device Name and Port and Node WWNs respectively. Write-Host $([string]::Format("`t`t`t{0} {1:X} {2:X}",$_.Device, $_.PortWorldWideName, $_.NodeWorldWideName)) -ForegroundColor Yellow if ($FileName) {Add-Content -Path $FileName -Value $([string]::Format("`t`t`t{0} {1:X} {2:X}",$_.Device, $_.PortWorldWideName, $_.NodeWorldWideName))} } } } } } } Process { } End { }
PowerShellCorpus/PoshCode/ProcessSnapshot.ps1
ProcessSnapshot.ps1
function Get-ProcessList { #snapshot time $now = Get-Date -f 'HH:mm:ss' #building list [int]$hndl = 0 $script:ret = @() ps | % -b {$arr = @()} -p { $str = "" | select Name, StartTime, PID, PM, WS, Desc, Publ $str.Name = $_.ProcessName $str.StartTime = $(try { $_.StartTime} catch { return [DateTime]::MinValue }) $str.PID = $_.Id $str.PM = $_.PrivateMemorySize64 $str.WS = $_.WorkingSet64 $str.Desc = $_.Description $str.Publ = $_.Company $arr += $str; $hndl += $_.Handles } -end { $arr | sort StartTime | % { try { $dgvView.Rows.Add($_.Name, $_.PID, ($_.PM / 1Kb), ($_.WS / 1Kb), $_.Desc, $_.Publ) $script:ret += $_.PID } catch {} } } #counting processes $sbPnl_1.Text = "Processes: " + $script:ret.Count #counting NET processes $net = @($clr.GetInstanceNames() | ? {$_ -ne "_Global_"} | % {ps -ea 0 $_}).Count $sbPnl_2.Text = ".NET Processes: " + $net #total handles $sbPnl_3.Text = "Handles: " + $hndl #current snapshot $sbPnl_4.Text = "Snap at: " + $now } $mnuSUpd_Click= { $dgvView.Rows.Clear() Get-ProcessList } $mnuFont_Click= { (New-Object Windows.Forms.FontDialog) | % { $_.MaxSize = 11 $_.ShowEffects = $false if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { $dgvView.Font = $_.Font $lstView.Font = $_.Font } } } $mnuPane_Click= { switch ([bool]$mnuPane.Checked) { $true { $mnuPane.Checked = $false; $scSplit.Panel2Collapsed = $true; break; } $false { $mnuPane.Checked = $true; $scSplit.Panel2Collapsed = $false; break; } } } $mnuSBar_Click= { [bool]$toggle =! $mnuSBar.Checked $mnuSBar.Checked = $toggle $sbStats.Visible = $toggle } $dgvView_Click= { $lstView.Items.Clear() $row = $dgvView.CurrentCell.RowIndex try { (ps | ? {$_.Id -eq $script:ret[$row]}).Modules | % { $itm = $lstView.Items.Add($_.ModuleName) $itm.SubItems.Add($_.Size) $itm.SubItems.Add($_.Description) $itm.SubItems.Add($_.Company) $itm.SubItems.Add($_.FileName) $itm.SubItems.Add($('0x{0:X}' -f [int]$_.BaseAddress)) $itm.SubItems.Add($_.ProductVersion) } } catch {} #last selected update $sbPnl_5.Text = "Last selected (PID): " + $script:ret[$row] } $frmMain_Load= { Get-ProcessList $sbPnl_5.Text = "Last selected (PID): <none>" } function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() $clr = New-Object Diagnostics.PerformanceCounterCategory(".NET CLR Memory") $usr = [Security.Principal.WindowsIdentity]::GetCurrent() $frmMain = New-Object Windows.Forms.Form $mnuMain = New-Object Windows.Forms.MainMenu $mnuFile = New-Object Windows.Forms.MenuItem $mnuSUpd = New-Object Windows.Forms.MenuItem $mnuEmp1 = New-Object Windows.Forms.MenuItem $mnuExit = New-Object Windows.Forms.MenuItem $mnuView = New-Object Windows.Forms.MenuItem $mnuFont = New-Object Windows.Forms.MenuItem $mnuEmp2 = New-Object Windows.Forms.MenuItem $mnuPane = New-Object Windows.Forms.MenuItem $mnuSBar = New-Object Windows.Forms.MenuItem $mnuTool = New-Object Windows.Forms.MenuItem $mnuFind = New-Object Windows.Forms.MenuItem $mnuAsms = New-Object Windows.Forms.MenuItem $mnuHelp = New-Object Windows.Forms.MenuItem $mnuInfo = New-Object Windows.Forms.MenuItem $scSplit = New-Object Windows.Forms.SplitContainer $dgvView = New-Object Windows.Forms.DataGridView $lstView = New-Object Windows.Forms.ListView $chView1 = New-Object Windows.Forms.ColumnHeader $chView2 = New-Object Windows.Forms.ColumnHeader $chView3 = New-Object Windows.Forms.ColumnHeader $chView4 = New-Object Windows.Forms.ColumnHeader $chView5 = New-Object Windows.Forms.ColumnHeader $chView6 = New-Object Windows.Forms.ColumnHeader $chView7 = New-Object Windows.Forms.ColumnHeader $sbStats = New-Object Windows.Forms.StatusBar $sbPnl_1 = New-Object Windows.Forms.StatusBarPanel $sbPnl_2 = New-Object Windows.Forms.StatusBarPanel $sbPnl_3 = New-Object Windows.Forms.StatusBarPanel $sbPnl_4 = New-Object Windows.Forms.StatusBarPanel $sbPnl_5 = New-Object Windows.Forms.StatusBarPanel # #mnuMain # $mnuMain.MenuItems.AddRange(@($mnuFile, $mnuView, $mnuTool, $mnuHelp)) # #mnuFile # $mnuFile.MenuItems.AddRange(@($mnuSUpd, $mnuEmp1, $mnuExit)) $mnuFile.Text = "&File" # #mnuSUpd # $mnuSUpd.Shortcut = "F5" $mnuSUpd.Text = "&Refresh Now" $mnuSUpd.Add_Click($mnuSUpd_Click) # #mnuEmp1 # $mnuEmp1.Text = "-" # #mnuExit # $mnuExit.Shortcut = "CtrlX" $mnuExit.Text = "E&xit" $mnuExit.Add_Click({$frmMain.Close()}) # #mnuView # $mnuView.MenuItems.AddRange(@($mnuFont, $mnuEmp2, $mnuPane, $mnuSBar)) $mnuView.Text = "&View" # #mnuFont # $mnuFont.Text = "&Font..." $mnuFont.Add_Click($mnuFont_Click) # #mnuEmp2 # $mnuEmp2.Text = "-" # #mnuPane # $mnuPane.Shortcut = "CtrlD" $mnuPane.Text = "&DLLs Lower Pane" $mnuPane.Add_Click($mnuPane_Click) # #mnuSBar # $mnuSbar.Checked = $true $mnuSBar.Shortcut = "CtrlB" $mnuSBar.Text = "Toggle Status &Bar" $mnuSBar.Add_Click($mnuSBar_Click) # #mnuTool # $mnuTool.MenuItems.AddRange(@($mnuFind, $mnuAsms)) $mnuTool.Text = "&Tools" # #mnuFind # $mnuFind.Shortcut = "CtrlF" $mnuFind.Text = "&Find DLL..." $mnuFind.Add_Click({frmFind_Show}) # #mnuAsms # $mnuAsms.Text = "&Loaded Assemblies" $mnuAsms.Add_Click({frmAsms_Show}) # #mnuHelp # $mnuHelp.MenuItems.AddRange(@($mnuInfo)) $mnuHelp.Text = "&Help" # #mnuInfo # $mnuInfo.Text = "About..." $mnuInfo.Add_Click({frmInfo_Show}) # #scSplit # $scSplit.Dock = "Fill" $scSplit.Orientation = "Horizontal" $scSplit.Panel1.Controls.Add($dgvView) $scSplit.Panel2.Controls.Add($lstView) $scSplit.Panel2Collapsed = $true # #dgvView # $dgvView.AutoSizeColumnsMode = "AllCells" $dgvView.ColumnCount = 6 $dgvView.Columns[0].Name = "Process" $dgvView.Columns[1].Name = "PID" $dgvView.Columns[2].Name = "Private Bytes (K)" $dgvView.Columns[3].Name = "Working Set (K)" $dgvView.Columns[4].Name = "Description" $dgvView.Columns[5].Name = "Company Name" #$dgvView.ColumnHeadersHeightSizeMode = "AutoSize" $dgvView.Dock = "Fill" $dgvView.MultiSelect = $false $dgvView.Add_Click($dgvView_Click) # #lstView # $lstView.AllowColumnReorder = $true $lstView.Columns.AddRange(@($chView1, $chView2, $chView3, ` $chView4, $chView5, $chView6, $chView7)) $lstView.Dock = "Fill" $lstView.FullRowSelect = $true $lstView.ShowItemToolTips = $true $lstView.Sorting = "Ascending" $lstView.View = "Details" # #chView1 # $chView1.Text = "Name" $chView1.Width = 90 # #chView2 # $chView2.Text = "Size" $chView2.TextAlign = "Right" $chView2.Width = 50 # #chView3 # $chView3.Text = "Description" $chView3.Width = 190 # #chView4 # $chView4.Text = "Company Name" $chView4.Width = 150 # #chView5 # $chView5.Text = "Path" $chView5.Width = 289 # #chView6 # $chView6.Text = "Base" $chView6.TextAlign = "Right" $chView6.Width = 90 # #chView7 # $chView7.Text = "Version" $chView7.Width = 100 # #sbStats # $sbStats.Panels.AddRange(@($sbPnl_1, $sbPnl_2, $sbPnl_3, $sbPnl_4, $sbPnl_5)) $sbStats.ShowPanels = $true $sbStats.SizingGrip = $false # #sbPnl_1 # $sbPnl_1.AutoSize = "Contents" # #sbPnl_2 # $sbPnl_2.AutoSize = "Contents" # #sbPnl_3 # $sbPnl_3.AutoSize = "Contents" # #sbPnl_4 # $sbPnl_4.AutoSize = "Contents" # #sbPnl_5 # $sbPnl_5.AutoSize = "Contents" # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(790, 550) $frmMain.Controls.AddRange(@($scSplit, $sbStats)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.MaximizeBox = $false $frmMain.Menu = $mnuMain $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Process Snapshot [" + $usr.Name + "]" $frmMain.Add_Load($frmMain_Load) [void]$frmMain.ShowDialog() } ################################################################################################# $btnFind_Click= { $lstFind.Items.Clear() if ($txtFind.Text -ne "") { #checking items in current snapshot only $script:ret | % { foreach ($p in (ps -id $_)) { foreach ($m in $p.Modules) { if ($m.ModuleName -match $txtFind.Text) { $itm = $lstFind.Items.Add($p.Name) $itm.SubItems.Add($p.Id) $itm.SubItems.Add($m.FileName) } } } } } } function frmFind_Show { $frmFind = New-Object Windows.Forms.Form $txtFind = New-Object Windows.Forms.TextBox $btnFind = New-Object Windows.Forms.Button $lstFind = New-Object Windows.Forms.ListView $chFind1 = New-Object Windows.Forms.ColumnHeader $chFind2 = New-Object Windows.Forms.ColumnHeader $chFind3 = New-Object Windows.Forms.ColumnHeader # #txtFind # $txtFind.Location = New-Object Drawing.Point(13, 13) $txtFind.Width = 341 # #btnFind # $btnFind.Location = New-Object Drawing.Point(361, 12) $btnFind.Text = "Search" $btnFind.Add_Click($btnFind_Click) # #lstFind # $lstFind.Columns.AddRange(@($chFind1, $chFind2, $chFind3)) $lstFind.FullRowSelect = $false $lstFind.Location = New-Object Drawing.Point(13, 43) $lstFind.MultiSelect = $false $lstFind.Size = New-Object Drawing.Size(421, 190) $lstFind.ShowItemToolTips = $true $lstFind.View = "Details" # #chFind1 # $chFind1.Text = "Process" $chFind1.Width = 107 # #chFind2 # $chFind2.Text = "PID" $chFind2.Width = 45 # #chFind3 # $chFind3.Text = "Name" $chFind3.Width = 230 # #frmFind # $frmFind.ClientSize = New-Object Drawing.Size(447, 255) $frmFind.Controls.AddRange(@($txtFind, $btnFind, $lstFind)) $frmFind.FormBorderStyle = "FixedSingle" $frmFind.MaximizeBox = $false $frmFind.MinimizeBox = $false $frmFind.Text = "Process Snapshot Search" $frmFind.ShowInTaskbar = $false $frmFind.StartPosition = "CenterParent" [void]$frmFind.ShowDialog() } ################################################################################################# $empty = "<none>" function Get-AssembliesTree { $dom = [AppDomain]::CurrentDomain $tvAssem.Nodes.Clear() $dom.GetAssemblies() | % { $nod = New-Object Windows.Forms.TreeNode $nod.Text = $_.GetName().Name $nod.Tag = $_ $tvAssem.Nodes.Add($nod) $nod.Nodes.Add($empty) } } $tvAssem_BeforeExpand= { $_.Node.Nodes.Clear() foreach ($t in $_.Node.Tag.GetTypes()) { if ($t.IsPublic) { $new = $_.Node.Nodes.Add($t.FullName) $new.Tag = $t } } } $tvAssem_BeforeSelect= { $lstView.Items.Clear() $sbStats.Text = $_.Node.Tag foreach ($p in $_.Node.Tag.PSObject.Properties) { $itm = $lstView.Items.Add($p.Name) if ($p.Value -ne $null) { $itm.Subitems.Add($p.Value.ToString()) switch ($p.Value) { $true {$itm.ForeColor = "Blue"; break;} $false {$itm.ForeColor = "Crimson"; break;} } } else { $itm.ForeColor = "Gray" $itm.SubItems.Add("<NULL>") } } } function frmAsms_Show { $frmAsms = New-Object Windows.Forms.Form $mnuMain = New-Object Windows.Forms.MainMenu $mnuFile = New-Object Windows.Forms.MenuItem $mnuExit = New-Object Windows.Forms.MenuItem $scSplit = New-Object Windows.Forms.SplitContainer $tvAssem = New-Object Windows.Forms.TreeView $lstView = New-Object Windows.Forms.ListView $chView1 = New-Object Windows.Forms.ColumnHeader $chView2 = New-Object Windows.Forms.ColumnHeader $sbStats = New-Object Windows.Forms.StatusBar # #mnuMain # $mnuMain.MenuItems.AddRange(@($mnuFile)) # #mnuFile # $mnuFile.MenuItems.AddRange(@($mnuExit)) $mnuFile.Text = "&File" # #mnuExit # $mnuExit.Shortcut = "CtrlX" $mnuExit.Text = "E&xit" $mnuExit.Add_Click({$frmAsms.Close()}) # #scSplit # $scSplit.Dock = "Fill" $scSplit.Panel1.Controls.Add($tvAssem) $scSplit.Panel2.Controls.Add($lstView) $scSplit.SplitterWidth = 1 # #tvAssem # $tvAssem.Dock = "Fill" $tvAssem.Sorted = $true $tvAssem.Add_BeforeExpand($tvAssem_BeforeExpand) $tvAssem.Add_BeforeSelect($tvAssem_BeforeSelect) # #lstView # $lstView.Columns.AddRange(@($chView1, $chView2)) $lstView.Dock = "Fill" $lstView.FullRowSelect = $true $lstView.MultiSelect = $false $lstView.ShowItemToolTips = $true $lstView.Sorting = "Ascending" $lstView.View = "Details" # #chView1 # $chView1.Text = "Name" $chView1.Width = 205 # #chView2 # $chView2.Text = "Property Value" $chView2.Width = 300 # #sbStats # $sbStats.SizingGrip = $false # #frmAsms # $frmAsms.ClientSize = New-Object Drawing.Size(790, 550) $frmAsms.Controls.AddRange(@($scSplit, $sbStats)) $frmAsms.FormBorderStyle = "FixedSingle" $frmAsms.Menu = $mnuMain $frmAsms.ShowInTaskbar = $false $frmAsms.StartPosition = "CenterParent" $frmAsms.Text = "Process Snapshot Loaded Assemblies" $frmAsms.Add_Load({Get-AssembliesTree}) [void]$frmAsms.ShowDialog() } ################################################################################################# $frmInfo_Load= { $ico = [Drawing.Icon]::ExtractAssociatedIcon($($PSHome + "\\powershell.exe")) $pbImage.Image = $ico.ToBitmap() } function frmInfo_Show { $frmInfo = New-Object Windows.Forms.Form $pbImage = New-Object Windows.Forms.PictureBox $lblName = New-Object Windows.Forms.Label $lblCopy = New-Object Windows.Forms.Label $btnExit = New-Object Windows.Forms.Button # #pbImage # $pbImage.Location = New-Object Drawing.Point(16, 16) $pbImage.Size = New-Object Drawing.Size(32, 32) $pbImage.SizeMode = "StretchImage" # #lblName # $lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 9, [Drawing.FontStyle]::Bold) $lblName.Location = New-Object Drawing.Point(53, 19) $lblName.Size = New-Object Drawing.Size(360, 18) $lblName.Text = "Process Snapshot v1.00" # #lblCopy # $lblCopy.Location = New-Object Drawing.Point(67, 37) $lblCopy.Size = New-Object Drawing.Size(360, 23) $lblCopy.Text = "(C) 2013 greg zakharov gregzakh@gmail.com" # #btnExit # $btnExit.Location = New-Object Drawing.Point(135, 67) $btnExit.Text = "OK" # #frmInfo # $frmInfo.AcceptButton = $btnExit $frmInfo.CancelButton = $btnExit $frmInfo.ClientSize = New-Object Drawing.Size(350, 110) $frmInfo.ControlBox = $false $frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit)) $frmInfo.ShowInTaskBar = $false $frmInfo.StartPosition = "CenterParent" $frmInfo.Text = "About..." $frmInfo.Add_Load($frmInfo_Load) [void]$frmInfo.ShowDialog() } ################################################################################################# frmMain_Show
PowerShellCorpus/PoshCode/Invoke-VMCommand.ps1
Invoke-VMCommand.ps1
# Invoke-VMCommand.ps1 # Purpose : Run a remote command and return the results # Requirements: plink.exe from the Putty project must be in $env:path # Use -help parameter for instructions Param ( $VMHost, $username, $Command, [switch]$Help, [switch]$Verbose ) # Obtains list of VMX (config files) corresponding to each VM on a given ESX server function GetVMX ($user, $pass, $srv) { $cmd = "plink.exe $user@$srv -pw $pass" $cmd += " vmware-cmd -l" Write-Verbose "Command line: $cmd" $VMList = Invoke-Expression $cmd $collOut = @() $VmList | ForEach-Object { $objOut = "" | Select-Object VmHost, VmName, VMXpath, HasSnapshot # create our output object with desired properties $objOut.VmHost = $srv $objOut.VMXpath = $_ $objOut.VmName = (Split-Path $_ -Leaf) -replace ".vmx$" $collOut += $objOut } $collOut } function Get-ESXProcess($user, $pass, $srv){ $cmd = "plink.exe -t $user@$srv -pw $pass " $cmd += "`"ps -Af | grep `'`'`"" Write-Verbose "Command line: $cmd" $results = invoke-Expression $cmd $colObj = @() foreach($result in $results) { if($result -match "^UID"){continue} $myobj = "" | Select-Object UID,PID,PPID,C,STIME,TTY,TIME,CMD $ary = $result.split([string[]]" ",[System.StringSplitOptions]::RemoveEmptyEntries) $myobj.UID = $ary[0] $myobj.PID = $ary[1] $myobj.PPID = $ary[2] $myobj.C = $ary[3] $myobj.STIME = $ary[4] $myobj.TTY = $ary[5] $myobj.Time = $ary[6] $proc = $null write-verbose "Length: $($ary.Length)" for($i = 7;$i -le $ary.Length;$i++) { $proc = "$proc $($ary[$i])" write-Verbose "Adding [$i] $($ary[$i])" } Write-Verbose "COMMAND = $proc" $myobj.CMD = $proc $colObj += $myobj } $colObj } function Kill-Process{ Param($User,$Pass,$Srv,$killcmd) $cmd = "plink.exe -t $user@$srv -pw $pass " $killme = $killcmd.split(":")[1] Write-Verbose " - $killcmd" Write-Verbose " - $killme" if($killme -notmatch "^\\d") { $vmprocess = Get-ESXProcess $User $Pass $Srv | where{$_.Cmd -match $killme} $vmpid = $vmprocess.pid } else { $vmpid = $killme } $cmd += "`"kill -9 $vmpid`'`'`"" $results = invoke-Expression $cmd $results } function RunVMCommand ($user, $pass, $srv, $vmcmd) { $cmd = "plink.exe $user@$srv -pw $pass " $cmd += "`"$vmcmd | grep `'`'`"" Write-Verbose "Command line: $cmd" invoke-Expression $cmd } function GetSecurePass ($SecurePassword) { $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SecurePassword) $password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr) $password } # Returns help text function ShowUsage { $helptext = @" Invoke-VMCommand Requirements: plink.exe from the Putty project must be in your Path INPUT: VMHost : name or IP of ESX server(s) (REQUIRED) UserName : User to ssh With (REQUIRED) Command : Command to Run. This can be a GetVMX, PSList, Kill:<PID/VMName>, or a Custome String (REQUIRED) Help : shows usage "@ Write-Host $helptext } # Main if ($help) { ShowUsage; exit; } if ($verbose) { $verbosepreference = "continue" } $password = (Read-Host "Enter Password" -AsSecureString) if($Command -eq "GetVMX"){GetVMX $username (GetSecurePass $password) $VMHost} elseif($command -eq "PSList"){Get-ESXProcess $username (GetSecurePass $password) $VMHost} elseif($command -match "^KILL"){Kill-Process $username (GetSecurePass $password) $VMHost $command} else{RunVMCommand $username (GetSecurePass $password) $VMHost $Command}
PowerShellCorpus/PoshCode/Windows Startup Script.ps1
Windows Startup Script.ps1
<#====================================================================================== File Name : Startup.ps1 Original Author : Kenneth C. Mazie : Description : This is a personal startup script with pop-up notification and : checks to assure things are not already running. : : There are 2 samples included, taskmanager and Firefox. Add as many : as required. : : To call the script use the following in a shortcut or in the RUN registry key. : "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden –Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}" : Change the script name and path as needed to suit your environment. : : Be sure to enter the proper process name or errors will result. Use : "get-process" by itself to list running proces names that PowerShell : will be happy with, just make sure each app you want a name for is already : running first. : : A sleep delay is added to smooth out processing but can be removed if needed. : Notes : Sample script is safe to run as written. : Warnings : None. : : Last Update by : Kenneth C. Mazie (kcmjr) Version History : v1.0 - 05-03-12 - Original Change History : v1.1 - 00-00-00 - : =======================================================================================#> clear-host $Icon = [System.Drawing.SystemIcons]::Information $Notify = new-object system.windows.forms.notifyicon $Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none, specified in lines below following "tooltipicon" $Notify.visible = $true Function LoadApps { if((get-process "taskmgr" -ea SilentlyContinue) -eq $Null){start-process "C:\\Windows\\System32\\taskmgr.exe";$Notify.ShowBalloonTip(2500,"Custom Startup Script","Task Manager is loading",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,"Custom Startup Script","Task Manager is already running",[system.windows.forms.tooltipicon]::Info) } sleep (2) if((get-process "firefox" -ea SilentlyContinue) -eq $Null){start-process "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe";$Notify.ShowBalloonTip(2500,"Custom Startup Script","FireFox is loading",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,"Custom Startup Script","Firefox Already Running",[system.windows.forms.tooltipicon]::Info) } sleep (2) } LoadApps
PowerShellCorpus/PoshCode/Invoke-RemoteExpression_1..ps1
Invoke-RemoteExpression_1..ps1
############################################################################## ## ## Invoke-RemoteExpression ## ## From Windows PowerShell Cookbook (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) ## ############################################################################## <# .SYNOPSIS Invoke a PowerShell expression on a remote machine. Requires PsExec from http://live.sysinternals.com/tools/psexec.exe. If the remote machine supports PowerShell version two, use PowerShell remoting instead. .EXAMPLE Invoke-RemoteExpression \\\\LEE-DESK { Get-Process } Retrieves the output of a simple command from a remote machine .EXAMPLE (Invoke-RemoteExpression \\\\LEE-DESK { Get-Date }).AddDays(1) Invokes a command on a remote machine. Since the command returns one of PowerShell's primitive types (a DateTime object,) you can manipulate its output as an object afterward. .EXAMPLE Invoke-RemoteExpression \\\\LEE-DESK { Get-Process } | Sort Handles Invokes a command on a remote machine. The command does not return one of PowerShell's primitive types, but you can still use PowerShell's filtering cmdlets to work with its structured output. #> param( ## The computer on which to invoke the command. $ComputerName = "\\\\$ENV:ComputerName", ## The scriptblock to invoke on the remote machine. [Parameter(Mandatory = $true)] [ScriptBlock] $ScriptBlock, ## The username / password to use in the connection $Credential, ## Determines if PowerShell should load the user's PowerShell profile ## when invoking the command. [switch] $NoProfile ) Set-StrictMode -Version Latest ## Prepare the command line for PsExec. We use the XML output encoding so ## that PowerShell can convert the output back into structured objects. ## PowerShell expects that you pass it some input when being run by PsExec ## this way, so the 'echo .' statement satisfies that appetite. $commandLine = "echo . | powershell -Output XML " if($noProfile) { $commandLine += "-NoProfile " } ## Convert the command into an encoded command for PowerShell $commandBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptblock) $encodedCommand = [Convert]::ToBase64String($commandBytes) $commandLine += "-EncodedCommand $encodedCommand" ## Collect the output and error output $errorOutput = [IO.Path]::GetTempFileName() if($Credential) { ## This lets users pass either a username, or full credential to our ## credential parameter $credential = Get-Credential $credential $networkCredential = $credential.GetNetworkCredential() $username = $networkCredential.Username $password = $networkCredential.Password $output = psexec $computername /user $username /password $password ` /accepteula cmd /c $commandLine 2>$errorOutput } else { $output = psexec /acceptEula $computername ` cmd /c $commandLine 2>$errorOutput } ## Check for any errors $errorContent = Get-Content $errorOutput Remove-Item $errorOutput if($errorContent -match "(Access is denied)|(failure)|(Couldn't)") { $OFS = "`n" $errorMessage = "Could not execute remote expression. " $errorMessage += "Ensure that your account has administrative " + "privileges on the target machine.`n" $errorMessage += ($errorContent -match "psexec.exe :") Write-Error $errorMessage } ## Return the output to the user $output
PowerShellCorpus/PoshCode/image2excel.ps1
image2excel.ps1
None
PowerShellCorpus/PoshCode/Get-WarningsAndErrors.ps.ps1
Get-WarningsAndErrors.ps.ps1
##############################################################################\n##\n## Get-WarningsAndErrors\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the functionality of the Write-Warning, Write-Error, and throw\nstatements\n\n#>\n\nSet-StrictMode -Version Latest\n\nWrite-Warning "Warning: About to generate an error"\nWrite-Error "Error: You are running this script"\nthrow "Could not complete operation."
PowerShellCorpus/PoshCode/ScriptTransforms module_4.ps1
ScriptTransforms module_4.ps1
function New-ParameterTransform { #.Synopsis # Generates Parameter Transformation Attributes in simple PowerShell syntax #.Description # New-ParameterTransform allows the creation of .Net Attribute classes which can be applied to PowerShell parameters to transform or manipulate data as it's being passed in. #.Example # Transform TrimBraces { # param($string) # if($string -is [String] -and $string.Length -gt 2 -and $string[0] -eq '[' -and $string[-1] -eq ']') { # $string.SubString(1, $string.Length-2) # } else { # $string # } # } # # function Where-Type { # param( # [Type][TrimBraces()][String] # [Parameter(Mandatory=$true, Position=0)] # $Type, # # [Parameter(ValueFromPipeline=$true)] # $InputObject # ) # process { # if($InputObject -is $Type) { $InputObject } # } # } # # Description # ----------- # This example allows us to pass the "Type" to Where-Type with or without the [Braces] which would normally cause an exception when casting to a type: # # Get-ChildItem | Where-Type IO.FileInfo # # Get-ChildItem | Where-Type [IO.FileInfo] # # Get-ChildItem | Where-Type ([IO.FileInfo]) # #.Notes # It is possible to redefine transforms by name by running the New-ParameterTransform command again, but the type aliases that are generated are bound at function definition time, so any functions that are using the transform before it is redefined must also be redefined to take advantage of the new transform definition. # # v 1.4 Fixes crashes when the transform output is null # v 1.3 Fixes an ascii paste bug in the class name randomization # v 1.2 Randomization of class names with type accelerators # v 1.1 Modularization by "beefarino":http://poshcode.org/author/beefarino # v 1.0 Original code from Joel's blog [cmdletbinding()] param( # The name of the parameter transform to generate [Parameter(Mandatory=$true,Position=0)] [string] $name, # The script definition of the parameter transform [Parameter(Mandatory=$true, Position=1)] [scriptblock] $script ) end { $className = [Convert]::ToBase64String( ([Guid]::NewGuid().ToByteArray()) ).Replace('+',([char]241)).Replace('/',([char]223)).TrimEnd('=') $Type = Add-Type -Passthru -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ${name}Attribute${className} : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public ${name}Attribute${className}() { this.Script = ScriptBlock.Create( @" $($script.ToString() -replace '"','""' ) " ); } public override string ToString() { return Script.ToString(); } public override Object Transform( EngineIntrinsics engine, Object inputData) { Collection<PSObject> output; try { output = engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData ); } catch (ArgumentTransformationMetadataException) { throw; } catch (Exception e) { throw new ArgumentTransformationMetadataException( string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.", e.Message), e); } if(output == null || output.Count == 0 ) { throw new ArgumentTransformationMetadataException(NoOutputMessage); } if(output.Count > 1) { Object[] transformed = new Object[output.Count]; for(int i =0; i < output.Count;i++) { if(output[i] == null) { transformed[i] = null; } else { transformed[i] = output[i].BaseObject; } } return transformed; } else // (output.Count == 1) { if(output[0] == null) { return null; } return output[0].BaseObject; } } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") if($xlr8r::AddReplace) { $xlr8r::AddReplace( ${name}, $Type) } else { $null = $xlr8r::Remove( ${name} ) $xlr8r::Add( ${name}, $Type) } }} New-Alias -Name Transform -Value New-ParameterTransform; Export-ModuleMember -Alias Transform -Function * # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUiseSTw8ZDs4/WyAi4TlGsBiB # yUWggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp # Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy # dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw # MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp # BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV # BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 # IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J # 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj # Id6ZNavcSa6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+P3xlV2vlEJkk3etB/FpNDOQf8j # RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D # dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT # DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj # YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ # bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3 # AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBTNfKnuBQMU # THK1FpgQp3lahPwKODANBgkqhkiG9w0BAQEFAASCAQBy/tVZJPNVzpSJhoW28FmA # QF+7mZTBatgkRnvfEJ1QwMI7TkUZF3C0woOwmkNUfRuxLOITq9ZFE5zIDiQ3ijS1 # p6dpmH0EmBh2kBGBvJdw41/H/v3dyVRHMJgClXR2dL++j9bdFzsIHLhsQMuJSks/ # dX6a2ETq6+IMJ3TQA/qdLEJTUGvzfHGComW7pAI92ErM+SMQBbTeVtWOr4cbQxCW # 1+489NSS7FpWjyLyCazTUPFPHzv+gEmryNa6nBOKOJ4urXw9x08GSWqM8G821YVe # eYbbVSce5o1eu8vEREGpJMUotZCNmql8fOYN4TGXG7CNtfKojbeCzKyvE0GW1qd/ # SIG # End signature block
PowerShellCorpus/PoshCode/New-ISEMenu_3.ps1
New-ISEMenu_3.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/Get-DellWarranty_1.ps1
Get-DellWarranty_1.ps1
function Get-DellWarranty { <# .Synopsis Provides warranty information for one or more Dell service tags. .Description Queries the Dell Website for a list of service tags and returns the warranty information as a custom object. If a service tag has multiple warranties, they are returned as multiple separate objects. If no service tag is specified, it will attempt to retrieve and lookup the local system's service tag. The service tag can be provided to the command in several ways: 1. Using the -servicetag parameter 2. By passing one or more Service Tags via the pipeline 3. By passing objects that have either servicetag or serialnumber defined as a property, such as win32_bios WMI objects See examples for details. .Parameter ServiceTag ALIAS: serialnumber The Dell service tag you wish to query. Example: XYZ12A3 .Example C:\\PS> Get-DellWarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- If no service tags are provided, the script retrieves the local computer's serial number from WMI and queries for it. .Example C:\\PS> Get-DellWarranty -ServiceTag XXXX123 Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- You can pass the service tag as a parameter, or as the first positional parameter (e.g. Get-DellWarranty XXXX123) .Example C:\\PS> "XXXX123","XXXX124","XXXX125" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can pass serial numbers via the pipeline either directly or as a variable. .Example C:\\PS> get-wmiobject win32_bios -computername "computer1","computer2","1.2.3.4" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can also pass any object that has a "serialnumber" or "servicetag" property. In this example, we query computers directly for their serial numbers, and pass those results (which are WMI objects that have a serialnumber property) via pipeline directly to the command to obtain warranty information. .Notes AUTHOR: Justin Grote <jgrote NOSPAM-AT allieddigital NOSPAM-DOT net> WARNING: Since Dell does not provide a formal API, this script works by screen-scraping the HTML from the Dell product support site. Any future change to the layout or logic of this site will break the script or cause unpredictable results. HISTORY: v1.0 [31 Jan 2011] - Initial Module Creatio .Link http://support.dell.com/support/topics/global.aspx/support/my_systems_info #> [CmdletBinding()] param( [Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] [alias("serialnumber")] [string[]]$ServiceTag ) PROCESS { # If nothing was passed, retrieve the local system service tag if ($ServiceTag -eq $null) { write-verbose "No Service Tags provided. Using Local Computer's Service Tag" write-verbose "START Obtaining Serial number via WMI for localhost" $ServiceTag = (get-wmiobject win32_bios).SerialNumber write-verbose "SUCCESS Obtaining Serial number via WMI for localhost - $ServiceTag" } # Detect if an array of service tags were passed via parameter and unwind them. foreach ($strServicetag in $servicetag) { write-verbose "START Querying Dell for Service Tag $_" Get-DellWarrantyWorker $strServicetag write-verbose "SUCCESS Querying Dell for Service Tag $_" } } } Function Get-DellWarrantyWorker { Param( [String]$serviceTag ) #Dell Warranty URL Path $URL = "http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=$serviceTag" trap [System.FormatException] { write-error -category invalidresult "The service tag $serviceTag was not found. This is either because you entered the tag incorrectly, it is not present in Dell's database, or Dell changed the format of their website causing this search to fail." -recommendedaction "Please check that you entered the service tag correctly" return; } #Screenscrape the HTML for the warranty Table $HTML = (New-Object Net.WebClient).DownloadString($URL) If ($HTML -Match '<table[\\w\\s\\d"=%]*contract_table">.+?</table>') { $htmltable = $Matches[0] } else { throw (New-Object System.FormatException) } $HtmlLines = $htmltable -Split "<tr" | Where-Object { $_ -Match '<td' } $Header = ($HtmlLines[0] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*' | Where-Object { $_ -ne '' } #Convert the warranty table fields into a powershell object For ($i = 1; $i -lt $HtmlLines.Count; $i++) { $Output = New-Object PSObject $Output | Add-Member NoteProperty "Service Tag" -value $serviceTag $Values = ($HtmlLines[$i] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*|<a.+?>' For ($j = 1; $j -lt $Values.Count; $j++) { $Output | Add-Member NoteProperty $Header[$j - 1] -Value $Values[$j] } #Minor formatting fix if days remaining on warranty is zero if ($output.'Days Left' -match '<<0') {write-host -fore darkgreen "match!";$output.'Days Left' = 0} return $Output } }
PowerShellCorpus/PoshCode/Boots & Background Jobs_1.ps1
Boots & Background Jobs_1.ps1
## NOTE: This requires the current changeset download of PowerBoots (not the 0.2 beta) Import-Module PowerBoots # This simulates a download function, say Jaykul's Get-Webfile # You can output current progress for a large file, or if it's an array of links then out put the current (index/length)% # You will need to run the function as a background thread in order for it to not interfere with the UI thread (freezes UI) when called from event handler. Function global:Start-FakeDownload { $global:job = Start-Job { $max = 50 foreach ($i in $(1..$max)){ sleep 1 # lock up the thread for a second at a time ($i/$max) * 100 # return a number we can use for progress reporting } } } # GUI using boots. Registers controls as global variables. $global:Window = Boots -Width 250 -Async -Passthru -Title "Progress Meter" { DockPanel { ProgressBar -Height 25 -Name "Progress" -Dock Top | tee -var global:progress Statusbar { Textblock | Tee -var global:status } -Dock Bottom WrapPanel { Button "Download" -Name "Download" | tee -var global:download } -horizontalalignment center } -LastChildFill } # Add event handler for the Download button. # Runs Background job and updates Ui $download.Add_Click({ # Prevents download from being pressed while running ... causes overload with $timer. $download.IsEnabled = $false $download.Content = "Downloading..." # Get background job out and updates controls with value $updateblock = { # Notice the -Keep usage. Job result/output clears everytime you Receive-Job. # -Keep allows us to get the result from the background job multiple times and also serves as a marker to figure out when the job completes if($($job.State -eq "Running") -or $($($job.State -eq "Completed") -and $($(Receive-Job $job -Keep)[-1] -eq 100))){ Invoke-BootsWindow $Window { $progress.Value = $(Receive-Job $job -Keep)[-1] $status.Text = "$($(Receive-Job $job)[-1])`% done" } } if($($job.State -eq "Completed") -and $($(Receive-Job $job) -eq $null)){ Invoke-BootsWindow $Window { $status.Text = "Download Complete" } $timer.Stop() $download.Content = "Download" $download.IsEnabled = $true } } $timer = new-object System.Windows.Threading.DispatcherTimer $timer.Interval = [TimeSpan]"0:0:3" $timer.Add_Tick( $updateBlock ) Start-FakeDownload $timer.start() })
PowerShellCorpus/PoshCode/Solarized (Dark) Theme_1.ps1
Solarized (Dark) Theme_1.ps1
<?xml version="1.0" encoding="utf-16"?> <StorableColorTheme xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Keys> <string>ErrorForegroundColor</string> <string>ErrorBackgroundColor</string> <string>WarningForegroundColor</string> <string>WarningBackgroundColor</string> <string>VerboseForegroundColor</string> <string>VerboseBackgroundColor</string> <string>DebugForegroundColor</string> <string>DebugBackgroundColor</string> <string>OutputPaneBackgroundColor</string> <string>OutputPaneTextBackgroundColor</string> <string>OutputPaneForegroundColor</string> <string>CommandPaneBackgroundColor</string> <string>ScriptPaneBackgroundColor</string> <string>ScriptPaneForegroundColor</string> <string>TokenColors\\Attribute</string> <string>TokenColors\\Command</string> <string>TokenColors\\CommandArgument</string> <string>TokenColors\\CommandParameter</string> <string>TokenColors\\Comment</string> <string>TokenColors\\GroupEnd</string> <string>TokenColors\\GroupStart</string> <string>TokenColors\\Keyword</string> <string>TokenColors\\LineContinuation</string> <string>TokenColors\\LoopLabel</string> <string>TokenColors\\Member</string> <string>TokenColors\\NewLine</string> <string>TokenColors\\Number</string> <string>TokenColors\\Operator</string> <string>TokenColors\\Position</string> <string>TokenColors\\StatementSeparator</string> <string>TokenColors\\String</string> <string>TokenColors\\Type</string> <string>TokenColors\\Unknown</string> <string>TokenColors\\Variable</string> <string>ConsoleTokenColors\\Attribute</string> <string>ConsoleTokenColors\\Command</string> <string>ConsoleTokenColors\\CommandArgument</string> <string>ConsoleTokenColors\\CommandParameter</string> <string>ConsoleTokenColors\\Comment</string> <string>ConsoleTokenColors\\GroupEnd</string> <string>ConsoleTokenColors\\GroupStart</string> <string>ConsoleTokenColors\\Keyword</string> <string>ConsoleTokenColors\\LineContinuation</string> <string>ConsoleTokenColors\\LoopLabel</string> <string>ConsoleTokenColors\\Member</string> <string>ConsoleTokenColors\\NewLine</string> <string>ConsoleTokenColors\\Number</string> <string>ConsoleTokenColors\\Operator</string> <string>ConsoleTokenColors\\Position</string> <string>ConsoleTokenColors\\StatementSeparator</string> <string>ConsoleTokenColors\\String</string> <string>ConsoleTokenColors\\Type</string> <string>ConsoleTokenColors\\Unknown</string> <string>ConsoleTokenColors\\Variable</string> <string>XmlTokenColors\\Comment</string> <string>XmlTokenColors\\CommentDelimiter</string> <string>XmlTokenColors\\ElementName</string> <string>XmlTokenColors\\MarkupExtension</string> <string>XmlTokenColors\\Attribute</string> <string>XmlTokenColors\\Quote</string> <string>XmlTokenColors\\QuotedString</string> <string>XmlTokenColors\\Tag</string> <string>XmlTokenColors\\Text</string> <string>XmlTokenColors\\CharacterData</string> </Keys> <Values> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>203</R> <G>75</G> <B>22</B> <ScA>1</ScA> <ScR>0.5972018</ScR> <ScG>0.0703601</ScG> <ScB>0.008023193</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>38</R> <G>139</G> <B>210</B> <ScA>1</ScA> <ScR>0.0193823632</ScR> <ScG>0.258182883</ScG> <ScB>0.6444797</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>133</R> <G>153</G> <B>0</B> <ScA>1</ScA> <ScR>0.23455061</ScR> <ScG>0.3185468</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>181</R> <G>137</G> <B>0</B> <ScA>1</ScA> <ScR>0.462077022</ScR> <ScG>0.2501583</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>108</R> <G>113</G> <B>196</B> <ScA>1</ScA> <ScR>0.149959788</ScR> <ScG>0.1651322</ScG> <ScB>0.55201143</ScB> </Color> <Color> <A>255</A> <R>133</R> <G>153</G> <B>0</B> <ScA>1</ScA> <ScR>0.23455061</ScR> <ScG>0.3185468</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>88</R> <G>110</G> <B>117</B> <ScA>1</ScA> <ScR>0.0975873545</ScR> <ScG>0.155926466</ScG> <ScB>0.177888423</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>211</R> <G>211</G> <B>211</B> <ScA>1</ScA> <ScR>0.651405632</ScR> <ScG>0.651405632</ScG> <ScB>0.651405632</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>42</R> <G>161</G> <B>152</B> <ScA>1</ScA> <ScR>0.0231533684</ScR> <ScG>0.356400162</ScG> <ScB>0.313988745</ScB> </Color> <Color> <A>255</A> <R>203</R> <G>75</G> <B>22</B> <ScA>1</ScA> <ScR>0.5972018</ScR> <ScG>0.0703601</ScG> <ScB>0.008023193</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>38</R> <G>139</G> <B>210</B> <ScA>1</ScA> <ScR>0.0193823632</ScR> <ScG>0.258182883</ScG> <ScB>0.6444797</ScB> </Color> <Color> <A>255</A> <R>176</R> <G>196</G> <B>222</B> <ScA>1</ScA> <ScR>0.434153676</ScR> <ScG>0.55201143</ScG> <ScB>0.730460763</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>238</R> <G>130</G> <B>238</B> <ScA>1</ScA> <ScR>0.8549926</ScR> <ScG>0.223227978</ScG> <ScB>0.8549926</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>228</G> <B>181</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.7758222</ScG> <ScB>0.462077022</ScB> </Color> <Color> <A>255</A> <R>152</R> <G>251</G> <B>152</B> <ScA>1</ScA> <ScR>0.313988745</ScR> <ScG>0.9646863</ScG> <ScB>0.313988745</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>228</G> <B>196</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.7758222</ScG> <ScB>0.55201143</ScB> </Color> <Color> <A>255</A> <R>211</R> <G>211</G> <B>211</B> <ScA>1</ScA> <ScR>0.651405632</ScR> <ScG>0.651405632</ScG> <ScB>0.651405632</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>219</R> <G>112</G> <B>147</B> <ScA>1</ScA> <ScR>0.7083758</ScR> <ScG>0.162029386</ScG> <ScB>0.291770667</ScB> </Color> <Color> <A>255</A> <R>143</R> <G>188</G> <B>143</B> <ScA>1</ScA> <ScR>0.274677336</ScR> <ScG>0.5028865</ScG> <ScB>0.274677336</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>69</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.0595112443</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>100</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.127437681</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>128</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.215860531</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>139</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>0.258182883</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>140</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.2622507</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>255</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>139</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0.258182883</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>139</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0.258182883</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>128</R> <G>128</G> <B>128</B> <ScA>1</ScA> <ScR>0.215860531</ScR> <ScG>0.215860531</ScG> <ScB>0.215860531</ScB> </Color> </Values> @@ <Name>Solarized (Dark)</Name> <FontFamily>Consolas</FontFamily> <FontSize>14</FontSize> </StorableColorTheme>
PowerShellCorpus/PoshCode/GPRS Online log_2.ps1
GPRS Online log_2.ps1
<# .SYNOPSIS Get-GprsTime (V3.0 Update for Windows 7) Check the total connect time of any GPRS devices from a specified date. Use Get-Help .\\Get-GprsTime -full to view Help for this file. .DESCRIPTION Display all the GPRS modem Event Log entries. While applications issued by the mobile phone manufacturers will invariably monitor only their own usage, this will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc. Use the -Verbose switch for some extra information if desired. A default value can be set with the -Monthly switch but can be temporarily overridden with any -Start value and deleted by entering an invalid date. Now uses .NET Parse to use any culture date input. Switches -M and -S cannot be used together. A Balloon prompt will be issued in the Notification area for the 5 days before the nominal month end. NOTE: this can effectively be suppressed by using a value higher than the SIM card term, ie something like -Account 90 for a 30 day card which will override the default setting. Use -Today to check only today's usage. Define a function in $profile to set any permanent switches, for example to set the account value permanently to 30 days. function GPRS { Invoke-Expression "Get-GprsTime -Account 30 $args" } .EXAMPLE .\\Get-GprsTime.ps1 -Monthly 4/8/2011 This will set the default search date to start from 4/8/2011 and is used to reset the start date each month for the average 30/31 day SIM card. .EXAMPLE .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose Search from 12/07/2011 and also show (Verbose) details for each session. The Account switch will override any balloon prompt near the SIM expiry date. .EXAMPLE .\\Get-GprsTime.ps1 5/9/2011 -v Search one day only and show session details. .EXAMPLE .\\Get-GprsTime.ps1 -Today Show all sessions for today. This always defaults to verbose output. .EXAMPLE .\\Get-GprsTime.ps1 -Debug Shows the first available Event Log record and confirms switch settings. .NOTES A shorter total time than that actually used will result if the Event Log does not contain earlier dates; just increase the log size in such a case. The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a (binary compiled) Module version of this procedure is included in the file Gprs3038.zip download there; the execution time of the module being about 10 times faster than this script. For the Event Log to record connect & disconnect events, the modem software should be set to RAS rather than NDIS. #> Param ([String] $start, [String] $monthly, [Int] $account = 0, #Start warning prompt 5 days before month end. [Switch] $today, [Switch] $verbose, [Switch] $debug) Trap [System.Management.Automation.MethodInvocationException] { [Int]$line = $error[0].InvocationInfo.ScriptLineNumber [System.Media.SystemSounds]::Hand.Play() if ($line -eq 196) { Write-Warning "[$name] Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } else { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" } exit 1 } #Establish the Operating System...We only need to confirm XP or later. function Get-OSVersion($computer,[ref]$osv) { $os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer Switch ($os.Version) { "5.1.2600" { $osv.value = "xp" } default { "Version not listed" } } } $osv = $null $version = Get-OSVersion "localhost" ([ref]$osv) if ($osv -eq 'xp') { $logname = 'System' $connEvent = 20158 $discEvent = 20159 $source = 'RemoteAccess' } else { #Treat As Vista or Windows 7. $logname = 'Application' $connEvent = 20225 $discEvent = 20226 $source = 'RasClient' } $entryType = 'Information' $logEntry = $null $oldest = Get-eventlog -LogName $logname | #Get the earliest Log record. Where-Object {$_.Source -eq $source} | Where-Object {$_.EntryType -eq $entryType } | Sort-Object TimeGenerated | Select-Object -first 1 if ($oldest.TimeGenerated) { $logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())" } $name = $myInvocation.MyCommand $newLine = "[$name] The switches -Start and -Monthly can only be used separately." if ($debug) { $DebugPreference = 'Continue' } if ($start -and $monthly) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$newLine" exit 1 } $SCRIPT:form = "" #In certain cases Culture & UICulture can be different and have been known to # return conflicting results regarding '-is [DateTime]' queries, etc. if ($Host.CurrentCulture -eq $Host.CurrentUICulture) { $SCRIPT:form = '-Use format mm/dd/year' [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day. If ($culture -eq 6) { $SCRIPT:form = '-Use format dd/mm/year' } } $ErrorActionPreference = 'SilentlyContinue' $VerbosePreference = 'SilentlyContinue' $WarningPreference = 'Continue' $conn = $disc = $default = $print = $null $timeNow = [DateTime]::Now $total = $timeNow - $timeNow #Set initial value to 00:00:00. $insert = "since" if ($verbose) { $VerbosePreference = 'Continue' } function CreditMsg ($value, $value2) { $value = [Math]::Abs($value) $prefix = "CURRENT" [DateTime] $creditDT = $value2 $creditDT = $creditDT.AddDays($value) #Add the -Account days. $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format. #If we use '$number = $creditDT - (Get-Date)' instead of the line below we #can sometimes get a value of 1 returned instead 2, hence the above lines. $number = $creditDT - [DateTime] $thisDay [String] $credit = $creditDT $credit = $credit.Replace('00:00:00','') #Remove any trailing time. $credit = "{0:d}" -f [DateTime]$credit Switch($number.Days) { 1 {$prefix = "($value days) will expire tomorrow"; break} 0 {$prefix = "($value days) will expire today"; break} -1 {$prefix = "($value days) expired yesterday"; break} {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break} {($_ -le 5)} {$prefix = "($value days) will expire on $credit"} Default {$prefix = "CURRENT"} #Only come here if over 5 days. } return $prefix } function Interval ([String] $value) { Switch -regex ($value) { '^00:00:\\d+(.*)$' {$suffix = "seconds"; break} '^00:\\d+:\\d+(.*)$' {$suffix = "minutes"; break} '^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break} '^(\\d+)\\D(\\d+)(.*)$' {$suffix = " hours" $pDays = $matches[1] $pHours = $matches[2] [string]$pMinSec = $matches[3] [string]$tHours = (([int]$pDays) * 24)+[int]$pHours $value = $tHours + $pminSec; break} default {$suffix = " hours"} #Should never come here! } return "$value $suffix" } function CheckSetting ($value) { if ($value) { #Correct for local culture. $print = $default.ToShortDateString() } else { $print = "(Value not set)" } return $print } #The Script effectively starts here............................................. $getGprs = [Environment]::GetEnvironmentVariable("GPRS","User") #First check for GPRS variable and change from US date format to current locale. if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid. $default = "{0:d}" -f [datetime]$getGprs $default = [DateTime]::Parse($default) $checkParts = "{0:yyyy},{0:%M}" -f $default $times = $checkParts.Split(',') $dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31. if($account -eq 0) { $account = $dayCount $summary = "$($dayCount.ToString()) days" } else { $summary = "$($account.Tostring()) days" } $text = CreditMsg $account $getGprs #Check if within 5 days of expiry date. if ($text -ne "CURRENT") { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipTitle = "GPRS online account" $objNotifyIcon.BalloonTipText = "Credit $text" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) } } else { $summary = "(Days not set)" if ((!$today) -and (!$monthly) -and (!$start)) { [System.Media.SystemSounds]::Hand.Play() Write-Warning("Monthly date is either invalid or not set.") exit 1 } } if ($start) { $start = [DateTime]::Parse($start) #Trigger TRAP if invalid! [DateTime]$limit = $start $convert = "{0:D}" -f $limit $print = CheckSetting $default } if ($monthly) { $start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid! Write-Output "Setting GPRS (monthly) environment variable to: $monthly" $gprs = [String]$start.Replace('00:00:00','') [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User") [DateTime] $limit = $start #Change to required US date format. $convert = "{0:D}" -f $limit $print = $limit.ToShortDateString() $summary = "(Days undetermined)" #Will show next time around. } if ($today) { $verBosePreference = 'Continue' #Show VERBOSE by default. [DateTime] $limit = (Get-Date) $convert = "{0:D}" -f $limit $limit = $limit.Date #Override any start date if using -Today input. $insert = "for today" $print = CheckSetting $default } if ((!$today) -and (!$monthly) -and (!$start)) { if ($default) { $monthly = $default [DateTime] $limit = $monthly $convert = "{0:D}" -f $limit $print = CheckSetting $default } } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" if ($logEntry) { Write-Debug "$logEntry" } $lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)} if ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log." } else { Write-Output "(There are no events indicated in the System Event Log)" } $lines | ForEach-Object { $source = $_.Source if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = Interval $diff Write-Verbose "Disconnect at $convDisc. Online - $period" Write-Verbose " Connect at $convConn." } } #End ForEach if (!$source) { $source = '(Undetermined)' } Write-Verbose "Using local event source - System Event Log [$source]" $period = Interval $total Write-Output "Total online usage $insert $convert is $($period.Replace(' ',' '))." Write-Output ""
PowerShellCorpus/PoshCode/Show-Sample1.ps1
Show-Sample1.ps1
Show -Width 300 -Height 150 { DockPanel { Menu -DockPanel-Dock Top -Height 20 { MenuItem -Header "_File" { ## Hook up the "New" menuitem to the New command ... MenuItem -Header "_New" -Command ([system.windows.input.applicationcommands]::new) MenuItem -Header "_Open" MenuItem -Header "_Save" MenuItem -Header "Save _As" Separator MenuItem -Header "_Print" Separator MenuItem -Header "E_xit" } MenuItem -Header "_Edit" { MenuItem -Header "_Undo" Separator MenuItem -Header "Cu_t" MenuItem -Header "_Copy" MenuItem -Header "_Paste" MenuItem -Header "De_lete" Separator MenuItem -Header "_Find" MenuItem -Header "Find _Next" MenuItem -Header "_Replace" MenuItem -Header "_Go To" Separator MenuItem -Header "Select _All" MenuItem -Header "Time/_Date" } MenuItem -Header "F_ormat" { MenuItem -Header "_Word Wrap" MenuItem -Header "_Font" } MenuItem -Header "_View" { MenuItem -Header "_Status Bar" } MenuItem -Header "_Help" { MenuItem -Header "_About" } } TextBox -Name "Content" } ## Down here you can hook up command bindings as usual... $this.CommandBindings.Add( ( CommandBinding -Command ([system.windows.input.applicationcommands]::new) ` -On_CanExecute { param($sender, $e) $e.CanExecute = $true } ` -On_Executed { (Select-UIElement $this Content).Text = ""; } ) ) | Out-Null }
PowerShellCorpus/PoshCode/8c9f21a1-4924-4551-ae6d-1fc52d7751a4.ps1
8c9f21a1-4924-4551-ae6d-1fc52d7751a4.ps1
#################################################################################################### ## Write-Sitemap.ps1 ## ## Generates a basic Sitemap for your website, based on a list of locations / products or whatever, ## (depending on your requirements). Can easily be extended to create more complex Sitemaps. ## ## This uses XMLTextWriter and is based on the RSS creator script at ## http`://pshscripts.blogspot.com/2008/12/write-rssstreamps1.html ## ## Note the URLs in this script have been escaped. You may have to remove the backticks. #################################################################################################### ## Sitemap format, as output by this script (see http`://www.sitemaps.org/protocol.php for more) ## ## <?xml version="1.0" encoding="utf-8"?> ## <urlset xmlns="http`://www.google.com/schemas/sitemap/0.9"> ## <url> ## <loc>http`://your.url/here/product1</loc> ## </url> ## <url> ## <loc>http`://your.url/here/product2</loc> ## </url> ## </urlset> #################################################################################################### # Let's Set up some variables $workingdir = "c:\\scripts" $Domain = "http`://www.somesite.url" # Base URL - CHANGE THIS! $path = "$workingdir\\sitemap.xml" # Where the output file will go $Statics = @("help", "contact", "terms", "privacy") # Any static links go here $Locations = Get-Content "$workingdir\\products.txt" # A list of product IDs $Counter = 0 # Keep track of how many URLs we include. Must be less than 50k per file. # This function does the bulk of the work, creating a new <url> and <loc> element for each URL function CreateElement([string]$url) { $w = $global:writer $w.WriteStartElement("url") $w.WriteStartElement("loc") $w.WriteString($url) $w.WriteEndElement() #end loc $w.WriteEndElement() #end url $global:counter++ # Increment URL counter } #### MAIN ##### # Set up encoding, and create new instance of XMLTextWriter $encoding = [System.Text.Encoding]::UTF8 $writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding ) $writer.Formatting = [system.xml.formatting]::indented Write-Host "`r`n`r`nGenerating $Domain Sitemap... $path" # Write start of XML document $writer.WriteStartDocument() # Write Start of sitemap doc $writer.WriteStartElement( "urlset" ) $writer.WriteAttributeString( "xmlns", "http`://www.sitemaps.org/schemas/sitemap/0.9" ) # Write our static URLs foreach ($static in $statics) { CreateElement "$Domain/$Static" } # Write all location URLs foreach ($Location in $Locations) { $r = "$domain/product/$location" CreateElement $r } # You could add more URL definitions here as needed... # Write end of document information $writer.WriteEndElement() # End urlset # Make sure we close the file $writer.close() # Let's see what it has done # cat $path # See how many elements were output Write-Host "`n`rTotal number of URLs : $Counter" # If this is more than 50,000 we should split into multiple sitemap files...
PowerShellCorpus/PoshCode/7f98fa6b-12e6-4938-a5e7-254d4d3ef2dd.ps1
7f98fa6b-12e6-4938-a5e7-254d4d3ef2dd.ps1
Import-Module : Process should have elevated status to access IIS configuration data. At C:\\Users\\ca27573\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1:18 char:29 + Get-Module -ListAvailable | Import-Module + ~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [Import-Module], InvalidOperationException + FullyQualifiedErrorId : Module_ImportModuleError,Microsoft.PowerShell.Commands.ImportModuleCommand PSVersion Name --------- ---- 3.0 Microsoft.PowerShell.Core 1.0 Microsoft.EnterpriseManagement.OperationsManager.Client 2.0 VMware.VimAutomation.Core 1.0 Microsoft.Exchange.Management.PowerShell.E2010 1.0 Microsoft.Exchange.Management.Powershell.Support 1.0 Quest.ActiveRoles.ADManagement 2.0 VMware.DeployAutomation 2.0 VMware.ImageBuilder 2.0 VMware.VimAutomation.License ModuleType Name ---------- ---- Manifest ActiveDirectory Manifest AppLocker Script BackcompatCmdlets Manifest BitsTransfer Script BSonPosh Binary CimCmdlets Manifest GroupPolicy Script ISE Manifest Lync Manifest Microsoft.PowerShell.Diagnostics Manifest Microsoft.PowerShell.Host Manifest Microsoft.PowerShell.Management Manifest Microsoft.PowerShell.Security Manifest Microsoft.PowerShell.Utility Manifest Microsoft.WSMan.Management Script MyTools Script PSDiagnostics Binary PSScheduledJob Script PSTerminalServices Manifest PSWorkflow Manifest PSWorkflowUtility Script SetCsPinSendCAWelcomeMail Script startup Manifest TroubleshootingPack Manifest WebAdministration To list all cmdlets from a specific module use PS:> Get-Command -Module <Name> Welcome to the VMware vSphere PowerCLI! Log in to a vCenter Server or ESX host: Connect-VIServer To find out what commands are available, type: Get-VICommand To show searchable help for all PowerCLI commands: Get-PowerCLIHelp Once you've connected, display all virtual machines: Get-VM If you need more help, visit the PowerCLI community: Get-PowerCLICommunity Copyright (C) 1998-2012 VMware, Inc. All rights reserved. Loading custom functions library.
PowerShellCorpus/PoshCode/RegQuery.ps1
RegQuery.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Searches the registry key for the specified pattern on the specified computer ### Useful in finding installed S/W ### </Description> ### <Usage> ### ./RegQuery.ps1 Server1 "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" SQL ### </Usage> ### </Script> # --------------------------------------------------------------------------- param ($computer,$regkey,$pattern) $p = $($regkey -replace "HKLM","HKEY_LOCAL_MACHINE") -replace "\\\\","\\\\" $p += "(?<pattern>.*$pattern.*)" $matchArray = @() REG QUERY \\\\$computer\\$regKey | foreach { if ($_ -match $p) { $matchArray += $matches.pattern }} if ($matchArray.length -gt 0) { $matchArray | foreach {new-object psobject | add-member -pass NoteProperty computer $computer | add-member -pass NoteProperty pattern $_}} else {new-object psobject | add-member -pass NoteProperty computer $computer | add-member -pass NoteProperty pattern $null}
PowerShellCorpus/PoshCode/Get Virtual ESXi IP Addr_1.ps1
Get Virtual ESXi IP Addr_1.ps1
function Get-VirtualEsxiIp { param($vm) $tmpFileTemplate = ($env:TEMP + "\\ipdetect-") $tmpFile = $tmpFileTemplate + (Get-Random) + ".png" # Take the screenshot. $view = $vm | Get-View -Property Name $path = $view.CreateScreenShot() $path -match "([^/]+/[^/]+$)" | Out-Null $relativePath = $matches[1] # Determine the VM's datastore. $datastore = $vm | Get-Datastore $remotePath = ($datastore.DatastoreBrowserPath + "\\" + $relativePath) Write-Verbose ("Use remote path " + $remotePath) # Copy it locally. Requires PowerCLI 4.0 U1. Write-Verbose ($remotePath + ", " + $tmpFile) Copy-DatastoreItem $remotePath $tmpFile # OCR the screenshot. $output = Apply-Ocr -pngFile $tmpFile # Pull out the IP address. $output -match "http://([^/]+)" | Out-Null $ip = $matches[1] # Clean up. Write-Verbose "Cleaning up" # Remove-Item -Force $remotePath Remove-Item -Force $tmpFile # Output the IP. Write-Output $ip } # Apply OCR to a PNG file and return the text results. function Apply-Ocr { param($pngFile) $tmpFileTemplate = ($env:TEMP + "\\ipdetectocr-") $tmpFile = $tmpFileTemplate + (Get-Random) + ".tif" # Convert the PNG to TIFF. [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null $image = [System.Drawing.Image]::FromFile($pngFile) $image.Save($tmpFile, [System.Drawing.Imaging.ImageFormat]::TIFF) # OCR it! (Requires Microsoft Office Document Imaging) $modi = new-object -com MODI.Document $modi.Create($tmpFile) $modi.OCR() $OCRText = ($modi.Images | select -expand Layout).Text $modi.Close() $image.Dispose() # Clean out old left over files. foreach ($file in ( Get-Childitem $tmpFileTemplate* | Where { $_.LastWriteTime -lt ((Get-Date).addMinutes(-1)) } )) { Remove-Item -Force $file } Write-Output $OCRText } # Example use: # Get-VirtualEsxiIp -vm (Get-VM "ESXi 4.0 Instance 3")
PowerShellCorpus/PoshCode/Share Perms.ps1
Share Perms.ps1
$FolderPath = "\\\\FilerName\\ShareName" $rootfolder = Get-ChildItem -Path $FolderPath -recurse foreach ($file in $rootfolder) { $file.FullName Get-Acl $file.FullName | Format-List $acl = Get-Acl $file.FullName $acl.Access | %{$acl.RemoveAccessRule($_)} $acl.SetAccessRuleProtection($True, $False) $Rights = [System.Security.AccessControl.FileSystemRights]::FullControl $inherit = [System.Security.AccessControl.FileSystemAccessRule]::ContainerInherit -bor [System.Security.AccessControl.FileSystemAccessRule]::ObjectInherit $Propagation = [System.Security.AccessControl.PropagationFlags]::None $Access = [System.Security.AccessControl.AccessControlType]::Allow #Copy the next 2 lines and uncomment them for each GROUP that you want to add $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("DomainName\\GroupName",$Rights, $inherit, $Propagation, $Access) $acl.AddAccessRule($rule) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("DomainName\\GroupName",$Rights, $inherit, $Propagation, $Access) $acl.AddAccessRule($rule) #Stays in Place to set the owner $acct=New-Object System.Security.Principal.NTAccount("Builtin\\Administrators") $acl.SetOwner($acct) #Applies all changes above to the ACL Set-Acl $file.FullName $acl Get-Acl $file.FullName | Format-List }
PowerShellCorpus/PoshCode/Split-String.ps1
Split-String.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/Get-CountDown.ps1
Get-CountDown.ps1
function Get-CountDown() { <# .Synopsis CountDown timer and progress bar .Description A simple countdown timer as an advanced function. Displays the time remaining along with a_ progress bar displaying percentage time elapsed. If no parameters are passed, the script will_ default to 1 hour. .parameter hours Hours .parameter Minutes Minutes .parameter Seconds Seconds .Example Get-CountDown -hours 1 -Mins 30 -Seconds 30 Description ----------- Will display a 1:30:30 countdown along with progress bar. .Example c:\\> powershell c:\\scripts\\Get-CountDown.ps1 -hours 1 Description ----------- How to run script from a DOS command line, batch file or shortcut. Will display a 1 hour countdown .Notes NAME: Get-CountDown.ps1 VERSION: 2.0 AUTHOR: Matthew Painter LASTEDIT: 28/03/2011 HISTORY: 1.0 02/22/2011 By xb90 at http://poshtips.com 2.0 28/03/2011 By MJP - Practice for Scripting games #> [CmdletBinding()] param( [Parameter( Mandatory=$false)] [int]$hours=0, [Parameter( Mandatory=$false)] [int]$minutes=0, [Parameter( Mandatory=$false)] [int]$seconds=0 ) #if no time passed then default to 1 hour if($hours-eq0 -and $minutes-eq0 -and $seconds-eq0){ $hours=1 } #setup timespan variables $startTime = get-date $endTime = $startTime.addHours($hours) $endTime = $endTime.addMinutes($minutes) $endTime = $endTime.addSeconds($seconds) $Check=0 $timeSpan = new-timespan $(get-date) $endTime #loop to update progress bar while ($timeSpan -gt 0) { $timeSpan = new-timespan $(get-date) $endTime if($Check -ne 1){$timeSpan2=$timeSpan;$Check=1} #generate time remaining string $TimeRemaining = $([string]::Format("Time Remaining: {0:d2}:{1:d2}:{2:d2}", ` $timeSpan.hours, ` $timeSpan.minutes, ` $timeSpan.seconds)) #calc percent time elapsed $percentRem = ([math]::round($timeSpan.ticks/$timeSpan2.ticks*100,0)) if($percentRem-lt0){$percentRem=0} $percentRem=100-$percentRem write-progress -activity "Shutdown" -status $TimeRemaining -percentcomplete $percentRem sleep 1 } } get-countdown
PowerShellCorpus/PoshCode/HelpModules 2.1.ps1
HelpModules 2.1.ps1
# HelpModules # A Module for generating module stubs so you can Update-Help (or Save-Help) # Includes two options for reading the help from those modules (StubFunctions or Get-ModuleHelp) # 1.0 - 2013/2/1 - Initial release Friday, Feb 1st, 2013 # 2.0 - 2013/2/1 - Updated release with improved pipeline/remoting support # 2.1 - 2013/2/1 - Minor change to allow the ModuleName to be empty in Get-ModuleHelp $PSModuleHelpRoot = Convert-Path "~\\Documents\\WindowsPowerShellModuleHelp" function New-HelpModule { #.Synopsis # Creates a dummy module and fetches the help files for it #.Example # Get-Module Hyper-V -ListAvailable | New-HelpModule # # Generates a new module stub from an existing module #.Example # Invoke-Command -ComputerName $Servers { Get-Module -ListAvailable | Where HelpInfoUri } | New-HelpModule # # Generates local Help-only Modules for all the updatable help modules which exist on the specified server #.Example # New-HelpModule Hyper-V '1.0' 'af4bddd0-8583-4ff2-84b2-a33f5c8de8a7' 'http://go.microsoft.com/fwlink/?LinkId=206726' # # Generates a new help module from the specified values (You can get the information about the module in an email, text message, phone call, etc!) [CmdletBinding(DefaultParameterSetName="ModuleInfo")] param( # The name of the module you want to create a dummy for. [Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=0)] [Alias("Name")] [String]$ModuleName, # The version of the module you want to create a dummy for. [Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=1)] [String]$Version, # The exact guid of the module you want to create a dummy for. [Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=2)] [Guid]$Guid, # The HelpInfoUri of the module you want to create a dummy for. [Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=3)] [String]$HelpInfoUri, # A list of commands to generate StubFunctions for. # # NOTE: stub functions will not be generated unless you also specify the -StubFunctions switch (see help on that parameter) [Parameter(ValueFromPipelineByPropertyName=$true)] $ExportedCommands, # A path to put the help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp"). [String]$ModuleHelpRoot = $PSModuleHelpRoot, # The culture(s) you want to fetch help for (defaults to $PSUICulture) [Alias("Culture","PSCulture")] [CultureInfo[]]$HelpCulture = ${PSUICulture}, # If set, generates a Blank.psm1 with stub functions in it so that you can import the dummy module and use the built-in Get-Help instead of our Get-ModuleHelp # # Setting this may pollute your PowerShell session with dozens or hudreds of commands which don't do anything. You probably shouldn't, for instance, add your ModuleHelpRoot path to your PSModulePath if you do this. [Switch]$StubFunctions ) begin { $ModulesToUpdate = @() } process { # Make the ModuleHelpRoot\\ModuleName folder if it's not there $ModuleDir = mkdir ${ModuleHelpRoot}\\${ModuleName}\\ -Force if($ExportedCommands -is [System.Collections.Generic.Dictionary[System.String,System.Management.Automation.CommandInfo]]) { [string[]]$ExportedCommands = $ExportedCommands.Keys } # Generate the stub ModuleManifest New-ModuleManifest -Path ${ModuleHelpRoot}\\${ModuleName}\\${ModuleName}.psd1 ` -Guid $Guid -HelpInfoUri $HelpInfoUri -ModuleVersion $Version ` -FunctionsToExport $ExportedCommands ` -RootModule "Blank.psm1" $ModulesToUpdate += $ModuleName # Generate stub FunctionsToExport if($StubFunctions) { Remove-Item "${ModuleHelpRoot}\\${ModuleName}\\Blank.psm1" -ErrorAction SilentlyContinue foreach($name in $ExportedCommands) { Add-Content "${ModuleHelpRoot}\\${ModuleName}\\Blank.psm1" "#.ExternalHelp *.xml `nfunction $name {}`n" } } } end { # Update the help files -- this is why we're here. # TODO: if we're generating a lot of modules, it would be really to only do this once! PowerShell -NoProfile -Command "&{ `$Env:PSModulePath = '$ModuleHelpRoot'; Update-Help -Module '$($ModulesToUpdate -join "','")' -UICulture '$($HelpCulture -join "','")'}" } } function Get-ModuleHelp { #.Synopsis # Gets help from the XML help files directly without worrying about whether the commands actually exist. [CmdletBinding(DefaultParameterSetName="MamlCommandHelpInfo")] param( # The command you want help for [Alias("Name")] [Parameter(Mandatory=$true, Position = 0, ValueFromPipelineByPropertyName = $true)] $CommandName, # The name of the module the command is in # TODO: Search Get-Module -ListAvailable for modules which *say* they have the command [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] $ModuleName = "*", # A path to search for help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp"). $ModuleHelpRoot = $PSModuleHelpRoot, # Displays only the detailed descriptions of the specified parameters. Wildcards are permitted. [Parameter(ParameterSetName="MamlCommandHelpInfo#parameter")] [String]$Parameter, # Displays only the name, synopsis, and examples". [Parameter(ParameterSetName="MamlCommandHelpInfo#ExamplesView")] [Switch]$Examples, # Displays the entire help topic for a cmdlet, including parameter descriptions and attributes, examples, input and output object types, and additional notes. [Parameter(ParameterSetName="MamlCommandHelpInfo#FullView")] [Switch]$Full, # Adds parameter descriptions and examples to the basic help display. [Parameter(ParameterSetName="MamlCommandHelpInfo#DetailedView")] [Switch]$Detailed, # The culture you want to fetch help for (defaults to $PSUICulture) [Alias("Culture","PSCulture")] [CultureInfo]$HelpCulture = ${PSUICulture} ) process { Write-Verbose "Culture: $HelpCulture HelpSet: $($PSCmdlet.ParameterSetName)" $matched = $false foreach($node in Select-Xml "//*[local-name() = 'details']/*[local-name() = 'name' and text() = '$CommandName']/../.." -Path ${ModuleHelpRoot}\\${ModuleName}\\${PSUICulture}\\*.xml | Select-Object -Expand Node) { if($Parameter) { foreach($param in $node.parameters.parameter) { if($param.name -like $Parameter) { $matched = $true $param | FixMaml -Type $($PSCmdlet.ParameterSetName) } } if(!$matched) { throw "No parameter matches criteria $Parameter" } } else { $matched = $true $node | FixMaml -Type $($PSCmdlet.ParameterSetName) } } } } function FixMaml { #.Synopsis # Internal command for tweaking the XML just enough that PowerShell will format it properly [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] $Node, [Parameter(Mandatory=$true)] $Type = "MamlCommandHelpInfo" ) process { $node.PSTypeNames.Clear() $node.PSTypeNames.Add($type) if($node.description) { Add-Member -Input $node NoteProperty description @( $Node.RemoveChild($node.description).para | % { $p = New-Object PSObject -Property @{ Text = $_ }; $p.PSTypeNames.Clear(); $p.PSTypeNames.Add("MamlParaTextItem"); $p } ) } if($node.details) { # Fix them, but don't output recursively $null = $node.details | FixMaml -Type $Type } Write-Output $node } } Export-ModuleMember -Function New-HelpModule, Get-ModuleHelp -Variable PSModuleHelpRoot # SIG # Begin signature block # MIIfIAYJKoZIhvcNAQcCoIIfETCCHw0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUe4XjjCbhvPRJIycXpKAA3E/Y # waqgghpSMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZS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7JaTpgNeOtOMqfszfJgil9rXrzwkySugiys # RW1xOKsdF4bnyPiFqQAzhfdkQFCF5wtN5wHE5Q8v1yICG/WKYBAKuYBMo+Emx8LU # t/L6EL6hggILMIICBwYJKoZIhvcNAQkGMYIB+DCCAfQCAQEwcjBeMQswCQYDVQQG # EwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5 # bWFudGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMgIQDs/0OMj+vzVu # BNhqmBsaUDAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAc # BgkqhkiG9w0BCQUxDxcNMTMwMjAxMjMzNDA2WjAjBgkqhkiG9w0BCQQxFgQUMGM7 # nZoLnCWWZDPJXWGuK5v0jkgwDQYJKoZIhvcNAQEBBQAEggEAdRSlZCVnBvRuKDhZ # bPB5zM6VCP7bHD0ll/mYl4InHRSg4F74i5GvCv5jis8ys+uLeCAFodkMzUUzzQTL # dCJT1wgqMpKt4TQI0wow2cVTaHQrVSGF1wm1ZZqaWy6XQwdfUf4cNDIcdWes0e3+ # eV5K2lNAMti488HxOD6kFOlE3zz+kURW8qLJtYM4D198W85FoPgRJ6RbyrEDFy0U # CReOV9p5rjSC8kaPiEwyqJbhwOJGGYnNGUOO9MAi7pz7qc5eGxXJwCaB6RGyVj0k # oVIcFCaQ9RjfjX02WZ61wqZM0t+ByjKk4eTUYfFZyjJsiJJwizV21N1vBxpq0/0t # 7wQEfg== # SIG # End signature block
PowerShellCorpus/PoshCode/Reflection Module_2.ps1
Reflection Module_2.ps1
#requires -version 2.0 # ALSO REQUIRES Autoload for some functionality # You should create a Reflection.psd1 with the contents: @{ RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="3.5.0.0" } #History: # 1.0 - First public release (March 19, 2010) # 2.0 - Private Build # - Included the Accelerator function inline # - Added a few default aliases # 3.0 - September 3, 2010 # - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!) # - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312 # 3.5 - January 28, 2011 # - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature # - Fixed alias exporting so aliases will show up now # - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies # 3.6 - January 28, 2011 # - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets information about one or more loaded types, or gets the possible values for an enumerated type or value. .Parameter Assembly The Assemblies to search for types. Can be an actual Assembly object or a regex to pass to Get-Assembly. .Parameter TypeName The type name(s) to search for (wildcard patterns allowed). .Parameter BaseType A Base type they should derive from (wildcard patterns allowed). .Parameter Enum An enumeration to list all of enumeration values for .Parameter Namespace A namespace to restrict where we selsect types from (wildcard patterns allowed). .Parameter Force Causes Private types to be included .Example Get-Type Gets all loaded types (takes a VERY long time to print out) .Example Get-Type -Assembly ([PSObject].Assembly) Gets types from System.Management.Automation .Example [Threading.Thread]::CurrentThread.ApartmentState | Get-Type Gets all of the possible values for the ApartmentState property .Example [Threading.ApartmentState] | Get-Type Gets all of the possible values for an apartmentstate #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The assembly to collect types from [Parameter(ValueFromPipeline=$true)] [PsObject[]]$Assembly , # The type names to return from [Parameter(Mandatory=$false)] [String[]]$TypeName , # The type names to return from [Parameter(Mandatory=$false)] [String[]]$Namespace , # A Base Type they should derive from [Parameter(Mandatory=$false)] [String[]]$BaseType , # The enumerated value to get all of the possibilties of [Parameter(ParameterSetName="Enum")] [PSObject]$Enum , [Parameter()][Alias("Private","ShowPrivate")] [Switch]$Force ) process { if($psCmdlet.ParameterSetName -eq 'Enum') { if($Enum -is [Enum]) { [Enum]::GetValues($enum.GetType()) } elseif($Enum -is [Type] -and $Enum.IsEnum) { [Enum]::GetValues($enum) } else { throw "Specified Enum is neither an enum value nor an enumerable type" } } else { if($Assembly -as [Reflection.Assembly[]]) { ## This is what we expected, move along } elseif($Assembly -as [String[]]) { $Assembly = Get-Assembly $Assembly } elseif(!$Assembly) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } :asm foreach ($asm in $assembly) { Write-Verbose "Testing Types from Assembly: $($asm.Location)" if ($asm) { trap { if( $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) { $PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail") continue asm } Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail" Write-Debug $( $_.Exception.LoaderExceptions | Out-String ) continue asm } $asm.GetTypes() | Where { ( $Force -or $_.IsPublic ) -AND ( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND ( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND ( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) } } } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = "." , [Alias("Types")] [Switch]$Passthru , [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly. #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=0)] [string[]]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() | Where { $Assembly = $_ if($Name){ $( foreach($n in $Name){ if(Resolve-Path $n -ErrorAction 0) { $n = [Regex]::Escape( (Resolve-Path $n).Path ) } $Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n) } ) -contains $True } else { $true } } } } function Get-Constructor { <# .Synopsis Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type. .Description Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor. .Parameter Type The type to get the constructor for .Parameter Force Force inclusion of Private and Static constructors which are hidden by default. .Parameter NoWarn Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors. .Example Get-Constructor System.IO.FileInfo Description ----------- Gets all the information about the single constructor for a FileInfo object. .Example Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax Description ----------- Displays the constructor syntax for all of the *Info objects in the System.IO namespace. Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors. .Example $path = $pwd $driveName = $pwd.Drive $fileName = "$Profile" Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax } Description ----------- Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo. Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical. #> [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ParameterType")] [Type]$Type , [Switch]$Force , [Switch]$NoWarn ) process { $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *, @{ name = "TypeName"; expression = { $_.ReflectedType.FullName } }, @{ name = "Definition"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "Syntax"; expression = {Get-MemberSignature $_ -Simple} }, @{ name = "SafeSyntax"; expression = {Get-MemberSignature $_} } if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" } } } function Get-Method { <# .Synopsis Returns MethodInfo for the (public) methods of the specified Type. .Description Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method. .Parameter Type The type to get methods on .Parameter Name The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns) .Parameter Force Force inclusion of Private methods and property accessors which are hidden by default. #> [CmdletBinding(DefaultParameterSetName="Type")] param( [Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Type]$Type , [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)] [String[]]$Name ="*" , [Switch]$Definition , [Switch]$Force ) process { foreach($method in $type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } | # Hide the Property accessor methods Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } | Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } ) { $method | Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru | Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member AliasProperty Syntax Definition -Passthru | #Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru | Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru } } } function Get-MemberSignature { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [System.Reflection.MethodBase]$MethodBase, [Switch]$Simple ) process { $parameters = $( foreach($param in $MethodBase.GetParameters()) { # Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)" if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' } if($Simple) { '{0} {1}' -f $param.ParameterType.ToString(), $param.Name } else { '{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.ToString().TrimEnd('&'), $param.Name } } ) if($MethodBase.IsConstructor) { "New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')" } elseif($Simple) { "$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))" } elseif($MethodBase.IsStatic) { "[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))" } else { "[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))" } } } function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Get-Argument { param( [Type]$Target , [String]$Method , $Arguments ) end { trap { write-error $_ break } Write-Verbose "Get $Method Method on $($Target.FullName):" $MethodBase = Get-Method $target $Method Write-Verbose $($MethodBase | Out-String) if(@($MethodBase).Count -gt 1) { $i = 0 $i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:" [System.Reflection.MethodBase]$MethodBase = $MethodBase[$i] } ForEach($parameter in $MethodBase.GetParameters()) { $found = $false For($a =0;$a -lt $Arguments.Count;$a++) { if($argument[$a] -as $parameter.ParameterType) { Write-Output $argument[$a] if($a -gt 0 -and $a -lt $Arguments.Count) { $Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a) } elseif($a -eq 0) { $Arguments = $Arguments | Select -Last ($Arguments.Count - 1) } else { # a -eq count $Arguments = $Arguments | Select -First ($Arguments.Count - 1) } $found = $true break } } if(!$Found) { $userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)" if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) { Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType) } else { Write-Output ($userInput -as $parameter.ParameterType) } } } } } function Invoke-Member { [CmdletBinding()] param( [parameter(position=0, valuefrompipeline=$true, mandatory=$true)] [allownull()] [allowemptystring()] $InputObject , [parameter(position=1, mandatory=$true)] [validatenotnullorempty()] $Method , [parameter(valuefromremainingarguments=$true)] [allowemptycollection()] [object[]]$Arguments , [parameter()] [switch]$Static ) # begin { # if(!(get-member SafeSyntax -input $method -type Property)){ # if(get-member Name -inpup $Method -Type Property) { # $Method = Get-Method $InputObject $Method.Name # } else { # $Method = Get-Method $InputObject $Method # } # } # $SafeSyntax = [ScriptBlock]::Create( $Method.SafeSyntax ) # } process { # if ($InputObject) # { # if ($InputObject | Get-Member $Method -static:$static) # { if ($InputObject -is [type]) { $target = $InputObject } else { $target = $InputObject.GetType() } if($Method -match "ctor|constructor") { $Method = ".ctor" [System.Reflection.BindingFlags]$flags = "CreateInstance" $InputObject = $Null } else { [System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod" if($Static) { $flags += "Static" } else { $flags += "Instance" } } [Object[]]$Parameters = Get-Argument $target $Method $Arguments Write-Verbose "$($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ })" try { Write-Verbose "Invoking $Method on [$target]$InputObject with $flags and $Parameters" Write-Verbose "[$($target.FullName)].InvokeMember('$Method', '$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))" $target.InvokeMember($Method, $flags, $null, $InputObject, $Parameters) } catch { if ($_.Exception.Innerexception -is [MissingMethodException]) { write-warning "Method argument count (or type) mismatch." } } # } else { # write-warning "Method $Method not found." # } # } } } function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On','Type')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias('Returns')] [Type[]]$Types , [Parameter(Position=3, ValueFromPipelineByPropertyName=$true)] [Type[]]$ArgumentTypes , [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs ) process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs) { if(!$ArgumentTypes) { [Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() } } [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($Types).Invoke( $on, $Arguments ) } else { [Type[]]$ArgumentTypes = New-Object Type[] 0 $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($Types).Invoke( $on ) } } } # get a reference to the Type $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") function Import-Namespace { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string]$Namespace , [Switch]$Force ) Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator } function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list System.Collections.Generic.List``1 $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator "List T", "GList" System.Collections.Generic.List``1 $list = New-Object "list t[string]" Creates two accelerators for the Generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate (without square brackets) .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64]) Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type]$Type ) process { # add a user-defined accelerator foreach($a in $Accelerator) { $xlr8r::Add( $a, $Type) trap [System.Management.Automation.MethodInvocationException] { if($xlr8r::get.keys -contains $a) { if($xlr8r::get[$a] -ne $Type) { Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]" } Continue; } throw } } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator System.String Returns the KeyValue pair for the [System.String] accelerator(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pairs for the matching accelerator definition(s) .Parameter Accelerator One or more short form accelerators to search for (Accept wildcard characters). .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] param( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator , [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type[]]$Type ) process { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int Int64 Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator that you want to remove (Accept wildcard characters). .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","FullName")] [string[]]$Accelerator ) process { foreach($a in $Accelerator) { foreach($key in $xlr8r::Get.Keys -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]", "Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?", "Removing Type Accelerator" )) { # remove a user-defined accelerator $xlr8r::remove($key) } } } } } ############################################################################### ##### Imported from PowerBoots $Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree' $DependencyProperties = @{} if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) { #$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) ) $DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml } function Get-ReflectionModule { $executioncontext.sessionstate.module } function Set-ObjectProperties { [CmdletBinding()] param( $Parameters, [ref]$DObject ) if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() } if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White } foreach ($param in $Parameters) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" } ## INGORE DEPENDENCY PROPERTIES FOR NOW :) if($param.Key -eq "DependencyProps") { ## HANDLE EVENTS .... } elseif ($param.Key.StartsWith("On_")) { $EventName = $param.Key.SubString(3) if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" } $sb = $param.Value -as [ScriptBlock] if(!$sb) { $sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock } $Dobject.Value."Add_$EventName".Invoke( $sb ); # $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) ); # $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) ); } ## HANDLE PROPERTIES .... else { try { ## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here. if($DebugPreference -ne "SilentlyContinue") { Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray } if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) { $Values = @() foreach($sb in $param.Value) { $Values += & (Get-ReflectionModule) $sb } } else { $Values = $param.Value } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green } Set-Property $Dobject $Param.Key $Values if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta } if($DebugPreference -ne "SilentlyContinue") { if( $Dobject.Value.$($param.Key) -ne $null ) { Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green } } } catch [Exception] { Write-Host "COUGHT AN EXCEPTION" -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } while($DependencyProps) { $name, $value, $DependencyProps = $DependencyProps $name = ([string]@($name)[0]).Trim("-") if($name -and $value) { Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value } } } if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host } if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() } } function Set-Property { PARAM([ref]$TheObject, $Name, $Values) $DObject = $TheObject.Value if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta } $PropertyType = $DObject.GetType().GetProperty($Name).PropertyType if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green} # [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject ) # [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) ) # In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. [Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject ) [Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) ) $Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null $TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() ) } elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) { $Binding = @($Values)[0]; if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan} if(!$Binding.Source -and !$Binding.ElementName) { $Binding.Source = $DObject.DataContext } if($DependencyProperties.ContainsKey($Name)) { $field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType) if($field) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue } if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue} $DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null } else { throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )" } } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan } try { $DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null # $DObject.Add_Loaded( { # $this.SetBinding( ($this.GetType())::ItemsSourceProperty, (Binding -Source $this.DataContext) ) # } ) if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow } } catch { Write-Host "Nope, was not able to set it." -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } } elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) { if($Values -is [System.Collections.IEnumerable]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan } $DObject.$($Name) = $Values } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan } $DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]" $DObject.$($Name).Add($Values) } } elseif($DObject.$($Name) -is [System.Collections.IList]) { foreach ($value in @($Values)) { try { $null = $DObject.$($Name).Add($value) } catch { # Write-Host "CAUGHT array problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) ) } else { Write-Error $_.Exception throw } } } } else { ## If they pass an array of 1 when we only want one, we just use the first value if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White} try { $DObject.$($Name) = $Values[0] } catch [Exception] { # Write-Host "CAUGHT collection value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $Values[0]) ) }else { throw } } } else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan} try { $DObject.$($Name) = $Values } catch [Exception] { # Write-Host "CAUGHT value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $values) ) }else { throw } } } } } function Set-DependencyProperty { [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true)] $Property , [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Element , [Parameter()] [Switch]$Passthru ) DYNAMICPARAM { $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter $Param1.Name = "Value" # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) ) $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) ) if( $Property ) { if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))) { $Param1.ParameterType = $Property.PropertyType } elseif($Property -is [string] -and $Property.Contains(".")) { $Class,$Property = $Property.Split(".") if($DependencyProperties.ContainsKey($Property)){ $type = $DependencyProperties.$Property.Keys -like "*$Class" if($type) { $Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType } } } elseif($DependencyProperties.ContainsKey($Property)){ if($Element) { if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) { $Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType } } else { $Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType } } else { $Param1.ParameterType = [PSObject] } } else { $Param1.ParameterType = [PSObject] } $paramDictionary.Add("Value", $Param1) return $paramDictionary } PROCESS { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red continue } if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])) ){ trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red continue } $Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType)) } else { if("$Property".Contains(".")) { $Class,$Property = "$Property".Split(".") } if( $DependencyProperties.ContainsKey("$Property" ) ) { $fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } ) if($fields.Count -eq 0 ) { $fields = @($DependencyProperties.$Property.Keys -like "*$Class" ) } if($fields.Count) { $success = $false foreach($field in $fields) { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red continue } $Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType))) if($?) { $success = $true; break } } if(!$success) { throw "food" } } else { Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red } } else { Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red } } if( $Passthru ) { $Element } } } function Add-ConstructorFunction { <# .Synopsis Add support for a new class by creating the dynamic constructor function(s). .Description Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias. Exposes all of the properties and events of the type as perameters to the function. NOTE: The Type MUST have a default parameterless constructor. .Parameter Assembly The Assembly you want to generate constructors for. All public types within it will be generated if possible. .Parameter Type The type you want to create a constructor function for. It must have a default parameterless constructor. .Example Add-ConstructorFunction System.Windows.Controls.Button Creates a new function for the Button control. .Example [Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) .Example Add-ConstructorFunction -Assembly PresentationFramework Will create constructor functions for all the WPF components in the PresentationFramework assembly. .Links http://HuddledMasses.org/powerboots .ReturnValue The name(s) of the function(s) created -- so you can export them, if necessary. .Notes AUTHOR: Joel Bennett http://HuddledMasses.org LASTEDIT: 2009-01-13 16:35:23 #> [CmdletBinding(DefaultParameterSetName="FromType")] PARAM( [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)] [type[]]$type , [Alias("FullName")] [Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)] [string[]]$Assembly , [Parameter()] [string]$Path = "$PSScriptRoot\\Types_Generated" , [switch]$Force , [switch]$ShortAliases , [Switch]$Quiet ) BEGIN { [Type[]]$Empty=@() if(!(Test-Path $Path)) { MkDir $Path } $ErrorList = @() } END { #Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties )) Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." } $ErrorList | Write-Error } PROCESS { if($PSCmdlet.ParameterSetName -eq "FromAssembly") { [type[]]$type = @() foreach($lib in $Assembly) { $asm = $null trap { continue } if(Test-Path $lib) { $asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") ) } if(!$asm) { ## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5 $asm = [Reflection.Assembly]::LoadWithPartialName( $lib ) } if($asm) { $type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and !$_.IsAbstract -and !$_.IsInterface -and $_.GetConstructor( "Instance,Public", $Null, $Empty, @() )} } else { Write-Error "Can't find the assembly $lib, please check your spelling and try again" } } } foreach($T in $type) { $TypeName = $T.FullName $ScriptPath = Join-Path $Path "New-$TypeName.ps1" Write-Verbose $TypeName ## Collect all dependency properties .... $T.GetFields() | Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } | ForEach-Object { [string]$Field = $_.DeclaringType::"$($_.Name)".Name [string]$TypeName = $_.DeclaringType.FullName if(!$DependencyProperties.ContainsKey( $Field )) { $DependencyProperties.$Field = @{} } $DependencyProperties.$Field.$TypeName = @{ Name = [string]$_.Name PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName } } if(!( Test-Path $ScriptPath ) -OR $Force) { $Pipelineable = @(); ## Get (or generate) a set of parameters based on the the Type Name $PropertyNames = New-Object System.Text.StringBuilder "@(" $Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n" ## Add all properties $Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") | Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) } $Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique foreach ($p in $Properties) { $null = $PropertyNames.AppendFormat(",'{0}'",$p.Name) switch( $p.MemberType ) { Event { $null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name) $null = $Parameters.AppendFormat(@' [Parameter()] [PSObject]${{On_{0}}} , '@, $p.Name) } Property { if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") { $null = $Parameters.AppendFormat(@' [Parameter(Position=1,ValueFromPipeline=$true)] [Object[]]${{{0}}} , '@, $p.Name) $Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru) } elseif($p.PropertyType -eq [System.Boolean]) { $null = $Parameters.AppendFormat(@' [Parameter()] [Switch]${{{0}}} , '@, $p.Name) } else { $null = $Parameters.AppendFormat(@' [Parameter()] [Object[]]${{{0}}} , '@, $p.Name) } } } } $null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)] [string[]]$DependencyProps )') $null = $PropertyNames.Remove(2,1).Append(')') $collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true) $ofs = "`n"; $function = $( " if(!( '$TypeName' -as [Type] )) { $( if( $T.Assembly.GlobalAssemblyCache ) { " `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) " } else { " `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) " } ) } ## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) { ## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`" ## # `$scriptParam = `$PSBoundParameters ## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`" ## } Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!"" function New-$TypeName { <# .Synopsis Create a new $($T.Name) object .Description Generates a new $TypeName object, and allows setting all of it's properties. (From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version)) .Notes GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org GENERATED : $(Get-Date) ASSEMBLY : $($T.Assembly.FullName) FULLPATH : $($T.Assembly.Location) #> $Parameters BEGIN { `$DObject = New-Object $TypeName `$All = $PropertyNames } PROCESS { " if(!$collectable) { " # The content of $TypeName is not a collection # So if we're in a pipeline, make a new $($T.Name) each time if(`$_) { `$DObject = New-Object $TypeName } " } @' foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) { $PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure() } Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject) '@ if(!$collectable) { @' Microsoft.PowerShell.Utility\\Write-Output $DObject } #Process '@ } else { @' } #Process END { Microsoft.PowerShell.Utility\\Write-Output $DObject } '@ } @" } ## New-$TypeName `@PSBoundParameters "@ ) Set-Content -Path $ScriptPath -Value $Function } # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName" } }#PROCESS } function Import-ConstructorFunctions { #.Synopsis # Autoload pre-generated constructor functions and generate aliases for them. #.Description # Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory. #.Parameter Path # The path to a folder with functions to preload param( [Parameter()] [Alias("PSPath")] [string[]]$Path = "$PSScriptRoot\\Types_Generated" ) end { $Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" }) Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")" foreach($script in Get-ChildItem $Paths -ErrorAction 0) { $TypeName = $script.Name -replace 'New-(.*).ps1','$1' $ShortName = ($TypeName -split '\\.')[-1] Write-Verbose "Importing constructor for type: $TypeName ($ShortName)" # Note: set the aliases global for now, because it's too late to export them # E.g.: New-Button = New-System.Windows.Controls.Button Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) if($ShortAliases) { # E.g.: Button = New-System.Windows.Controls.Button Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet) } New-Autoload -Name $Script.FullName -Alias "New-$TypeName" # Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String) Get-Command "New-$TypeName" } } } #.Parameter Snapin # The full path to where the snapin .dll is #.Parameter OutputPath # Force the module manifest(s) to output in a different location than where the snapin .dll is #.Parameter ModuleName # Override the snapin name(s) for the module manifest #.Parameter Author # Overrides the Company Name from the manifest when generating the module's "Author" comment #.Parameter Passthru # Returns the ModuleManifest (same as -Passthru on New-ModuleManifest) #.Example # New-ModuleManifestFromSnapin ".\\Quest Software\\Management Shell for AD" -ModuleName QAD # # Description # ----------- # Generates a new module manifest file: QAD.psd1 in the folder next to the Quest.ActiveRoles.ArsPowerShellSnapIn.dll #.Example # New-ModuleManifestFromSnapin "C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\\" -Output $pwd # # Description # ----------- # Generates module manifest files for the SqlServer PSSnapins and stores them in the current folder function New-ModuleManifestFromSnapin { param( [Parameter(Mandatory=$true, Position="0", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [String[]]$Snapin , [Parameter()] $OutputPath , [Parameter()] $ModuleName , [Parameter()] [String]$Author , [Switch]$Passthru ) # $SnapinPath = $(Get-ChildItem $SnapinPath -Filter *.dll) $EAP = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" Add-Assembly $Snapin $ErrorActionPreference = $EAP $SnapinTypes = Get-Assembly $Snapin | Get-Type -BaseType System.Management.Automation.PSSnapIn, System.Management.Automation.CustomPSSnapIn -WarningAction SilentlyContinue foreach($SnapinType in $SnapinTypes) { $Installer = New-Object $SnapinType if(!$PSBoundParameters.ContainsKey("OutputPath")) { $OutputPath = (Split-Path $SnapinType.Assembly.Location) } if(!$PSBoundParameters.ContainsKey("ModuleName")) { $ModuleName = $Installer.Vendor } if(!$PSBoundParameters.ContainsKey("Author")) { $Author = $Installer.Name } $ManifestPath = (Join-Path $OutputPath "$ModuleName.psd1") Write-Verbose "Creating Module Manifest: $ManifestPath" $RequiredAssemblies = @( $SnapinType.Assembly.GetReferencedAssemblies() | Get-Assembly | Where-Object { (Split-Path $_.Location) -eq (Split-Path $SnapinType.Assembly.Location) } | Select-Object -Expand Location | Resolve-Path -ErrorAction Continue) # New-ModuleManifest has a bad bug -- it makes paths relative to the current location (and it does it wrong). Push-Location $OutputPath if($Installer -is [System.Management.Automation.CustomPSSnapIn]) { $Cmdlets = $Installer.Cmdlets | Select-Object -Expand Name $Types = $Installer.Types | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } $Formats = $Installer.Formats | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } } else { $Types = $Installer.Types | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } $Formats = $Installer.Formats | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } } } if(!$Cmdlets) { $Cmdlets = "*" } if(!$Types) { $Types = @() } if(!$Formats) { $Formats = @() } New-ModuleManifest -Path $ManifestPath -Author $Author -Company $Installer.Vendor -Description $Installer.Description ` -ModuleToProcess $SnapinType.Assembly.Location -Types $Types -Formats $Formats -Cmdlets $Cmdlets ` -RequiredAssemblies $RequiredAssemblies -Passthru:$Passthru ` -NestedModules @() -Copyright $Installer.Vendor -FileList @() Pop-Location } } ############################################################################### Add-Accelerator list System.Collections.Generic.List``1 Add-Accelerator dictionary System.Collections.Generic.Dictionary``2 Set-Alias aasm Add-Assembly Set-Alias gt Get-Type Set-Alias gasm Get-Assembly Set-Alias gctor Get-Constructor Set-Alias gax Get-Accelerator Set-Alias aax Add-Accelerator Set-Alias rax Remove-Accelerator Export-ModuleMember -Function * -Alias * # SIG # Begin signature block # MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUwQma6YfrFSpi4wl+OodIvVev # zCSgggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj # dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY # BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh # dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId # KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P # n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl # 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC # m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AlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl # IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY # aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0 # LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC # NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor # BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU4p8ZBRzz # oMAfab+GkwwIeAKHOHYwDQYJKoZIhvcNAQEBBQAEggEAY15q+K/iQGqtj9ftUEi4 # fGkqj/c3hBQzlvRJuf8Bs8AeroWfYGLU0EaXNpcsi0LSIzt6gWMjgSSY4fs+sNLB # 4NAc0ivir3ifbCVZoidn2n8oQ5+RapX42U2ukMjYq4E239zqsmmPls/2cVYQEy7N # b/Y66cLH5+o02CnrXQozSfHvZ/+aEVVI5roDbkPFJcLEVUjzZQtBAgc6UKzKRoLy # hqSl3jnoh45Po/LC7iZ53Q8gdD1EzhjaHT56T//NKw1FntKEeIoh4Mm+BVj974Kp # ud2nEvHEwIAzM0llf7NijczWxK4FMcYc7yvVYOUktX/GEXYQNEID2QwcBOzoWng6 # 7A== # SIG # End signature block
PowerShellCorpus/PoshCode/Get-Tail_1.ps1
Get-Tail_1.ps1
# Name: Get-Tail.ps1 # Author: William Stacey # Created: 02/22/2007 # Description: Gets the last N lines of a file. Does scan from end-of-file so works on large files. Also has a loop flag that prompts for refresh. function Get-Tail([string]$path = $(throw "Path name must be specified."), [int]$count = 10, [bool]$loop = $false) { if ( $count -lt 1 ) {$(throw "Count must be greater than 1.")} function get-last { $lineCount = 0 $reader = new-object -typename System.IO.StreamReader -argumentlist $path, $true [long]$pos = $reader.BaseStream.Length - 1 while($pos -gt 0) { $reader.BaseStream.Position = $pos if ($reader.BaseStream.ReadByte() -eq 10) { if($pos -eq $reader.BaseStream.Length - 1) { $count++ } $lineCount++ if ($lineCount -ge $count) { break } } $pos-- } if ($lineCount -lt $count) { $reader.BaseStream.Position = 0 } while($line = $reader.ReadLine()) { $lines += ,$line } $reader.Close() $lines } while(1) { get-last if ( ! $loop ) { break } $in = read-host -prompt "Hit [Enter] to tail again or Ctrl-C to exit" } }
PowerShellCorpus/PoshCode/6a35f0a2-b19c-4518-8c2b-56793070490d.ps1
6a35f0a2-b19c-4518-8c2b-56793070490d.ps1
[sourcecode language="css"] ## # ----------------------------------------------------- function Release-Ref ($ref) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } # ----------------------------------------------------- $objExcel = new-object -comobject excel.application $objExcel.Visible = $True $objWorkbook = $objExcel.Workbooks.Open("C:\\Users\\username\\Desktop\\scripts\\groupmaps.xlsx") # write into cell B2 (column 2, line 2): #$objWorkbook.ActiveSheet.Cells.Item(2,2)= "Test a Write" # read cell content #$content = $objWorkbook.ActiveSheet.Cells.Item(3,1).Text #"Cell B2 content: $content" $RowNum = 2 While ($objWorkbook.ActiveSheet.Cells.Item($RowNum, 1).Text -ne "") { $lusername = $objWorkbook.ActiveSheet.Cells.Item($RowNum,2).Text Import-Csv C:\\Users\\username\\Desktop\\scripts\\usermaps.csv | foreach { if ($lusername -eq $_.ousername){ #Write-Host Match $lusername $_.ousername $_.nusername $objWorkbook.ActiveSheet.Cells.Item($RowNum,4)= $_.nusername $objWorkbook.ActiveSheet.Cells.Item($RowNum,5)= $_.DisplayName } } $RowNum++ } #close $a = Release-Ref($objWorkbook) $a = Release-Ref($objExcel) [/sourcecode]
PowerShellCorpus/PoshCode/PowerShell Template_4.ps1
PowerShell Template_4.ps1
Function New-Script { $strName = $env:username $date = get-date -format d $name = Read-Host "Filename" if ($name -eq "") { $name="NewTemplate" } $email = Read-Host "eMail Address" if ($email -eq "") { $email="email@mycompany.com" } $comment=@(); while($s = (Read-Host "Comment").Trim()){$comment+="$s`r`n#"} $file = New-Item -type file "$name.ps1" -force $template=@" ########################################################################### # # NAME: $name.ps1 # # AUTHOR: $strName # EMAIL: $email # # COMMENT: $comment # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 $date - Initial release # ########################################################################### "@ | out-file $file ii $file } Set-Alias new New-Script
PowerShellCorpus/PoshCode/Write-Log_1.ps1
Write-Log_1.ps1
function Write-Log { #region Parameters [cmdletbinding()] Param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $Message, [Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)] [string] $Level = “Info”, [Parameter()] [ValidateRange(1,30)] [Int16] $Indent = 0, [Parameter()] [IO.FileInfo] $Path = ”$env:temp\\PowerShellLog.txt”, [Parameter()] [Switch] $Clobber, [Parameter()] [String] $EventLogName, [Parameter()] [String] $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name, [Parameter()] [Int32] $EventID = 1 ) #endregion Begin {} Process { try { $msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message switch ($Level) { 'Error' { Write-Error $Message } 'Warn' { Write-Warning $Message } 'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor White} } if ($Clobber) { $msg | Out-File -FilePath $Path } else { $msg | Out-File -FilePath $Path -Append } if ($EventLogName) { if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) } $log = New-Object System.Diagnostics.EventLog $log.set_log($EventLogName) $log.set_source($EventSource) switch ($Level) { “Error” { $log.WriteEntry($Message, 'Error', $EventID) } “Warn” { $log.WriteEntry($Message, 'Warning', $EventID) } “Info” { $log.WriteEntry($Message, 'Information', $EventID) } } } } catch { throw “Failed to create log entry in: ‘$Path’. The error was: ‘$_’.” } } End {} <# .SYNOPSIS Writes logging information to screen and log file simultaneously. .DESCRIPTION Writes logging information to screen and log file simultaneously. Supports multiple log levels. .PARAMETER Message The message to be logged. .PARAMETER Level The type of message to be logged. .PARAMETER Indent The number of spaces to indent the line in the log file. .PARAMETER Path The log file path. .PARAMETER Clobber Existing log file is deleted when this is specified. .PARAMETER EventLogName The name of the system event log, e.g. 'Application'. .PARAMETER EventSource The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER EventID The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .EXAMPLE PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application' .EXAMPLE PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script" .INPUTS System.String .OUTPUTS No output. #> }
PowerShellCorpus/PoshCode/Select-Xml 2.2.ps1
Select-Xml 2.2.ps1
#requires -version 2.0 # Select-Xml 2.2 and Remove-XmlNamespace # Version History: # Select-Xml 2.0 was the first script version I wrote, and 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 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* function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform # [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(ParameterSetName="Content",Mandatory=$true)] [String[]]$Content , [Parameter(Position=0,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [String[]]$Path , [Parameter(Position=0,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true)] [Alias("IO","InputObject")] [System.Xml.XmlDocument[]]$Xml ) BEGIN { $xslt = New-Object System.Xml.Xsl.XslCompiledTransform $xslt.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { [System.Xml.XmlDocument[]]$Xml = @( [Xml]($Content -Join "`n") ) } "Path" { [System.Xml.XmlDocument[]]$Xml = @() foreach($file in Get-ChildItem $Path) { $Xml += [Xml](Get-Content $file) } } "Xml" { } } foreach($input in $Xml) { $Output = New-Object System.Xml.XmlDocument $writer =$output.CreateNavigator().AppendChild() $xslt.Transform( $input.CreateNavigator(), $null, $writer ) $writer.Close() # $writer.Dispose() Write-Output $output } } }
PowerShellCorpus/PoshCode/Resolve-Aliases _3.7.ps1
Resolve-Aliases _3.7.ps1
#requires -version 2.0 ## ResolveAliases Module v 1.6 ######################################################################################################################## ## Sample Use: ## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1 ## ls *.ps1 | Resolve-Aliases -Inplace ######################################################################################################################## ## Version History ## 1.0 - First Version. "It worked on my sample script" ## 1.1 - Now it parses the $(...) blocks inside strings ## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts) ## 1.3 - I went back to processing the whole script at once (instead of a line at a time) ## Processing a line at a time makes it impossible to handle Here-Strings... ## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it ## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is ## 1.4 - Now resolves parameters too ## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem) ## - Refactored the Resolve-Line filter right out of existence ## - Created a test script for validation, and ## 1.6 - Added resolving parameter ALIASES instead of just short-forms ## 1.7 - Minor tweak to make it work in CTP3 ## ## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path ## * *TODO:* Add an option to put #requires statements at the top for each snapin used ######################################################################################################################## function which { PARAM( [string]$command ) # aliases, functions, cmdlets, scripts, executables, normal files $cmds = @(Get-Command $command -EA "SilentlyContinue") if($cmds.Count -gt 1) { $cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0] } else { $cmd = $cmds[0] } if(!$cmd) { $cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0] } if( $cmd.CommandType -eq "Alias" ) { $cmd = which $cmd.Definition } return $cmd } function Resolve-Aliases { [CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")] Param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")] [string]$Line , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")] [Alias("FullName","PSChildName","PSPath")] [IO.FileInfo]$File , [Parameter(Position=1, ParameterSetName="Files")] [Switch]$InPlace ) BEGIN { Write-Debug $PSCmdlet.ParameterSetName } PROCESS { if($PSCmdlet.ParameterSetName -eq "Files") { if($File -is [System.IO.FileInfo]){ $Line = ((Get-Content $File) -join "`n") } else { throw "We can't resolve a whole folder at once yet" } } $Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null) for($t = $Tokens.Count; $t -ge 0; $t--) { $token = $Tokens[$t] # DEBUG $token | fl * | out-host switch($token.Type) { "Command" { $cmd = which $token.Content Write-Debug "Command $($token.Content) => $($cmd.Name)" #if($cmd.CommandType -eq "Alias") { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name ) #} } "CommandParameter" { Write-Debug "Parameter $($token.Content)" for($c = $t; $c -ge 0; $c--) { if( $Tokens[$c].Type -eq "Command" ) { $cmd = which $Tokens[$c].Content # if($cmd.CommandType -eq "Alias") { # $cmd = @(which $cmd.Definition)[0] # } $short = $token.Content -replace "^-?","^" Write-Debug "Parameter $short" $parameters = $cmd.ParameterSets | Select -expand Parameters $param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique) if($param.Count -eq 1) { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" ) } break } } } } } switch($PSCmdlet.ParameterSetName) { "Text" { $Line } "Files" { switch($File.GetType()) { "System.IO.FileInfo" { if($InPlace) { $Line | Set-Content $File } else { $Line } } default { throw "We can't resolve a whole folder at once yet" } } } default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" } } } }
PowerShellCorpus/PoshCode/Xml Module 4.ps1
Xml Module 4.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 $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } function Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Indent # The indent level (defaults to 2 spaces) Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] [xml]$xml , [Parameter(Mandatory=$false)] $indent=2 ) $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 function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter Xsl # Specifies an Xml StyleSheet to transform with... [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias cvxml Convert-Xml function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace 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 # [XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # [string]$xml = New-XDocument rss -dc $dc -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # dc:language {"en"} # dc:creator {"Jaykul@HuddledMasses.org"} # dc:rights {"Copyright 2009, CC-BY"} # dc:date {(Get-Date -f u) -replace " ","T"} # # 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"} # } # } # } # # $xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # $xml.ToString() # # # OUTPUT: (NOTE: I added the space in the http: to paste it on PoshCode -- those aren't in the output) # # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss xmlns:dc="http ://purl.org/dc/elements/1.1" 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> # <dc:language>en</dc:language> # <dc:creator>Jaykul@HuddledMasses.org</dc:creator> # <dc:rights>Copyright 2009, CC-BY</dc:rights> # <dc:date>2009-07-26T00:50:08Z</dc:date> # <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> # #.Example # This time with a default namespace ## IMPORTANT! ## NOTE that I use the "xe" shortcut which is redefined when you specify a namespace ## ## for the root element, so that all child elements (by default) inherit that. ## ## You can still control the prefixes by passing the namespace as a parameter ## ## e.g.: -atom $atom ## The `: in the http`: is still only there for PoshCode, you can just use http: ... # # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # [XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # 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() } # # # OUTPUT: (NOTE: I added the spaces again to the http: to paste it on PoshCode) # # # <?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> # # 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" , [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) BEGIN { $script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]' $script:NameSpaceStack = New-Object 'Stack[XNamespace]' if(![string]::IsNullOrEmpty( $root.NamespaceName )) { $script:NameSpaceStack.Push( $root.Namespace ) } elseif( $script:NameSpaceStack.Count -gt 0 ) { $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() ) } else { $script:NameSpaceStack.Push( $null ) } } PROCESS { #New-Object XDocument (New-Object XDeclaration "1.0", "UTF-8", "yes"),( 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 = DSL $attrib Write-Verbose "Reparsed DSL: $attrib" &$attrib } elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) { $value = DSL $value &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $value } } )) } END { $null = $script:NameSpaceStack.Pop() } } Set-Alias xml New-XDocument Set-Alias New-Xml New-XDocument function New-XAttribute { #.Synopsys # Creates a new XAttribute (an xml attribute on an XElement for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter name # The attribute name #.Parameter value # The attribute value Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value) New-Object XAttribute $name, $value } Set-Alias xa New-XAttribute Set-Alias New-XmlAttribute New-XAttribute function New-XElement { #.Synopsys # Creates a new XElement (an xml tag for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter tag # The name of the xml tag #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$tag , [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)) { # then it's content &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $value } } ) } END { $null = $script:NameSpaceStack.Pop() } } Set-Alias xe New-XElement Set-Alias New-XmlElement New-XElement function DSL { Param([ScriptBlock]$script) $parserrors = $null $global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) $duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and ($(Get-Command $_.Content -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) + "'" ) } # insert 'xe' before everything (unless it's a valid command) $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " ) } Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") )) } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml
PowerShellCorpus/PoshCode/DefaultParameterValues_1.ps1
DefaultParameterValues_1.ps1
function Export-DefaultParameter { #.Synopsis # Exports the current default parameter values [CmdletBinding()] param( # The path to export default parameter values to (defaults to "DefaultParameterValues.clixml" in your profile directory) [String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml) ) Export-CliXml -InputObject $Global:PSDefaultParameterValues -Path $Path } function Import-DefaultParameter { #.Synopsis # Imports new default parameter values [CmdletBinding()] param( # The path to import default parameter values from (defaults to "DefaultParameterValues.clixml" in your profile directory) [String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml), # If set, overwrite current values (otherwise, keep current values) [Switch]$Force ) $TempParameterValues = $Global:PSDefaultParameterValues if(Test-Path $Path) { [System.Management.Automation.DefaultParameterDictionary]$NewValues = Import-CliXml -Path ${ProfileDir}\\DefaultParameterValues.clixml foreach($key in $NewValues.Keys) { if($Global:PSDefaultParameterValues.ContainsKey($key)) { if($Force) { $Global:PSDefaultParameterValues.$Key = $NewValues.$key } else { Write-Warning ("Key already defined, use -Force to overwrite:`n{0} = {1}" -f $Key, $NewValues.$key) } } else { $Global:PSDefaultParameterValues.$Key = $NewValues.$key } } } else { Write-Warning "Default Parameter file not found: '$Path'" } } function Set-DefaultParameter { #.Synopsis # Sets a default parameter value for a command #.Description # Safely sets the default parameter value for a command, making sure that you've correctly typed the command and parameter combination [CmdletBinding(DefaultParameterSetName="Colonated")] param( # The command that you want to change the default value of a parameter for [parameter(Position=0,Mandatory=$true)] $command, # The name of the parameter that you want to change the default value for [parameter(Position=1,Mandatory=$true,ParameterSetName="SeparateInputs")] $parameter, # The new default parameter value [parameter(Position=2,Mandatory=$true)] $value ) if($PSCmdlet.ParameterSetName -eq "Colonated") { $parameter = $command -split ":" } if($parameter.StartsWith("-")) { $parameter = $parameter.TrimStart("-") } ## Resolve the parameter to be sure $cmd = Get-Command $command $parameters = $cmd.ParameterSets | Select -expand Parameters $param = @($parameters | Where-Object { $_.Name -match $parameter -or $_.Aliases -match $parameter} | Select -Expand Name -Unique) if($param.Count -eq 1) { Write-Verbose "Parameter $parameter => $($param[0])" $Global:PSDefaultParameterValues["${Command}:$($param[0])"] = $Value } } function Disable-DefaultParameter { #.Synopsis # Turns OFF default parameters #.Description # By setting $PSDefaultParameterValues["Disable"] to $true, we make sure that NONE of our default parameter values will be used [CmdletBinding()] param() $Global:PSDefaultParameterValues["Disable"]=$true } function Enable-DefaultParameter { #.Synopsis # Turns ON default parameters #.Description # By setting $PSDefaultParameterValues["Disable"] to $false, we make sure that all of our default parameter values will be used [CmdletBinding()] param() $Global:PSDefaultParameterValues["Disable"]=$false } Set-Alias Add-DefaultParameter Set-DefaultParameter -ErrorAction SilentlyContinue Import-DefaultParameter
PowerShellCorpus/PoshCode/Get-Weather_2.ps1
Get-Weather_2.ps1
Function Get-Weather { <# .SYNOPSIS Display weather data for a specific country and city. .DESCRIPTION Display weather data for a specific country and city. There is a possibility for this to fail if the web service being used is unavailable. .PARAMETER Country URL of the website to test access to. .PARAMETER ListCities Use the currently authenticated user's credentials .PARAMETER City Used to connect via a proxy .NOTES Name: Get-Weather Author: Boe Prox DateCreated: 15Feb2011 .LINK http://www.webservicex.net/ws/default.aspx .LINK http://boeprox.wordpress.com .EXAMPLE Get-Weather -Country "United States" -ListCities Description ------------ Returns all of the available cities that are available to retrieve weather information from. .EXAMPLE Get-Weather -Country "United States" -City "San Francisco" Description ------------ Retrieves the current weather information for San Francisco #> [cmdletbinding( DefaultParameterSetName = 'Weather', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [string]$Country, [Parameter( Position = 1, Mandatory = $False, ParameterSetName = 'listcities')] [switch]$ListCities, [Parameter( Mandatory = $False, ParameterSetName = '')] [string]$City ) Begin { $psBoundParameters.GetEnumerator() | % { Write-Verbose "Parameter: $_" } Try { #Make connection to known good weather service Write-Verbose "Create web proxy connection to weather service" $weather = New-WebServiceProxy 'http://www.webservicex.net/globalweather.asmx?WSDL' } Catch { Write-Warning "$($Error[0])" Break } } Process { #Determine if we are only to list the cities for a given country or get the weather from a city Switch ($PSCmdlet.ParameterSetName) { ListCities { Try { #List all cities available to query for weather Write-Verbose "Listing cities in country: $($country)" (([xml]$weather.GetCitiesByCountry("$country")).newdataset).table | Sort City | Select City Break } Catch { Write-Warning "$($Error[0])" Break } } Weather { Try { #Get the weather for the city and country Write-Verbose "Getting weather for Country: $($country), City $($city)" ([xml]$weather.GetWeather("$city", "$country")).CurrentWeather } Catch { Write-Warning "$($Error[0])" } } } } End { Write-Verbose "End function, performing clean-up" Remove-Variable city -Force Remove-Variable country -Force } }
PowerShellCorpus/PoshCode/File navigator.ps1
File navigator.ps1
$empty = "<NULL>" $itmType = "Directory", "File" function LoadTreeView { $nodes = [IO.Directory]::GetLogicalDrives() $trvRoot.Nodes.Clear() foreach ($nod in $nodes) { $node = New-Object Windows.Forms.TreeNode $node = $trvRoot.Nodes.Add($nod) $node.Nodes.Add($empty) } } function AddFolders { $strPath = $_.Node.FullPath $_.Node.Nodes.Clear() trap {[Windows.Forms.MessageBox]::Show($_.Exception.Message, "Error", ` [Windows.Forms.MessageBoxButtons]::OK, ` [Windows.Forms.MessageBoxIcon]::Exclamation); continue } foreach ($strDir in [IO.Directory]::GetDirectories($strPath)) { $newNode = $_.Node.Nodes.Add([IO.Path]::GetFileName($strDir)) $newNode.Tag = $itmType[0] $newNode.Nodes.Add($empty) } } function AddFiles { $strPath = $_.Node.FullPath $ErrorActionPreference = "SilentlyContinue" foreach ($strFile in [IO.Directory]::GetFiles($strPath)) { $newNode = $_.Node.Nodes.Add([IO.Path]::GetFileName($strFile)) $newNode.Tag = $itmType[1] } } function ClearProperties { $lblAttributes.Text = [String]::Empty $lblCreationTime.Text = [String]::Empty $lblLastAccessTime.Text = [String]::Empty $lblLastWriteTime.Text = [String]::Empty $lblExtension.Text = [String]::Empty $lblFullName.Text = [String]::Empty $lblName.Text = [String]::Empty $lblParent.Text = [String]::Empty $lblRoot.Text = [String]::Empty $lblLength.Text = [String]::Empty } $trvRoot_OnBeforeExpand= { AddFolders AddFiles } $trvRoot_OnAfterSelect= { if ($_.Node.Tag -eq $itmType[0]) { $lblExtension.Text = [String]::Empty $lblLength.Text = [String]::Empty $lblLabel5.Enabled = $false $lblLabel8.Enabled = $true $lblLabel9.Enabled = $true $lblLabel10.Enabled = $false $di = [IO.DirectoryInfo]($_.Node.FullPath) $lblAttributes.Text = $di.Attributes $lblCreationTime.Text = $di.CreationTime $lblLastAccessTime.Text = $di.LastAccessTime $lblLastWriteTime.Text = $di.LastWriteTime $lblFullName.Text = $di.FullName $lblName.Text = $di.Name $lblParent.Text = $di.Parent.Name $lblRoot.Text = $di.Root.Name } elseif ($_.Node.Tag -eq $itmType[1]) { $lblParent.Text = [String]::Empty $lblRoot.Text = [String]::Empty $lblLabel5.Enabled = $true $lblLabel8.Enabled = $false $lblLabel9.Enabled = $false $lblLabel10.Enabled = $true $fi = [IO.FileInfo]($_.Node.FullPath) $lblAttributes.Text = $fi.Attributes $lblCreationTime.Text = $fi.CreationTime $lblLastAccessTime.Text = $fi.LastAccessTime $lblLastWriteTime.Text = $fi.LastWriteTime $lblExtension.Text = $fi.Extension $lblFullName.Text = $fi.FullName $lblName.Text = $fi.Name $lblLength.Text = $fi.Length } else { ClearProperties } } $mnuRefresh_OnClick= { LoadTreeView ClearProperties } $frmMain_OnLoad= { LoadTreeView } function ShowMainWindow { [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Drawing") [Windows.Forms.Application]::EnableVisualStyles() $frmMain = New-Object Windows.Forms.Form $mnuMain = New-Object Windows.Forms.MainMenu $mnuFile = New-Object Windows.Forms.MenuItem $mnuRefresh = New-Object Windows.Forms.MenuItem $mnuExit = New-Object Windows.Forms.MenuItem $mnuHelp = New-Object Windows.Forms.MenuItem $mnuAbout = New-Object Windows.Forms.MenuItem $trvRoot = New-Object Windows.Forms.TreeView $lblLabel1 = New-Object Windows.Forms.Label $lblLabel2 = New-Object Windows.Forms.Label $lblLabel3 = New-Object Windows.Forms.Label $lblLabel4 = New-Object Windows.Forms.Label $lblLabel5 = New-Object Windows.Forms.Label $lblLabel6 = New-Object Windows.Forms.Label $lblLabel7 = New-Object Windows.Forms.Label $lblLabel8 = New-Object Windows.Forms.Label $lblLabel9 = New-Object Windows.Forms.Label $lblLabel10 = New-Object Windows.Forms.Label $lblAttributes = New-Object Windows.Forms.Label $lblCreationTime = New-Object Windows.Forms.Label $lblLastAccessTime = New-Object Windows.Forms.Label $lblLastWriteTime = New-Object Windows.Forms.Label $lblExtension = New-Object Windows.Forms.Label $lblFullName = New-Object Windows.Forms.Label $lblName = New-Object Windows.Forms.Label $lblParent = New-Object Windows.Forms.Label $lblRoot = New-Object Windows.Forms.Label $lblLength = New-Object Windows.Forms.Label #mnuMain $mnuMain.MenuItems.AddRange(@($mnuFile, $mnuHelp)) #mnuFile $mnuFile.MenuItems.AddRange(@($mnuRefresh, $mnuExit)) $mnuFile.Text = "&File" #mnuRefresh $mnuRefresh.Shortcut = "F5" $mnuRefresh.Text = "&Refresh" $mnuRefresh.Add_Click($mnuRefresh_OnClick) #mnuExit $mnuExit.Shortcut = "CtrlX" $mnuExit.Text = "E&xit" $mnuExit.Add_Click( { $frmMain.Close() } ) #mnuHelp $mnuHelp.MenuItems.AddRange(@($mnuAbout)) $mnuHelp.Text = "&Help" #mnuAbout $mnuAbout.Text = "About" $mnuAbout.Add_Click( { ShowAboutWindow } ) #trvRoot $trvRoot.Anchor = "Top, Bottom, Left, Right" $trvRoot.Location = New-Object Drawing.Point(8, 8) $trvRoot.Size = New-Object Drawing.Size(392, 195) $trvRoot.Add_BeforeExpand($trvRoot_OnBeforeExpand) $trvRoot.Add_AfterSelect($trvRoot_OnAfterSelect) #lblLabel1 $lblLabel1.Anchor = "Bottom, Left" $lblLabel1.Location = New-Object Drawing.Point(8, 210) $lblLabel1.Size = New-Object Drawing.Size(104, 23) $lblLabel1.Text = "Attributes:" $lblLabel1.TextAlign = "MiddleRight" #lblLabel2 $lblLabel2.Anchor = "Bottom, Left" $lblLabel2.Location = New-Object Drawing.Point(8, 234) $lblLabel2.Size = New-Object Drawing.Size(104, 23) $lblLabel2.Text = "Creation Time:" $lblLabel2.TextAlign = "MiddleRight" #lblLabel3 $lblLabel3.Anchor = "Bottom, Left" $lblLabel3.Location = New-Object Drawing.Point(8, 258) $lblLabel3.Size = New-Object Drawing.Size(104, 23) $lblLabel3.Text = "Last Access Time:" $lblLabel3.TextAlign = "MiddleRight" #lblLabel4 $lblLabel4.Anchor = "Bottom, Left" $lblLabel4.Location = New-Object Drawing.Point(8, 282) $lblLabel4.Size = New-Object Drawing.Size(104, 23) $lblLabel4.Text = "Last Write Time:" $lblLabel4.TextAlign = "MiddleRight" #lblLabel5 $lblLabel5.Anchor = "Bottom, Left" $lblLabel5.Location = New-Object Drawing.Point(8, 314) $lblLabel5.Size = New-Object Drawing.Size(104, 23) $lblLabel5.Text = "Extension:" $lblLabel5.TextAlign = "MiddleRight" #lblLabel6 $lblLabel6.Anchor = "Bottom, Left" $lblLabel6.Location = New-Object Drawing.Point(8, 338) $lblLabel6.Size = New-Object Drawing.Size(104, 23) $lblLabel6.Text = "Full Name:" $lblLabel6.TextAlign = "MiddleRight" #lblLabel7 $lblLabel7.Anchor = "Bottom, Left" $lblLabel7.Location = New-Object Drawing.Point(8, 362) $lblLabel7.Size = New-Object Drawing.Size(104, 23) $lblLabel7.Text = "Name:" $lblLabel7.TextAlign = "MiddleRight" #lblLabel8 $lblLabel8.Anchor = "Bottom, Left" $lblLabel8.Location = New-Object Drawing.Point(8, 386) $lblLabel8.Size = New-Object Drawing.Size(104, 23) $lblLabel8.Text = "Parent:" $lblLabel8.TextAlign = "MiddleRight" #lblLabel9 $lblLabel9.Anchor = "Bottom, Left" $lblLabel9.Location = New-Object Drawing.Point(8, 410) $lblLabel9.Size = New-Object Drawing.Size(104, 23) $lblLabel9.Text = "Root:" $lblLabel9.TextAlign = "MiddleRight" #lblLabel10 $lblLabel10.Anchor = "Bottom, Left" $lblLabel10.Location = New-Object Drawing.Point(8, 434) $lblLabel10.Size = New-Object Drawing.Size(104, 23) $lblLabel10.Text = "Length:" $lblLabel10.TextAlign = "MiddleRight" #lblAttributes $lblAttributes.Anchor = "Bottom, Left, Right" $lblAttributes.BorderStyle = "Fixed3D" $lblAttributes.Location = New-Object Drawing.Point(120, 211) $lblAttributes.Size = New-Object Drawing.Size(280, 20) $lblAttributes.TextAlign = "MiddleLeft" #lblCreationTime $lblCreationTime.Anchor = "Bottom, Left, Right" $lblCreationTime.BorderStyle = "Fixed3D" $lblCreationTime.Location = New-Object Drawing.Point(120, 235) $lblCreationTime.Size = New-Object Drawing.Size(280, 20) $lblCreationTime.TextAlign = "MiddleLeft" #lblLastAccessTime $lblLastAccessTime.Anchor = "Bottom, Left, Right" $lblLastAccessTime.BorderStyle = "Fixed3D" $lblLastAccessTime.Location = New-Object Drawing.Point(120, 259) $lblLastAccessTime.Size = New-Object Drawing.Size(280, 20) $lblLastAccessTime.TextAlign = "MiddleLeft" #lblLastWriteTime $lblLastWriteTime.Anchor = "Bottom, Left, Right" $lblLastWriteTime.BorderStyle = "Fixed3D" $lblLastWriteTime.Location = New-Object Drawing.Point(120, 283) $lblLastWriteTime.Size = New-Object Drawing.Size(280, 20) $lblLastWriteTime.TextAlign = "MiddleLeft" #lblExtension $lblExtension.Anchor = "Bottom, Left, Right" $lblExtension.BorderStyle = "Fixed3D" $lblExtension.Location = New-Object Drawing.Point(120, 315) $lblExtension.Size = New-Object Drawing.Size(280, 20) $lblExtension.TextAlign = "MiddleLeft" #lblFullName $lblFullName.Anchor = "Bottom, Left, Right" $lblFullName.BorderStyle = "Fixed3D" $lblFullName.Location = New-Object Drawing.Point(120, 339) $lblFullName.Size = New-Object Drawing.Size(280, 20) $lblFullName.TextAlign = "MiddleLeft" #lblName $lblName.Anchor = "Bottom, Left, Right" $lblName.BorderStyle = "Fixed3D" $lblName.Location = New-Object Drawing.Point(120, 363) $lblName.Size = New-Object Drawing.Size(280, 20) $lblName.TextAlign = "MiddleLeft" #lblParent $lblParent.Anchor = "Bottom, Left, Right" $lblParent.BorderStyle = "Fixed3D" $lblParent.Location = New-Object Drawing.Point(120, 387) $lblParent.Size = New-Object Drawing.Size(280, 20) $lblParent.TextAlign = "MiddleLeft" #lblRoot $lblRoot.Anchor = "Bottom, Left, Right" $lblRoot.BorderStyle = "Fixed3D" $lblRoot.Location = New-Object Drawing.Point(120, 411) $lblRoot.Size = New-Object Drawing.Size(280, 20) $lblRoot.TextAlign = "MiddleLeft" #lblLength $lblLength.Anchor = "Bottom, Left, Right" $lblLength.BorderStyle = "Fixed3D" $lblLength.Location = New-Object Drawing.Point(120, 435) $lblLength.Size = New-Object Drawing.Size(280, 20) $lblLength.TextAlign = "MiddleLeft" #frmMain $frmMain.ClientSize = New-Object Drawing.Size(408, 463) $frmMain.Controls.AddRange(@($trvRoot, $lblLabel1, $lblLabel2, $lblLabel3, $lblLabel4, ` $lblLabel5, $lblLabel6, $lblLabel7, $lblLabel8, $lblLabel9, ` $lblLabel10, $lblAttributes, $lblCreationTime, $lblLastAccessTime, ` $lblLastWriteTime, $lblExtension, $lblFullName, $lblName, ` $lblParent, $lblRoot, $lblLength)) $frmMain.Menu = $mnuMain $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "File Navigator" $frmMain.Add_Load($frmMain_OnLoad) [void]$frmMain.ShowDialog() } function ShowAboutWindow { $frmAbout = New-Object Windows.Forms.Form $lblInfo = New-Object Windows.Forms.Label $btnExit = New-Object Windows.Forms.Button #lblInfo $lblInfo.Location = New-Object Drawing.Point(13, 23) $lblInfo.Size = New-Object Drawing.Size(270, 50) $lblInfo.Text = "(C) 2012 Grigori Zakharov `n This is just an example that you can make better." #btnExit $btnExit.Location = New-Object Drawing.Point(100, 80) $btnExit.TabIndex = 0 $btnExit.Text = "Close" $btnExit.Add_Click( { $frmAbout.Close() } ) #frmAbot $frmAbout.ClientSize = New-Object Drawing.Size(280, 117) $frmAbout.ControlBox = $false $frmAbout.Controls.AddRange(@($lblInfo, $btnExit)) $frmAbout.FormBorderStyle = "FixedSingle" $frmAbout.ShowInTaskbar = $false $frmAbout.StartPosition = "CenterScreen" $frmAbout.Text = "About..." [void]$frmAbout.ShowDialog() } ShowMainWindow
PowerShellCorpus/PoshCode/MainulatingCustomObjects.ps1
MainulatingCustomObjects.ps1
function JoinTwoCustomObjs($Parent,$Child,$Key) { $CurrentErrorSetting = $ErrorActionPreference $ErrorActionPreference = 'SilentlyContinue' $new = New-Object -TypeName PsObject $ParentProps = Get-Member -InputObject $Parent -MemberType NoteProperty foreach($prop in $ParentProps) { $PropName = $prop.Name $value = $Parent.$PropName Write-Host $value Add-Member -InputObject $new -MemberType NoteProperty -Name $PropName -Value $value } $ChildProps = Get-Member -InputObject $Child -MemberType NoteProperty foreach($Prop in $ChildProps) { $PropName = $prop.Name $ChildValue = $Child.$PropName if($PropName -notmatch $key) { Add-Member -InputObject $new -MemberType NoteProperty -Name $PropName -Value $ChildValue } if(!$?) { if($new.$PropName -notmatch $ChildValue) { $new.$PropName += ', ' + $ChildValue } } } $ErrorActionPreference = $CurrentErrorSetting $new } function Insert-Object($Child,$Key) { begin { $CurrentErrorSetting = $ErrorActionPreference $ErrorActionPreference = 'SilentlyContinue' $objs = @() $childHash = @{} $child | %{ $ChildHash.Add($_.$Key,$_) ; if(!$?) { JoinTwoCustomObjs $ChildHash[$Key] $_ $Key } } $ErrorActionPreference = $CurrentErrorSetting } process { $obj = New-Object -TypeName PsObject $thisKey = $_.$key if($ChildHash.ContainsKey($thisKey)) { $obj = JoinTwoCustomObjs -Parent $_ -Child $($childHash[$thisKey]) -Key $Key $objs += $obj } } end { $objs } }
PowerShellCorpus/PoshCode/finddupe_10.ps1
finddupe_10.ps1
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]; $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; } write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]" $matches = 0 # initialize number of matches for summary. $filesdeleted = 0 # number of files deleted. $bytesrec = 0 # Number of bytes recovered. $files=@() $del = $false # delete duplicates $noprompt = $false # delete without prompting toggle for ($i=0;$i -ne $args.count; $i++) { if ($args[$i] -eq "-delete") { $del=$true;continue } else { if ($args[$i] -eq "-noprompt") { $noprompt=$true;continue } else { $files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true}) } } } if ($files -eq $null) {write-host "No files found." -f red; exit} for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} $md5 = $null $filecheck = $files[$i] $files[$i] = $null for ($c=0;$c -ne $files.count; $c++) { if ($files[$c] -eq $null) {continue} # write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline if ($filecheck.length -eq $files[$c].length) { #write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)} if ($md5 -eq (get-md5 $files[$c])) { write-host "Size and MD5 match: " -fore red -nonewline "{0} and {1}" -f $filecheck.fullname, $files[$c].fullname $matches++ if ($del -eq $true) { if ($noprompt -eq $true) { del $files[$c].fullname;write-host "$($files[$c].fullname) deleted." -f Red } else { del $files[$c].fullname -confirm } if ((get-item -ea 0 $files[$c].fullname) -eq $null) { $filesdeleted += 1 $bytesrec += $files[$c].length } } $files[$c] = $null } } } } write-host "" write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found. write-host "Number of matches found: $matches." Write-host "Number of files deleted: $filesdeleted." # Display number of files deleted and bytes recovered. write-host "Number of bytes recovered: $bytesrec." write-host ""
PowerShellCorpus/PoshCode/Exchange AutoReply Admin.ps1
Exchange AutoReply Admin.ps1
<# .NOTES Name : Exchange Automatic Replies Administrator.ps1 Author : Bryan Jaudon <bryan.jaudon@gmail.com> Version : 1.0 Date : 11/23/2012 .SYNOPSIS Provides a graphical front-end to the Get-MailboxAutoReplyConfiguration and Set-MailboxAutoReplyConfiguration Exchange cmdlets. Requires Exchange management tools be installed on the same system as the script. #> #requires -version 2 $Script:ScriptTitle="Exchange Automatic Replies Administrator" #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() #endregion #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 # Generated On: 11/21/2012 1:56 PM # Generated By: bjaudon ######################################################################## #region Generated Form Objects $form1 = New-Object System.Windows.Forms.Form $labelConnectedFQDN = New-Object System.Windows.Forms.Label $labelConnected = New-Object System.Windows.Forms.Label $buttonOK = New-Object System.Windows.Forms.Button $buttonCancel = New-Object System.Windows.Forms.Button $labelAutoreply = New-Object System.Windows.Forms.Label $tabControl1 = New-Object System.Windows.Forms.TabControl $tabPage1 = New-Object System.Windows.Forms.TabPage $textInside = New-Object System.Windows.Forms.TextBox $tabPage2 = New-Object System.Windows.Forms.TabPage $textOutside = New-Object System.Windows.Forms.TextBox $dateEndTime = New-Object System.Windows.Forms.DateTimePicker $dateEndDate = New-Object System.Windows.Forms.DateTimePicker $labelEndTime = New-Object System.Windows.Forms.Label $dateStartTime = New-Object System.Windows.Forms.DateTimePicker $dateStartDate = New-Object System.Windows.Forms.DateTimePicker $labelStartTime = New-Object System.Windows.Forms.Label $checkOnlySend = New-Object System.Windows.Forms.CheckBox $radioSend = New-Object System.Windows.Forms.RadioButton $radioDoNotSend = New-Object System.Windows.Forms.RadioButton $comboIdentity = New-Object System.Windows.Forms.ComboBox $labelIdentity = New-Object System.Windows.Forms.Label $labelTitle = New-Object System.Windows.Forms.Label $pbIcon = New-Object System.Windows.Forms.PictureBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $dateEndDate_ValueChanged= { $buttonOK.Enabled=$true } $dateStartTime_ValueChanged= { $buttonOK.Enabled=$true } $textOutside_TextChanged= { $buttonOK.Enabled=$true } $textInside_TextChanged= { $buttonOK.Enabled=$true } $dateStartDate_ValueChanged= { $buttonOK.Enabled=$true } $dateEndTime_ValueChanged= { $buttonOK.Enabled=$true } $buttonOK_OnClick= { $commandHashTable=@{ "Identity"=$comboIdentity.SelectedItem } if ($radioDoNotSend.Checked) { $commandHashTable.Add("AutoReplyState","Disabled") } else { if ($checkOnlySend.Checked) { $commandHashTable.Add("AutoReplyState","Scheduled") $commandHashTable.Add("StartTime",$(Get-Date -Month $dateStartDate.value.Month -Day $dateStartDate.Value.Day -Year $dateStartDate.value.Year -Hour $dateStartTime.Value.Hour -Minute $dateStartTime.value.Minute -Second $dateStartTime.value.Second)) $commandHashTable.Add("EndTime",$(Get-Date -Month $dateEndDate.value.Month -Day $dateEndDate.Value.Day -Year $dateEndDate.value.Year -Hour $dateEndTime.Value.Hour -Minute $dateEndTime.value.Minute -Second $dateEndTime.value.Second)) if ($commandHashTable["EndTime"] -le $commandHashTable["StartTime"]) { ShowPrompt -Message "The end time cannot be less than or equal to start time." -icon Error -Buttons OK;return } if ($commandHashTable["EndTime"] -le (Get-Date)) { ShowPrompt -Message "The end time that you entered occurs before the current time." -icon Error -Buttons OK;return } } else { $commandHashTable.Add("AutoReplyState","Enabled") } $commandHashTable.Add("InternalMessage",$textInside.Text) $commandHashTable.Add("ExternalMessage",$textOutside.Text) } try { $status=Get-MailboxAutoReplyConfiguration -Identity $comboIdentity.SelectedItem } catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return } $result=ShowPrompt -Message "You have chosen to change the Automatic Reply configuration for`n'$($comboIdentity.SelectedItem)' from the state of '$($status.AutoReplyState)' to the state of '$($commandhashtable["AutoReplyState"])'.`n`nDo you wish to commit this change?" -Buttons "YesNo" -icon Warning if ($result -eq "Yes") { try { Set-MailboxAutoReplyConfiguration @commandHashTable -ErrorAction STOP } catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return } try { $status=Get-MailboxAutoReplyConfiguration -Identity $comboIdentity.SelectedItem } catch { ShowPrompt -Message $_ -Icon Error -Buttons OK;return } if (($status.AutoReplyState -eq $commandHashTable["AutoReplyState"]) -and ($status.IsValid -eq $True)) { ShowPrompt -Message "Automatic Reply configuration successful!" -Icon Information -Buttons OK;GetAutoReplyStatus -identity $comboIdentity.SelectedItem;$buttonOK.Enabled=$false;$form1.Refresh();return } else { ShowPrompt -Message "Automatic Reply configuration failed. `n`nCurrent Status is: $($status.AutoReplyState)" -Icon Error -Buttons OK;GetAutoReplyStatus -identity $comboIdentity.SelectedItem;$form1.Refresh();return } } else { ShowPrompt -Message "Automatic Reply configuration cancelled!" -Icon Error -Buttons OK;return } } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $form1.WindowState = $InitialFormWindowState $form1.Update() try { $comboIdentity.items.AddRange($(Get-CASMailbox | sort -Property Identity | Select -ExpandProperty Identity)) } catch { ShowPrompt -Message $_ -Buttons OK -Icon Error } if ($comboIdentity.items.count -lt 1) { ShowPrompt -Message "There were no Mailboxes found in the Exchange Organization.`nExiting Application." -Buttons OK -Icon Error;$form1.Close() } } $comboIdentity_SelectionChangeCommitted= { GetAutoReplyStatus -identity $comboIdentity.SelectedItem } $handler_radioSend_Click= { $scheduledstate=$checkOnlySend.Checked Status-EnabledAutoReply $checkOnlySend.Checked=$scheduledstate } $handler_radioDoNotSend_Click= { $scheduledstate=$checkOnlySend.Checked Status-DisabledAutoReply $checkOnlySend.Checked=$scheduledstate } $handler_checkOnlySend_Click= { switch ($checkOnlySend.Checked) { true { Status-ScheduledAutoReply } false { Status-EnabledAutoReply } } } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 494 $System_Drawing_Size.Width = 538 $form1.ClientSize = $System_Drawing_Size $form1.DataBindings.DefaultDataSourceUpdateMode = 0 $form1.FormBorderStyle = 1 $form1.MaximizeBox = $False $form1.MinimizeBox = $False $form1.Name = "form1" $form1.ShowIcon = $True $form1.Text = $script:ScriptTitle $form1.Icon = $icon $labelConnectedFQDN.AutoEllipsis = $True $labelConnectedFQDN.DataBindings.DefaultDataSourceUpdateMode = 0 $labelConnectedFQDN.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 120 $System_Drawing_Point.Y = 459 $labelConnectedFQDN.Location = $System_Drawing_Point $labelConnectedFQDN.Name = "labelConnectedFQDN" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 238 $labelConnectedFQDN.Size = $System_Drawing_Size $labelConnectedFQDN.TabIndex = 18 $labelConnectedFQDN.Text = $connectedFqdn $labelConnectedFQDN.TextAlign = 16 $form1.Controls.Add($labelConnectedFQDN) $labelConnected.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 459 $labelConnected.Location = $System_Drawing_Point $labelConnected.Name = "labelConnected" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 101 $labelConnected.Size = $System_Drawing_Size $labelConnected.TabIndex = 17 $labelConnected.Text = "Connected Server:" $labelConnected.TextAlign = 16 $form1.Controls.Add($labelConnected) $buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonOK.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 370 $System_Drawing_Point.Y = 459 $buttonOK.Location = $System_Drawing_Point $buttonOK.Name = "buttonOK" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $buttonOK.Size = $System_Drawing_Size $buttonOK.TabIndex = 16 $buttonOK.Text = "OK" $buttonOK.UseVisualStyleBackColor = $True $buttonOK.add_Click($buttonOK_OnClick) $form1.Controls.Add($buttonOK) $buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonCancel.DialogResult = 2 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 451 $System_Drawing_Point.Y = 459 $buttonCancel.Location = $System_Drawing_Point $buttonCancel.Name = "buttonCancel" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 75 $buttonCancel.Size = $System_Drawing_Size $buttonCancel.TabIndex = 15 $buttonCancel.Text = "Cancel" $buttonCancel.UseVisualStyleBackColor = $True $form1.Controls.Add($buttonCancel) $labelAutoreply.DataBindings.DefaultDataSourceUpdateMode = 0 $labelAutoreply.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 234 $labelAutoreply.Location = $System_Drawing_Point $labelAutoreply.Name = "labelAutoreply" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 514 $labelAutoreply.Size = $System_Drawing_Size $labelAutoreply.TabIndex = 14 $labelAutoreply.Text = "Automatically reply once for each sender with the following messages:" $labelAutoreply.TextAlign = 16 $form1.Controls.Add($labelAutoreply) $tabControl1.DataBindings.DefaultDataSourceUpdateMode = 0 $tabControl1.Enabled = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 260 $tabControl1.Location = $System_Drawing_Point $tabControl1.Name = "tabControl1" $tabControl1.SelectedIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 179 $System_Drawing_Size.Width = 514 $tabControl1.Size = $System_Drawing_Size $tabControl1.TabIndex = 13 $form1.Controls.Add($tabControl1) $tabPage1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 4 $System_Drawing_Point.Y = 22 $tabPage1.Location = $System_Drawing_Point $tabPage1.Name = "tabPage1" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 3 $System_Windows_Forms_Padding.Bottom = 3 $System_Windows_Forms_Padding.Left = 3 $System_Windows_Forms_Padding.Right = 3 $System_Windows_Forms_Padding.Top = 3 $tabPage1.Padding = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 153 $System_Drawing_Size.Width = 506 $tabPage1.Size = $System_Drawing_Size $tabPage1.TabIndex = 0 $tabPage1.Text = "Inside My Organization" $tabPage1.UseVisualStyleBackColor = $True $tabControl1.Controls.Add($tabPage1) $textInside.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 7 $textInside.Location = $System_Drawing_Point $textInside.Multiline = $True $textInside.Name = "textInside" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 140 $System_Drawing_Size.Width = 494 $textInside.Size = $System_Drawing_Size $textInside.TabIndex = 0 $textInside.enabled=$false $textInside.ScrollBars=3 $textInside.add_TextChanged($textInside_TextChanged) $tabPage1.Controls.Add($textInside) $tabPage2.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 4 $System_Drawing_Point.Y = 22 $tabPage2.Location = $System_Drawing_Point $tabPage2.Name = "tabPage2" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 3 $System_Windows_Forms_Padding.Bottom = 3 $System_Windows_Forms_Padding.Left = 3 $System_Windows_Forms_Padding.Right = 3 $System_Windows_Forms_Padding.Top = 3 $tabPage2.Padding = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 153 $System_Drawing_Size.Width = 506 $tabPage2.Size = $System_Drawing_Size $tabPage2.TabIndex = 1 $tabPage2.Text = "Outside My Organization" $tabPage2.UseVisualStyleBackColor = $True $tabControl1.Controls.Add($tabPage2) $textOutside.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 7 $textOutside.Location = $System_Drawing_Point $textOutside.Multiline = $True $textOutside.Name = "textOutside" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 140 $System_Drawing_Size.Width = 494 $textOutside.Size = $System_Drawing_Size $textOutside.TabIndex = 0 $textOutside.enabled=$false $textOutside.ScrollBars=3 $textOutside.add_TextChanged($textOutside_TextChanged) $tabPage2.Controls.Add($textOutside) $dateEndTime.CustomFormat = "h:mm tt" $dateEndTime.DataBindings.DefaultDataSourceUpdateMode = 0 $dateEndTime.Enabled = $False $dateEndTime.Format = 8 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 282 $System_Drawing_Point.Y = 204 $dateEndTime.Location = $System_Drawing_Point $dateEndTime.Name = "dateEndTime" $dateEndTime.ShowUpDown = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 76 $dateEndTime.Size = $System_Drawing_Size $dateEndTime.TabIndex = 12 $dateEndTime.add_ValueChanged($dateEndTime_ValueChanged) $form1.Controls.Add($dateEndTime) $dateEndDate.CustomFormat = "ddd MM/dd/yyyy" $dateEndDate.DataBindings.DefaultDataSourceUpdateMode = 0 $dateEndDate.Enabled = $False $dateEndDate.Format = 8 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 152 $System_Drawing_Point.Y = 204 $dateEndDate.Location = $System_Drawing_Point $dateEndDate.Name = "dateEndDate" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 124 $dateEndDate.Size = $System_Drawing_Size $dateEndDate.TabIndex = 11 $dateEndDate.add_ValueChanged($dateEndDate_ValueChanged) $form1.Controls.Add($dateEndDate) $labelEndTime.DataBindings.DefaultDataSourceUpdateMode = 0 $labelEndTime.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 82 $System_Drawing_Point.Y = 202 $labelEndTime.Location = $System_Drawing_Point $labelEndTime.Name = "labelEndTime" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 64 $labelEndTime.Size = $System_Drawing_Size $labelEndTime.TabIndex = 10 $labelEndTime.Text = "End time:" $labelEndTime.TextAlign = 16 $form1.Controls.Add($labelEndTime) $dateStartTime.CustomFormat = "h:mm tt" $dateStartTime.DataBindings.DefaultDataSourceUpdateMode = 0 $dateStartTime.Enabled = $False $dateStartTime.Format = 8 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 282 $System_Drawing_Point.Y = 178 $dateStartTime.Location = $System_Drawing_Point $dateStartTime.Name = "dateStartTime" $dateStartTime.ShowUpDown = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 77 $dateStartTime.Size = $System_Drawing_Size $dateStartTime.TabIndex = 9 $dateStartTime.add_ValueChanged($dateStartTime_ValueChanged) $form1.Controls.Add($dateStartTime) $dateStartDate.CustomFormat = "ddd MM/dd/yyyy" $dateStartDate.DataBindings.DefaultDataSourceUpdateMode = 0 $dateStartDate.Enabled = $False $dateStartDate.Format = 8 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 152 $System_Drawing_Point.Y = 178 $dateStartDate.Location = $System_Drawing_Point $dateStartDate.Name = "dateStartDate" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 124 $dateStartDate.Size = $System_Drawing_Size $dateStartDate.TabIndex = 8 $dateStartDate.add_ValueChanged($dateStartDate_ValueChanged) $form1.Controls.Add($dateStartDate) $labelStartTime.DataBindings.DefaultDataSourceUpdateMode = 0 $labelStartTime.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 82 $System_Drawing_Point.Y = 175 $labelStartTime.Location = $System_Drawing_Point $labelStartTime.Name = "labelStartTime" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 64 $labelStartTime.Size = $System_Drawing_Size $labelStartTime.TabIndex = 7 $labelStartTime.Text = "Start time:" $labelStartTime.TextAlign = 16 $form1.Controls.Add($labelStartTime) $checkOnlySend.DataBindings.DefaultDataSourceUpdateMode = 0 $checkOnlySend.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 52 $System_Drawing_Point.Y = 148 $checkOnlySend.Location = $System_Drawing_Point $checkOnlySend.Name = "checkOnlySend" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 190 $checkOnlySend.Size = $System_Drawing_Size $checkOnlySend.TabIndex = 6 $checkOnlySend.Text = "Only send during this time range:" $checkOnlySend.UseVisualStyleBackColor = $True $checkOnlySend.add_Click($handler_checkOnlySend_Click) $form1.Controls.Add($checkOnlySend) $radioSend.DataBindings.DefaultDataSourceUpdateMode = 0 $radioSend.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 125 $radioSend.Location = $System_Drawing_Point $radioSend.Name = "radioSend" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 182 $radioSend.Size = $System_Drawing_Size $radioSend.TabIndex = 5 $radioSend.Text = "Send automatic replies" $radioSend.UseVisualStyleBackColor = $True $radioSend.add_Click($handler_radioSend_Click) $form1.Controls.Add($radioSend) $radioDoNotSend.Checked = $True $radioDoNotSend.DataBindings.DefaultDataSourceUpdateMode = 0 $radioDoNotSend.Enabled = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 104 $radioDoNotSend.Location = $System_Drawing_Point $radioDoNotSend.Name = "radioDoNotSend" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 24 $System_Drawing_Size.Width = 182 $radioDoNotSend.Size = $System_Drawing_Size $radioDoNotSend.TabIndex = 4 $radioDoNotSend.TabStop = $True $radioDoNotSend.Text = "Do not send automatic replies" $radioDoNotSend.UseVisualStyleBackColor = $True $radioDoNotSend.add_Click($handler_radioDoNotSend_Click) $form1.Controls.Add($radioDoNotSend) $comboIdentity.DataBindings.DefaultDataSourceUpdateMode = 0 $comboIdentity.DropDownStyle = 2 $comboIdentity.FormattingEnabled = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 69 $System_Drawing_Point.Y = 67 $comboIdentity.Location = $System_Drawing_Point $comboIdentity.Name = "comboIdentity" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 21 $System_Drawing_Size.Width = 458 $comboIdentity.Size = $System_Drawing_Size $comboIdentity.TabIndex = 3 $comboIdentity.add_SelectionChangeCommitted($comboIdentity_SelectionChangeCommitted) $form1.Controls.Add($comboIdentity) $labelIdentity.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 66 $labelIdentity.Location = $System_Drawing_Point $labelIdentity.Name = "labelIdentity" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 50 $labelIdentity.Size = $System_Drawing_Size $labelIdentity.TabIndex = 2 $labelIdentity.Text = "Identity:" $labelIdentity.TextAlign = 16 $form1.Controls.Add($labelIdentity) $labelTitle.DataBindings.DefaultDataSourceUpdateMode = 0 $labelTitle.Font = New-Object System.Drawing.Font("Trebuchet MS",9.75,1,3,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 52 $System_Drawing_Point.Y = 13 $labelTitle.Location = $System_Drawing_Point $labelTitle.Name = "labelTitle" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 31 $System_Drawing_Size.Width = 350 $labelTitle.Size = $System_Drawing_Size $labelTitle.TabIndex = 1 $labelTitle.Text = $script:ScriptTitle $labelTitle.TextAlign = 16 $form1.Controls.Add($labelTitle) $pbIcon.BackgroundImageLayout = 3 $pbIcon.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 13 $pbIcon.Location = $System_Drawing_Point $pbIcon.Name = "pbIcon" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 32 $System_Drawing_Size.Width = 32 $pbIcon.Size = $System_Drawing_Size $pbIcon.TabIndex = 0 $pbIcon.TabStop = $False $pbIcon.Image = $logobmp $form1.Controls.Add($pbIcon) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $form1.WindowState #Init the OnLoad event to correct the initial state of the form $form1.add_Load($OnLoadForm_StateCorrection) #Show the Form $form1.ShowDialog()| Out-Null } #End Function function GetAutoReplyStatus ($identity) { try { $status=Get-MailboxAutoReplyConfiguration $identity switch ($status.autoreplystate) { enabled { Status-EnabledAutoReply } disabled { Status-DisabledAutoReply } scheduled { Status-ScheduledAutoReply } } $dateStartDate.Value=$status.StartTime $dateStartTime.Value=$status.StartTime $dateEndDate.Value=$status.EndTime $dateEndTime.Value=$status.EndTime $textInside.Text=$status.InternalMessage $textOutside.Text=$status.ExternalMessage $buttonOK.Enabled=$true $form1.Update() } catch { ShowPrompt -Message $_ -Buttons OK -Icon Error;return } } function Status-DisabledAutoReply { $radioDoNotSend.enabled=$true $radioDoNotSend.checked = $true $radioSend.enabled=$true $radioSend.Checked=$false $checkOnlySend.checked=$false $checkOnlySend.enabled=$false $labelStartTime.enabled=$false $labelEndTime.enabled=$false $dateStartDate.enabled=$false $dateStartTime.enabled=$false $dateEndDate.enabled=$false $dateEndTime.enabled=$false $labelAutoReply.enabled=$false $textInside.enabled=$false $textOutside.enabled=$false $buttonOK.Enabled=$true $form1.Update() } function Status-EnabledAutoReply { $radioDoNotSend.enabled=$true $radioDoNotSend.checked = $false $radioSend.enabled=$true $radioSend.Checked=$true $checkOnlySend.checked=$false $checkOnlySend.enabled=$true $labelStartTime.enabled=$false $labelEndTime.enabled=$false $dateStartDate.enabled=$false $dateStartTime.enabled=$false $dateEndDate.enabled=$false $dateEndTime.enabled=$false $labelAutoReply.enabled=$true $textInside.enabled=$true $textOutside.enabled=$true $buttonOK.Enabled=$true $form1.Update() } function Status-ScheduledAutoReply { $radioDoNotSend.enabled=$true $radioDoNotSend.checked = $false $radioSend.enabled=$true $radioSend.Checked=$true $checkOnlySend.checked=$true $checkOnlySend.enabled=$true $labelStartTime.enabled=$true $labelEndTime.enabled=$true $dateStartDate.enabled=$true $dateStartTime.enabled=$true $dateEndDate.enabled=$true $dateEndTime.enabled=$true $labelAutoReply.enabled=$true $textInside.enabled=$true $textOutside.enabled=$true $buttonOK.Enabled=$true $form1.Update() } Function ShowPrompt { param ($Message,$Title=$Script:ScriptTitle,$Buttons,$Icon,$DefaultButton="button1") return [System.Windows.Forms.MessageBox]::Show($Message,$Title,$Buttons,$Icon,$DefaultButton) } Function Hide-PowerShell { $null = $showWindowAsync::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0) } $script:showWindowAsync = Add-Type -MemberDefinition @" [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); "@ -name Win32ShowWindowAsync -namespace Win32Functions -PassThru if ($host.name -ne "Windows PowerShell ISE Host") { Hide-PowerShell } #Only hide console if not run from ISE. [string]$logob64=@" iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AsVFgcLeQdwxQAAAB1pVFh0Q29tbWVudAAAAAAAQ3Jl YXRlZCB3aXRoIEdJTVBkLmUHAAABsklEQVRYw+2XS0sCURiG31M2OqZol8EobNEiKGjhONEvCNq2 62K1iv5Bi4KsQfoH0Toic9GinS1dBBGl7cKuUF5IJHIodTSH0yKUBMVFHRXy25zNMO/De16+7ztE 0zQ0strQ4NLV+iB1sUV/K2Idd5OmdaAF0AJoAbQAmr8VF4sfnILeNoFc4hzZ55P6O8D1OsrOugPk EmdlZ92vQI0FoMYC/zCElWb5X+wINQFu4wrd9IaQyRUAAF0mPeQ5EXbBRJg7EI6mqOy7Kon3mA2Q 50UMdPPIPvkpU4Bq4v3WDnzceVFQHthloJL49qIEoVMj6Zs9WkjH2YUwHE3RzcMQ1Pz3mi5YDPC4 JNisPAEA0+gyYbG86gDgOvJGZd9VSRwAkoqKlZ1TAKj54+P1SfKrPrDrD5eJ130ark6PwWLkGteI 7IKJyPMi3TgIQcnkAQA2Kw+PSwoKFoPEEoD8fBs+vrxTtzeI9+xnKYjbC+PBHj4vpe+PqJaOsH0Z DfWZiXtWhFGvKwVxbf/C+ZrlLs0jS4QTnGwdqNaGi06wuI6K03C430I2ZhwwcO1lTiQV9fKvAb4A EHe5VK0uOSAAAAAASUVORK5CYII= "@ $logostream=[System.IO.MemoryStream][System.Convert]::FromBase64String($logob64) $logobmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($logostream) $iconhandle=$logobmp.GetHicon() $icon=[System.Drawing.Icon]::FromHandle($iconhandle) if (!(Test-Path $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1)) { ShowPrompt -Message "This application requires the Exchange Management Shell to be installed on this computer. Please install the Exchange Management Tools from the Microsoft Exchange Server installation media." -icon Error -buttons OK;break } try { .$env:ExchangeInstallPath\\bin\\RemoteExchange.ps1 | Out-Null Connect-ExchangeServer -auto | Out-Null } catch { ShowPrompt -Message $_ -Buttons OK -Icon Error; break } GenerateForm Get-PSSession | Remove-PSSession -Confirm:$false Exit-PSSession
PowerShellCorpus/PoshCode/Get_Set Signature _1.0.ps1
Get_Set Signature _1.0.ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping) #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## Get all the signatures ## ## ls | Select-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 2.1 - Added some extra exports and aliases, and included my Start-AutoSign script... ## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support ## 1.7 - Modified the reading of certs to better support people who only have one :) ## 1.6 - Converted to work with CTP 3, and added function help comments ## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file ## Note: If you get this off PoshCode, you'll have to create it yourself, see below: ## 1.4 - Moved the default certificate setting into an external psd1 file. ## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-AuthenticodeSigned ## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned ## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files ## It's important to remember that the signatures are NOT checked by PowerShell yet... ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## #################################################################################################### ## README! README! README! README! ################################################################# ## README! README! README! README! ################################################################# ## ## You should set the location to your default signing certificate. The permanent way to do that is ## to modify (or create) the .psd1 file to set the PrivateData member variable. Otherwise you'll be ## prompted to provide a cert path whenever you try to sign a script without passing a certificate. ## ## The PrivateData variable should point at your code-signing certificate either with a full path ## or with the THUMBPRINT of a certificate you have available in your Cert:\\CurrentUser\\My\\ provider ## ## EG: ## 4F8842037D878C1FCDC6FD1313B200449716C353 ## OR: ## "Cert:\\CurrentUser\\My\\4F8842037D878C1FCDC6FD1313B200449716C353" ## OR a file name: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## ## The simplest thing is to just update the PSD1 ## ## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 ` ## -Author "" -COmpany "" -Copy "" -Desc "" ` ## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() ` ## -PrivateData 4F8842037D878C1FCDC6FD1313B200449716C353 ## #################################################################################################### #################################################################################################### function Get-UserCertificate { <#.SYNOPSIS Gets the user's default signing certificate so we don't have to ask them over and over... .DESCRIPTION The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can be reused without re-querying for the location and/or password ... .RETURNVALUE An X509Certificate2 suitable for code-signing #> [CmdletBinding()] Param() Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)" $UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData $ExecutionContext.SessionState.Module.PrivateData = $UserCertificate.Thumbprint return $UserCertificate } function Get-AuthenticodeCertificate { [CmdletBinding()] PARAM ( $Name = $ExecutionContext.SessionState.Module.PrivateData ) BEGIN { if(!$ExecutionContext.SessionState.Module.PrivateData -and $Name) { $ExecutionContext.SessionState.Module.PrivateData = $Name } } PROCESS { trap { Write-Host "The authenticode script module requires configuration to function fully!" Write-Host Write-Host "You must put the path to your default signing certificate in the module metadata"` "file before you can use the module's Set-Authenticode cmdlet or to the 'mine'"` "feature of the Select-AuthenticodeSigned or Test-AuthenticodeSignature. To set it up, you can do this:" Write-Host Write-Host "PrivateData = 'C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\PoshCerts\\Code-Signing.pfx'" Write-Host Write-Host "If you load your certificate into your 'CurrentUser\\My' store, or put the .pfx file"` "into the folder with the Authenthenticode module script, you can just specify it's"` "thumprint or filename, respectively. Otherwise, it should be a full path." Write-Error $_ return } # Import-LocalizedData -bindingVariable CertificatePath -EA "STOP" if(!$Name) { $certs = ls Cert:\\CurrentUser\\My if($certs.Count) { Write-Host "You have $($certs.Count) certs in your local cert storage which you can specify by Thumbprint:" -fore cyan $certs | Out-Host } $Name = $(Read-Host "Please specify a user certificate") } if($Name -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { Write-Debug "CertificatePath: $Name" $ResolvedPath = $Null $ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue" if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { Write-Debug "Not a full path: $ResolvedPath" $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { Write-Debug "Not a file Path: $ResolvedPath" $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $("$Name".ToUpper()) -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" Write-Debug "ResolvedPath: $ResolvedPath" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } Write-Verbose "Certificate: $($Certificate | Out-String)" $Name = $Certificate } return $Name } } #################################################################################################### function Test-AuthenticodeSignature { <#.SYNOPSIS Tests a script signature to see if it is valid, or at least unaltered. .DESCRIPTION The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it is Valid, OR **unaltered** and signed by the user's certificate .NOTES Test-AuthenticodeSignature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate. .EXAMPLE ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_} To get the signature reports for all the scripts that we consider safely signed. .EXAMPLE ls | ? { gas $_ | Test-AuthenticodeSignature } List all the valid signed scripts (or scripts signed by our cert) .INPUTTYPE System.Management.Automation.Signature .PARAMETER Signature Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature. .PARAMETER ForceValid Switch parameter, forces the signature to be valid -- otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate). Aliases Valid .RETURNVALUE Boolean value representing whether the script's signature is valid, or YOUR certificate ################################################################################################## #> [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] # The signature to test. $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint) ) ) } #################################################################################################### function Set-AuthenticodeSignature { <#.SYNOPSIS Adds an Authenticode signature to a Windows PowerShell script or other file. .DESCRIPTION The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed. .NOTES After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script. When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate To sign all of the files with the specified certificate .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate. .INPUTTYPE String. You can pipe a file path to Set-AuthenticodeSignature. .PARAMETER FilePath Specifies the path to a file that is being signed. Aliases Path, FullName .PARAMETER Certificate Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails. .PARAMETER Force Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions. .Parameter HashAlgorithm Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm. Files that are signed with a different hashing algorithm might not be recognized on other systems. .PARAMETER IncludeChain Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default. Valid values are: -- Signer: Includes only the signer's certificate. -- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority. --All: Includes all the certificates in the certificate chain. .PARAMETER TimestampServer Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string. Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing. .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) , [Switch]$Force , [ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")] [String]$HashAlgorithm #="SHA1" , [ValidateSet("Signer","NotRoot","All")] [String]$IncludeChain #="NotRoot" , [String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll" ) BEGIN { if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $Certificate = Get-AuthenticodeCertificate $Certificate } $PSBoundParameters["Certificate"] = $Certificate } PROCESS { Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)" $PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath) if(Test-Path $FilePath -Type Leaf) { Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters } else { Write-Warning "Cannot sign folders: '$FilePath'" } } } #################################################################################################### function Get-AuthenticodeSignature { <#.SYNOPSIS Gets information about the Authenticode signature in a file. .DESCRIPTION The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE Get-AuthenticodeSignature script.ps1 To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string[]] $FilePath ) PROCESS { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath } } #################################################################################################### function Select-AuthenticodeSigned { <#.SYNOPSIS Select files based on the status of their Authenticode Signature. .DESCRIPTION The Select-AuthenticodeSigned function filters files on the pipeline based on the state of their authenticode signature. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1,*.ps[dm]1 | Select-AuthenticodeSigned To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter()] # Return only files that are signed with the users' certificate (as returned by Get-UserCertificate). [switch]$MineOnly , [Parameter()] # Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate). [switch]$NotMineOnly , [Parameter()] [Alias("HashMismatch")] # Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match). [switch]$BrokenOnly , [Parameter()] # Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate). # # That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly) [switch]$TrustedOnly , [Parameter()] # Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate. [switch]$ValidOnly , [Parameter()] # Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate). [switch]$InvalidOnly , [Parameter()] # Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed. [switch]$UnsignedOnly ) PROCESS { if(!(Test-Path -PathType Leaf $FilePath)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$FilePath'" # } } else { foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) { # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $FilePath" return } # Trusted only returns ONLY things which are Valid if($ValidOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $FilePath" return } # AllValid returns only things that are SIGNED and not HashMismatch if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $FilePath" return } # InvalidOnly returns things that are Either NotSigned OR HashMismatch ... if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $FilePath" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $FilePath" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint)))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" return } # NotMine returns only things that were NOT signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint)))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Signed: $FilePath" return } get-childItem $sig.Path }} } } function Start-AutoSign { # .Synopsis # Start a FileSystemWatcher to automatically sign scripts when you save them # .Description # Create a FileSystemWatcher with a scriptblock that uses the Authenticode script Module to sign anything that changes # .Parameter Path # The path to the folder you want to monitor # .Parameter Filter # A filter to select only certain files: by default, *.ps* (because we can only sign .ps1, .psm1, .psd1, and .ps1xml # .Parameter Recurse # Whether we should also watch autosign files in subdirectories # .Parameter CertPath # The path or name of a certain certificate, to override the defaults from the Authenticode Module # .Parameter NoNotify # Whether wo should avoid using Growl to notify the user each time we sign something. # .NOTE # Don't run this on a location where you're going to be generating dozens or hundreds of files ;) PARAM($Path=".", $Filter= "*.ps*", [Switch]$Recurse, $CertPath, [Switch]$NoNotify) if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) { Import-Module Growl Register-GrowlType AutoSign "Signing File" -ErrorAction 0 } else { $NoNotify = $false } $realItem = Get-Item $Path -ErrorAction Stop if (-not $realItem) { return } $Action = { ## Files that can't be signed show up as "UnknownError" with this message: $InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider" ## Files that are signed with a cert we don't trust also show up as UnknownError, but with different messages: # $UntrustedCert = "A certificate chain could not be built to a trusted root authority" # $InvalidCert = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider" # $ExpiredCert = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file" ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature | Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } | Select-Object -ExpandProperty Path ) { if(!$NoNotify) { Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file" } if($CertPath) { Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath } else { Set-AuthenticodeSignature -FilePath $file } } } $watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse } Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null } Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias slas Select-AuthenticodeSigned -Description "Authenticode Module Alias" Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias" Export-ModuleMember -Alias gas,sas,slas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate, Start-AutoSign # SIG # Begin signature block # MIIIPAYJKoZIhvcNAQcCoIIILTCCCCkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUbRDcSlj31gB3Dj0E/HWIHY/w # 5IKgggVaMIIFVjCCBD6gAwIBAgIQSX2g7+3+PL1oSJra3tEBIzANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1U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TANBgkqhkiG9w0BAQEFAASCAQBKs1LvUwZC+0Bs9/3D03/L # xp9NYjTfnXfeKI73KOnw4RMKY4rnnbEi0eLxsKOyFTDLbvEkO0dPeRa8LVANktgx # H2zHECjyud949UaU1CnAhJhbx0EHQQatumsBEcaQqO/vJGTTE3F1faxIbQoyxkZC # bax1ISAF1JeR8avSDgLEEDj1kqTP7a5lNTO0k9CX0kvmF7GXGBwEJJ0XZh1ipCFW # PEF9xdE3wP3iXs2rVk8LZIKx6Iz14PPhp/004hKKPUolAg9PPJM+fiN6vsluTpoH # tDe5OXi71/Hpl51E9XNpRz/kUyB5MSxvsl9bf0DTHwWTa4hOrvWUBpkPU10FT7y6 # SIG # End signature block
PowerShellCorpus/PoshCode/Get-LocalGroupMembers_1.ps1
Get-LocalGroupMembers_1.ps1
function Get-LocalGroupMembers { param($groupname) $pattern = "*Name=`"$groupname`"" $groupusers = gwmi Win32_GroupUser | Where { $_.GroupComponent -like $pattern } # Now extract the usernames. foreach ($user in $groupusers) { if ($user.PartComponent -match 'Name="([^"]+)') { Write-Output $matches[1] } } } # Use it like this. # Get-GroupMembers Administrators
PowerShellCorpus/PoshCode/Get-WebPage.ps1
Get-WebPage.ps1
function Get-WebPage { <# .SYNOPSIS Downloads web page from site. .DESCRIPTION Downloads web page from site and displays source code or displays total bytes of webpage downloaded .PARAMETER Url URL of the website to test access to. .PARAMETER UseDefaultCredentials Use the currently authenticated user's credentials .PARAMETER Proxy Used to connect via a proxy .PARAMETER Credential Provide alternate credentials .PARAMETER ShowSize Displays the size of the downloaded page in Kilobytes .NOTES Name: Get-WebPage Author: Boe Prox DateCreated: 08Feb2011 .EXAMPLE Get-WebPage -url "http://www.bing.com" Description ------------ Returns information about Bing.Com to include StatusCode and type of web server being used to host the site. #> [cmdletbinding( DefaultParameterSetName = 'url', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [string][ValidatePattern("^(http|https)\\://*")]$Url, [Parameter( Position = 1, Mandatory = $False, ParameterSetName = 'defaultcred')] [switch]$UseDefaultCredentials, [Parameter( Mandatory = $False, ParameterSetName = '')] [string]$Proxy, [Parameter( Mandatory = $False, ParameterSetName = 'altcred')] [switch]$Credential, [Parameter( Mandatory = $False, ParameterSetName = '')] [switch]$ShowSize ) Begin { $psBoundParameters.GetEnumerator() | % { Write-Verbose "Parameter: $_" } #Create the initial WebClient object Write-Verbose "Creating web client object" $wc = New-Object Net.WebClient #Use Proxy address if specified If ($PSBoundParameters.ContainsKey('Proxy')) { #Create Proxy Address for Web Request Write-Verbose "Creating proxy address and adding into Web Request" $wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True) } #Determine if using Default Credentials If ($UseDefaultCredentials) { #Set to True, otherwise remains False Write-Verbose "Using Default Credentials" $wc.UseDefaultCredentials = $True } #Determine if using Alternate Credentials If ($Credential) { #Prompt for alternate credentals Write-Verbose "Prompt for alternate credentials" $wc.Credential = (Get-Credential).GetNetworkCredential() } } Process { Try { If ($ShowSize) { #Get the size of the webpage Write-Verbose "Downloading web page and determining size" "{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT] } Else { #Get the contents of the webpage Write-Verbose "Downloading web page and displaying source code" $wc.DownloadString($url) } } Catch { Write-Warning "$($Error[0])" } } }
PowerShellCorpus/PoshCode/GET-Remoteapps.ps1
GET-Remoteapps.ps1
# Original posting on how to access a remote Registry from The Powershell Guy # # http://thepowershellguy.com/blogs/posh/archive/2007/06/20/remote-registry-access-and-creating-new-registry-values-with-powershell.aspx # # This script will Query the Uninstall Key on a computer specified in $computername and list the applications installed there # $Branch contains the branch of the registry being accessed # ' # format of Computerlist.csv # Line 1 - NameOfComputer # Line 2 etcetc etc etc etc An Actual name of a computer $COMPUTERS=IMPORT-CSV C:\\Powershell\\Computerlist.csv FOREACH ($PC in $COMPUTERS) { $computername=$PC.NameOfComputer # Branch of the Registry $Branch='LocalMachine' # Main Sub Branch you need to open $SubBranch="SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall" $registry=[microsoft.win32.registrykey]::OpenRemoteBaseKey('Localmachine',$computername) $registrykey=$registry.OpenSubKey($Subbranch) $SubKeys=$registrykey.GetSubKeyNames() # Drill through the list of SubKeys and examine the Display name Foreach ($key in $subkeys) { $exactkey=$key $NewSubKey=$SubBranch+"\\\\"+$exactkey $ReadUninstall=$registry.OpenSubKey($NewSubKey) $Value=$ReadUninstall.GetValue("DisplayName") Write-Host $computername, $Value }
PowerShellCorpus/PoshCode/7697c70c-75c8-4a8e-86cd-5e8f3f2f1eb7.ps1
7697c70c-75c8-4a8e-86cd-5e8f3f2f1eb7.ps1
Function PowerOn-VM($vm){ Start-VM -VM $vm -Confirm:$false -RunAsync | Out-Null do { $vmview = get-VM $vm | Get-View $status = $vmview.Guest.ToolsStatus Write-Host $vm is starting! -ForegroundColor Yellow sleep 5 }until(($status -match "toolsOld") -or ($status -match "toolsOk")) if ($status -match "Ok"){ $Startup = "Ok"} elseif($status -match "toolsOld"){ $Startup = "ToolsOld"} else{ $Startup = "Not Ready"} return $Startup } Function PowerOff-VM($vm){ sleep 20 Shutdown-VMGuest -VM $vm -Confirm:$false | Out-Null do { $vmview = Get-VM $vm | Get-View $status = $vmview.Guest.ToolsStatus Write-Host $vm is stopping! -ForegroundColor Yellow sleep 5 }until($status -match "toolsNotRunning") if ($status -match "toolsNotRunning"){ $Shutdown = "Ok"} else{ $Shutdown = "Not Ready"} return $Shutdown } Function Check-ToolsStatus($vm){ $vmview = get-VM $vm | Get-View $status = $vmview.Guest.ToolsStatus if ($status -match "toolsOld"){ $vmTools = "Old"} elseif($status -match "toolsNotRunning"){ $vmTools = "Not Running"} else{ $vmTools = "Ok"} return $vmTools } Function Check-VMHardwareVersion($vm){ $vmView = get-VM $vm | Get-View $vmVersion = $vmView.Config.Version $v4 = "vmx-04" $v7 = "vmx-07" if ($vmVersion -eq $v4){ $vmHardware = "Old"} elseif($vmVersion -eq $v7){ $vmHardware = "Ok"} else{Write-Host "Error!!" -ForegroundColor Red $vmHardware = "Error"} return $vmHardware } Function Upgrade-VMHardware($vm){ $vmview = Get-VM $vm | Get-View $vmVersion = $vmView.Config.Version $v4 = "vmx-04" $v7 = "vmx-07" if ($vmVersion -eq $v4){ Write-Host "Version 4 detected" -ForegroundColor Red # Update Hardware Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow Get-View ($vmView.UpgradeVM_Task($v7)) | Out-Null } } Function CreateBeforeList{ Write-Host "Creating a CSV File with VM info" -ForegroundColor Yellow $MyCol = @() ForEach ($vm in Get-Folder $Folder | Get-VM ) { $vmview = get-VM $vm | Get-View $myObj = "" | Select Host, VMName, PowerState, IPAddress, MacAddress, Nics, VMToolsVersion, VMToolsStatus, VMToolsRunningStatus $myObj.Host = $VM.Host.Name $myObj.VMName = $VM.Name $myObj.PowerState = $VM.PowerState $myObj.IPAddress = [String]($vmview.Guest.Net| ForEach {$_.IpAddress}) $myObj.MacAddress = [String]($vmview.Guest.Net | ForEach {$_.MacAddress}) $myObj.Nics = $vmview.Guest.Net.Count $myObj.VMToolsVersion = $vmview.Config.Tools.ToolsVersion $myObj.VMToolsStatus = $vmview.Guest.ToolsStatus $myObj.VMToolsRunningStatus = $vmview.Guest.ToolsRunningStatus $myCol += $myObj } $myCol | Export-Csv C:\\beforeHWchange.csv -NoTypeInformation } Function CreateAfterList{ Write-Host "Creating a CSV and an Excel File with VM info" -ForegroundColor Yellow $xlCSV = 6 $xlXLS = 56 $csvfile = "C:\\afterHWchange.csv" $xlsfile = "C:\\afterHWchange.xls" $Excel = New-Object -ComObject Excel.Application $Excel.visible = $True $Excel = $Excel.Workbooks.Add() $Sheet = $Excel.Worksheets.Item(1) $Sheet.Cells.Item(1,1) = "VMName" $Sheet.Cells.Item(1,2) = "IPAddress" $Sheet.Cells.Item(1,3) = "Settings" $intRow = 2 $WorkBook = $Sheet.UsedRange $WorkBook.Interior.ColorIndex = 19 $WorkBook.Font.ColorIndex = 11 $WorkBook.Font.Bold = $True $import = Import-Csv "C:\\beforeHWchange.csv" $vms = Get-Folder $Folder | Get-VM foreach($vm in $vms){ $vmview = $vm | Get-View foreach($item in $import){ $oldIp = $item.IPAddress $newIP = $vm.Guest.IPAddress if($item.VMName -eq $vm){ if($oldIp -eq $newIP){ $Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name $Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress $Sheet.Cells.Item($intRow, 3) = "Good" $Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 4 } else{ $Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name $Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress $Sheet.Cells.Item($intRow, 3) = "Wrong" $Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 3 } } } $intRow = $intRow + 1} $WorkBook.EntireColumn.AutoFit() sleep 5 $Sheet.SaveAs($xlsfile,$xlXLS) $Sheet.SaveAs($csvfile,$xlCSV) } Function CreateAfterListreboot{ Write-Host "Creating a CSV and an Excel File with VM info" -ForegroundColor Yellow $xlCSV = 6 $xlXLS = 56 $csvfile = "C:\\afterHWchangeRB.csv" $xlsfile = "C:\\afterHWchangeRB.xls" $Excel = New-Object -ComObject Excel.Application $Excel.visible = $True $Excel = $Excel.Workbooks.Add() $Sheet = $Excel.Worksheets.Item(1) $Sheet.Cells.Item(1,1) = "VMName" $Sheet.Cells.Item(1,2) = "IPAddress" $Sheet.Cells.Item(1,3) = "Settings" $intRow = 2 $WorkBook = $Sheet.UsedRange $WorkBook.Interior.ColorIndex = 19 $WorkBook.Font.ColorIndex = 11 $WorkBook.Font.Bold = $True $import = Import-Csv "C:\\beforeHWchange.csv" $vms = Get-Folder $Folder | Get-VM foreach($vm in $vms){ $vmview = $vm | Get-View foreach($item in $import){ $oldIp = $item.IPAddress $newIP = $vm.Guest.IPAddress if($item.VMName -eq $vm){ if($oldIp -eq $newIP){ $Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name $Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress $Sheet.Cells.Item($intRow, 3) = "Good" $Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 4 } else{ $Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name $Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress $Sheet.Cells.Item($intRow, 3) = "Wrong" $Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 3 } } } $intRow = $intRow + 1} $WorkBook.EntireColumn.AutoFit() sleep 5 $Sheet.SaveAs($xlsfile,$xlXLS) $Sheet.SaveAs($csvfile,$xlCSV) } $vCenter = "vCenterServer" $Folder = "FolderNAme" Connect-VIServer $vCenter $vms = Get-Folder $Folder | Get-VM | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-04" } | Select Name CreateBeforeList foreach($item in $vms){ $vm = $item.Name $vmHardware = Check-VMHardwareVersion $vm $vmToolsStatus = Check-ToolsStatus $vm Write-Host "Hardware is old on:" $vm -ForegroundColor Red if($vmToolsStatus -eq "Old"){ Write-Host "The VMware Tools are old on:" $vm -ForegroundColor Red Sleep 20 Get-VMGuest $vm | Update-Tools Sleep 120 Write-Host "VMware Tools are installed on:" $vm -ForegroundColor Cyan $vmToolsStatus = Check-ToolsStatus $vm if($vmToolsStatus -eq "Ok"){ $PowerOffVM = PowerOff-VM $vm if($PowerOffVM -eq "Ok"){ Write-Host $vm "is down" -ForegroundColor Yellow Upgrade-VMHardware $vm PowerOn-VM $vm Write-Host $vm "is up to date" -ForegroundColor Green } } } else{ $PowerOffVM = PowerOff-VM $vm if($PowerOffVM -eq "Ok"){ Upgrade-VMHardware $vm PowerOn-VM $vm Write-Host $vm "is up to date" -ForegroundColor Green } } } Sleep 40 CreateAfterList Get-Folder $Folder | Get-VM | Restart-VMGuest -Confirm:$false Sleep 300 CreateAfterListreboot Disconnect-VIServer -Confirm:$false
PowerShellCorpus/PoshCode/Test-Host V1.ps1
Test-Host V1.ps1
Param($property,$tport=135,$timeout=1000,[switch]$port,[switch]$verbose) Begin{ function TestPort { Param($srv) $error.Clear() $ErrorActionPreference = "SilentlyContinue" $tcpclient = new-Object system.Net.Sockets.TcpClient $iar = $tcpclient.BeginConnect($srv,$tport,$null,$null) $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false) # Traps trap {if($verbose){Write-Host "General Exception"};return $false} trap [System.Net.Sockets.SocketException] { if($verbose){Write-Host "Exception: $($_.exception.message)"} return $false } if(!$wait) { $tcpclient.Close() if($verbose){Write-Host "Connection Timeout"} return $false } else { $tcpclient.EndConnect($iar) | out-Null $tcpclient.Close() } if(!$error[0]){return $true} } function PingServer { Param($MyHost) $pingresult = Get-WmiObject win32_pingstatus -f "address='$MyHost'" if($pingresult.statuscode -eq 0) {$true} else {$false} } } Process{ if($_) { if($port) { if($property) { if(TestPort $_.$property){$_} } else { if(TestPort $_){$_} } } else { if($property) { if(PingServer $_.$property){$_} } else { if(PingServer $_){$_} } } } }
PowerShellCorpus/PoshCode/Convert-ToCHexString_1.ps1
Convert-ToCHexString_1.ps1
function Convert-ToCHexString { param([String] $input) $ans = '' [System.Text.Encoding]::ASCII.GetBytes($str) | % { $ans += "0x{0:X2}, " -f $_ } return $ans.Trim(',',' ') }
PowerShellCorpus/PoshCode/Get-LocalGroupMember_1.ps1
Get-LocalGroupMember_1.ps1
function Get-LocalGroupMember { param( # The name of the local group to retrieve members of [Parameter(Position=0,Mandatory=$true)] [String]$GroupName = "administrators", # A filter for the user name(s) [Parameter(Position=1)] [String]$UserName = "*", # The computer to query (defaults to the local machine) [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("CN")] [String[]]$ComputerName = ${Env:ComputerName}, # If set, returns only local computer accounts [Switch]$LocalAccountsOnly, # If set, returns only domain accounts [Switch]$DomainAccountsOnly ) process { foreach($cName in $ComputerName) { $Group = [System.DirectoryServices.DirectoryEntry][ADSI]"WinNT://$cName/$GroupName,group" try{ $Null = $Group.PSBase.InvokeGet("Name") } catch { Write-Error $_.Exception.InnerException.Message continue } $Group.Members() | ForEach-Object { [System.DirectoryServices.DirectoryEntry]$_ | ## Overwrite or Create an NTAccountName property Add-Member ScriptProperty NTAccountName {$this.Path.Replace("WinNT://","").Replace("/","\\")} -force -passthru | ## Create a distinguishedName, because that displays by default, but is empty Add-Member AliasProperty distinguishedName NTAccountName -force -passthru | ## Add a PSComputerName Add-Member NoteProperty PSComputerName $cName -force -passthru | ## Add IsLocalAccount Add-Member ScriptProperty IsLocalAccount {$this.Path -match "/$($this.PSComputerName)/"} -force -passthru } | Where-Object { ($_.Name -like $UserName) -And (!$LocalAccountsOnly -or ($_.Path -match "/${ComputerName}/")) -And (!$DomainAccountsOnly -or ($_.Path -notmatch "/${ComputerName}/") ) } } } <# .Synopsis Lists the members of the specified local group .Description List all members of local Groups from a specified computer (eg: administrators, power users, backup operators, etc.) .Example Get-LocalGroupMember administrators -LocalAccount Retrieves all the local computer accounts that are members of the administrators group on the local machine .Example Get-LocalGroupMember "Power Users" Retrieves all the accounts that are members of the Power Users group .Example Get-LocalGroupMember administrators Admin* Retrieves all the administrators who's name starts with "admin" .Example Get-LocalGroupMember administrators -ComputerName Server1, Server2 | ft PSComputerName, Name, IsLocalAccount Retrieves administrators from several computers and displays specific information about them .Notes Copyright (c) 2010 Joel Bennett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************** NOTE: YOU MAY *ALSO* DISTRIBUTE THIS FILE UNDER ANY OF THE FOLLOWING... PERMISSIVE LICENSES: BSD: http://www.opensource.org/licenses/bsd-license.php MIT: http://www.opensource.org/licenses/mit-license.html Ms-PL: http://www.opensource.org/licenses/ms-pl.html RECIPROCAL LICENSES: Ms-RL: http://www.opensource.org/licenses/ms-rl.html GPL 2: http://www.gnu.org/copyleft/gpl.html ***************************************************************************** LASTLY: THIS IS NOT LICENSED UNDER GPL v3 (although the above are compatible) #> }
PowerShellCorpus/PoshCode/Save-Credentials_6.ps1
Save-Credentials_6.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 .\\Save-Credentials.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/WinFirewall-Stoped.ps1
WinFirewall-Stoped.ps1
function WinFirewall-Stoped(){ param ( $computer ) c:\\PsTools\\PsExec.exe \\\\"$computer" sc stop sharedaccess }
PowerShellCorpus/PoshCode/1716db2c-bd83-404b-b8ec-beb189e225b4.ps1
1716db2c-bd83-404b-b8ec-beb189e225b4.ps1
$mykey = "xxx" $newkey = "yyy" $OFS = "" cd C:\\Users\\kagami\\Downloads ls | % { if ($_.name -match "^\\[rutracker\\.org\\].*\\.torrent") { $file = $_.name $data = cat -en byte -LiteralPath $file $data2 = ([string][char[]]$data) -replace "ann\\?uk=$mykey", "ann?uk=$newkey" sc -en byte -value ([byte[]][char[]]$data2) -LiteralPath "_torrent/$file" rm -LiteralPath $file } }
PowerShellCorpus/PoshCode/Set-IPAddress_9.ps1
Set-IPAddress_9.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/Trim Working Set for PID.ps1
Trim Working Set for PID.ps1
## Trim Working set Function TrimWorkingSet { param([int] $procid) <#.NOTES AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com) WEBSITE: http://tekout.wordpress.com CREATED: 9/20/2012 This starts the Evil Monkey series of scripts. .DESCRIPTION MSDN - http://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx Trim's working set to minimum levels (-1, -1) You can give a max / min values by modifying the signature. .WARNING ***********READ CAREFULLY*********** !!!! Do not use in production environment before thoroughly testing and understanding the script. !!!! Do not use this to Trim Working Set for SQL Databases, there will be data-loss. Do not use this to Trim Working Set database for msExchange store.exe I havent tried this on IIS w3wp.exe processes. More NEGATIVE effects here - http://support.microsoft.com/kb/2001745 I have primarily used this to trim browser WorkingSet data. Tested on firefox / iexplore / chrome. It works with no tab crashing. Trimming Working Set data, doesnt mean that browser Working Set values wont climb to their previous numbers. I have seen some IE windows go back to similar working set numbers. However, this script is really useful for a stuck browser and freezing screeing situations. ***********READ CAREFULLY*********** .EXAMPLE .\\TrimWorkingSet.ps1 1920 #> $sig = @" [DllImport("kernel32.dll")] public static extern bool SetProcessWorkingSetSize( IntPtr proc, int min, int max ); "@ $apptotrim = (get-process -Id $procid).Handle Add-Type -MemberDefinition $sig -Namespace User32 -Name Util -UsingNamespace System.Text -PassThru [User32.Util]::SetProcessWorkingSetSize($apptotrim,-1,-1) } TrimWorkingSet(5960)
PowerShellCorpus/PoshCode/Quest Dynamic Group 003.ps1
Quest Dynamic Group 003.ps1
<# 2012.07.06 Information will be uploaded shortly. #>
PowerShellCorpus/PoshCode/http___harleydavidsonmot.ps1
http___harleydavidsonmot.ps1
Sow nothing, reap nothing. -----------------------------------
PowerShellCorpus/PoshCode/Custom Speech Commands_3.ps1
Custom Speech Commands_3.ps1
#Filename commands.ps1 import-module "G:\\Documents\\Speech Macros\\custom.psm1" import-module "G:\\Documents\\Speech Macros\\alice.psm1" Add-SpeechCommands @{ "test command" = { Say $(Respond "3:2,4:0-2") } " * the percentages * " = { Say $(Percentages) } " * star date * " = { Say "Current, Star date,$("$((Get-Date).year).$([math]::round($((Get-Date).dayofyear)/365, 2)*100)" -replace "([A-Za-z0-9.]){1}","`$1 " -replace "\\.","point")" } " * mail * " = { Start-Process "https://mail.google.com" } "Google * please" = { $term = $_ -replace "$Computer(.+?)Google (.+?) please", '$2'; Start-Process "http://www.google.com/search?q=$term" } "What * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What is * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What time * " = { Say "It is $(Get-Date -f "h:mm tt")" } " * some music * " = { Start-Process "grooveshark.exe" } "What * date today" = { Say $(Get-Date -f "dddd, MMMM dd") } #list processes "What's running?" = { $proc = ps | sort ws -desc Say $("$($proc.Count) processes, including $($proc[0].name), which is using " + "$([int]($proc[0].ws/1mb)) megabytes of memory") } #Word Definition " * the definition for * please" = {$define = $_ -replace "$Computer(.+?)the definition for (.+?) please", '$2' ;$outtext = Get-Definition("$define");Say "Definitions for $define, , , $outtext"} } -Computer "alice" -Verbose #eof #Filename custom.psm1 function Get-Definition($word) { #.Synopsis # Polls wiktionary for top text definitons for a given $word input #.Description # This Function parses the top $lines definitions for a given # $term into one string formatted for speech synthesis # # Say "Sure" if($word -match " "){Say "Fail, one word at a time please"; break} $page = "http://simple.wiktionary.org/wiki/$word" $ie = new-object -com "InternetExplorer.Application" $ie.visible = $false $ie.navigate($page) while($ie.busy){Start-Sleep 1} $output = " " $lines = 0 for($d=0;$d -le $lines;$d++) { ## grab the definition strings from each table $ol = @($ie.Document.getElementsByTagName("ol"))[0] $li = @($ol.getElementsByTagName("li"))[$d] $def = @($li.innerHTML) $output += "$def" if($d -lt $lines){ $output += ", or, " } } $ie.Quit() $closeIE = [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($ie) Remove-Variable ie $Clean-String($output) } function Clean-String([string]$str){ #.Synopsis # Cleans string from web (most concerned about x/html tags) #.Description # Cleans input string of xml tags # returns $str # # $str = $str -replace "\\<[^<]*\\>", " " $str = $str.replace("&nbsp", "") $str } function Respond($in, [string]$del = ","){ #.Synopsis # Recursive. # Returns a random response from $responses via the three dimensional array of choices: $choices[<groups>][<dimensions>][<values>] # This function takes in a string indicating which responses from the $responses array # to to choose from. It supports ranges (-) and direct selections (/) in each seed separated by (,). #.Description # the idea here is to respond based on this format: $in = "3:2,4:1-2,0/2-4/6:1" # where 3:2 is a direct seed, 4:1-2 is a range seed (from 4:1 to 4:2), # and 0/2-4/6:1 combines the two (effectively adds 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the choices) # In heap, the above example would effectively add 3:2, 4:1, 4:2, 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the # available choices, and will appear as $choices(@($xs(3),$ys(2)),@($xs(4),$ys(1,2)),@($xs(0,2,3,4,6),$ys(1))) # switch -wildcard ($del){ "`,"{ if($in -match "`,"){ #if more than one coordset, handle each $coordsets = $in -split "`," #split coordsets apart foreach($coordset in $coordsets){ $choices += ,(Respond $coordset "`:") } } else{ #else pass the string to the next step, $choices = ,(Respond $in "`:") } $choice = $choices[(get-random -min 0 -max $choices.count)] #choose one of the groups randomly $responses[$choice[0]][$choice[1]];#pass response out of the function } "`:"{ $coords = $in -split "`:" #split coordset apart foreach ($coord in $coords){ if(($coord -match "`/")-or($coord -match "`-")){ #if there's an or operator or a range $dimensions += ,(Respond $coord "`/") # handle them, and add all values (in array) to this dimension (split fails elegantly) } else{ $dimensions += ,$coord #else just add the coord value (in an array) via comma operator } } $dimensions #pass dimensions out dimensions is two dimensional array } "`/"{ $ranges = $in -split "`/" #split ORs apart (if theres not OR, the string is still added to $ranges[0]) foreach($range in $ranges){ if($range -match "`-"){#if theres a range to handle, do so foreach ($val in (Respond $range "`-")){ $orVals += ,$val #append all values in returned range array to new array } } else{# else just append the value to teh new array $orVals += ,$range } } ,($orVals | get-random) #pass out single element array of random value from vals array } "`-"{ $vals = $in -split "`-" #split ranges apart $vals[0]..$vals[1] # pass out array containing all values in range } } } $responses = (#Response Array (##0-correct "Right", "Correct" ), (##1-incorrect "Wrong", "Incorrect" ), (##2-positive "Yes", "Aye", "I'll give it a shot" ), (##3-negative "No", "Negative", "Not going to happen" ), (##4-affirmation "Sure", "OK", "Lets See" ), (##5-retort "your mom", "your face" ), (##6-insult "You\\'re dumb", "you fail" ), (##7-eager "I'm ready", "Lets check it out" ), (##8-apprehensive "I don't know", "Just a seck" ), (##9-neutral "oh", "Hum" ) ) function Percentages { #.Synopsis # Specific speech command that reads back # remaining percentages of year, month, week, and day #.Description # Pretty self explanitory, basic maths, elucidatory var names # # $date = get-date #capture date object $daysInYear = [int]$(if([datetime]::IsLeapYear($date.year)){366}else{365}) #if leap year, 366, else 365 $daysInMonth = [int]$([datetime]::DaysInMonth($date.year, $date.month)) #capture days in month $dayOfYear = [int]$date.dayofyear #days past (including today) $dayOfMonth = [int]$date.day #days past (including today) $hoursOfDay = [int]$date.hour #hours past (including current) $minutesOfHour = [int]$date.minute #minutes past (including current) switch ($date.dayofweek.toString()){ #assumes start of week is sunday Sunday { [int]$dayOfWeek="1"; break } Monday { [int]$dayOfWeek="2"; break } Tuesday { [int]$dayOfWeek="3"; break } Wednesday { [int]$dayOfWeek="4"; break } Thursday { [int]$dayOfWeek="5"; break } Friday { [int]$dayOfWeek="6"; break } Saturday { [int]$dayOfWeek="7"; break } } $percentYearGone = $dayOfYear/$daysInYear #days of this year (including today) divided by total days in this year $percentMonthGone = ((($dayOfMonth*24)-24)+$hoursOfDay)/($daysInMonth*24) #hours of this month divided by total hours in this month $percentWeekGone = ((($dayOfWeek*24)-24)+$hoursOfDay)/(7*24) #hours of this week divided by total hours in a week $percentDayGone = ((($hoursOfDay*60)-60)+$minutesOfDay)/(24*60) #minutes of today divided by total minutes in a day $percentYearLeft = [math]::round((1-$percentYearGone)*100,1) #opposite percentages rounded to one decimal place $percentMonthLeft = [math]::round((1-$percentMonthGone)*100,1) #^ $percentWeekLeft = [math]::round((1-$percentWeekGone)*100,1) #^ $percentDayLeft = [math]::round((1-$percentDayGone)*100,1) #^ $str = "" $str += "There's " $str += $percentYearLeft $str += "% of this year, " $str += $percentMonthLeft $str += "% of this month, " $str += $percentWeekLeft $str += "% of this week, and " $str += $percentDayLeft $str += "% of today remaining, what will you do with it?" $str } #eof
PowerShellCorpus/PoshCode/Build-TFSProjects_1.ps1
Build-TFSProjects_1.ps1
#------------------------------------------------------------------------- # Script that will: # 1. Create a workspace. Workspacce Name: _Root # 2. Get the latest code from repository #------------------------------------------------------------------------- Param( [switch] $CSRWEB, [switch] $CSRWS, [switch] $CSRServices, [string] $LogPath [String] $Outdir = "C:\\Application\\CSR" ) Begin { $MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild" $WEBPROJECTOUTPUTDIR="$OUTDIR\\CSRWeb" $script:Log=@() #------------------------------------------------------------------------- Function SetTFS { $SCRIPT:tfsServer = "172.29.4.179" $script:userName = [system.environment]::UserName; $script:computerName = [system.environment]::machinename $script:workspaceName = $computerName + "_" + $userName +"_WS" #Use 'WS' as an acronym for "WorkSpace" $script:CSRDIR = "C:\\Brassring2\\Application\\"; $script:WEBPROJECTOUTPUTDIR="$Outdir\\CSRWeb" $script:WEBPROJECTOUTPUTDIR1="$Outdir\\CSRWS" $script:WEBPROJECTOUTPUTDIR2="$Outdir\\CSRServices" $script:REFPATH="referenceToAllAssembiesUsedInTheProjectSeperatedbySemiColon" $script:MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild" $script:failed = $false # Set up the TF Alias # Find where VS is installed. $key = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\VisualStudio\\9.0 $dir = [string] (Get-ItemProperty $key.InstallDir) $script:tf = "$dir\\tf.exe" } # End SetTFS #------------------------------------------------------------------------- Function CreateWorkspace { Begin { Write-Debug "Starting CreateWorkspace" Function DeleteWorkspace { # Delete the workspace if it exists. Write-Verbose "Deleting workspace (if exists): $workspaceName" $log += "Deleting workspace (if exists): $workspaceName" &$TF workspace /delete $workspaceName /noprompt | out-null Write-Verbose "Done deleting workspace." $log += "Done deleting workspace." } #END DeleteWorkspace } Process { DeleteWorkspace # Create the folder if (! (Test-Path $CSRDIR)) { Write-Verbose "Creating folder: $CSRDIR" $log += "Creating folder: $CSRDIR" new-item -itemtype directory -path $CSRDIR -force | out-null Write-Verbose "Completed Creating folder: $CSRDIR" $log += "Completed Creating folder: $CSRDIR" } # Move to folder cd $CSRDIR # Create the workspace Write-Verbose "Creating workspace: $workspaceName" $log += "Creating workspace: $workspaceName" &$TF workspace /new /computer:$computerName /server:$TFsServer /noprompt $workspaceName Write-Verbose "Done Creating workspace: $workspaceName" $log += "Done Creating workspace: $workspaceName" # Get the latest Write-Verbose "Getting the latest code from: $TFsServer. This could take awhile..." $log += "Getting the latest code from: $TFsServer. This could take awhile..." &$TF get $/CSR/CSR /recursive Write-Verbose "Done getting latest." $log += "Done getting latest." Write-Verbose "Tree initialization is complete." $log += "Tree initialization is complete." } End { Write-Debug "CreateWorkspace Complete" } } #END CreateWorkspace #------------------------------------------------------------------------- # Get Next Label # # Labels are BL{major}.{minor} # major = 1 - ??? # minor = 001 - 999 #------------------------------------------------------------------------- Function GetNextLabel() { Begin { Write-Debug "Starting GetNextLabel" } Process { $major = 1 $minor = 1 $list = (&$TF labels /format:brief |? { $_ -notmatch "-.+" -and $_ -notmatch "Label.+Owner.+Date"}) if ($list -ne $null) { # Split label into major minor $major,[int]$minor= (($list | Select-Object -last 1).split()).split(".") # Increment minor label $minor++ # Remove BL from string, and cast to int [int]$major = $major.substring(2) # If minor gt 999 increment major and reset minor if ($minor -gt 999) { $major++ $minor = 1 } } # return label $label = "BL{0}.{1:000}" -f $major, $minor write-output $label } End { Write-Debug "GetNextLabel Completed" } } #------------------------------------------------------------------------- Function MSBuild($outputdir, $webproject, $project, $ref) { Begin { Write-Debug "Starting MSBuild" Write-Debug "outputdir: $outputdir webproject: $webproject project: $project ref: $ref" } Process { # I think this can be cleaned up with where-object, but it's too important to play with $failed = $false &$MSBUILD /p:Configuration=Release /p:OutDir=$Outputdir /p:WebProjectOutputDir=$webproject $project |% { if ($_ -match "Build FAILED") { $failed = $true } ; $_ } if ($failed) { throw (new-object NullReferenceException) } $failed = $false &$MSBUILD /p:Configuration=Release /t:ResolveReferences /p:OutDir=$Outputdir\\bin\\ /p:ReferencePath=$ref $project |% { if ($_ -match "Build FAILED") { $failed = $true } ; $_ } if ($failed) { throw (new-object NullReferenceException) } } End { Write-Debug "MSBuild Completed" } } #------------------------------------------------------------------------- # Create the Label #------------------------------------------------------------------------- Function ApplyLabel() { Write-verbose "Create the Label" $log += "Create the Label" $label = GetNextLabel &$TF label $label $/CSR/CSR /recursive &$TF get /version:L$($label) Write-verbose "Applied label $label" $log += "Applied label $label" return $Label } # END ApplyLabel } # End Begin Process { trap [Exception] { write-verbose "Build Failed" $log += "Build Failed" exit 1; } . SetTFS . CreateWorkspace . ApplyLabel IF (!$CSRWS -AND !$CSRWEB -AND !$CSRServices) { Write-Debug "No Options Found Setting ALL" $CSRWS = $TRUE $CSRWEB = $TRUE $CSRServices = $TRUE } Switch ("") { {$CSRWEB} { Write-Verbose "Building CSRWEB" $log += "Building CSRWEB" . MsBuild "$Outdir\\CSRWeb\\" $WEBPROJECTOUTPUTDIR "$CSRDIR\\CSR\\CSR\\CSRWeb\\CSRWeb\\CSRWeb.csproj" $REFPATH # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential rm $Outdir\\CSRWeb\\*.config -recurse rm $Outdir\\CSRWeb\\*.pdb -recurse rm $Outdir\\CSRWeb\\*.dll -recurse rm $Outdir\\CSRWeb\\*.xml -recurse rm $Outdir\\CSRWeb\\bin\\*.pdb -recurse rm $Outdir\\CSRWeb\\bin\\*.config -recurse rm $Outdir\\CSRWeb\\bin\\*.xml -recurse Write-verbose "Build CSRWEB Successful" $log += "Build CSRWEB Successful" } {$CSRWS} { Write-verbose "Building CSRWS" $log +="Building CSRWS" . MsBuild "$Outdir\\CSRWS\\" $WEBPROJECTOUTPUTDIR1 "$CSRDIR\\CSR\\CSR\\CSRWS\\CSRWS\\CSRWS.csproj" $REFPATH # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential rm $Outdir\\CSRWS\\*.config -recurse rm $Outdir\\CSRWS\\*.pdb -recurse rm $Outdir\\CSRWS\\*.dll -recurse rm $Outdir\\CSRWS\\*.xml -recurse rm $Outdir\\CSRWS\\bin\\*.pdb -recurse rm $Outdir\\CSRWS\\bin\\*.config -recurse rm $Outdir\\CSRWS\\bin\\*.xml -recurse Write-verbose "Build CSRWS Successful" $log += "Build CSRWS Successful" } {$CSRServices} { Write-verbose "Building CSR Services" $Log += "Building CSR Services" . MsBuild "$Outdir\\CSRSERVICES\\" $WEBPROJECTOUTPUTDIR2 "$CSRDIR\\CSR\\CSR\\CSRSERVICES\\CSRSERVICES\\CSRSERVICES.csproj" $REFPATH # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential # copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential rm $Outdir\\CSRSERVICES\\*.config -recurse rm $Outdir\\CSRSERVICES\\*.pdb -recurse rm $Outdir\\CSRSERVICES\\*.dll -recurse rm $Outdir\\CSRSERVICES\\*.xml -recurse rm $Outdir\\CSRSERVICES\\bin\\*.pdb -recurse rm $Outdir\\CSRSERVICES\\bin\\*.config -recurse rm $Outdir\\CSRSERVICES\\bin\\*.xml -recurse Write-verbose "Build CSR Services Successful" $Log += "Build CSR Services Successful" } } # End Switch } #End Process End { IF ($LogPath) { $log | Out-file -FilePath $LogPath -Encoding ascii -Append } } #END End
PowerShellCorpus/PoshCode/Set-LocalUserAccount.ps1
Set-LocalUserAccount.ps1
function Set-LocalUserAccount { param ( [parameter(Mandatory=$true)] [string] $Username, [string] $Description, [string] $FullName, [string] $ComputerName = $env:COMPUTERNAME, [system.Security.SecureString] $Password, [switch] $PasswordChangeAtNextLogon, [switch] $CannotChangePassword, [switch] $PasswordNeverExpires, [switch] $Enable, [switch] $Disable, [switch] $UnLock, [switch] $ResetAllFlags ) try { if ($Enable -and $Disable) { Write-Warning "Please use only -Enable or -Disable."; return } if ($Password) { $pass = [Runtime.InteropServices.marshal]::PtrToStringAuto([Runtime.InteropServices.marshal]::SecureStringToBSTR($Password)) } $AccountOptions = @{ ACCOUNTDISABLE = 2; LOCKOUT = 16; PASSWD_CANT_CHANGE = 64; NORMAL_ACCOUNT = 512; DONT_EXPIRE_PASSWD = 65536 } $user = [ADSI] "WinNT://$ComputerName/$Username" if ($Description) {$user.Description = $Description} if ($FullName) {$user.FullName = $FullName} if ($pass) { $user.psbase.invoke("SetPassword", $pass) $user.psbase.CommitChanges() } if ($ResetAllFlags) { $user.UserFlags = $user.UserFlags.Value -band $AccountOptions.NORMAL_ACCOUNT } else { # Disables "User cannot change password" and "Password never expires" if ($PasswordChangeAtNextLogon) { $user.UserFlags = $AccountOptions.PASSWD_CANT_CHANGE -band $AccountOptions.DONT_EXPIRE_PASSWD $user.PasswordExpired = 1 } else { if ($CannotChangePassword) { $user.PasswordExpired = 0 $user.UserFlags = $user.UserFlags.Value -bor $AccountOptions.PASSWD_CANT_CHANGE } if ($PasswordNeverExpires) {$user.UserFlags = $user.UserFlags.Value -bor $AccountOptions.DONT_EXPIRE_PASSWD} } if ($Enable) {$user.InvokeSet("AccountDisabled", "False")} if ($Disable) {$user.InvokeSet("AccountDisabled", "True")} if ($UnLock) {$user.IsAccountLocked = $false} } $user.SetInfo() } catch { throw 'Failed to set local user account properties. The error was: "{0}".' -f $_ } }
PowerShellCorpus/PoshCode/Split-Job V 1.2.ps1
Split-Job V 1.2.ps1
#requires -version 2.0 <# ################################################################################ ## Run commands in multiple concurrent pipelines ## by Arnoud Jansveld - www.jansveld.net/powershell ## ## Basic "drop in" usage examples: ## - Functions that accept pipelined input: ## Without Split-Job: ## Get-Content hosts.txt | MyFunction | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {MyFunction} | Export-Csv results.csv ## - Functions that do not accept pipelined input (use foreach): ## Without Split-Job: ## Get-Content hosts.txt |% { .\\MyScript.ps1 -ComputerName $_ } | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {%{ .\\MyScript.ps1 -ComputerName $_ }} | Export-Csv results.csv ## ## Example with an imported function: ## function Test-WebServer ($ComputerName) { ## $WebRequest = [System.Net.WebRequest]::Create("http://$ComputerName") ## $WebRequest.GetResponse() ## } ## Get-Content hosts.txt | Split-Job {%{Test-WebServer $_ }} -Function Test-WebServer | Export-Csv results.csv ## ## Example with importing a module ## Get-Content Clusters.txt | Split-Job { % { Get-Cluster -Name $_ } } -InitializeScript { Import-Module FailoverClusters } ## ## ## Version History ## 1.2 Changes by Stephen Mills - stephenmills at hotmail dot com ## Only works with PowerShell V2 ## Modified error output to use ErrorRecord parameter of Write-Error - catches Category Info then. ## Works correctly in powershell_ise. Previous version would let pipelines continue if ESC was pressed. If Escape pressed, then it will do an async cancel of the pipelines and exit. ## Add seconds remaining to progress bar ## Parameters Added and related functionality: ## InitializeScript - allows to have custom scripts to initilize ( Import-Module ...), parameter might be renamed Begin in the future. ## MaxDuration - Cancel all pending and in process items in queue if the number of seconds is reached before all input is done. ## ProgressInfo - Allows you to add additional text to progress bar ## NoProgress - Hide Progress Bar ## DisplayInterval - frequency to update Progress bar in milliseconds ## InputObject - not yet used, planned to be used in future to support start processing the queue before pipeline isn't finished yet ## Added example for importing a module. ## 1.0 First version posted on poshcode.org ## Additional runspace error checking and cleanup ## 0.93 Improve error handling: errors originating in the Scriptblock now ## have more meaningful output ## Show additional info in the progress bar (thanks Stephen Mills) ## Add SnapIn parameter: imports (registered) PowerShell snapins ## Add Function parameter: imports functions ## Add SplitJobRunSpace variable; allows scripts to test if they are ## running in a runspace ## 0.92 Add UseProfile switch: imports the PS profile ## Add Variable parameter: imports variables ## Add Alias parameter: imports aliases ## Restart pipeline if it stops due to an error ## Set the current path in each runspace to that of the calling process ## 0.91 Revert to v 0.8 input syntax for the script block ## Add error handling for empty input queue ## 0.9 Add logic to distinguish between scriptblocks and cmdlets or scripts: ## if a ScriptBlock is specified, a foreach {} wrapper is added ## 0.8 Adds a progress bar ## 0.7 Stop adding runspaces if the queue is already empty ## 0.6 First version. Inspired by Gaurhoth's New-TaskPool script ################################################################################ #> function Split-Job { param ( [Parameter(Position=0, Mandatory=$true)]$Scriptblock, [Parameter()][int]$MaxPipelines=10, [Parameter()][switch]$UseProfile, [Parameter()][string[]]$Variable, [Parameter()][string[]]$Function = @(), [Parameter()][string[]]$Alias = @(), [Parameter()][string[]]$SnapIn, [Parameter()][float]$MaxDuration = $( [Int]::MaxValue ), [Parameter()][string]$ProgressInfo ='', [Parameter()][int]$ProgressID = 0, [Parameter()][switch]$NoProgress, [Parameter()][int]$DisplayInterval = 300, [Parameter()][scriptblock]$InitializeScript, [Parameter(ValueFromPipeline=$true)][object[]]$InputObject ) begin { $StartTime = Get-Date #$DisplayTime = $StartTime.AddMilliseconds( - $DisplayInterval ) $ExitForced = $false function Init ($InputQueue){ # Create the shared thread-safe queue and fill it with the input objects $Queue = [Collections.Queue]::Synchronized([Collections.Queue]@($InputQueue)) $QueueLength = $Queue.Count # Do not create more runspaces than input objects if ($MaxPipelines -gt $QueueLength) {$MaxPipelines = $QueueLength} # Create the script to be run by each runspace $Script = "Set-Location '$PWD'; " $Script += { $SplitJobQueue = $($Input) & { trap {continue} while ($SplitJobQueue.Count) {$SplitJobQueue.Dequeue()} } | }.ToString() + $Scriptblock # Create an array to keep track of the set of pipelines $Pipelines = New-Object System.Collections.ArrayList # Collect the functions and aliases to import $ImportItems = ($Function -replace '^','Function:') + ($Alias -replace '^','Alias:') | Get-Item | select PSPath, Definition $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() } function Add-Pipeline { # This creates a new runspace and starts an asynchronous pipeline with our script. # It will automatically start processing objects from the shared queue. $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host) $Runspace.Open() if (!$?) { throw "Could not open runspace!" } $Runspace.SessionStateProxy.SetVariable('SplitJobRunSpace', $True) function CreatePipeline { param ($Data, $Scriptblock) $Pipeline = $Runspace.CreatePipeline($Scriptblock) if ($Data) { $Null = $Pipeline.Input.Write($Data, $True) $Pipeline.Input.Close() } $Null = $Pipeline.Invoke() $Pipeline.Dispose() } # Optionally import profile, variables, functions and aliases from the main runspace if ($UseProfile) { CreatePipeline -Script "`$PROFILE = '$PROFILE'; . `$PROFILE" } if ($Variable) { foreach ($var in (Get-Variable $Variable -Scope 2)) { trap {continue} $Runspace.SessionStateProxy.SetVariable($var.Name, $var.Value) } } if ($ImportItems) { CreatePipeline $ImportItems { foreach ($item in $Input) {New-Item -Path $item.PSPath -Value $item.Definition} } } if ($SnapIn) { CreatePipeline (Get-PSSnapin $Snapin -Registered) {$Input | Add-PSSnapin} } #Custom Initialization Script for startup of Pipeline - needs to be after other other items added. if ($InitializeScript -ne $null) { CreatePipeline -Scriptblock $InitializeScript } $Pipeline = $Runspace.CreatePipeline($Script) $Null = $Pipeline.Input.Write($Queue) $Pipeline.Input.Close() $Pipeline.InvokeAsync() $Null = $Pipelines.Add($Pipeline) } function Remove-Pipeline ($Pipeline) { # Remove a pipeline and runspace when it is done $Pipeline.RunSpace.CloseAsync() #Removed Dispose so that Split-Job can be quickly aborted even if currently running something waiting for a timeout. #Added call to [System.GC]::Collect() at end of script to free up what memory it can. #$Pipeline.Dispose() $Pipelines.Remove($Pipeline) } } end { # Main # Initialize the queue from the pipeline . Init $Input # Start the pipelines try { while ($Pipelines.Count -lt $MaxPipelines -and $Queue.Count) {Add-Pipeline} # Loop through the pipelines and pass their output to the pipeline until they are finished while ($Pipelines.Count) { # Only update the progress bar once per $DisplayInterval if (-not $NoProgress -and $Stopwatch.ElapsedMilliseconds -ge $DisplayInterval) { $Completed = $QueueLength - $Queue.Count - $Pipelines.count $Stopwatch.Reset() $Stopwatch.Start() #$LastUpdate = $stopwatch.ElapsedMilliseconds $PercentComplete = (100 - [Int]($Queue.Count)/$QueueLength*100) $Duration = (Get-Date) - $StartTime $DurationString = [timespan]::FromSeconds( [Math]::Floor($Duration.TotalSeconds)).ToString() $ItemsPerSecond = $Completed / $Duration.TotalSeconds $SecondsRemaining = [math]::Round(($QueueLength - $Completed)/ ( .{ if ($ItemsPerSecond -eq 0 ) { 0.001 } else { $ItemsPerSecond}})) Write-Progress -Activity "** Split-Job ** *Press Esc to exit* Next item: $(trap {continue}; if ($Queue.Count) {$Queue.Peek()})" ` -status "Queues: $($Pipelines.Count) QueueLength: $($QueueLength) StartTime: $($StartTime) $($ProgressInfo)" ` -currentOperation "$( . { if ($ExitForced) { 'Aborting Job! ' }})Completed: $($Completed) Pending: $($QueueLength- ($QueueLength-($Queue.Count + $Pipelines.Count))) RunTime: $($DurationString) ItemsPerSecond: $([math]::round($ItemsPerSecond, 3))"` -PercentComplete $PercentComplete ` -Id $ProgressID ` -SecondsRemaining $SecondsRemaining } foreach ($Pipeline in @($Pipelines)) { if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline) { $Pipeline.Output.NonBlockingRead() $Pipeline.Error.NonBlockingRead() | % { Write-Error -ErrorRecord $_ } } else { # Pipeline has stopped; if there was an error show info and restart it if ($Pipeline.PipelineStateInfo.State -eq 'Failed') { Write-Error $Pipeline.PipelineStateInfo.Reason # Restart the runspace if ($Queue.Count -lt $QueueLength) {Add-Pipeline} } Remove-Pipeline $Pipeline } if ( ((Get-Date) - $StartTime).TotalSeconds -ge $MaxDuration -and -not $ExitForced) { Write-Warning "Aborting job! The MaxDuration of $MaxDuration seconds has been reached. Inputs that have not been processed will be skipped." $ExitForced=$true } if ($ExitForced) { $Pipeline.StopAsync(); Remove-Pipeline $Pipeline } } while ($Host.UI.RawUI.KeyAvailable) { if ($Host.ui.RawUI.ReadKey('NoEcho,IncludeKeyDown,IncludeKeyUp').VirtualKeyCode -eq 27 -and !$ExitForced) { $Queue.Clear(); Write-Warning 'Aborting job! Escape pressed! Inputs that have not been processed will be skipped.' $ExitForced = $true; #foreach ($Pipeline in @($Pipelines)) #{ # $Pipeline.StopAsync() #} } } if ($Pipelines.Count) {Start-Sleep -Milliseconds 50} } #Clear the Progress bar so other apps don't have to keep seeing it. Write-Progress -Completed -Activity "`0" -Status "`0" # Since reference to Dispose was removed. I added this to try to help with releasing resources as possible. # This might be a bad idea, but I'm leaving it in for now. (Stephen Mills) [GC]::Collect() } finally { foreach ($Pipeline in @($Pipelines)) { if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline) { Write-Warning 'Pipeline still runinng. Stopping Async.' $Pipeline.StopAsync() Remove-Pipeline $Pipeline } } } } }
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 # # There is no help (yet) because I'm still changing and renaming everything every time I mess with this code # Full RoundTrip capability: # # > ls | ConvertTo-Json | ConvertFrom-Json # > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json # # You may frequently want to use the DEPTH or NoTypeInformation parameters: # # > ConvertTo-Json -Depth 2 -NoTypeInformation # # But then you have to specify the type when you reimport (and you can't do that for deep objects). # This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject). # For Example: # # > PS | Select PM, WS, CPU, ID, ProcessName | # >> ConvertTo-json -NoType | # >> convertfrom-json -Type System.Diagnostics.Process Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization $utf8 = [System.Text.Encoding]::UTF8 function Write-String { PARAM( [Parameter()]$stream, [Parameter(ValueFromPipeline=$true)]$string ) PROCESS { $bytes = $utf8.GetBytes($string) $stream.Write( $bytes, 0, $bytes.Length ) } } function Convert-JsonToXml { PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json) BEGIN { $mStream = New-Object System.IO.MemoryStream } PROCESS { $json | Write-String -stream $mStream } END { $mStream.Position = 0 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,ParameterSetName="ManualType")] [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 # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUXAqZYYkg9cBlXfWUCYbkYZzl # ynaggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp # Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy # dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw # MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp # BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV # BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 # IENBM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ESXi_1.ps1
* UNAUTHORISED ACCESS PROHIBITED: * * ------------------------------- * * This network is provided for authorised staff of Test
PowerShellCorpus/PoshCode/Xml Module 4.2.ps1
Xml Module 4.2.ps1
#requires -version 2.0 # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492 # to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations # and prefixes are removed from all XML nodes (by an XSL transform) before searching. # IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did. # Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible # with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node # Version History: # Select-Xml 2.0 This was the first script version I wrote. # it didn't function identically to the built-in Select-Xml with regards to parameter parsing # Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement # BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node # Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed* # Version 3.0 Added New-XDocument and associated generation functions for my XML DSL # Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released # Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument # Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack. # Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags. # Fixed some alias error messages caused when PSCX is already loaded (we were failing to overwrite aliases for cvxml and fxml) # Renamed the internal DSL function $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } function Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Indent # The indent level (defaults to 2 spaces) Param( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] [xml]$xml , [Parameter(Mandatory=$false)] $indent=2 ) $StringWriter = New-Object System.IO.StringWriter $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter $xmlWriter.Formatting = "indented" $xmlWriter.Indentation = $Indent $xml.WriteContentTo($XmlWriter) $XmlWriter.Flush() $StringWriter.Flush() Write-Output $StringWriter.ToString() } Set-Alias fxml Format-Xml -EA 0 function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter Xsl # Specifies an Xml StyleSheet to transform with... [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias cvxml Convert-Xml -EA 0 function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace -EA 0 function New-XDocument { #.Synopsis # Creates a new XDocument (the new xml document type) #.Description # This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML # It creates a new XDocument, and takes scritpblock(s) to define it's contents #.Parameter root # The root node name #.Parameter version # Optional: the XML version. Defaults to 1.0 #.Parameter encoding # Optional: the Encoding. Defaults to UTF-8 #.Parameter standalone # Optional: whether to specify standalone in the xml declaration. Defaults to "yes" #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) # #.Example # [string]$xml = New-XDocument rss -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # item { # title {"The First Item"} # link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # description {"Ema Lazarus' Poem"} # pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"} # } # } # } # # C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # C:\\PS>$xml.ToString() # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss version="2.0"> # <channel> # <title>Test RSS Feed</title> # <link>http ://HuddledMasses.org</link> # <description>An RSS Feed generated simply to demonstrate my XML DSL</description> # <item> # <title>The First Item</title> # <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link> # <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid> # <description>Ema Lazarus' Poem</description> # <pubDate>2003-10-31T00:00:00Z</pubDate> # </item> # </channel> # </rss> # # # Description # ----------- # This example shows the creation of a complete RSS feed with a single item in it. # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output. # # #.Example # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc { # title {"Test First Entry"} # link {"http`://HuddledMasses.org"} # updated {(Get-Date -f u) -replace " ","T"} # author { # name {"Joel Bennett"} # uri {"http`://HuddledMasses.org"} # } # id {"http`://huddledmasses.org/" } # # entry { # title {"Test First Entry"} # link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" } # id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" } # updated {(Get-Date 10/31/2003 -f u) -replace " ","T"} # summary {"Ema Lazarus' Poem"} # link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution" # dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" } # category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses" # } # } | % { $_.Declaration.ToString(); $_.ToString() } # # <?xml version="1.0" encoding="UTF-16" standalone="yes"?> # <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom"> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org</link> # <updated>2009-07-29T17:25:49Z</updated> # <author> # <name>Joel Bennett</name> # <uri>http ://HuddledMasses.org</uri> # </author> # <id>http ://huddledmasses.org/</id> # <entry> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link> # <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id> # <updated>2003-10-31T00:00:00Z</updated> # <summary>Ema Lazarus' Poem</summary> # <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" /> # <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights> # <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" /> # </entry> # </feed> # # # Description # ----------- # This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString(). # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.# # Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$root , [Parameter(Mandatory = $false)] [string]$Version = "1.0" , [Parameter(Mandatory = $false)] [string]$Encoding = "UTF-8" , [Parameter(Mandatory = $false)] [string]$Standalone = "yes" , [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)) { $value = ConvertFrom-XmlDsl $value &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $value } } )) } } Set-Alias xml New-XDocument -EA 0 Set-Alias New-Xml New-XDocument -EA 0 function New-XAttribute { #.Synopsys # Creates a new XAttribute (an xml attribute on an XElement for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter name # The attribute name #.Parameter value # The attribute value Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value) New-Object XAttribute $name, $value } Set-Alias xa New-XAttribute -EA 0 Set-Alias New-XmlAttribute New-XAttribute -EA 0 function New-XElement { #.Synopsys # Creates a new XElement (an xml tag for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter tag # The name of the xml tag #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$tag , [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)) { # then it's content &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $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 ) $duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) } [Array]::Reverse( $duds ) [string[]]$ScriptText = "$script" -split "`n" ForEach($token in $duds ) { # replace : notation with namespace notation if( $token.Content.Contains(":") ) { $key, $localname = $token.Content -split ":" $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" ) } else { $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" ) } # insert 'xe' before everything (unless it's a valid command) $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " ) } Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") )) } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml
PowerShellCorpus/PoshCode/get-GPOReportSize.ps1
get-GPOReportSize.ps1
param( [Parameter(Position=0,ValueFromPipeline=$True)]$GPOs = @(Get-GPO -All), [string] $Reportfolder = [Environment]::getfolderpath("mydocuments") + "\\GPOreports" ) begin{ $script:GPObj = @() $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name $startfolder = "\\\\$domain\\SYSVOL\\$domain\\Policies" write-verbose "getting info from $startfolder" Function GPOSize($objGPO){ $colItems = (Get-ChildItem "$("$startfolder\\`{")$($objGPO.Id)$("`}")" -recurse | Measure-Object -property length -sum) $Result = "{0:N2}" -f ($colItems.sum / 1KB) + " KB" write-verbose "the size for $objGPO is $Result" return $Result } }# end begin process{ foreach ($GPO in $GPOs){ write-verbose "getting GPO $($GPO.DisplayName)" $DateRevMin = get-date -uformat "%Y-%m-%d" New-Item $Reportfolder\\$DateRevMin -ItemType directory -Force | out-null $OutPath = $Reportfolder + "\\" + $DateRevMin + "\\" + $GPO.DisplayName + ".html" Get-GPOReport $GPO.Id -ReportType html -Path $OutPath $script:GPObj += New-Object PSObject -Property @{ GPName = $GPO.DisplayName GPGUID = $GPO.ID Size = $(GPOSize $GPO) Report = $OutPath } } }# end process end{ $script:GPObj } # alternative oneliner to get reports for all GPO objects in domain # Get-GPO -All | %{Get-GPOReport -guid $_.id -ReportType html -Path (join-path -path "c:\\temp" -childpath "$($_.displayname).html")}
PowerShellCorpus/PoshCode/Email-ExpiringADAccounts.ps1
Email-ExpiringADAccounts.ps1
Function GetMsgBody { Write-Output @" <p>Dear $name,</p> Your ABC network account is about to expire.<br/> Please email helpdesk@abc.com or simply hit 'reply', and include the following details to have your account extended.<br/> <br/> Your name:<br/> The department you currently volunteer in:<br/> The staff supervisor's name you currently report to:<br/> The current status of your involvement with ABC (Staff/Student/Volunteer):<br/> <br/> Kind Regards,<br/> ABC IT Services "@ } Get-QADUser -AccountExpiresBefore "31/01/2012" -Enabled -SizeLimit 0 | ForEach-Object { $email = $_.mail $name = $_.givenName [string]$body = GetMsgBody Send-MailMessage -BodyAsHtml:$true -Body $body -To $email -From 'helpdesk@abc.com' -SmtpServer 'smtp.abc.com' -Subject "Your account is about to expire" }
PowerShellCorpus/PoshCode/Get_Set Signature (CTP2)_1.ps1
Get_Set Signature (CTP2)_1.ps1
#Requires -version 2.0 ## Authenticode.psm1 #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## ls | If-Signed -Broken | Set-AuthenticodeSignature Get-PfxCertificate C:\\My.pfx #################################################################################################### ## History: ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## CMDLET Set-AuthenticodeSignature -snapin Huddled.BetterDefaults { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path , ## TODO: you should CHANGE THIS to a method which gets *your* default certificate $Certificate # = $(ls cert:\\CurrentUser\\my\\0DA3A2A2189CD74AE371E6C57504FEB9A59BB22E) ) Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $Path } CMDLET Get-AuthenticodeSignature -snapin Huddled.BetterDefaults { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path ) Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path } CMDLET If-Signed -snapin Huddled.BetterDefaults { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path , [Parameter()] [switch]$BrokenOnly , [Parameter()] [switch]$TrustedOnly , [Parameter()] [switch]$ValidOnly , [Parameter()] [switch]$InvalidOnly , [Parameter()] [switch]$UnsignedOnly ) $sig = Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $Path" return } # Trusted only returns ONLY things which are Valid if($TrustedOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $Path" return } # AllValid returns only things that are SIGNED and not HashMismatch if($ValidOnly -and (($sig.Status -ne "HashMismatch") -or !$_.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $Path" return } # NOTValid returns only things that are SIGNED and not HashMismatch if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $Path" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $_.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $Path" return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !$_.SignerCertificate ) { Write-Debug "$($sig.Status) - Not Signed: $Path" return } get-childItem $sig.Path } Export-ModuleMember Set-AuthenticodeSignature,Get-AuthenticodeSignature,If-Signed
PowerShellCorpus/PoshCode/New-XVM_6.ps1
New-XVM_6.ps1
#Examples <# New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx' New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"} #> Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { Try { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Invoke-Expression -Command $command } End {} }
PowerShellCorpus/PoshCode/Set Logfile length_4.ps1
Set Logfile length_4.ps1
<# .SYNOPSIS Set any text file to a fixed number of lines. Use 'Get-Help .\\SetFileLines -full' to view Help for this file. .DESCRIPTION This script will maintain the PS Transcript file (default setting), or any text file, at a fixed length, ie matching the number of lines entered. However, omitting the lines parameter will just remove any blank lines; and using the -Blanks switch will remove blanks from the desired length. Can be included in $profile. .EXAMPLE Set-FileLines -File c:\\Scripts\\anyfile.txt Remove all blank lines from the file 'anyfile.txt'. .EXAMPLE Set-FileLines 1500 -Blanks This will set the file length of 'Transcript.txt' to 1500 lines and also remove all blank lines. .EXAMPLE Set-FileLines Remove any blank lines from the default file 'Transcript.txt'. .NOTES The 'Lines' property returned by '(Get-Content $file | Measure-Object -line)' excludes any blank lines so the resulting calculated totals may not be 100% accurate. The author can be contacted via www.SeaStarDevelopment.Bravehost.com V2.1 Use 'Switch -regex' instead of 'Get-Content | foreach', 22 Dec 2011. #> Param ([int] $lines = 0, [String]$file = "$pwd\\Transcript.txt", [Switch]$blanks) if ($file -notlike "*.txt") { [System.Media.SystemSounds]::Hand.Play() Write-Warning "This script can only process .txt files" exit 1 } if (!(Test-Path $file)) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "File $file does not exist - please enter valid filename." exit 1 } [int]$count = 0 [int]$blankLines = 0 $encoding = 'Default' $errorActionPreference = 'SilentlyContinue' if ($lines -eq 0) { #A value of 0 lines will just remove blanks. [int]$extra = 1 [int]$count = 1 [switch]$blanks = $true #Otherwise no blanks will be deleted below. } else { $fileLength = (Get-Content $file | Measure-Object -line) [int]$extra = $fileLength.Lines - $lines #Number of lines to remove. } #Note: $fileLength.Lines excludes any blank lines, so not 100% accurate. if ($extra -gt 0) { $fileLength = $null $date = "{0:G}" -f [DateTime]::Now Write-Output "$date Starting maintenance on file <$file>" $tempfile = [IO.Path]::GetTempFileName() if ($file -like "*transcript*.txt") { $encoding = 'Unicode' Stop-Transcript | Out-Null $status = $? # $true if we are running transcript. } switch -regex -file $file { { $count -lt $extra } { $count++; continue} '^\\s*$' { if ($blanks) { $blankLines++ continue } $_ | Out-File $tempFile -encoding $encoding -Append -Force } #End blank line. default { $_ | Out-File $tempFile -encoding $encoding -Append -Force } } #End switch Remove-Item $file -Force #File in use by another process. if (!$?) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$($error[0]) Application terminating." Remove-Item $tempfile $ErrorActionPreference = 'Continue' exit 2 } Move-Item $tempfile -Destination $file -Force if ($lines -eq 0) { #Only interested in blank lines here. $tag = "$blankLines blank lines removed." } elseIf ($blanks) { $tag = "$extra lines removed (+ $blankLines blank)." } else { $tag = "$extra lines removed." } if (($file -like "*transcript.txt") -and $status) { Start-Transcript -append -path $file -force | Out-Null } Write-Output "Maintenance of file completed: $tag" } else { Write-Output "[$file] Filesize ($($FileLength.Lines) lines) is below minimum; no lines removed." } $ErrorActionPreference = 'Continue'
PowerShellCorpus/PoshCode/New-WebServiceProxy.ps1
New-WebServiceProxy.ps1
# # New-WebServiceProxy.ps1 (v2.0 Aug 6, 2007) # # Oisin Grehan <oising@gmail.com> (x0n) # # Usage: # $proxy = .\\New-WebServiceProxy.ps1 [-Url] http://site/service.asmx [-Anonymous] [[-SoapProtocol] <Soap | Soap12>] # # to see available webmethods: # $proxy | gm # # $url = "http://services.msdn.microsoft.com/contentservices/contentservice.asmx?wsdl" param($url = $(throw "need `$url"), [switch]$Anonymous, [string]$protocol = "Soap") [void][system.Reflection.Assembly]::LoadWithPartialName("system.web.services") trap { "Error:`n`n $error"; break; } #$request = [System.Net.WebRequest]::Create($url); $dcp = new-object system.web.services.discovery.discoveryclientprotocol if (! $Anonymous) { Write-Progress "Network Credentials" "Awaiting input..." $dcp.Credentials = (Get-Credential).GetNetworkCredential() } Write-Progress "Discovery" "Searching..." $dcp.AllowAutoRedirect = $true [void]$dcp.DiscoverAny($url) $dcp.ResolveAll() # get service name foreach ($entry in $dcp.Documents.GetEnumerator()) { # needed for Dictionary if ($entry.Value -is [System.Web.Services.Description.ServiceDescription]) { $script:serviceName = $entry.Value.Services[0].Name Write-Verbose "Service: $serviceName" } } Write-Progress "WS-I Basic Profile 1.1" "Validating..." $ns = new-Object System.CodeDom.CodeNamespace # "WebServices" $wref = new-object System.Web.Services.Description.WebReference $dcp.Documents, $ns $wrefs = new-object system.web.services.description.webreferencecollection [void]$wrefs.Add($wref) $ccUnit = new-object System.CodeDom.CodeCompileUnit [void]$ccUnit.Namespaces.Add($ns) $violations = new-object system.web.Services.Description.BasicProfileViolationCollection $wsi11 = [system.web.services.WsiProfiles]::BasicProfile1_1 if ([system.web.Services.Description.WebServicesInteroperability]::CheckConformance($wsi11, $wref, $violations)) { Write-Progress "Proxy Generation" "Compiling..." $webRefOpts = new-object System.Web.Services.Description.WebReferenceOptions $webRefOpts.CodeGenerationOptions = "GenerateNewAsync","GenerateProperties" #,"GenerateOldAsync" #StringCollection strings = ServiceDescriptionImporter.GenerateWebReferences( # webReferences, codeProvider, codeCompileUnit, parameters.GetWebReferenceOptions()); $csprovider = new-object Microsoft.CSharp.CSharpCodeProvider $warnings = [System.Web.Services.Description.ServiceDescriptionImporter]::GenerateWebReferences( $wrefs, $csprovider, $ccunit, $webRefOpts) if ($warnings.Count -eq 0) { $param = new-object system.CodeDom.Compiler.CompilerParameters [void]$param.ReferencedAssemblies.Add("System.Xml.dll") [void]$param.ReferencedAssemblies.Add("System.Web.Services.dll") $param.GenerateInMemory = $true; #$param.TempFiles = (new-object System.CodeDom.Compiler.TempFileCollection "c:\\temp", $true) $param.GenerateExecutable = $false; #$param.OutputAssembly = "$($ns.Name)_$($sdname).dll" $param.TreatWarningsAsErrors = $false; $param.WarningLevel = 4; # do it $compileResults = $csprovider.CompileAssemblyFromDom($param, $ccUnit); if ($compileResults.Errors.Count -gt 0) { Write-Progress "Proxy Generation" "Failed." foreach ($output in $compileResults.Output) { write-host $output } foreach ($err in $compileResults.Errors) { write-warning $err } } else { $assembly = $compileResults.CompiledAssembly if ($assembly) { $serviceType = $assembly.GetType($serviceName) $assembly.GetTypes() | % { Write-Verbose $_.FullName } } else { Write-Warning "Failed: `$assembly is null" return } # return proxy instance $proxy = new-object $serviceType.FullName if (! $Anonymous) { $proxy.Credentials = $dcp.Credentials } $proxy # dump instance to pipeline } } else { Write-Progress "Proxy Generation" "Failed." Write-Warning $warnings } #Write-Progress -Completed }
PowerShellCorpus/PoshCode/Export-WLANSettings.ps1
Export-WLANSettings.ps1
# ============================================================================================== # # # NAME: Export-WLANSettings.ps1 # # AUTHOR: Jan Egil Ring # # DATE : 14.03.2010 # # COMMENT: Using netsh.exe to loop through each WLAN on the system and export the settings to the user-provided output-file. # Must be run with Administrator-privileges for the Key Content (security key) to be exported. # # # ============================================================================================== Write-Warning "Must be run with Administrator-privileges for Key Content to be exported" $filepath = Read-Host "Provide path to output-file. E.g. C:\\temp\\wlan.txt" $wlans = netsh wlan show profiles | Select-String -Pattern "All User Profile" | Foreach-Object {$_.ToString()} $exportdata = $wlans | Foreach-Object {$_.Replace(" All User Profile : ",$null)} $exportdata | ForEach-Object {netsh wlan show profiles name="$_" key=clear} | Out-File $filepath
PowerShellCorpus/PoshCode/b50414a2-209f-4936-a4a8-5fcd9719f5ba.ps1
b50414a2-209f-4936-a4a8-5fcd9719f5ba.ps1
################################################################################ # Get-GprsTime.ps1(V 1006A) # Check the total connect time of any GPRS devices from a specified date. # Use the -Detail switch for some extra information if desired. A default value # can be set with the -Monthly switch but can be temporarily overridden with any # -Start value and deleted by entering an invalid date. Now uses .NET Parse to # use any culture date input. Switches -M and -S cannot be used together. # A Balloon prompt will be issued in the Notification area for the 5 days # before the nominal month end, and a suitable Icon (exclamation.ico) file needs # to be available in the $PWD directory for this to work. # NOTE: this can effectively be suppressed by using a value higher than the SIM # card term, ie something like -Expire 100 for a 30 day card which will override # the default setting. Use -Today to check only today's usage. # Examples: # .\\Get-GprsTime.ps1 -Monthly 4/8/2009 # .\\Get-GprsTime.ps1 -Start 12/07/2009 -Expires 100 -Detail # .\\Get-GprsTime.ps1 -m 5/9/2009 # .\\Get-GprsTime.ps1 10/4/2009 -d # .\\Get-GprsTime.ps1 -d # .\\Get-GprsTime.ps1 -Today # .\\Get-GprsTime.ps1 # # The author can be contacted at www.SeaStarDevelopment.Bravehost.com and the # 'exclamation.ico' file is included in the Gprs100x.zip download there. ################################################################################ Param ([String] $start, [String] $monthly, [Int] $expires = 30, #Start warning prompt 5 days before month end. [Switch] $today, [Switch] $detail) Trap [System.Management.Automation.MethodInvocationException] { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" [System.Media.SystemSounds]::Hand.Play() [Int]$line = $error[0].InvocationInfo.ScriptLineNumber If ($line -eq 114) { Write-Warning "Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } Exit 1 } $name = $myInvocation.MyCommand $newLine = "[$name] The switches -Start and -Monthly `n $(' '*($name.ToString().Length +10)) can only be used separately." If ($start -and $monthly) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$newLine" Exit 1 } $SCRIPT:form = "" #In certain cases Culture & UICulture can be different and have been known to # return conflicting results regarding '-is [DateTime]' queries, etc. If ($Host.CurrentCulture -eq $Host.CurrentUICulture) { $SCRIPT:form = '-Use format mm/dd/year' [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day. If ($culture -eq 6) { $SCRIPT:form = '-Use format dd/mm/year' } } $VerbosePreference = 'SilentlyContinue' $WarningPreference = 'Continue' $conn = $disc = $null $timeNow = [DateTime]::Now $total = $timeNow - $timeNow #Set initial value to 00:00:00 $insert = "since" If ($detail) { $VerbosePreference = 'Continue' } Function CreditMsg ($value) { $value = [Math]::Abs($value) $prefix = "CURRENT" $creditDate = [Environment]::GetEnvironmentVariable("GPRS","User") If ($creditDate) { #Do nothing if no monthly date set. [DateTime] $creditDT = $creditDate $creditDT = $creditDT.AddDays($value) #Add the -Expires days. $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format. #If we use '$number = $creditDT - (Get-Date)' instead of the line below #we can sometimes get a value of 1 returned instead 2, hence the above. $number = $creditDT - [DateTime] $thisDay [String] $credit = $creditDT $credit = $credit.Replace('00:00:00','') #Remove any trailing time. $credit = "{0:d}" -f [DateTime]$credit Switch($number.Days) { 1 {$prefix = "($value days) will expire tomorrow"; break} 0 {$prefix = "($value days) will expire today"; break} -1 {$prefix = "($value days) expired yesterday"; break} {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break} {($_ -le 5)} {$prefix = "($value days) will expire on $credit"} Default {$prefix = "CURRENT"} #Only come here if over 5 days. } } Return $prefix } Function Interval ([String] $value) { Switch($value) { { $_ -match '^00:00:\\d+(.*)$' } {$suffix = "seconds"; break} { $_ -match '^00:\\d+:\\d+(.*)$'} {$suffix = "minutes"; break} Default {$suffix = " hours"} } Return $suffix } #The Script effectively starts here............................................. If ($start) { [DateTime] $limit = [DateTime]::Parse($start) #Trigger TRAP if invalid! $convert = "{0:D}" -f $limit } If ($monthly) { $start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid! Write-Output "Setting GPRS (monthly) environment variable to: $monthly" $gprs = [String]$start.Replace('00:00:00','') [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User") [DateTime] $limit = $start #Change to required US date format. $convert = "{0:D}" -f $limit } If ($today) { $verBosePreference = 'Continue' #Show VERBOSE by default. [DateTime] $limit = (Get-Date) $convert = "{0:D}" -f $limit $limit = $limit.Date #Override any start date if using -Today input. $insert = "for today" } #Now we can only continue if we have a valid GPRS environment variable. If ((!$today) -and (!$monthly) -and (!$start)) { #Come here if -Expires. $monthly = [Environment]::GetEnvironmentVariable("GPRS","User") #If no GPRS we have to generate an error for TRAP to catch. If (!$monthly) { $monthly = [DateTime]::Parse($monthly) } [DateTime] $limit = $monthly $convert = "{0:D}" -f $limit } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" $text = CreditMsg $expires #Check if we are within 5 days of expiry date. If (($text -ne "CURRENT") -and (Test-Path "$pwd\\exclamation.ico")) { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $objNotifyIcon.Icon = "$pwd\\exclamation.ico" $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipTitle = "GPRS online account" $objNotifyIcon.BalloonTipText = "Credit $text" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) } Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. $lines = Get-EventLog system | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq 20159 -or $_.EventID -eq 20158)} If ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log." } Else { Write-Output "(There are no events indicated in the System Event Log)" } $lines | ForEach-Object { $source = $_.Source If ($_.EventID -eq 20159) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } Else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... If ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = Interval $diff Write-Verbose "Disconnect at $convDisc. Online - $diff $period" Write-Verbose " Connect at $convConn." } } #End ForEach If (!$source) { $source = '(Undetermined)' } Write-Verbose "Using local event source - System Event Log [$source]" $period = Interval $total Write-Output "Total online usage $insert $convert is $total $($period.Trim())." Write-Output ""
PowerShellCorpus/PoshCode/Test-UserCredential_2.ps1
Test-UserCredential_2.ps1
function Test-UserCredential { [CmdletBinding()] [OutputType([System.Boolean])] param( [Parameter(Mandatory=$true, ParameterSetName="string", position=0)] [ValidateNotNullOrEmpty()] [String] $Username, [Parameter(Mandatory=$true, ParameterSetName="string", position=1)] [ValidateNotNullOrEmpty()] [String] $Password, [Parameter(Mandatory=$true, ParameterSetName="PSCredential", ValueFromPipeline=$true, position=0)] [ValidateNotNullOrEmpty()] [Management.Automation.PSCredential] $Credential, [Parameter(position=2)] [Switch] $Domain ) Begin { try { $assem = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement') } catch { throw 'Failed to load assembly "System.DirectoryServices.AccountManagement". The error was: "{0}".' -f $_ } } Process { try { $system = Get-WmiObject -Class Win32_ComputerSystem if ($PSCmdlet.ParameterSetName -eq 'PSCredential') { $Username = $Credential.GetNetworkCredential().UserName $Password = $Credential.GetNetworkCredential().Password } if ($Domain) { if (0, 2 -contains $system.DomainRole) { throw 'This computer is not a member of a domain.' } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain } } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME } return $principalContext.ValidateCredentials($Username, $Password) } catch { throw 'Failed to test user credentials. The error was: "{0}".' -f $_ } finally { Remove-Variable -Name Username -ErrorAction SilentlyContinue Remove-Variable -Name Password -ErrorAction SilentlyContinue } } <# .SYNOPSIS Validates credentials for local or domain user. .PARAMETER Username The user's username. .PARAMETER Password The user's password. .PARAMETER Credential A PSCredential object created by Get-Credential. This can be pipelined to Test-UserCredential. .EXAMPLE PS C:\\> Test-UserCredential -Username andy -password secret .EXAMPLE PS C:\\> Test-UserCredential -Username 'mydomain\\andy' -password secret -domain .EXAMPLE PS C:\\> Test-UserCredential -Username 'andy' -password secret -domain .EXAMPLE PS C:\\> Get-Credential | Test-UserCredential .INPUTS None. .OUTPUTS System.Boolean. .NOTES Revision History 2011-08-21: Andy Arismendi - Created. 2011-08-22: Andy Arismendi - Add pipelining support for Get-Credential. #> }
PowerShellCorpus/PoshCode/c63c9baf-0890-494c-ba9c-4cadeb312a6c.ps1
c63c9baf-0890-494c-ba9c-4cadeb312a6c.ps1
function Get-WebConfigSqlConnectionString { param( [switch]$help, [string]$configfile = $(read-host "Please enter a web.config file to read"), [string]$conname = $(read-host "Please enter connection name")); $usage = "Usage: Get-WebConfigSqlConnectionString -configfile c:\\inetpub\\wwwroot\\web.config -conname 'ConName'"; if ($help) {Write-Host $usage;break} $webConfigPath = (Resolve-Path $configfile).Path; $xml = [xml](get-content $webConfigPath); $root = $xml.get_DocumentElement(); $connStrings = $root.connectionStrings; $addTag = $connStrings.add $conStringTag = $addTag | Where { $_.Name -eq $conname} return $conStringTag.connectionString }
PowerShellCorpus/PoshCode/Send-Paste.ps1
Send-Paste.ps1
## Send-Paste.ps1 (aka sprunge for Pastebin)\n##############################################################################################################\n## Uploads code to any pastebin.com based pastebin site and returns the url for you.\n## History:\n## v 2.0 - works with "pastebin" (including http://posh.jaykul.com/p/ and http://PowerShellCentral.com/Scripts/)\n## v 1.0 - Worked with a special pastebin\n##############################################################################################################\n#function Send-Paste {\nparam( \n $Title, \n $Description="Automated paste from PowerShell console", \n $KeepFor="d", \n $Language="posh", \n $Author = "Jaykul", # $(Read-Host "Your name"), \n $url="http://posh.jaykul.com/p/" \n)\n \nBEGIN {\n $null = [Reflection.Assembly]::LoadWithPartialName("System.Web")\n [string]$data = $null;\n [string]$meta = $null;\n\n if($language) {\n $meta = "format=" + [System.Web.HttpUtility]::UrlEncode($language)\n # $url = $url + "?" +$lang\n } else {\n $meta = "format=text"\n }\n \n do {\n switch -regex ($KeepFor) {\n "^d.*" { $meta += "&expiry=d" }\n "^m.*" { $meta += "&expiry=m" }\n "^f.*" { $meta += "&expiry=f" }\n default { \n $KeepFor = Read-Host "Invalid value for 'KeepFor' parameter. Please specify 'day', 'month', or 'forever'"\n }\n }\n } until ( $meta -like "*&expiry*" )\n\n if($Description) {\n $meta += "&descrip=" + [System.Web.HttpUtility]::UrlEncode($Description)\n } else {\n $meta += "&descrip="\n } \n $meta += "&poster=" + [System.Web.HttpUtility]::UrlEncode($Author)\n \n function PasteBin-Text ($meta, $title, $data) {\n $meta += "&paste=Send&posttitle=" + [System.Web.HttpUtility]::UrlEncode($Title)\n $data = $meta + "&code2=" + [System.Web.HttpUtility]::UrlEncode($data)\n \n # Write-Host $data -fore yellow\n \n $request = [System.Net.WebRequest]::Create($url)\n $request.ContentType = "application/x-www-form-urlencoded"\n $request.ContentLength = $data.Length\n $request.Method = "POST"\n\n $post = new-object IO.StreamWriter $request.GetRequestStream()\n $post.Write($data,0,$data.Length)\n $post.Flush()\n $post.Close()\n\n # $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8\n # write-output $reader.ReadToEnd()\n # $reader.Close()\n write-output $request.GetResponse().ResponseUri.AbsoluteUri\n $request.Abort() \n }\n}\n\nPROCESS {\n switch($_) {\n {$_ -is [System.IO.FileInfo]} {\n $Title = $_.Name\n Write-Output $_.FullName\n Write-Output $(PasteBin-Text $meta $Title $([string]::join("`n",(Get-Content $_.FullName))))\n }\n {$_ -is [String]} {\n if(!$data -and !$Title){\n $Title = Read-Host "Give us a title for your post"\n }\n $data += "`n" + $_ \n }\n ## Todo, handle folders?\n default {\n Write-Error "Unable to process $_"\n }\n }\n}\nEND {\n if($data) { \n Write-Output $(PasteBin-Text $meta $Title $data)\n }\n}\n#}
PowerShellCorpus/PoshCode/Write-DataTable_2.ps1
Write-DataTable_2.ps1
####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-Alias | Out-DataTable This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 .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() $Col.DataType = $property.value.gettype() $DT.Columns.Add($Col) } if ($property.IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/Select-ToString.ps1
Select-ToString.ps1
[CmdletBinding(DefaultParameterSetName='DefaultParameter')] param( [Parameter(ValueFromPipeline=$true)] [System.Management.Automation.PSObject] ${InputObject}, [Parameter(ParameterSetName='DefaultParameter', Position=0)] [System.String[]] ${Property}, [Parameter(ParameterSetName='DefaultParameter')] [System.String[]] ${ExcludeProperty}, [Parameter(ParameterSetName='DefaultParameter')] [System.String] ${ExpandProperty}, [Switch] ${Unique}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Last}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${First}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Skip}, [Parameter(ParameterSetName='IndexParameter')] [ValidateRange(0, 2147483647)] [System.Int32[]] ${Index} ) begin { try { $propHash = @() foreach($Prop in $Property) { $propHash += @{Name=$Prop; Expression=$(iex "{if(`$_.'$Prop' -is [Array]){ ""{`$(`$_.'$Prop' -join "", "")}"" }else{ `$_.'$Prop' } }")} } write-host $($propHash|out-string) $PSBoundParameters['Property'] = $propHash $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Select-Object', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Select-Object .ForwardHelpCategory Cmdlet #>
PowerShellCorpus/PoshCode/2b09949e-6005-4a68-8379-aec09cbeea8e.ps1
2b09949e-6005-4a68-8379-aec09cbeea8e.ps1
function Get-EasterEastern { Param( [Parameter(Mandatory=$true)] [int] $Year ) $a = $Year % 4 $b = $Year % 7 $c = $Year % 19 $d = ((19 * $c) + 15) % 30 $e1 = -$d #here because powershell is picking up - (subtraction operator) as incorrect toekn $e = ((2 * $a) + (4 * $b) + $e1 + 34) % 7 $month = [Math]::Floor(($d + $e + 114) / 31) $day = (($d + $e + 114) % 31) + 1 $cal = New-Object -TypeName System.Globalization.JulianCalendar New-Object -TypeName System.DateTime -ArgumentList $Year,$month,$day,$cal <# .SYNOPSIS Calculates the Julian Easter date in the Julian calendar for a given year. .DESCRIPTION Calculates the Julian Easter date in the Julian calendar for a given year. This is not the Gregorian Easter now used by Western churches. Algorithm sourced from http://en.wikipedia.org/wiki/Computus, Meeus Julian algorithm. .PARAMETER Year The year to calculate easter for. .EXAMPLE PS C:\\> Get-EasterEastern 2017 .INPUTS System.Int32 .OUTPUTS System.DateTime #> }
PowerShellCorpus/PoshCode/PoshCode ISE Addon_1.ps1
PoshCode ISE Addon_1.ps1
\nif (!(Get-Module WPK)) {Import-Module -global WPK} if (!(Get-Module PoshCode)) {Import-Module -global PoshCode} Function Get-PoshCodePreferences { if (Get-Item $global:xmlPath -ErrorAction SilentlyContinue) { try { $pcPreferences = Import-Clixml -Path $global:xmlPath $global:PCSyntax = $pcPreferences.Syntax $global:PCExpiry = $pcPreferences.Expiry $global:PCAuthor = $pcPreferences.Author } catch { Write-Host "Import-CliXml failed with following error" return } } else { $global:PCSyntax = "posh" $global:PCExpiry = "forever" $global:PCAuthor = "$($env:USERNAME)" } } Function Save-PoshCodePreferences { param($syntax, $expiry, $author) $pcPreferences = New-Object PSObject $pcPreferences | Add-Member -MemberType NoteProperty -Name "Syntax" -Value $syntax $pcPreferences | Add-Member -MemberType NoteProperty -Name "Expiry" -Value $expiry $pcPreferences | Add-Member -MemberType NoteProperty -Name "Author" -Value $author try { Export-Clixml -InputObject $pcPreferences -Path $global:xmlPath -Force } catch { Write-Host "Export-Clixml; failed with the following error" Write-Host $error[0].InnerException return } [system.Windows.Forms.MessageBox]::show('Your preferences have been saved') } function Show-PoshCodeGUI { Get-PoshCodePreferences New-Window -Title "PoshCode addon" -WindowStartupLocation CenterScreen -Width 836 -Height 477 -Show -ResizeMode NoResize -On_Loaded { $txtPasteCode = $Window | Get-ChildControl txtPasteCode $cmbSyntax = $Window | Get-ChildControl cmbSyntax $cmbExpiry = $Window | Get-ChildControl cmbExpiry $txtTitle = $window | Get-ChildControl txtTitle $txtDescription = $window | Get-ChildControl txtDescription $txtAuthor = $window | Get-ChildControl txtAuthor $btnSavePref = $window | Get-ChildControl btnSavePref $btnSubmit = $window | Get-ChildControl btnSubmit } { New-Grid { New-TextBox -Name txtPasteCode -Margin "12,12,0,0" -Height 258 -Width 800 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:SelectedText ` -IsReadOnly -VerticalScrollBarVisibility "Auto" -HorizontalScrollBarVisibility "Auto" New-Label -Name lblLang -Margin "12,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Scripting Language" -FontWeight "Bold" New-ComboBox -Name cmbSyntax -Margin "175,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:cmbSyntaxOptions -SelectedIndex $global:cmbSyntaxOptions.IndexOf($global:PCSyntax) New-Label -Name lblExpiry -Margin "12,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Keep" -FontWeight "Bold" New-ComboBox -Name cmbExpiry -Margin "175,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:Expiry -SelectedIndex $global:Expiry.IndexOf($global:PCExpiry) New-Label -Name lblTitle -Margin "450,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Title" -FontWeight "Bold" New-TextBox -Name txtTitle -Margin "570,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Label -Name lblAuthor -Margin "450,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Author" -FontWeight "Bold" New-TextBox -Name txtAuthor -Margin "570,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:PCAuthor New-Label -Name lblDescription -Margin "12,361,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Description" -FontWeight "Bold" New-TextBox -Name txtDescription -Margin "175,361,0,0" -Height 35 -Width 590 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Button -Name btnSavePref -Margin "280,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Save Preferences" -On_Click { Save-PasteBinPreferences -Syntax $cmbSyntax.SelectedItem -Expiry $cmbExpiry.SelectedItem -Author $txtAuthor.Text } New-Button -Name btnSubmit -Margin "410,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Submit to PoshCode" -On_Click { $returnUri = $global:SelectedText | New-PoshCode -title $txtTitle.Text ` -description $txtDescription.Text -Author $txtAuthor.Text ` -keep $cmbExpiry.SelectedItem -Language $cmbSyntax.SelectedItem if ($returnUri) { [System.Diagnostics.Process]::Start($returnUri) $window.Close() } else { [system.Windows.Forms.MessageBox]::show('Error occured while uploading to PoshCode') $window.Close() } } } } } [System.Collections.ArrayList]$global:cmbSyntaxOptions = "posh","text","vbnet","xml","asp","bash","csharp" [System.Collections.ArrayList]$global:Expiry = "forever","day","month" $global:xmlPath = $("$env:APPDATA\\PoshCodePrefs.xml") if ($host.Name –eq 'Windows PowerShell ISE Host') { $scriptBlock = { if (($psISE.CurrentFile.Editor.SelectedText -ne "")) { $global:SelectedText = $psISE.CurrentFile.Editor.SelectedText } elseif (($psISE.CurrentFile.Editor.Text -ne "")) { $global:SelectedText = $psISE.CurrentFile.Editor.Text } else { [system.Windows.Forms.MessageBox]::show('There is nothing to upload. Select some text or open a script') return } Show-PoshCodeGUI } $submenus = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus $menuExists = $false foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to Posh_Code") { $menuExists = $true } } if (!$menuExists) { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Send To Posh_Code",$ScriptBlock,"CTRL+ALT+C") } $ExecutionContext.SessionState.Module.OnRemove = { foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to PPosh_Code") { $submenus.Remove($menuItem) return } } } } else { Write-Host "This module is meant for either ISE or PGSE" return } Export-ModuleMember -Function * -Variable *
PowerShellCorpus/PoshCode/Ping-Subnet.ps1
Ping-Subnet.ps1
#requires -Version 2.0 Function Ping-Subnet { #.Synopsis # Ping a subnet returning all alive hosts. #.Example # Ping-Subnet -IP 192.168.1.0 -Netmask /24 #.Example # Ping-Subnet -IP 192.168.1.128 -Netmask 255.255.255.128 Param( [string] $IP, [string] $netmask ) Begin { $IPs = New-Object System.Collections.ArrayList $Jobs = New-Object System.Collections.ArrayList $max = 50 Function Get-NetworkAddress { #.Synopsis # Get the network address of a given lan segment #.Example # Get-NetworkAddress -IP 192.168.1.36 -mask 255.255.255.0 Param ( [string] $IP, [string] $Mask, [switch] $Binary ) Begin { $NetAdd = $null } Process { $BinaryIP = ConvertTo-BinaryIP $IP $BinaryMask = ConvertTo-BinaryIP $Mask 0..34 | %{ $IPBit = $BinaryIP.Substring($_,1) $MaskBit = $BinaryMask.Substring($_,1) IF ($IPBit -eq '1' -and $MaskBit -eq '1') { $NetAdd = $NetAdd + "1" } elseif ($IPBit -eq ".") { $NetAdd = $NetAdd +'.' } else { $NetAdd = $NetAdd + "0" } } if ($Binary) { return $NetAdd } else { return ConvertFrom-BinaryIP $NetAdd } } } Function ConvertTo-BinaryIP { #.Synopsis # Convert an IP address to binary #.Example # ConvertTo-BinaryIP -IP 192.168.1.1 Param ( [string] $IP ) Process { $out = @() Foreach ($octet in $IP.split('.')) { $strout = $null 0..7|% { IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { $octet = $octet - [math]::pow(2,(7-$_)) [string]$strout = $strout + "1" } else { [string]$strout = $strout + "0" } } $out += $strout } return [string]::join('.',$out) } } Function ConvertFrom-BinaryIP { #.Synopsis # Convert from Binary to an IP address #.Example # Convertfrom-BinaryIP -IP 11000000.10101000.00000001.00000001 Param ( [string] $IP ) Process { $out = @() Foreach ($octet in $IP.split('.')) { $strout = 0 0..7|% { $bit = $octet.Substring(($_),1) IF ($bit -eq 1) { $strout = $strout + [math]::pow(2,(7-$_)) } } $out += $strout } return [string]::join('.',$out) } } Function ConvertTo-MaskLength { #.Synopsis # Convert from a netmask to the masklength #.Example # ConvertTo-MaskLength -Mask 255.255.255.0 Param ( [string] $mask ) Process { $out = 0 Foreach ($octet in $Mask.split('.')) { $strout = 0 0..7|% { IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { $octet = $octet - [math]::pow(2,(7-$_)) $out++ } } } return $out } } Function ConvertFrom-MaskLength { #.Synopsis # Convert from masklength to a netmask #.Example # ConvertFrom-MaskLength -Mask /24 #.Example # ConvertFrom-MaskLength -Mask 24 Param ( [int] $mask ) Process { $out = @() [int]$wholeOctet = ($mask - ($mask % 8))/8 if ($wholeOctet -gt 0) { 1..$($wholeOctet) |%{ $out += "255" } } $subnet = ($mask - ($wholeOctet * 8)) if ($subnet -gt 0) { $octet = 0 0..($subnet - 1) | %{ $octet = $octet + [math]::pow(2,(7-$_)) } $out += $octet } for ($i=$out.count;$i -lt 4; $I++) { $out += 0 } return [string]::join('.',$out) } } Function Get-IPRange { #.Synopsis # Given an Ip and subnet, return every IP in that lan segment #.Example # Get-IPRange -IP 192.168.1.36 -Mask 255.255.255.0 #.Example # Get-IPRange -IP 192.168.5.55 -Mask /23 Param ( [string] $IP, [string] $netmask ) Process { iF ($netMask.length -le 3) { $masklength = $netmask.replace('/','') $Subnet = ConvertFrom-MaskLength $masklength } else { $Subnet = $netmask $masklength = ConvertTo-MaskLength -Mask $netmask } $network = Get-NetworkAddress -IP $IP -Mask $Subnet [int]$FirstOctet,[int]$SecondOctet,[int]$ThirdOctet,[int]$FourthOctet = $network.split('.') $TotalIPs = ([math]::pow(2,(32-$masklength)) -2) $blocks = ($TotalIPs - ($TotalIPs % 256))/256 if ($Blocks -gt 0) { 1..$blocks | %{ 0..255 |%{ if ($FourthOctet -eq 255) { If ($ThirdOctet -eq 255) { If ($SecondOctet -eq 255) { $FirstOctet++ $secondOctet = 0 } else { $SecondOctet++ $ThirdOctet = 0 } } else { $FourthOctet = 0 $ThirdOctet++ } } else { $FourthOctet++ } Write-Output ("{0}.{1}.{2}.{3}" -f ` $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) } } } $sBlock = $TotalIPs - ($blocks * 256) if ($sBlock -gt 0) { 1..$SBlock | %{ if ($FourthOctet -eq 255) { If ($ThirdOctet -eq 255) { If ($SecondOctet -eq 255) { $FirstOctet++ $secondOctet = 0 } else { $SecondOctet++ $ThirdOctet = 0 } } else { $FourthOctet = 0 $ThirdOctet++ } } else { $FourthOctet++ } Write-Output ("{0}.{1}.{2}.{3}" -f ` $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) } } } } } Process { #get every ip in scope Get-IPRange $IP $netmask | %{ [void]$IPs.Add($_) } #loop untill we've pinged them all While ($IPs.count -gt 0 -or $jobs.count -gt 0) { #if we have open spots kick off some more IF ($jobs.count -le $max) { # determin how many to kick off $addjobs = ($max - $jobs.count) Foreach ($IP in ($IPS | Select -first $addjobs)) { #save the job id, and move on [VOID]$Jobs.Add((gwmi -q "SELECT Address,StatusCode FROM Win32_Pingstatus WHERE Address = `'$IP`'" -asjob).Id) #remove the IP from our pool $IPs.Remove($IP) } } #we'll use this array to track what's comeback $Clean = @() Foreach ($J in $jobs) { # If this job is done get the results if ((Get-Job -id $j).JobStateInfo.state -eq 'Completed') { # if the ping was sucessfull return the IP Address write-output (Receive-Job -id $j) | ?{$_.StatusCode -eq 0}| select -expand Address # dispose of the job remove-job -id $j $clean += $j } } Foreach ($c in $Clean) { #remove the jobs that we just processed $jobs.remove($c) } } } }
PowerShellCorpus/PoshCode/Set-SolarizedHostColor.ps1
Set-SolarizedHostColor.ps1
# function Set-HostColor { param( [Switch]$Light = $( ## Based on whether we're elevated or not, switch between DARK and LIGHT versions of Solarized: $([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista or higher and ... new-object Security.Principal.WindowsPrincipal ( # current user is an administrator (Note: ROLE, not GROUP) [Security.Principal.WindowsIdentity]::GetCurrent()) ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) ) # SOLARIZED HEX 16/8 TERMCOL XTERM/HEX L*A*B RGB HSB # --------- ------- ---- ------- ----------- ---------- ----------- ----------- $base03 = "#002b36" # 8/4 brblack 234 #1c1c1c 15 -12 -12 0 43 54 193 100 21 $base02 = "#073642" # 0/4 black 235 #262626 20 -12 -12 7 54 66 192 90 26 $base01 = "#586e75" # 10/7 brgreen 240 #585858 45 -07 -07 88 110 117 194 25 46 $base00 = "#657b83" # 11/7 bryellow 241 #626262 50 -07 -07 101 123 131 195 23 51 $base0 = "#839496" # 12/6 brblue 244 #808080 60 -06 -03 131 148 150 186 13 59 $base1 = "#93a1a1" # 14/4 brcyan 245 #8a8a8a 65 -05 -02 147 161 161 180 9 63 $base2 = "#eee8d5" # 7/7 white 254 #e4e4e4 92 -00 10 238 232 213 44 11 93 $base3 = "#fdf6e3" # 15/7 brwhite 230 #ffffd7 97 00 10 253 246 227 44 10 99 $yellow = "#b58900" # 3/3 yellow 136 #af8700 60 10 65 181 137 0 45 100 71 $orange = "#cb4b16" # 9/3 brred 166 #d75f00 50 50 55 203 75 22 18 89 80 $red = "#dc322f" # 1/1 red 160 #d70000 50 65 45 220 50 47 1 79 86 $magenta = "#d33682" # 5/5 magenta 125 #af005f 50 65 -05 211 54 130 331 74 83 $violet = "#6c71c4" # 13/5 brmagenta 61 #5f5faf 50 15 -45 108 113 196 237 45 77 $blue = "#268bd2" # 4/4 blue 33 #0087ff 55 -10 -45 38 139 210 205 82 82 $cyan = "#2aa198" # 6/6 cyan 37 #00afaf 60 -35 -05 42 161 152 175 74 63 $green = "#859900" # 2/2 green 64 #5f8700 60 -20 65 133 153 0 68 100 60 ## BEGIN SOLARIZING ---------------------------------------------- if($Host.Name -eq "Windows PowerShell ISE Host" -and $psISE) { $psISE.Options.FontName = 'Consolas' $psISE.Options.TokenColors['Command'] = $yellow $psISE.Options.TokenColors['Position'] = $red $psISE.Options.TokenColors['GroupEnd'] = $red $psISE.Options.TokenColors['GroupStart'] = $red $psISE.Options.TokenColors['NewLine'] = '#FFFFFFFF' # not a printable token $psISE.Options.TokenColors['String'] = $cyan $psISE.Options.TokenColors['Type'] = $orange $psISE.Options.TokenColors['Variable'] = $blue $psISE.Options.TokenColors['CommandParameter'] = $green $psISE.Options.TokenColors['CommandArgument'] = $violet $psISE.Options.TokenColors['Number'] = $red if ($Light) { $psISE.Options.OutputPaneBackgroundColor = $base3 $psISE.Options.OutputPaneTextBackgroundColor = $base3 $psISE.Options.OutputPaneForegroundColor = $base00 $psISE.Options.CommandPaneBackgroundColor = $base3 $psISE.Options.ScriptPaneBackgroundColor = $base3 $psISE.Options.TokenColors['Unknown'] = $base00 $psISE.Options.TokenColors['Member'] = $base00 $psISE.Options.TokenColors['LineContinuation'] = $base01 $psISE.Options.TokenColors['StatementSeparator'] = $base01 $psISE.Options.TokenColors['Comment'] = $base1 $psISE.Options.TokenColors['Keyword'] = $base01 $psISE.Options.TokenColors['Attribute'] = $base00 } else { $psISE.Options.OutputPaneBackgroundColor = $base03 $psISE.Options.OutputPaneTextBackgroundColor = $base03 $psISE.Options.OutputPaneForegroundColor = $base0 $psISE.Options.CommandPaneBackgroundColor = $base03 $psISE.Options.ScriptPaneBackgroundColor = $base03 $psISE.Options.TokenColors['Unknown'] = $base0 $psISE.Options.TokenColors['Member'] = $base0 $psISE.Options.TokenColors['LineContinuation'] = $base1 $psISE.Options.TokenColors['StatementSeparator'] = $base1 $psISE.Options.TokenColors['Comment'] = $base01 $psISE.Options.TokenColors['Keyword'] = $base1 $psISE.Options.TokenColors['Attribute'] = $base0 } $Host.PrivateData.VerboseForegroundColor = $PSISE.Options.VerboseForegroundColor = $blue $Host.PrivateData.DebugForegroundColor = $PSISE.Options.DebugForegroundColor = $green $Host.PrivateData.WarningForegroundColor = $PSISE.Options.WarningForegroundColor = $orange $Host.PrivateData.ErrorForegroundColor = $PSISE.Options.ErrorForegroundColor = $red $PSISE.Options.OutputPaneForegroundColor = $base0 $PSISE.Options.ScriptPaneForegroundColor = $base0 } elseif($Host.Name -eq "ConsoleHost") { ## In the PowerShell Console, we can only use console colors, so we have to pick them by name. ## For it to look right, you have to have run PowerShell from a shortcut you've modified with Install-Solarized if($Light) { ## Set the WindowTitlePrefix for my prompt function, so it won't need to test for IsInRole Administrator again. # $Host.UI.RawUI.WindowTitle = $global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain} (ADMIN)" $Host.UI.RawUI.BackgroundColor = "White" $Host.PrivateData.ProgressBackgroundColor = "Black" $Host.UI.RawUI.ForegroundColor = "DarkCyan" } else { # $Host.UI.RawUI.WindowTitle = $global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain}" $Host.PrivateData.ProgressBackgroundColor = "White" $Host.UI.RawUI.BackgroundColor = "Black" $Host.UI.RawUI.ForegroundColor = "DarkRed" } $Host.PrivateData.ErrorForegroundColor = "Red" $Host.PrivateData.WarningForegroundColor = "DarkYellow" $Host.PrivateData.DebugForegroundColor = "Green" $Host.PrivateData.VerboseForegroundColor = "Blue" $Host.PrivateData.ProgressForegroundColor = "Magenta" $Host.PrivateData.ErrorBackgroundColor = $Host.PrivateData.WarningBackgroundColor = $Host.PrivateData.DebugBackgroundColor = $Host.PrivateData.VerboseBackgroundColor = $Host.UI.RawUI.BackgroundColor } # } # Set-HostColor
PowerShellCorpus/PoshCode/a39ded79-9953-4554-99ac-98c97462bfb8.ps1
a39ded79-9953-4554-99ac-98c97462bfb8.ps1
function Get-Help { <# .ForwardHelpTargetName Get-Help .ForwardHelpCategory Cmdlet #> [CmdletBinding(DefaultParameterSetName='AllUsersView')] param( [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)] [System.String] ${Name}, [System.String] ${Path}, [System.String[]] ${Category}, [System.String[]] ${Component}, [System.String[]] ${Functionality}, [System.String[]] ${Role}, [Parameter(ParameterSetName='DetailedView')] [Switch] ${Detailed}, [Parameter(ParameterSetName='AllUsersView')] [Switch] ${Full}, [Parameter(ParameterSetName='Examples')] [Switch] ${Examples}, [Parameter(ParameterSetName='Parameters')] [System.String] ${Parameter}, [Switch] ${Online} ) begin { try { $OnlineBaseHelpUrl = 'http://go.microsoft.com/fwlink/?LinkID=' $about = New-Object PSObject -Property @{ 'about_Aliases' = 113207 'about_Arithmetic_Operators' = 113208 'about_Arrays' = 113209 'about_Assignment_Operators' = 113210 'about_Automatic_Variables' = 113212 'about_Break' = 113213 'about_Command_Precedence' = 113214 'about_Command_Syntax' = 113215 'about_Comment_Based_Help' = 144309 'about_CommonParameters' = 113216 'about_Comparison_Operators' = 113217 'about_Continue' = 113218 'about_Core_Commands' = 113219 'about_Data_Sections' = 113220 'about_Debuggers' = 113221 'about_Do' = 135169 'about_Environment_Variables' = 113222 'about_Escape_Characters' = 113223 'about_EventLogs' = 113224 'about_Execution_Policies' = 135170 'about_For' = 113228 'about_Foreach' = 113229 'about_Format.ps1xml' = 113230 'about_Functions' = 113231 'about_Functions_Advanced' = 144511 'about_Functions_Advanced_Methods' = 135172 'about_Functions_Advanced_Parameters' = 135173 'about_Functions_CmdletBindingAttribute' = 135174 'about_Hash_Tables' = 135175 'about_History' = 113233 'about_If' = 113234 'about_Job_Details' = 135176 'about_jobs' = 113251 'about_Join' = 113235 'about_Language_Keywords' = 136588 'about_Line_Editing' = 113236 'about_Locations' = 113237 'about_Logical_Operators' = 113238 'about_Methods' = 113239 'about_Modules' = 144311 'about_Objects' = 113241 'about_Operators' = 113242 'about_Parameters' = 113243 'about_Parsing' = 113244 'about_Path_Syntax' = 113245 'about_Pipelines' = 113246 'about_Preference_Variables' = 113248 'about_Profiles' = 113729 'about_Prompts' = 135179 'about_Properties' = 113249 'about_Providers' = 113250 'about_PSSession_Details' = 135180 'about_PSSessions' = 135181 'about_PSsnapins' = 113252 'about_Quoting_Rules' = 113253 'about_Redirection' = 113254 'about_Ref' = 113255 'about_Regular_Expressions' = 113256 'about_Remote' = 135182 'about_Remote_FAQ' = 135183 'about_Remote_Jobs' = 135184 'about_Remote_Output' = 135185 'about_Remote_Requirements' = 135187 'about_Remote_Troubleshooting' = 135188 'about_Requires' = 135190 'about_Reserved_Words' = 113258 'about_Return' = 136587 'about_Scopes' = 113260 'about_Script_Blocks' = 113261 'about_Script_Internationalization' = 113262 'about_Scripts' = 144310 'about_Session_Configurations' = 145152 'about_Signing' = 113268 'about_Special_Characters' = 113269 'about_Split' = 113270 'about_Switch' = 113271 'about_Throw' = 145153 'about_Transactions' = 135192 'about_Trap' = 136586 'about_Try_Catch_Finally' = 113444 'about_Type_Operators' = 113273 'about_Types.ps1xml' = 113274 'about_Variables' = 157591 'about_While' = 113275 'about_Wildcards' = 113276 'about_Windows_Powershell_2.0' = 113247 'about_Windows_PowerShell_ISE' = 135178 'about_WMI_Cmdlets' = 145766 'about_WS-Management_Cmdlets' = 145774 } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Help', [System.Management.Automation.CommandTypes]::Cmdlet) if($Name -like 'about_*' -AND $about."$name" -AND $Online) { Start-Process ("$OnlineBaseHelpUrl" + $about."$name") continue } $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } }
PowerShellCorpus/PoshCode/Get-ParameterAlias.ps1
Get-ParameterAlias.ps1
##############################################################################\n##\n## Get-ParameterAlias\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\nLooks in the session history, and returns any aliases that apply to\nparameters of commands that were used.\n\n.EXAMPLE\n\nPS >dir -ErrorAction SilentlyContinue\nPS >Get-ParameterAlias\nAn alias for the 'ErrorAction' parameter of 'dir' is ea\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Get the last item from their session history\n$history = Get-History -Count 1\nif(-not $history)\n{\n return\n}\n\n## And extract the actual command line they typed\n$lastCommand = $history.CommandLine\n\n## Use the Tokenizer API to determine which portions represent\n## commands and parameters to those commands\n$tokens = [System.Management.Automation.PsParser]::Tokenize(\n $lastCommand, [ref] $null)\n$currentCommand = $null\n\n## Now go through each resulting token\nforeach($token in $tokens)\n{\n ## If we've found a new command, store that.\n if($token.Type -eq "Command")\n {\n $currentCommand = $token.Content\n }\n\n ## If we've found a command parameter, start looking for aliases\n if(($token.Type -eq "CommandParameter") -and ($currentCommand))\n {\n ## Remove the leading "-" from the parameter\n $currentParameter = $token.Content.TrimStart("-")\n\n ## Determine all of the parameters for the current command.\n (Get-Command $currentCommand).Parameters.GetEnumerator() |\n\n ## For parameters that start with the current parameter name,\n Where-Object { $_.Key -like "$currentParameter*" } |\n\n ## return all of the aliases that apply. We use "starts with"\n ## because the user might have typed a shortened form of\n ## the parameter name.\n Foreach-Object {\n $_.Value.Aliases | Foreach-Object {\n "Suggestion: An alias for the '$currentParameter' " +\n "parameter of '$currentCommand' is '$_'"\n }\n }\n }\n}
PowerShellCorpus/PoshCode/Get-ADGroupMembers.ps1
Get-ADGroupMembers.ps1
Function Get-ADGroupMembers { <# .SYNOPSIS Return a collection of users in an ActiveDirectory group. .DESCRIPTION This function returns an object that contains all the properties of a user object. This function works for small groups as well as groups in excess of 1000. .PARAMETER UserGroup The name of the group to get membership from. .PARAMETER UserDomain The LDAP URL of the domain that the group resides in. .EXAMPLE Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn name distinguishedName cn ---- ----------------- -- {Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts} {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple} ... Description ----------- This example shows passing in a group name, but leaving the default domain name in place. .NOTES The context under which this script is run must have rights to pull infromation from ActiveDirectory. .LINK http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers #> Param ( $UserGroup = "Domain Users", $UserDomain = ([ADSI]"LDAP://DC=company,DC=com") ) Begin { $DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path) $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher $LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))" $DirectorySearcher.SearchRoot = $DirectoryEntry $DirectorySearcher.PageSize = 1000 $DirectorySearcher.Filter = $LDAPFilter $DirectorySearcher.SearchScope = "Subtree" $SearchResult = $DirectorySearcher.FindAll() $UserAccounts = @() } Process { foreach ($Item in $SearchResult) { $Group = $Item.GetDirectoryEntry() $Members = $Group.member If ($Members -ne $Null) { foreach ($User in $Members) { $UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)") If ($UserObject.objectCategory.Value.Contains("Group")) { } Else { $ThisUser = New-Object -TypeName PSObject -Property @{ cn = $UserObject.cn distinguishedName = $UserObject.distinguishedName name = $UserObject.name nTSecurityDescriptor = $UserObject.nTSecurityDescriptor objectCategory = $UserObject.objectCategory objectClass = $UserObject.objectClass objectGUID = $UserObject.objectGUID objectSID = $UserObject.objectSID showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly } } $UserAccounts += $ThisUser } } } } End { Return $UserAccounts } }
PowerShellCorpus/PoshCode/POC csharp expressions_1.ps1
POC csharp expressions_1.ps1
function run-csharpexpression([string] $expression ) { $local:name = [system.guid]::NewGuid().tostring().replace('-','_').insert(0,"csharpexpr") $local:template = @" using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace ShellTools.DynamicCSharpExpression.N[[COUNTER]] { public class [[CLASSNAME]] { public static object RunExpression() { return [[EXPRESSION]]; } } } "@ $global:ccounter = [int]$ccounter + 1 $local:source = $local:template.replace("[[CLASSNAME]]",$local:name).replace("[[EXPRESSION]]",$expression).replace("[[COUNTER]]", $ccounter) add-Type $local:source -Language CsharpVersion3 | out-Null invoke-Expression $('[ShellTools.DynamicCsharpExpression.' + $local:name + ']::RunExpression()' ) } set-alias c run-csharpexpression c DateTime.Now c "new{a=1,b=2,c=3}" c 'from x in Directory.GetFiles(@"c:\\downloads") where x.Contains("win") select x'
PowerShellCorpus/PoshCode/Add SSL Cert to IIS.ps1
Add SSL Cert to IIS.ps1
function Add-SSLCertificate{ param([string]$pfxPath,[string]$pfxPassword,[string]$hostHeader,[string]$siteName) $certMgr = New-Object -ComObject IIS.CertObj -ErrorAction SilentlyContinue $certMgr.ImportToCertStore($pfxPath,$pfxPassword,$true,$true) Import-Module WebAdministration; New-WebBinding -Name $siteName -Port 443 -Protocol https -HostHeader $hostHeader }
PowerShellCorpus/PoshCode/DriveUtilization.ps1
DriveUtilization.ps1
Function Get-Utilization { Param([string]$computername=$env:computername, [string]$ID="C:" ) #suppress errors messages $errorActionPreference="silentlycontinue" $drive=Get-WmiObject Win32_Logicaldisk -filter "DeviceID='$ID'" ` -computername $computername -errorAction "silentlycontinue" if ($drive.size) { #divide size and freespace by 1MB because they are UInt64 #and I can't do anything with them in there native type $size=$drive.size/1MB $free=$drive.freespace/1MB $utilization=($size-$free)/$size write $utilization } else { #there as an error so return a value that can't be mistaken #for drive utilization write -1 } } #Sample usage $computer="PUCK" $drive="C:" $u=Get-Utilization $computer $drive #format $u as a percentage to 2 decimal points $percent="{0:P2}" -f $u if ($u -eq -1) { $msg="WARNING: Failed to get drive {0} on {1}" -f $drive,$computer $color="RED" } elseif ($u -ge .75) { $msg="WARNING: Drive {0} on {1} is at {2} utilization." -f $drive,$computer,$percent $color="RED" } else { $msg="WARNING: Drive {0} on {1} is at {2} utilization." -f $drive,$computer,$percent $color="GREEN" } Write-Host $msg -foregroundcolor $color
PowerShellCorpus/PoshCode/test_2.ps1
test_2.ps1
[CmdletBinding()] param() "This file is in the $PSScriptRoot folder." # SIG # Begin signature block # MIIPGwYJKoZIhvcNAQcCoIIPDDCCDwgCAQExCzAJBgUrDgMCGgUAM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A # FBVReRp8DFn52s3YxDoTmsl4LX9NMA0GCSqGSIb3DQEBBQUAA4IBAQAeavNt9I6p # Iv5wCGUuoV2rMzDdbHj6S+qtxY3sEHpqxViXOWuS85HiDKcoHNFddo6LB3wTb63E # NkOzwbwxWc8YONijO87/ymdYv+DxrGE+ojsevAJbQaxEa/Um8+1eqGX2ymWmP8r1 # d+ulhipYKVb4vhYQQOnS/FcsY2E3ZiU5IC4HA6A2AyWUvXzrftOjwsV2FnUwkrn/ # dkE1IWjRDl5cjsMDYOaAQPzAXaJUbm6SZ6eBEoeioyvbt03/5NXH5QXm1fGu/M1m # GCHzPkfJ5ZVCYSydJoCyD6g9DsmneN9udIwsRvZy6TxkayhVxEtkM8t4VBM48NVx # BtQ+DQo1DuCzMYIBkjCCAY4CAQEwcjBjMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQ # R2xvYmFsU2lnbiBudi1zYTEWMBQGA1UECxMNT2JqZWN0U2lnbiBDQTEhMB8GA1UE # AxMYR2xvYmFsU2lnbiBPYmplY3RTaWduIENBAgsBAAAAAAEeRkCdNjAJBgUrDgMC # GgUAoHgwGAYKKwYBBAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYK # KwYBBAGCNwIBBDAcBgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG # 9w0BCQQxFgQUoCdkwMl0ES8CZsg17ivyqxTyq3AwDQYJKoZIhvcNAQEBBQAEgYDD # fnDc8c/yFATC3FIr+g5NtOSXGZt8VNpRxdg6dQQlPnWxqZKs4mxzZpwwP1Q/dcEA # 5A2arDbXk+gT4FTtq0hbWF1QxzCC9ThiMyE7pkcge8/v/5eHlGetUij08qyrYne+ # KQ0yFUr4uCM+FDZzLX7L6bfuDpF2mYa8+eGpwjm19w== # SIG # End signature block
PowerShellCorpus/PoshCode/USB Script backup_2.ps1
USB Script backup_2.ps1
<# .SYNOPSIS Backup-ToUSB.ps1 (Version 2.2, 9 Jan 2012) .DESCRIPTION This script will backup recently changed *.ps1,*.psm1,*.psd1 files from any selected folder (default is $pwd) to any number of inserted USB devices, on which an archive folder 'PSarchive' will be created if it does not already exist. As a USB hard disk is a Type 3 device (similar to the system disk), use the -Unit D switch (drive letter 'D' for example) to distinguish such a unit and add it to the list of selected devices. .EXAMPLE Invoke-Expression ".\\Backup-ToUsb.ps1 -Unit D $args" Add this line in 'function Backup' in $profile and it will add the USB Hard Disk 'D' as the standard backup device. .EXAMPLE .\\Backup-ToUSB.ps1 -type ps1 -v Select *.ps1 files to be archived. 'Verbose' will display the name of each file processed. Using the '-Debug' switch shows the time difference that has tagged any file for archive. .NOTES The author may be contacted via www.SeaStarDevelopment.Bravehost.com #> param ([String]$types = 'ps1', [String]$folder = $pwd, [String]$unit = $null, [Switch]$debug, [Switch]$verbose) if ($verbose) { $verbosePreference = 'Continue' } if ($debug) { $debugPreference = 'Continue' } $drive = '-<BLANK>-' if ($types -notmatch '^ps1|psd1|psm1|ps\\*$') { #Adjust to suit. Write-Warning "Invalid filetype ($types): ps1, psm1, psd1 only." exit 1 } if (!(Test-path $folder -pathType Container )) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$folder is not a directory - resubmit." exit 3 } $filter = 'DriveType = 2' if ($unit -match '^[d-z]$') { #Allow any single letter drive unit here. $filter = "DriveType = 2 OR (DriveType = 3 AND DeviceID = '" + "$unit" + ":')" } function copyFile ([string]$value) { Copy-Item -Path $value -Destination $newFolder -Force Write-Verbose "--> Archiving file: $value" $SCRIPT:files++ } Get-WMIObject Win32_LogicalDisk -filter $filter | Select-Object VolumeName, DriveType, FreeSpace, DeviceID | Where-Object {$_.VolumeName -ne $null} | foreach { $vol = $_.VolumeName $drive = $_.DeviceID + '\\' $type = $_.DriveType [int]$free = $_.FreeSpace / 1MB Write-Verbose "Scanning USB devices - Drive = [$drive] Name = $vol, Free = $free Mb" if (!(Test-Path $drive)) { Write-Warning "Error on drive $drive - restart." [System.Media.SystemSounds]::Hand.Play() exit 4 } [int]$SCRIPT:files = 0 #Reset counter for each new drive. $newFolder = $drive + "PSarchive" #Check if folder exists. if (!(Test-Path $newFolder)) { New-Item -path ($drive) -name PSarchive -type directory | Out-Null } (Get-ChildItem $folder -filter "*.$types") | foreach { $checkFile = Join-Path ($drive + 'PSArchive') $_ if (Test-path $checkFile) { $lwtHdd = $_.LastWriteTime #HDD time last written. $lwtUsb = (Get-Item $checkFile).LastWriteTime if ($lwtHdd -gt $lwtUsb) { Write-Debug "(HDD) $lwtHdd (USB) $LwtUsb $_" copyFile $_ } } else { #New file, so archive it anyway. Write-Debug "(HDD) $($_.LastWriteTime) (USB Archiving new file) $_" copyFile $_ } } $print = "Backup to USB drive [{0}] (Volume = {2}) completed; {1} files copied." -f $drive, $SCRIPT:files, $vol Write-Host "--> $print" } if ($drive -eq '-<BLANK>-') { [System.Media.SystemSounds]::Asterisk.Play() Write-Warning "No USB drive detected - Insert a device and resubmit." }
PowerShellCorpus/PoshCode/Receive-Stream_1.ps1
Receive-Stream_1.ps1
function Receive-Stream { #.Synopsis # Read a stream to the end and close it #.Description # Will read from a byte stream and output a string or a file #.Param reader # The stream to read from #.Param fileName # A file to write to. If this parameter is provided, the function will output to file #.Param encoding # The text encoding, if you want to override the default. param( [System.IO.Stream]$reader, $fileName, $encoding = [System.Text.Encoding]::GetEncoding( $null ) ) if($fileName) { try { $writer = new-object System.IO.FileStream $fileName, ([System.IO.FileMode]::Create) } catch { Write-Error "Failed to create output stream. The error was: '$_'" return $false } } else { [string]$output = "" } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 try { $count = $reader.Read($buffer, 0, $buffer.Length) while ($count -gt 0) { if($fileName) { $writer.Write($buffer, 0, $count) } else { $output += $encoding.GetString($buffer, 0, $count) } $count = $reader.Read($buffer, 0, $buffer.Length) } } catch { Write-Error "Failed to write stream. The error was: '$_'" return $false } $reader.Close() $writer.Close() if(!$fileName) { return $output } else { return $true } }
PowerShellCorpus/PoshCode/ONTAPI Module.ps1
ONTAPI Module.ps1
# Requires Version 2.0 # Requires ManageOntap.Dll # Plenty of room left for documentation # Andy Schneider - http://get-powershell.com # 3/10/2009 $OnTapDll = (resolve-path $PSScriptRoot\\ManageOntap.dll).Path [System.Reflection.Assembly]::LoadFile($onTapDll) function New-NTAPServer { param ( [Parameter( Mandatory=$true, Position=0, ValueFromPipeline = $true)] [string] $filer, [Parameter( Mandatory=$true, Position=1)] [System.Management.Automation.PSCredential] $credential ) $username = $credential.GetNetworkCredential().UserName $password = $credential.GetNetworkCredential().Password $domain = $credential.GetNetworkCredential().Domain if ($domain) {$username = "$domain\\$username"} $NtapServer = New-Object NetApp.Manage.NaServer($filer,1,0) $NtapServer.SetAdminUser($username,$password) $NaElement = New-Object Netapp.Manage.NaElement("system-get-info") [xml]$sysinfo = $NtapServer.InvokeElem($NaElement) $sysinfo.results."system-info" | out-host return $NtapServer } Function Get-NTAPLun { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Path")] [String] $name = "*" ) $NaElement = New-Object Netapp.Manage.NaElement("lun-list-info") [xml]$result = $server.InvokeElem($NaElement) return $result.results.luns."lun-info" | where {$_.path -like $name} } Function Set-NTAPLun { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Path")] [String] $name , [Parameter( Mandatory=$false, Position=2, ValueFromPipeline = $false)] [int64] $size, [Parameter( Mandatory=$false, Position=3)] [Alias("description")] [string] $comment ) if($comment) { $NaElement = New-Object Netapp.Manage.NaElement("lun-set-comment") $NaElement.AddNewChild('path',$name) $NaElement.AddNewChild('comment',$comment) [xml]$result = $server.InvokeElem($NaElement) $result.results.status } if ($size) { $NaElement = New-Object Netapp.Manage.NaElement("lun-resize") $NaElement.AddNewChild('path',$name) $NaElement.AddNewChild('size',$size) [xml]$result = $server.InvokeElem($NaElement) $result.results.status } } Function New-NTAPLun { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Path")] [String] $name , [Parameter( Mandatory=$false, Position=2, ValueFromPipeline = $false)] [int64] $size, [Parameter( Mandatory=$false, Position=3, ValueFromPipeline = $false)] [Alias("description")] [string] $comment ) $NaElement = New-Object Netapp.Manage.NaElement("lun-create-by-size") $NaElement.AddNewChild('path',$name) $NaElement.AddNewChild('size',$size) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status $NaElement = New-Object Netapp.Manage.NaElement("lun-set-comment") $NaElement.AddNewChild('path',$name) $NaElement.AddNewChild('comment',$size) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status } Function Get-NTAPInitiator { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Initiator")] [String] $name = "*" ) $NaElement = New-Object Netapp.Manage.NaElement("iscsi-initiator-list-info") [xml]$result = $Server.InvokeElem($NaElement) return $result.results."iscsi-initiator-list-entries"."iscsi-initiator-list-entry-info" | where {$_."initiator-nodename" -like $name} } Function Get-NTAPVolume { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Path")] [String] $name = "*" ) $NaElement = New-Object Netapp.Manage.NaElement("volume-list-info") [xml]$r = $server.InvokeElem($NaElement) return $r.results.volumes."volume-info" | where {$_.name -like $name} } Function Set-NTAPVolume { param ( [Parameter( Mandatory=$true, Position=0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$true, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [String] $name, [Parameter( Mandatory=$false, Position=2, ValueFromPipelineByPropertyName = $true)] [int64] $size, [Parameter( Mandatory=$false, Position=3)] [ValidateSet("none", "file", "volume")] [String] $spaceReserveType = "none", [Parameter( Mandatory=$true, Position=4, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [String] $newName ) if ($newname) { $NaElement = New-Object Netapp.Manage.NaElement("volume-rename") $NaElement.AddNewChild('volume',$name) $NaElement.AddNewChild('new-volume-name',$newname) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status } if ($size) { $NaElement = New-Object Netapp.Manage.NaElement("volume-size") $NaElement.AddNewChild('volume',$name) $NaElement.AddNewChild('new-size',$size) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status } if ($spaceReserveType) { $NaElement = New-Object Netapp.Manage.NaElement("volume-set-option") $NaElement.AddNewChild('option-name','guarantee') $NaElement.AddNewChild('option-value',$spaceReserveType) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status } } Function New-NTAPVolume { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [String] $name = "*", [Parameter( Mandatory=$false, Position=2, ValueFromPipelineByPropertyName = $true)] [int64] $size, [Parameter( Mandatory=$false, Position=3, ValueFromPipeline = $true)] [Alias("Path")] [String] $containingAggregate, [Parameter( Mandatory=$false, Position=4)] [ValidateSet("none", "file", "volume")] [String] $spaceReserveType = "none" ) $NaElement = New-Object Netapp.Manage.NaElement("volume-create") $NaElement.AddNewChild('volume',$name) $NaElement.AddNewChild('size',$size) $NaElement.AddNewChild('containing-aggr-name',$containingaggregate) $NaElement.AddNewChild('space-reserve',$spaceReserveType) [xml]$result = $Server.InvokeElem($NaElement) $result.results.status } Function Get-NTAPAggregate { param ( [Parameter( Mandatory = $true, Position = 0)] [NetApp.Manage.NaServer] $server, [Parameter( Mandatory=$false, Position=1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias("Path")] [String] $name = "*" ) $NaElement = New-Object Netapp.Manage.NaElement("aggr-list-info") [xml]$r = $server.InvokeElem($NaElement) return $r.results.aggregates."aggr-info" | where {$_.name -like $name} }
PowerShellCorpus/PoshCode/New-LinkedClone.ps1
New-LinkedClone.ps1
#Requires -version 2 # TITLE: New-LinkedClone.ps1 # AUTHOR: Hal Rottenberg # Adapted from a technique published originally by Keshav Attrey http://www.vmdev.info/?p=40 # Also see William Lam's Perl script: http://engineering.ucsb.edu/~duonglt/vmware/vGhettoLinkedClone.html # And Leo's manual version for ESX 3.5: http://blog.core-it.com.au/?p=333 param ( [parameter(Mandatory=$true)][string]$SourceName, [parameter(Mandatory=$true)][string]$CloneName ) $vm = Get-VM $SourceName # Create new snapshot for clone $cloneSnap = $vm | New-Snapshot -Name "Clone Snapshot" # Get managed object view $vmView = $vm | Get-View # Get folder managed object reference $cloneFolder = $vmView.parent # Build clone specification $cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec $cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot # Make linked disk specification $cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec $cloneSpec.Location.DiskMoveType = [Vmware.Vim.VirtualMachineRelocateDiskMoveOptions]::createNewChildDiskBacking # Create clone $vmView.CloneVM( $cloneFolder, $cloneName, $cloneSpec ) # Write newly created VM to stdout as confirmation Get-VM $cloneName
PowerShellCorpus/PoshCode/Console Function Run_1.ps1
Console Function Run_1.ps1
function Run ([String]$scriptName = '-BLANK-') { <# The next function records any running scripts started in the console session (from $pwd) in the Scripts Event Log. It should be placed in the Console $profile. Scripts should be started by typing 'Run example' to capture example.ps1, for example. The default logfile is that used by the Windows Script Monitor Service, available from www.SeaStarDevelopment.Bravehost.com #> if ($host.Name -ne 'ConsoleHost') { return } $logfile = "$env:programfiles\\Sea Star Development\\" + "Script Monitor Service\\ScriptMon.txt" $parms = $myInvocation.Line -replace "run(\\s+)$scriptName(\\s*)" $script = $scriptName -replace "\\.ps1\\b" #Replace from word end only. $script = $script + ".ps1" if (Test-Path $pwd\\$script) { if(!(Test-Path Variable:\\Session.Script.Job)) { Set-Variable Session.Script.Job -value 1 -scope global ` -description "Script counter" } $Job = Get-Variable -name Session.Script.Job $number = $job.Value.ToString().PadLeft(4,'0') $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$startTime [$script] start. --> $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PS$number) started." Invoke-Expression -command "$pwd\\$script $parms" $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$endTime [$script] ended. --> $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PS$number) ended." $job.Value += 1 } else { Write-Error "$pwd\\$script does not exist." } }
PowerShellCorpus/PoshCode/Get-Netstat _1.2.ps1
Get-Netstat _1.2.ps1
Function Get-Netstat { $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+)' [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName, Services $Services = @{} get-wmiobject win32_service | ForEach-Object { [String]$SvcPID = $_.processid If ($Services.ContainsKey($SvcPID)) { $Services.Item($SvcPID) = $Services.Item($SvcPID) += $($_.Name) } Else { $Services.Add($SvcPID,@($_.Name)) } } foreach ($net in $netstat) { 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 -ea 0).ProcessName $process.Services = $Services.Item($matches.PID) } $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 -ea 0).ProcessName $process.Services = $Services.Item($matches.PID) } } $process } }
PowerShellCorpus/PoshCode/Kill Outlook + CopyPST.ps1
Kill Outlook + CopyPST.ps1
$rep_du_user = $env:userprofile $repertoire_pst = ($rep_du_user+"\\AppData\\Local\\Microsoft\\Outlook") $repertoire_sauvegarde = "directory" #Kill de outlook Get-Process | Where { $_.Name -Eq "outlook" } | Kill #wait and see :) sleep 10 #copy des pst xcopy $repertoire_pst $repertoire_sauvegarde /D /E /C /R /H /I /K /Y /G
PowerShellCorpus/PoshCode/Out-Balloon_1.ps1
Out-Balloon_1.ps1
<# .Synopsis Makes a baloon tip in the notification area .Description With just a few arguments, it is easy to make some text appear in a little balloon. You can specify an icon file (*.ico) with the -icon argument, if you don't then the first icon of the host is used. out-balloon accepts pipeline input, strings only please. It blocks for the duration of the balloon display, 3 seconds by default. Simple fixes for this are welcome. timeout should be an integer value. INSTALLATION: um, save this text in a file named out-balloon.ps1 in your path .Example out-balloon "hey, your job is done." -icon "C:\\Program Files\\Microsoft Office\\Office12\\MYSL.ICO" "job done." | out-balloon #> param( [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)] [Alias('output')] [string]$text, [string]$icon, [int32]$timeout = 3 ) begin { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") $not = new-object System.Windows.Forms.NotifyIcon if ($icon -eq $null) { if ($win32extraciconex -eq $null) { $script:ExtractIconEx = Add-Type ¢memberDefinition @" [DllImport("Shell32", CharSet=CharSet.Auto)] private static extern int ExtractIconEx (string lpszFile, int nIconIndex, IntPtr[] phIconLarge,IntPtr[] phIconSmall,int nIcons); [DllImport("user32.dll", EntryPoint="DestroyIcon", SetLastError=true)] private static extern int DestroyIcon(IntPtr hIcon); public static System.Drawing.Icon ExtractIconFromExe(string file, bool large) { int readIconCount = 0; IntPtr[] hDummy = new IntPtr[1] {IntPtr.Zero}; IntPtr[] hIconEx = new IntPtr[1] {IntPtr.Zero}; try { if(large) readIconCount = ExtractIconEx(file,0, hIconEx, hDummy, 1); else readIconCount = ExtractIconEx(file,0, hDummy, hIconEx, 1); if(readIconCount > 0 && hIconEx[0] != IntPtr.Zero) { System.Drawing.Icon extractedIcon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(hIconEx[0]).Clone(); return extractedIcon; } else // NO ICONS READ return null; } catch(Exception ex) { throw new ApplicationException("Failed extracting icon", ex); } finally { foreach(IntPtr ptr in hIconEx) if(ptr != IntPtr.Zero) DestroyIcon(ptr); foreach(IntPtr ptr in hDummy) if(ptr != IntPtr.Zero) DestroyIcon(ptr); } } "@ -name ōWin32ExtractIconExö -namespace win32api ¢passThru -ReferencedAssemblies "System.Drawing" } $not.Icon = $extractIconEx::ExtractIconFromExe((get-process -Id $pid).mainmodule.filename, $true) } else { $not.Icon = new-object System.Drawing.Icon($icon) } $not.visible = $true } process { $not.BalloonTipText = $text $not.ShowBalloonTip($timeout) sleep $timeout } end { $not.dispose() }
PowerShellCorpus/PoshCode/Join-Collections_1.ps1
Join-Collections_1.ps1
#requires -version 2.0 ## Version 1.0 First post http://poshcode.org/1459 ## Version 1.1 Fixed column uniqueness bug #.Note # Depends on ConvertFrom-HashTable http://poshcode.org/1118 #.Synopsis # Performs a inner join on two collections of objects based on a common key column. #.Description # Takes two sets of objects where there are multiple "rows" and where each set has a shared column where the values match, and generates new objects with all the values from each. #.Parameter GroupOnColumn # The name of the property to merge on. Items with the same value in this column will be combined. #.Parameter FirstCollection # The first set of data #.Parameter FirstJoinColumn # The name of the key id column in the first set #.Parameter SecondCollection # The second set of data #.Parameter SecondJoinColumn # The name of the matching key id column in the second set # OPTIONAL. Defaults to the same as FirstJoinColum #.Example # Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value # # Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects. # #.Example # $FirstCollection = @" # FirstName, LastName, MailingAddress, EmployeeID # John, Doe, 123 First Ave, J8329029 # Susan Q., Public, 3025 South Street, K4367143 #"@.Split("`n") | ConvertFrom-Csv # # $SecondCollection = @" # ID, Week, HrsWorked, PayRate, EmployeeID # 12276, 12, 40, 55, J8329029 # 12277, 13, 40, 55, J8329029 # 12278, 14, 42, 55, J8329029 # 12279, 12, 35, 40, K4367143 # 12280, 13, 32, 40, K4367143 # 12281, 14, 48, 40, K4367143 #"@.Split("`n") | ConvertFrom-Csv # # Join-Collections $FirstCollection EmployeeID $SecondCollection | ft -auto # #.Notes # Author: Joel Bennett # function Join-Collections { PARAM( $FirstCollection , [string]$FirstJoinColumn , $SecondCollection , [string]$SecondJoinColumn=$FirstJoinColumn ) PROCESS { $properties1 = $FirstCollection[0] | gm -type Properties | Select -Expand Name $properties2 = $SecondCollection[0] | gm -type Properties | Where { $Properties1 -notcontains $_.Name } | Select -Expand Name foreach($first in $FirstCollection) { foreach($second in $SecondCollection | Where{ $_."$SecondJoinColumn" -eq $first."$FirstJoinColumn" } ) { [string]$join = $first | gm -type Properties | select -expand Definition | %{($_ -split " ",2)[1]} $join += "`n" $join += $second | gm -Name $Properties2 -type Properties | select -expand Definition | %{($_ -split " ",2)[1]} ConvertFrom-StringData $join | ConvertFrom-Hashtable } } } #}
PowerShellCorpus/PoshCode/Set-UserCannotChangePass_1.ps1
Set-UserCannotChangePass_1.ps1
#########1#########2#########3#########4#########5#########6#########7#########8#########9#########1 #########0#########0#########0#########0#########0#########0#########0#########0#########0#########0 # # Author: Erik McCarty # # Description: Set the "user Cannot Change Password" property on an active # directory user object # # Remarks: There is poor documentation on the internet that would lead you # to believe the $user.userAccountControl property value bit 0x000040 can # be set to turn on the "user Cannot Change Password" account property. # However you cannot assign this permission by directly modifying the # userAccountControl attribute. # # History: # 20080107 EWM Initial Creation # # reference: # http://msdn2.microsoft.com/en-us/library/aa746398.aspx # http://mow001.blogspot.com/2006/08/powershell-and-active-directory-part-8.html # http://ewmccarty.spaces.live.com/blog/cns!CE2AE9EFF99E6598!132.entry # Example: # # Set-UserCannotChangePassword "BMcClellan" # #########1#########2#########3#########4#########5#########6#########7#########8#########9#########1 #########0#########0#########0#########0#########0#########0#########0#########0#########0#########0 # function set-UserCannotChangePassword( [string] $sAMAccountName ){ # set variables $everyOne = [System.Security.Principal.SecurityIdentifier]'S-1-1-0' $self = [System.Security.Principal.SecurityIdentifier]'S-1-5-10' $SelfDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ( $self,'ExtendedRight','Deny','ab721a53-1e2f-11d0-9819-00aa0040529b') $SelfAllow = new-object System.DirectoryServices.ActiveDirectoryAccessRule ( $self,'ExtendedRight','Allow','ab721a53-1e2f-11d0-9819-00aa0040529b') $EveryoneDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ( $Everyone,'ExtendedRight','Deny','ab721a53-1e2f-11d0-9819-00aa0040529b') $EveryOneAllow = new-object System.DirectoryServices.ActiveDirectoryAccessRule ( $Everyone,'ExtendedRight','Allow','ab721a53-1e2f-11d0-9819-00aa0040529b') # find the user object in the default domain $searcher = New-Object DirectoryServices.DirectorySearcher $searcher.filter = "(&(samaccountname=$sAMAccountName))" $results = $searcher.findone() $user = $results.getdirectoryentry() # set "user cannot change password" $user.psbase.get_ObjectSecurity().AddAccessRule($selfDeny) $user.psbase.get_ObjectSecurity().AddAccessRule($EveryoneDeny) $user.psbase.CommitChanges() }