full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Autoload (beta 5).ps1
Autoload (beta 5).ps1
#Requires -Version 2.0 ## Version History ## beta 5 - 2010.05.10 ## Fixed non-pipeline use using $MyInvocation.ExpectingInput ## beta 4 - 2010.05.10 ## I made a few tweaks and bug fixes while testing it's use with PowerBoots. ## beta 3 - 2010.05.10 ## fix for signed scripts (strip signature) ## beta 2 - 2010.05.09 ## implement module support ## beta 1 - 2010.04.14 ## Initial Release ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time. ## To use: ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments ## For example: <# function Skip-Object { param( [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $InputObject ) begin { if($Last) { $Queue = new-object System.Collections.Queue $Last } $e = $every; $UpTo++; $u = 0 } process { $InputObject | where { --$First -lt 0 } | foreach { if($Last) { $Queue.EnQueue($_) if($Queue.Count -gt $Last) { $Queue.DeQueue() } } else { $_ } } | foreach { if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo } } | foreach { if($every -and (--$e -le 0)) { $e = $every } else { $_ } } } } #> ## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1) ## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile) ## 4) Dot-source this file, or include it as part of your profile ## 5) Add one line to your profile (or on the commandline): <# autoload Skip-Object #> ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it. ## Now, you can just use the function: ## 1..10 | Skip-Object -first 2 -upto 2 function Autoloaded { [CmdletBinding()]Param() DYNAMICPARAM { $CommandName = $MyInvocation.InvocationName if(!$Script:AutoloadHash[$CommandName]) { do { $Alias = $CommandName $CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition } while(!$Script:AutoloadHash[$Alias] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue)) $CommandName = $Alias } if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" } Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])" $ScriptName, $ModuleName = $Script:AutoloadHash[$CommandName] if(!$ScriptName){ $ScriptName = $CommandName } if($ModuleName) { $Module = Get-Module $ModuleName } else { $Module = $null } ## Determine the command name based on the alias used to invoke us ## Store the parameter set for use in the function later... $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary # $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript #$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript ) $externalScript = Get-Command $ScriptName -Type ExternalScript Write-Verbose "Processing Script: $($externalScript |Out-String)" $parserrors = $null $prev = $null $script = $externalScript.ScriptContents [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]::Reverse($tokens) ForEach($token in $tokens) { if($prev -and $token.Content -eq "# SIG # Begin signature block") { $script = $script.SubString(0, $token.Start ) } if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $CommandName ) { $script = $script.Insert( $prev.Start, "global:" ) } $prev = $token } if($Module) { $script = Invoke-Expression "{ $Script }" Write-Verbose "What the $($Module)" &$Module $Script | Out-Null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Module Function: $($command |Out-String)" } else { Invoke-Expression $script | out-null $command = Get-Command $CommandName -Type Function Write-Verbose "Loaded Local Function: $($command |Out-String)" } if(!$command) { throw "Something went wrong autoloading the $($CommandName) function. Function definition doesn't exist in script: $($externalScript.Path)" } Remove-Item Alias::$($CommandName) Write-Verbose "Defined the function and removed the alias... $($command | Out-string)" foreach( $pkv in $command.Parameters.GetEnumerator() ){ $parameter = $pkv.Value if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue } $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes) $paramdictionary.Add($pkv.Key, $param) } return $paramdictionary }#DynamicParam begin { Write-Verbose "Autoloaded Begin: $CommandName" Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta $global:command = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::Function ) $scriptCmd = {& $command @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($myInvocation.ExpectingInput) } process { Write-Verbose "Autoloaded Process: $CommandName ($_)" try { if($_) { $steppablePipeline.Process($_) } else { $steppablePipeline.Process() } } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } Write-Verbose "Autoloaded End: $CommandName" } }#AutoLoaded function autoload { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Name , [Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)] [Alias("BaseName")] $Alias = $Name , [Parameter(Position=2,Mandatory=$false)] [String]$Module , [Parameter(Mandatory=$false)] [String]$Scope = '2' ) begin { $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } } process { for($i=0;$i -lt $Name.Count;$i++){ if($Alias -is [Scriptblock]) { $a = $Name[$i] | &$Alias } elseif($Alias -is [Array]) { $a = $Alias[$i] } else { $a = $Alias } Write-Verbose "Set-Alias $Module\\$a Autoloaded -Scope $Scope" Set-Alias $a Autoloaded -Scope $Scope $Script:AutoloadHash[$a] = $Name[$i],$Module Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])" } } } $Script:AutoloadHash = @{}
PowerShellCorpus/PoshCode/Patch-VMHost.ps1
Patch-VMHost.ps1
Add-PSSnapin "VMware.VimAutomation.Core" Add-PSSnapIn "VMware.VumAutomation" # Connect to vCenter $VC = Connect-VIServer (Read-Host "Enter vCenter server") $vumConfig = Get-VumConfig $EsxHost = Get-Inventory -Name (Read-Host "Enter ESX Host") $CriticalHost = Get-Baseline -Name "Critical Host Updates" $NonCriticalHost = Get-Baseline -Name "Non-critical Host Updates" # Enter Maintenance mode Set-VMHost $EsxHost -State Maintenance # Attach baseline Attach-Baseline -Entity $EsxHost -Baseline $CriticalHost, $NonCriticalHost # Check Compliance $ScanTask = Scan-Inventory $EsxHost -RunAsync Wait-Task -Task $ScanTask Get-Compliance -Entity $EsxHost # Remediate the ESX Host $RemediateTask = Remediate-Inventory -Entity $EsxHost -Baseline $CriticalHost, $NonCriticalHost -HostFailureAction $vumConfig.HostFailureAction -Confirm:$false Wait-Task -Task $RemediateTask # Detach Baseline Detach-Baseline -Baseline $CriticalHost, $NonCriticalHost -Entity $EsxHost # Exit Mantenance mode Set-VMHost $EsxHost -State Connected # Disconnect from vCenter Disconnect-VIServer -Confirm:$False
PowerShellCorpus/PoshCode/PowerCLI New-Farm.ps1
PowerCLI New-Farm.ps1
# Connect to vCenter Connect-VIServer vcenter.domain.com # root folder is used for datacenter location $rootfolder = Get-Folder -NoRecursion # datacenter $dc = New-Datacenter -Name "vFarm" -Location $rootfolder # Build hostname strings for ESX servers in format sssrrrnn (site/role/number) $esxname = 1..10 | ForEach-Object { "atlesx{0:00}" -f $_ } # prompt for ESX server credentials $esxcred = Get-Credential # Add ESX servers to vCenter $vmhost = $esxname | ForEach-Object { Add-VMHost -Name $_ -Credential $esxcred } # Customer codenames, same number as there are hosts $custname = "TGT", "WAL", "THD", "LOW", "KRO", "CVS", "TOY", "MAC", "SEA", "OLD" # Create customer resource pools, one per ESX host $rpool = for ( $i = 0; $i -lt $vmhost.length; $i++ ) { # Can set resource settings such as mem or cpu limit here New-ResourcePool -Location $vmhost[$i] -Name $custname[$i] } # Create array of hashtables (think of it like a spreadsheet) # describing role names and number of VMs in each $roleinfo = @( @{ Name = "ProxyServer"; Num = 2 }, @{ Name = "WebServer"; Num = 4 }, @{ Name = "AppServer"; Num = 2 }, @{ Name = "DBServer"; Num = 2 } ) # Create role resource pools and all VMs foreach ( $custpool in $rpool ) { foreach ( $role in $roleinfo ) { # Create role resource pool $rolepool = New-ResourcePool -Name $role["Name"] -Location $custpool # Use number field to determine how many VMs to make and what to name them 1..$role["Num"] | ForEach-Object { # Create VM name, e.g. KRO-WebServer-1 $vmname = $custpool.Name + "-" + $role["Name"] + "-$_" # Create VM based on predefined templates New-VM -Name $vmname -ResourcePool $rolepool -Template $role["Name"] } } }
PowerShellCorpus/PoshCode/986fdfec-754f-49c7-8315-a67f47f16823.ps1
986fdfec-754f-49c7-8315-a67f47f16823.ps1
If ([intptr]::size -eq 4) { $powerShellDir = $powershelldir = "$env:Windir\\Sysnative\\WindowsPowerShell\\V1.0\\" $dir = "& `"$env:ProgramFiles\\Check_MK\\plugins\\Ex2010_MBDB_Info.ps1`"" $bytes = [Text.Encoding]::Unicode.GetBytes($dir) $encodedCommand = [Convert]::ToBase64String($bytes) Invoke-Command -command { & $powershelldir\\powershell.exe -EncodedCommand $encodedCommand } } Else { Write-Host '<<<Ex2010_MBDB_Info>>>' Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 $DBS = Get-MailboxDatabase -Status -Server (hostname) $DBS | % { '{0,-10} {1,-20} {2, -6}' -f $_.name, ($_.Databasesize -replace ',', ''-replace '^.*\\((.*) bytes\\)', '$1'), (Get-MailboxStatistics -Database $_.name|where { $_.DisconnectReason -ne 'SoftDeleted' }).count }; }
PowerShellCorpus/PoshCode/3c9c5d54-adf5-44bb-bf12-ab18d089e443.ps1
3c9c5d54-adf5-44bb-bf12-ab18d089e443.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 $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } filter Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Path # The path to an xml document (on disc or any other content provider). #.Parameter Indent # The indent level (defaults to 2 spaces) #.Example # [xml]$xml = get-content Data.xml # C:\\PS>Format-Xml $xml #.Example # get-content Data.xml | Format-Xml #.Example # Format-Xml C:\\PS\\Data.xml #.Example # ls *.xml | Format-Xml # Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")] [xml]$Xml , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")] [Alias("PsPath")] [string]$Path , [Parameter(Mandatory=$false)] $Indent=2 ) ## Load from file, if necessary if($Path) { [xml]$xml = Get-Content $Path } $StringWriter = New-Object System.IO.StringWriter $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter $xmlWriter.Formatting = "indented" $xmlWriter.Indentation = $Indent $xml.WriteContentTo($XmlWriter) $XmlWriter.Flush() $StringWriter.Flush() Write-Output $StringWriter.ToString() } Set-Alias fxml Format-Xml -EA 0 function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter Xsl # Specifies an Xml StyleSheet to transform with... [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias cvxml Convert-Xml -EA 0 function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace -EA 0 function New-XDocument { #.Synopsis # Creates a new XDocument (the new xml document type) #.Description # This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML # It creates a new XDocument, and takes scritpblock(s) to define it's contents #.Parameter root # The root node name #.Parameter version # Optional: the XML version. Defaults to 1.0 #.Parameter encoding # Optional: the Encoding. Defaults to UTF-8 #.Parameter standalone # Optional: whether to specify standalone in the xml declaration. Defaults to "yes" #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) # #.Example # [string]$xml = New-XDocument rss -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # item { # title {"The First Item"} # link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # description {"Ema Lazarus' Poem"} # pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"} # } # } # } # # C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # C:\\PS>$xml.ToString() # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss version="2.0"> # <channel> # <title>Test RSS Feed</title> # <link>http ://HuddledMasses.org</link> # <description>An RSS Feed generated simply to demonstrate my XML DSL</description> # <item> # <title>The First Item</title> # <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link> # <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid> # <description>Ema Lazarus' Poem</description> # <pubDate>2003-10-31T00:00:00Z</pubDate> # </item> # </channel> # </rss> # # # Description # ----------- # This example shows the creation of a complete RSS feed with a single item in it. # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output. # # #.Example # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc { # title {"Test First Entry"} # link {"http`://HuddledMasses.org"} # updated {(Get-Date -f u) -replace " ","T"} # author { # name {"Joel Bennett"} # uri {"http`://HuddledMasses.org"} # } # id {"http`://huddledmasses.org/" } # # entry { # title {"Test First Entry"} # link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" } # id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" } # updated {(Get-Date 10/31/2003 -f u) -replace " ","T"} # summary {"Ema Lazarus' Poem"} # link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution" # dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" } # category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses" # } # } | % { $_.Declaration.ToString(); $_.ToString() } # # <?xml version="1.0" encoding="UTF-16" standalone="yes"?> # <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom"> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org</link> # <updated>2009-07-29T17:25:49Z</updated> # <author> # <name>Joel Bennett</name> # <uri>http ://HuddledMasses.org</uri> # </author> # <id>http ://huddledmasses.org/</id> # <entry> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link> # <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id> # <updated>2003-10-31T00:00:00Z</updated> # <summary>Ema Lazarus' Poem</summary> # <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" /> # <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights> # <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" /> # </entry> # </feed> # # # Description # ----------- # This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString(). # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.# # Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$root , [Parameter(Mandatory = $false)] [string]$Version = "1.0" , [Parameter(Mandatory = $false)] [string]$Encoding = "UTF-8" , [Parameter(Mandatory = $false)] [string]$Standalone = "yes" , [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 ) #force $duds to be an 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
PowerShellCorpus/PoshCode/Get-Constructor_3.ps1
Get-Constructor_3.ps1
function Get-Constructor { PARAM( [Type]$type, [Switch]$Simple) if($Simple) { $type.GetConstructors() | Select @{ l="$($type.Name) Constructor" e={ "New-Object $($type.FullName) $(($_.GetParameters() | ForEach { "[{0}]`${1}" -f $_.ParameterType.FullName, $_.Name }) -Join ", ")" } } } else { $type.GetConstructors() | Select @{ name = "$($type.Name) Constructors" expression = { $parameters = $( foreach($param in $_.GetParameters()) { Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' } '{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.FullName.TrimEnd('&'), $param.Name } ) "New-Object $($type.FullName) $($parameters -join ', ')" } } } } Set-Alias gctor Get-Constructor
PowerShellCorpus/PoshCode/Send mail to BCC.ps1
Send mail to BCC.ps1
<# .SYNOPSIS Send mail to BCC using PowerShell .DESCRIPTION This script is a re-developed MSDN Sample using PowerShell. It creates an email message then sends it with a BCC. .NOTES File Name : Send-BCCMail.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 CTP3 .LINK Original Sample Posted to http://pshscripts.blogspot.com/2009/01/send-bccmailps1.html MSDN Sample and details at: http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddresscollection.aspx .EXAMPLE PS C:\\foo> .\\Send-BCCMail.ps1 Sending an e-mail message to The PowerShell Doctor and "Thomas Lee" <tfl@reskit.net> #> ### # Start Script ### # Create from, to, bcc and the message strucures $From = New-Object system.net.Mail.MailAddress "tfl@cookham.net", "Thomas Lee" $To = new-object system.net.mail.mailaddress "doctordns@gmail.com", "The PowerShell Doctor" $Bcc = New-Object system.Net.Mail.mailaddress "tfl@reskit.net", "Thomas Lee" $Message = New-Object system.Net.Mail.MailMessage $From, $To # Populate message $Message.Subject = "Using the SmtpClient class and PowerShell." $Message.Body = "Using this feature, you can send an e-mail message from an" $Message.Body += "application very easily. `nEven better, you do it with PowerShell!" # Add BCC $Message.Bcc.Add($bcc); # Create SMTP Client $Server = "localhost" $Client = New-Object System.Net.Mail.SmtpClient $server $Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials "Sending an e-mail message to {0} and {1}" -f $to.DisplayName, $Message.Bcc.ToString() # send the message try { $client.Send($message); } catch { "Exception caught in CreateBccTestMessage(): {0}" -f $Error[0] }
PowerShellCorpus/PoshCode/Get-Application 2.1.ps1
Get-Application 2.1.ps1
function Find-Application { [CmdletBinding()] param( [string]$Name ) begin { [String[]]$Path = (Get-Content Env:Path).Split(";") | ForEach-Object { if($_ -match "%.*?%"){ $expansion = Get-Content ($_ -replace '.*%(.*?)%.*','Env:$1') ($_ -replace "%.*?%", $expansion).ToLower().Trim("\\","/") + "\\" } else { $_.ToLower().Trim("\\","/") + "\\" } } } end { ## First, try Get-Command (which searches the PATH) but suppress command not found error $eap, $ErrorActionPreference = $ErrorActionPreference, "SilentlyContinue" $command = Get-Command $Name -Type Application $ErrorActionPreference = $eap ## Second, try HKLM App Paths (which are used by ShellExecute) if(!$command) { $AppPaths = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths" if(Test-Path $AppPaths\\$Name) { $default = (Get-ItemProperty $AppPaths\\$Name)."(default)" if($default) { $command = Get-Command $default.Trim("`"'") # | Select -First 1 } } if(!$command) { $Name = [IO.Path]::GetFileNameWithoutExtension($Name) if(Test-Path $AppPaths\\$Name) { $default = (Get-ItemProperty $AppPaths\\$Name)."(default)" if($default) { $command = Get-Command $default.Trim("`"'") # | Select -First 1 } } } if(!$command){ if(Test-Path "$AppPaths\\$Name.exe") { $default = (Get-ItemProperty "$AppPaths\\$Name.exe")."(default)" if($default) { $command = Get-Command $default.Trim("`"'") # | Select -First 1 } } } } ## Third, try Windows Search against the start menu as a last resort if(!$command) { $Name = [IO.Path]::GetFileNameWithoutExtension($Name) $query =@" SELECT System.ItemName, System.Link.TargetParsingPath FROM SystemIndex WHERE System.Kind = 'link' AND System.ItemPathDisplay like '%Start Menu%' AND ( System.Link.TargetParsingPath like '%${Name}.exe' OR System.ItemName like '%${Name}%' ) "@ $Connection = New-Object System.Data.OleDb.OleDbConnection "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';" $Adapter = New-Object System.Data.OleDb.OleDbDataAdapter (New-Object System.Data.OleDb.OleDbCommand $Query, $Connection) $DataSet = New-Object System.Data.DataSet $Connection.Open() if($Adapter.Fill($DataSet)) { $command = $DataSet.Tables[0] | ForEach-Object { Get-Command $_["System.Link.TargetParsingPath"] | Add-Member -Type NoteProperty -Name Shortcut -Value $_["System.ItemName"] -Passthru } } $Connection.Close() } ## Now, make sure that we output everything in the right order: ## Get-Command, Keep the Shortcut value if there is one ## Then sort by the position in the PATH and make sure if it's not in there, it comes last ## Finally, sort LONG shortcut names after SHORT ones ... ## .... because we do partial matching on them, so the LONGER one matches less precisely. $( foreach($cmd in $command) { Get-Command $cmd.Path -ErrorAction SilentlyContinue -Type Application | ForEach-Object { Add-Member -InputObject $_ -Type NoteProperty -Name Shortcut -Value $cmd.ShortCut -Passthru } } ) | Sort-Object Definition -Unique | Sort-Object { $index = [array]::IndexOf( $Path, [IO.Path]::GetDirectoryName($_.Path).ToLower().Trim("\\","/") + "\\" ) if($index -lt 0) { $index = 1e5 } else { $index *= 100 } if($_.Shortcut) { $index += $_.Shortcut.Length } $index } } #.Synopsis # Finds an executable by searching the path, using Get-Command, the AppPaths registry key, and Windows Search. #.Example # Get-App Notepad # Finds notepad.exe using Get-Command #.Example # Get-App pbrush # Finds mspaint.exe using the "App Paths" registry key #.Example # &(Get-App WinWord) # Finds, and launches, Word (if it's installed) using the "App Paths" registry key #.Example # Get-App "Windows PowerShell" # Finds PowerShell.exe by searching the Start menu for the link #.Notes ## Revision History (latest first) ## 2.1 - Fix output and sorting so that: ## - We output more than one if there is more than one, ## - But sort them by path and accuracy ## 2.0 - Add Windows Search ## 1.1 - strip quotes from results... ## 1.0 - initial release }
PowerShellCorpus/PoshCode/Exchange07 Mbox Report.ps1
Exchange07 Mbox Report.ps1
#This script is designed to grab mailbox statistics for every user and give a more detailed #level of output about mailbox statistics in .html format param( [string] $SFileWDir ) # If there is no optional argument then make a filename for it. if (!$SFileWDir) { Write-Host "You didn't specify a filename w/dir to save to so I'm going to just make one in this directory" Write-Host "Saving the file as GUReport-$date.html" # Generate the date var $date = get-date -Format MM-dd-yyyy # FOR TESTING PURPOSES, CHANGE METHOD ON THIS LATER $OUTFILE = "GUReport-$date.html" } else { Write-Host "Saving file as $SFileWDir" $OUTFILE = $SFileWDir } # Gather the list of users with mailboxes to check $UserList = get-user | Sort-Object $_.DisplayName | Where {$_.RecipientType -eq "UserMailbox"} # Set the page up Write-Output "<html>" | Out-File $OUTFILE -Append -Encoding Ascii Write-Output " <head><title>Mailbox Granular Usage Report "$date"</title></head>" | Out-File $OUTFILE -Append -Encoding Ascii Write-Output "<body>" | Out-File $OUTFILE -Append -Encoding Ascii Write-Output "<font face = 'Times New Roman'>" | Out-File $OUTFILE -Append -Encoding Ascii # Go through the list of users and build out all of their information into html tables $UserList | ForEach-Object { # Generate a table for the user information Write-Output "<table border = '1' cellspacing = '1' cellpadding = '1' width = '900'>" # Heading with the users name Write-Output " <tr>" Write-Output " <td colspan = '4' bgcolor = '#667E7C'><center><font color = 'white'><b>"$_.DisplayName"</b></font></center></td>" Write-Output " </tr>" # Heading for each of the columns Write-Output " <tr>" Write-Output " <td><b>Folder Path</b></td>" Write-Output " <td><b>Items In Folder</b></td>" Write-Output " <td><b>Folder Size (MB)</b></td>" Write-Output " <td><b>Folder Size (B)</b></td>" Write-Output " </tr>" #Generate the users statistics into a variable $UserMBS = get-mailboxfolderstatistics -Identity $_.DisplayName | select FolderPath,ItemsInFolder,FolderSize # Go through the mailboxstatistics and build it into the $userMBStatsObj $UserMBS | ForEach-Object { # Generate the Folder Size in MB. Note that I had to change the output to int in order for it to work $FolderSizeBytes = $_.FolderSize #Need to convert the string to int for it to be divisable. #Remove any characters from the string as it's converted to int. [int]$FolderSizeBytesInt = [regex]::Replace($FolderSizeBytes, "B|K", "") #Most entries have a B at the end, some a K for some odd reason... [int]$FolderSize = $FolderSizeBytesInt / 1MB Write-Output " <tr>" Write-Output " <td>"$_.FolderPath"</td>" Write-Output " <td>"$_.ItemsInFolder"</td>" Write-Output " <td>"$FolderSize"</td>" Write-Output " <td>"$FolderSizeBytesInt"</td>" Write-Output " </tr>" } #Close the user table information Write-Output "</table><br>" } | Out-File $OUTFILE -Append -Encoding Ascii Write-Output "</font>" | Out-File $OUTFILE -Append -Encoding Ascii Write-Output "</body>" | Out-File $OUTFILE -Append -Encoding Ascii Write-Output "</html>" | Out-File $OUTFILE -Append -Encoding Ascii
PowerShellCorpus/PoshCode/Get-DiskUsage.ps1
Get-DiskUsage.ps1
## du.ps1 Get-DiskUsage ############################### ## Note: $unit can be: kb, mb, gb, or an empty string (to get bytes) ############################### ## -Force causes du to include System ReparsePoints ## This means including folders like Vista's ~\\Documents\\My Pictures (which is a symlink to ~\\Pictures) ## -Total forces a final "total" sum row which represents the total for $Path ## function du { PARAM($path = "$pwd", [switch]$force, $unit="MB", $round=2, [switch]$total) &{ foreach($dir in (get-childitem $path -force | Where { $_.PSIsContainer -and ($Force -or ($_.Attributes -notmatch "ReparsePoint" -or $_.Attributes -notmatch "System"))})) { get-childitem -lit $dir -recurse -force | measure-object -sum -prop Length -EA "SilentlyContinue" | Select-Object @{Name="Path"; Expr={$dir}}, Count, Sum } } | Tee-Object -Variable Totals | Select-Object Path, Count, @{Name="Size($unit)"; Expr={[Math]::Round($_.Sum/"1$unit",$round)}} if($total) { $totals = $totals | measure-object -Sum -Prop "Count","Sum" Get-Item $path | Select @{Name="Path"; Expr={$_}}, @{Name="Count"; Expr={$totals[0].Sum}}, @{Name="Size($unit)"; Expr={[Math]::Round((($totals[1].Sum)/"1$unit"),$round)}} } }
PowerShellCorpus/PoshCode/Get-LatestChromium.ps1
Get-LatestChromium.ps1
$sevenz = 'D:\\u\\7-Zip\\current\\7z.exe' $drops = 'D:\\chromium\\drops' $VerbosePreference = 'Continue' $wc = New-Object Net.WebClient $url = 'http://build.chromium.org/buildbot/snapshots/chromium-rel-xp' Write-Verbose 'Finding the latest build...' $latest = [Int32]$wc.DownloadString("$url/LATEST") if (-not $latest) { throw 'Could not find the latest build.' } Write-Verbose "Latest build is $latest" $source = "$url/$latest/chrome-win32.zip" $dest = "$drops\\chrome-win32-$latest" $link = "$drops\\latest" $zip = "$dest.zip" if (-not (Test-Path $dest)) { if (-not (Test-Path $zip)) { Write-Verbose "Downloading the $latest win32 build..." $wc.DownloadFile($source, $zip) } Write-Verbose "Extracting $zip..." & $sevenz 'x' "-o$drops" -y $zip > $null if (($LASTEXITCODE) -or -not (Test-Path "$drops\\chrome-win32")) { throw "Failed to extract $zip" } Rename-Item "$drops\\chrome-win32" $dest -ea Stop Remove-Item $zip -Force -ea SilentlyContinue } Write-Verbose "Latest build exists in $dest" if (Test-Path $link) { cmd /c rd $link } cmd /c mklink /j $link $dest
PowerShellCorpus/PoshCode/ConvertTo-ASCII_1.ps1
ConvertTo-ASCII_1.ps1
#requires �version 2.0 #region Help <# .SYNOPSIS Automation script for file character set format conversion to ASCII encoding. .DESCRIPTION Script for automating the conversion of files to ASCII format. Good for if you've used Out-File without specifying the encoding. Which would make a Unicode formatted file by default. If you then used Add-Content to append data to that file it would have garbage characters because even though it states it defaults to Unicode it will write ASCII/ANSI. .INPUTS Full Path to files to convert. .OUTPUTS Replacement files in ASCII format. .NOTES AUTHOR: Levon Becker TITLE: ConvertTo-Ascii VERSION: 1.001 DATE: 4/13/2011 ENV: Powershell v2 TOOLS: PowerGUI Script Editor, RegexBuddy .EXAMPLE .\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt" Will convert all of the files with a TXT file extension in the directory named Folder2. .EXAMPLE .\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt" Will convert a single file named filename.txt in the directory named Folder2 .EXAMPLE .\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt" -recursive $true Will convert all of the files with a TXT file extension in the directory named Folder2 and any subdirectories. .EXAMPLE .\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt" -recursive $true Will convert a single file named filename.txt in the directory named Folder2 and any subdirectories. .PARAMETER path Full path to file/s to process. Standard wild cards are excepted. Be sure to put in quotation marks. It should work without a trailing backslash or asterisk, but it's recommended to simply include. See examples .PARAMETER include File name filtering option. Standard wild cards are excepted. Be sure to put in quotation marks. .PARAMETER recursive Specifies if the script should look in sub-folders off the path provided. Default is False (Do not do recursive). Use -recursive $true to enable. .LINK #> #endregion Help #region Changelog <# 04/12/2011: Created 04/13/2011: Added time-stamp capture and write in order to keep the replacement files with the same time information as the original. Cleaned up comments and regions. #> #endregion Changelog #region Sources <# http://rosettacode.org/wiki/File_modification_time#PowerShell http://www.powergui.org http://www.regexbuddy.com #> #endregion Sources #region Parameters [CmdletBinding()] Param ( [parameter(Mandatory=$true)][string]$path, [parameter(Mandatory=$true)][string]$include, [parameter(Mandatory=$false)][string]$recursive = "$false" ) #endregion Parameters #region Variables $scriptver = '1.001' $originaltitle = $Host.UI.RawUI.WindowTitle $title = "File Convert to ASCII Script v$scriptver by Levon Becker" $count = $null $file = $null #endregion Variables Clear $Host.UI.RawUI.WindowTitle = $title #region Check Parameters If ((Test-Path -Path $path) -eq $false) { Write-Host "ERROR: PATH NOT FOUND ($path)" -BackgroundColor Red -ForegroundColor White Break } #endregion Check Parameters #region Main Process # Check that \\* is at the end of the path $regex = '\\b\\\\\\*' # If not then add \\* to the end of the path If ($path -notmatch $regex) { $path = $path + '\\*' } # Get list of filenames If ($recursive -eq $true) { $filelist = Get-ChildItem -path $path -Include $include -Recurse } Else { $filelist = Get-ChildItem -path $path -Include $include } Foreach ($file in $filelist) { $count++ # Get File Information $fullname = ($file.FullName) $creationtime = ($file.CreationTime) $creationtimeutc = ($file.CreationTimeUtc) $lastwritetime = ($file.LastWriteTime) $lastwritetimeutc = ($file.LastWriteTimeUtc) $lastaccesstime = ($file.LastAccessTime) $lastaccesstimeutc = ($file.LastAccessTimeUtc) # Get File Contents $content = Get-Content $fullname # Replace file with corrected character set Out-File -FilePath $fullname -Encoding ASCII -Force -InputObject $content # Set original time stamp information on new file Set-ItemProperty -Path $fullname -Name CreationTime ($creationtime) Set-ItemProperty -Path $fullname -Name CreationTimeUtc ($creationtimeutc) Set-ItemProperty -Path $fullname -Name LastWriteTime ($lastwritetime) Set-ItemProperty -Path $fullname -Name LastWriteTimeUtc ($lastwritetimeutc) Set-ItemProperty -Path $fullname -Name LastAccessTime ($lastaccesstime) Set-ItemProperty -Path $fullname -Name LastAccessTimeUtc ($lastaccesstimeutc) Write-Host $file } #endregion Main Process #region Conclusion Information Write-Host '----------------------------------------------------------------------' Write-Host '' Write-Host "Total Converted: " -ForegroundColor Green -NoNewline Write-Host $count Write-Host '' Write-Host '-------------' -ForegroundColor Green Write-Host '| COMPLETED |' -ForegroundColor Green Write-Host '-------------' -ForegroundColor Green Write-Host '' #endregion Conclusion Information $Host.UI.RawUI.WindowTitle = $title + ' (COMPLETED)' Sleep -Seconds 1 $Host.UI.RawUI.WindowTitle = $originaltitle
PowerShellCorpus/PoshCode/Remove broken NTFS perm.ps1
Remove broken NTFS perm.ps1
#========================================================================== # NAME: getunknownsids.ps1 # # AUTHOR: Stephen Wheet # Version: 4.0 # Date: 6/11/10 # # COMMENT: # This script was created to find unknown SIDs or old domain permissions # on folders. It ignores folders where inheirtance is turned on. # # This works on NETAPPS and WINDOWS servers. You will need the DLL's # # Version 2: completely changed the query method and ACL removal # Version 3: Added ability to query AD for servers, and handles getting # getting shares automatically from: # NETAPP FILERS # Windows servers # Version 4: Cleaned up folder checking and added checking for local # account checking so we could ignore. # #========================================================================== Function checkshare { Param($PassedShareName) Process { $path = "\\\\$serverFQDN\\$PassedShareName" $filename = $path.Replace("\\","-") + ".csv" #Place Headers on out-put file $list = "Task,Path,Access Entity," $list | format-table | Out-File "c:\\reports\\unknownsids\\$filename" #Populate Folders Array Write-Host "Writing results to : $filename" $date = Get-Date Write-Host $date Write-Host "Getting Folders in: $Path" #PSIscontainer means folders only [Array] $folders = Get-ChildItem -path $path -recurse | ? {$_.PSIsContainer} #Process data in array ForEach ($folder in [Array] $folders) { #Check to see if there are any folders If ($folder.pspath){ #Convert Powershell Provider Folder Path to standard folder path $PSPath = (Convert-Path $folder.pspath) Write-Host "Checking Dir: $PSPath" #Check to make sure valid If ($PSPath){ #Get the ACL's from each folder $error.clear() $acl = Get-Acl -Path $PSPath #Write log if no access if (!$?) { $errmsg = "Error,$PSPath,ACCESS DENIED" $errmsg | format-table | Out-File -append "$filename" } #end IF $ACL.Access | ?{!$_.IsInherited} | ?{ $_.IdentityReference -like $unknownsid -or $_.IdentityReference -like $olddomain } | % {$value = $_.IdentityReference.Value #Check for Local account $localsid = 0 If ($value -like $unknownsid){ $checkforlocal = $value.split("-") $total =$checkforlocal.count -1 if ($checkforlocal[$total] -match "100?" -or $checkforlocal[$total] -match "500"){ $localsid = 1 # You can uncomment the below if you want to report on local accounts. #$list = ("Local,$PSPath,$value") #$list | format-table | Out-File -append "$filename" } #end IF } #end IF If (!$localsid){ Write-host "Found - $PSPath - $value" $list = ("Found,$PSPath,$value") $list | format-table | Out-File -append "$filename" #Remove Bad SID if ($removeacl) { $ACL.RemoveAccessRuleSpecific($_) Write-host "Deleting - $PSPath - $value" $list = ("Deleting,$PSPath,$value") $list | format-table | Out-File -append "$filename" }#end IF if ($removeacl -and $value) { $date = Get-Date Write-Host $date Write-host "Setting - $PSPath" $list = ("Setting,$PSPath") $list | format-table | Out-File -append "$filename" Set-ACL $PSpath $ACL $value = "" } #end IF } #end if } #end foreachobj } #end if } #end if } #end ForEach }#end Process } #end function get-pssnapin -registered | add-pssnapin -passthru [void][Reflection.Assembly]::LoadFile('C:\\reports\\ManageOntap.dll') #Need this DLL from netapp 3.5SDK $ReqVersion = [version]"1.2.2.1254" $QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version #Need Quest plugins installed if($QadVersion -lt $ReqVersion) { throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version" } #end If #Set variables $value = "" $unknownsid = "*S-1-5-21-*" #Broken SID Verify the Broken SID number on your system and replace $olddomain = "Domain.local*" #Old w2k/nt4 domain $ErrorActionPreference = "SilentlyContinue" $removeacl = 0 #change to 1 if you want to remove the SID, 0 for only logging $localsid = 0 #Get all the servers from the specified OU $Servers = get-QADComputer -SearchRoot 'domain.local/ou/Server' # change the container. Foreach ($server in $Servers ) { $serverFQDN = $server.dnsname write-host $serverFQDN #Test ping server to make sure it's up before querying it $ping = new-object System.Net.NetworkInformation.Ping $Reply = $ping.Send($serverFQDN) if ($Reply.status -eq "Success"){ Write-Host "Online" #Check for Netapp .. if found get the shares differently If ($serverFQDN -like "*netapp*"){ $server = new-object netapp.manage.naserver($serverFQDN,1,0) #pass authentication $server.Style = "RPC" # Issue command to get the shares $NaElement = New-Object NetApp.Manage.NaElement("system-cli") $arg = New-Object NetApp.Manage.NaElement("args") $arg.AddNewChild('arg','cifs') $arg.AddNewChild('arg','shares') $NaElement.AddChildElement($arg) $CifsString = $server.InvokeElem($NaElement).GetChildContent("cli-output") # Split the returned txt up .. the $null makes it skip a line $null,$null,$Lines = $CifsString.Split("`n") Foreach ($line in $Lines ) { # Had to trick it so skip the line with permissions, then exclude ETC$ adn c$ if (!$line.startswith(" ") -and $line -notlike "*Etc$*" -and $line -notlike "*C$*"){ $l= $line.Split(" ") checkshare -PassedShareName $l[0] #Pass share to function } #end if } #end foreach } #end if Else{ #Else if a Windows server query via WMI Get-WMIObject Win32_Share -Computer $serverFQDN | where {$_.Name -like "*$*" -and $_.Name -notlike "*ADMIN*" -and $_.Name -notlike "*IPC*" -and $_.Name -notlike "*lib*"} | %{ #Set path $sharename = $_.name checkshare -PassedShareName $sharename #Pass share to function } #end ForEachObj } #End Else } #End If } #end ForEach
PowerShellCorpus/PoshCode/Get-LocalGroupMember_2.ps1
Get-LocalGroupMember_2.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 { switch -regex (($Exception = $_.Exception.InnerException).Message) { "Access Denied" { Write-Error -Exception $Exception -Category PermissionDenied -CategoryTargetName $cName -CategoryTargetType Computer -TargetObject ([ADSI]"WinNT://$cName") -CategoryReason $Exception.Message -RecommendedAction "Check your credentials and try again" } "group name|local group" { Write-Error -Exception $Exception -Category ObjectNotFound -CategoryTargetName $GroupName -CategoryTargetType Group -TargetObject ([ADSI]"WinNT://$cName") -CategoryReason $Exception.Message -RecommendedAction "Check the spelling of the group name and try again" } "network path" { Write-Error -Exception $Exception -Category ResourceUnavailable -CategoryTargetName $cName -CategoryTargetType Computer -TargetObject ([ADSI]"WinNT://$cName") -CategoryReason $Exception.Message -RecommendedAction "Verify the computer name is correctly and that it's turned on and network accessible" } default { Write-Error -Exception $Exception -Category NotSpecified -CategoryTargetName $cName -CategoryTargetType Computer -TargetObject ([ADSI]"WinNT://$cName") -CategoryReason $Exception.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/vProfile-ClusterAudit.ps1
vProfile-ClusterAudit.ps1
# vProfile-ClusterAudit.ps1 : vSphere cluster node auditing script # This script will compare all VI/vSphere cluster nodes against a reference node # Parameters: # $xmlFile : XML profile file, created by the vProfile.ps1 script # $csvFile : CSV file that will conatin the discovered differences # $referenceHost : hostname of the node that will the "reference" node # Author: LucD # History: # v1.0 27/08/09 first version # # Parameters $xmlFile = "C:\\vInventoryCluster-Clus1.xml" $csvFile = "C:\\Clus1-diff.csv" $referenceHost = "esx41.test.local" $global:report = @() function Compare-Attributes{ param($ref, $node, $path, $origrow) $refFirstAttrib = $ref.MoveToFirstAttribute() $nodeFirstAttrib = $node.MoveToFirstAttribute() if($refFirstAttrib -and $nodeFirstAttrib){ do { if($node.Value -ne $ref.Value){ $line = $origrow $line.Name = $ref.LocalName $line.RefValue = $ref.Value $line.CmpValue = $node.Value $global:report += $line } $refNextAttrib = $ref.MoveToNextAttribute() $nodeNextAttrib = $node.MoveToNextAttribute() } while ($refNextAttrib -and $nodeNextAttrib) $dummy = $ref.MoveToParent() $dummy = $node.MoveToParent() } } function Compare-Recursive{ param($ref, $nav, $path) $path += ("/" + $nav.LocalName) $report = @() $row = New-Object PsObject $row | Add-Member -MemberType NoteProperty -Name Path -Value "na" $row | Add-Member -MemberType NoteProperty -Name RefHost -Value "na" $row | Add-Member -MemberType NoteProperty -Name CmpHost -Value "na" $row | Add-Member -MemberType NoteProperty -Name Name -Value "na" $row | Add-Member -MemberType NoteProperty -Name RefValue -Value "na" $row | Add-Member -MemberType NoteProperty -Name CmpValue -Value "na" $row | Add-Member -MemberType NoteProperty -Name AttributeDiscrepancy -Value $false $row | Add-Member -MemberType NoteProperty -Name ChildrenDiscrepancy -Value $false $row.Path = $path $row.RefHost = $refHost.Name $row.CmpHost = $selHost.Name if($nav.HasAttributes -and $ref.HasAttributes){ Compare-Attributes $ref $nav $path $row } elseif($nav.HasAttributes -ne $ref.HasAttributes){ $row.AttributeDiscrepancy = $true } if($nav.HasChildren -and $ref.HasChildren){ $refFirstChild = $ref.MoveToFirstChild() $navFirstChild = $nav.MoveToFirstChild() if($refFirstChild -and $navFirstChild){ do { Compare-Recursive $ref $nav $path $refNextChild = $ref.MoveToNext() $navNextChild = $nav.MoveToNext() } while ($refNextChild -and $navNextChild) $dummy = $ref.MoveToParent() $dummy = $nav.MoveToParent() } } elseif($nav.HasChildren -ne $ref.HasChildren){ $row.ChildrenDiscrepancy = $true } } $path = "Inventory/Cluster" $xml = [xml](Get-Content $xmlFile) $refPath = "Inventory/Cluster/Host[@Name='" + $referenceHost + "']" $otherPath = "Inventory/Cluster/Host[@Name!='" + $referenceHost + "']" $refHost = $xml.SelectSingleNode($refPath) $refNav = $refHost.PSBase.CreateNavigator() foreach($selHost in $xml.SelectNodes($otherPath)){ $refCopy = $refNav $navigator = $selHost.PSBase.CreateNavigator() $result += (Compare-Recursive $refCopy $navigator $path) } $global:report | Export-Csv $csvFile -NoTypeInformation
PowerShellCorpus/PoshCode/Findup_19.ps1
Findup_19.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"-x", new List<string>()},{"-i",new List<string>()},{"-xf",new List<string>()},{"-if",new List<string>()}, {"-xd",new List<string>()},{"-id",new List<string>()},{"-paths",new List<string>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-regex", false }, { "-noerr", false }, {"-delete",false} }; public static long numOfDupes = 0; // number of duplicate files found. public static long dupeBytes = 0; // number of bytes in duplicates. public static long bytesrecovered = 0; // Bytes recovered from deleting dupes. public static long deletedfiles = 0; // Number of deleted dupes. public static string delconfirm; public static void Main(string[] args) { Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine(" "); string optionspathskey = "-paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem=args[i].ToLower(); if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help message."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -delete - delete each duplicate file with confirmation."); Console.WriteLine(" -x - eXcludes if full file path starts with (or RegEx matches if -regex supplied) one of the items following this switch until another switch is used."); Console.WriteLine(" -i - include if full file path starts with (or Regex matches if -regex supplied) one of the items following this switch until another switch is used."); Console.WriteLine(" -xd - eXcludes all directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -regex - Use Regex notation for exclude (-x) and include (-i) option."); Console.WriteLine(" -paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(jim)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\bobsmithquarter.doc -x \\"[bf]\\" -i \\"(smith)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); Console.WriteLine(" -xd,-id,-xf,-if are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa."); Console.WriteLine(" if for instance you wanted all files that contained the letter \\"d\\" on your D: drive but didn't want the d:\\\\ to cause all files on the d:\\\\ "); Console.WriteLine(" drive to be included, you would specify:"); Console.WriteLine(" findup.exe d:\\\\ -recurse -noerr -regex -if \\"[d]\\" "); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionspathskey = "-paths"; continue; } if (optionspaths.ContainsKey(argitem)) { optionspathskey = argitem; continue; } optionspaths[optionspathskey].Add(argitem); } if (optionspaths["-paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory."); optionspaths["-paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>(); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) { continue; } var breakout = false; while (true) { var _SHA512 = SHA512.Create(); try { using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } System.Text.Encoding enc = System.Text.Encoding.ASCII; string SHA512string = enc.GetString(_SHA512.Hash); if (SizeHashName.ContainsKey(files[i].Length)) { if (!SizeHashName[files[i].Length].ContainsKey(SHA512string)) { SizeHashName[files[i].Length][SHA512string] = new List<string>() {}; } } else { SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>()); SizeHashName[files[i].Length][SHA512string] = new List<string>() {}; } SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } } Console.WriteLine("Completed!"); foreach (var SizeGroup in SizeHashName) { foreach (var HashGroup in SizeGroup.Value) { var SGK = (long)SizeGroup.Key; var HGVC = (int)HashGroup.Value.Count; if (HGVC > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK*HGVC); foreach (var FileName in HashGroup.Value) { Console.WriteLine(FileName); numOfDupes++; if (optionsbools["-delete"]) if (DeleteDupe(FileName)) { bytesrecovered += SGK; } } dupeBytes += SGK * HGVC; } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); return; // Exit after displaying statistics. } private static void WriteErr(string Str) { if (!optionsbools["-noerr"]) Console.WriteLine(Str); } private static Boolean DeleteDupe(string FileName) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { File.Delete(FileName); Console.WriteLine("File Successfully deleted."); deletedfiles++; return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckAll(string full) { if (!CheckWorker(full, optionspaths["-x"])) return false; if ((optionspaths["-i"].Count > 0) == CheckWorker(full, optionspaths["-i"])) return false; var filePart = Path.GetFileName(full); var dirPart = Path.GetDirectoryName(full); if (!CheckWorker(filePart, optionspaths["-xf"])) return false; if (!CheckWorker(dirPart, optionspaths["-xd"])) return false; if ((optionspaths["-if"].Count > 0) == CheckWorker(filePart, optionspaths["-if"])) return false; if ((optionspaths["-id"].Count > 0) == CheckWorker(dirPart, optionspaths["-id"])) return false; return true; } private static Boolean CheckWorker(string full, List<string> pathsitems) { foreach (var x in pathsitems) { if (optionsbools["-regex"]) { try { Regex rgx = new Regex(x); if (rgx.IsMatch(full)) return false; } catch (Exception e) { WriteErr("Invalid regex used: " + x + " exception: " + e); } } else { if (full.ToLower().StartsWith(x)) { return false; } } } return true; } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckAll(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckAll(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP3).ps1
Set-Wallpaper (CTP3).ps1
#requires -version 2.0 ## Set-Wallpaper - set your windows desktop wallpaper ################################################################################################### ## Usage: ## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Wallpaper\\Dual Monitor\\mandolux-tiger.jpg" "Tile" ## ls *.jpg | get-random | Set-Wallpaper ## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch" ################################################################################################### ## History: ## v0.5 First release (on #PowerShell@irc.freenode.net) ## v1.0 Public release (http://www.poshcode.org/488) ## - Added Style: Tile|Center|Stretch ## v1.1 (http://poshcode.org/491) ## - Added "NoChange" style to just use the style setting already set ## - Made the Style parameter to the cmdlet optional ## v2.0 This Release ## - Updated for CTP3, and made it run as a script instead of a function. ################################################################################################### [CmdletBinding()] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [string] $Path , [Parameter(Position=1, Mandatory=$false)] [Wallpaper.Style] $Style = "NoChange" ) BEGIN { try { $WP = [Wallpaper.Setter] } catch { $WP = add-type @" using System; using System.Runtime.InteropServices; using Microsoft.Win32; namespace Wallpaper { public enum Style : int { Tile, Center, Stretch, NoChange } public class Setter { public const int SetDesktopWallpaper = 20; public const int UpdateIniFile = 0x01; public const int SendWinIniChange = 0x02; [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni); public static void SetWallpaper ( string path, Wallpaper.Style style ) { SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange ); RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true); switch( style ) { case Style.Stretch : key.SetValue(@"WallpaperStyle", "2") ; key.SetValue(@"TileWallpaper", "0") ; break; case Style.Center : key.SetValue(@"WallpaperStyle", "1") ; key.SetValue(@"TileWallpaper", "0") ; break; case Style.Tile : key.SetValue(@"WallpaperStyle", "1") ; key.SetValue(@"TileWallpaper", "1") ; break; case Style.NoChange : break; } key.Close(); } } } "@ -Passthru } } PROCESS { Write-Verbose "Setting Wallpaper ($Style) to $(Convert-Path $Path)" $WP::SetWallpaper( (Convert-Path $Path), $Style ) }
PowerShellCorpus/PoshCode/Portgroup NIC Team.ps1
Portgroup NIC Team.ps1
# PG-duplex.ps1 : NIC Teaming with failover set on duplexity # This script will configure the portgroup to use NIC Teaming where the failover is # depending on the duplexity of the Active NIC. # # Parameters: # $esxName : name of the ESX server # $vSwitch : name of the vSwitch # $portgroup : name of the portgroup # $actNIC : active NICs array # $sbyNIC : standby NICs array # # Author: LucD # History: # v1.0 27/08/09 first version # # Parameters $esxName = "esx41.test.local" $vSwitch = "vSwitch1" $pgname = "Net1" $actNIC = @("vmnic1") $sbyNIC = @("vmnic2") $esx = Get-VMHost $esxName | Get-View # Check if vSwitch has Beacon Probing selected $esx.Config.Network.Vswitch | where {$_.Name -eq $vSwitch} | %{ if(-not $_.Spec.Policy.NicTeaming.FailureCriteria.CheckBeacon){ "Beacon Probing should be enabled on the vSwitch first" | Out-Host exit } } $net = Get-View $esx.configmanager.networksystem $portgroupspec = New-Object VMWare.Vim.HostPortGroupSpec $portgroupSpec.vswitchname = $vSwitch $portgroupspec.Name = $pgname $portgroupspec.policy = New-object vmware.vim.HostNetworkPolicy # NIC team $portgroupspec.policy.NicTeaming = New-object vmware.vim.HostNicTeamingPolicy $portgroupspec.policy.NicTeaming.nicOrder = New-Object vmware.vim.HostNicOrderPolicy $portgroupspec.policy.NicTeaming.nicOrder.activeNic = $actNIC $portgroupspec.policy.NicTeaming.nicOrder.standbyNic = $sbyNIC # Failover Detection $portgroupspec.policy.NicTeaming.failureCriteria = New-Object vmware.vim.HostNicFailureCriteria $portgroupspec.policy.NicTeaming.failureCriteria.checkBeacon = $true $portgroupspec.policy.NicTeaming.failureCriteria.checkDuplex = $true $portgroupspec.policy.NicTeaming.failureCriteria.fullDuplex = "full" $portgroupspec.policy.NicTeaming.failureCriteria.checkSpeed = "exact" $portgroupspec.policy.NicTeaming.failureCriteria.speed = 1000 # Notify Switches $portgroupspec.policy.NicTeaming.notifySwitches = $true # Load Balancing $portgroupspec.policy.NicTeaming.policy = "failover_explicit" # Failback $portgroupspec.policy.NicTeaming.RollingOrder = $false $net.UpdatePortGroup($pgname, $PortGroupSpec)
PowerShellCorpus/PoshCode/e5112c21-82dc-44c8-8fa5-616b1b16b004.ps1
e5112c21-82dc-44c8-8fa5-616b1b16b004.ps1
#region Function: Get-DTWFileEncoding <# .SYNOPSIS Returns the encoding type of the file .DESCRIPTION Returns the encoding type of the file. It first attempts to determine the encoding by detecting the Byte Order Marker using Lee Holmes' algorithm (http://poshcode.org/2153). However, if the file does not have a BOM it makes an attempt to determine the encoding by analyzing the file content (does it 'appear' to be UNICODE, does it have characters outside the ASCII range, etc.). If it can't tell based on the content analyzed, then it assumes it's ASCII. I haven't checked all editors but PowerShell ISE and PowerGUI both create their default files as non-ASCII with a BOM (they use Unicode Big Endian and UTF-8, respectively). If your file doesn't have a BOM and 'doesn't appear to be Unicode' (based on my algorithm*) but contains non-ASCII characters after index ByteCountToCheck, the file will be incorrectly identified as ASCII. So put a BOM in there, would ya! For more information and sample encoding files see: http://danspowershellstuff.blogspot.com/2012/02/get-file-encoding-even-if-no-byte-order.html And please give me any tips you have about improving the detection algorithm. *For a full description of the algorithm used to analyze non-BOM files, see "Determine if Unicode/UTF8 with no BOM algorithm description". .PARAMETER Path Path to file .PARAMETER ByteCountToCheck Number of bytes to check, by default check first 10000 character. Depending on the size of your file, this might be the entire content of your file. .PARAMETER PercentageMatchUnicode If pecentage of null 0 value characters found is greater than or equal to PercentageMatchUnicode then this file is identified as Unicode. Default value .5 (50%) .EXAMPLE Get-IHIFileEncoding -Path .\\SomeFile.ps1 1000 Attempts to determine encoding using only first 1000 characters BodyName : unicodeFFFE EncodingName : Unicode (Big-Endian) HeaderName : unicodeFFFE WebName : unicodeFFFE WindowsCodePage : 1200 IsBrowserDisplay : False IsBrowserSave : False IsMailNewsDisplay : False IsMailNewsSave : False IsSingleByte : False EncoderFallback : System.Text.EncoderReplacementFallback DecoderFallback : System.Text.DecoderReplacementFallback IsReadOnly : True CodePage : 1201 #> function Get-DTWFileEncoding { #region Function parameters [CmdletBinding()] param( [Parameter(Mandatory = $true,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Alias("FullName")] [string]$Path, [Parameter(Mandatory = $false)] [int]$ByteCountToCheck = 10000, [Parameter(Mandatory = $false)] [decimal]$PercentageMatchUnicode = .5 ) #endregion process { # minimum number of characters to check if no BOM [int]$MinCharactersToCheck = 400 #region Parameter validation #region SourcePath must exist; if not, exit if ($false -eq (Test-Path -Path $Path)) { Write-Error -Message "$($MyInvocation.MyCommand.Name) :: Path does not exist: $Path" return } #endregion #region ByteCountToCheck should be at least MinCharactersToCheck if ($ByteCountToCheck -lt $MinCharactersToCheck) { Write-Error -Message "$($MyInvocation.MyCommand.Name) :: ByteCountToCheck should be at least $MinCharactersToCheck : $ByteCountToCheck" return } #endregion #endregion #region Determine file encoding based on BOM - if exists # the code in this section is mostly Lee Holmes' algorithm: http://poshcode.org/2153 # until we determine the file encoding, assume it is unknown $Unknown = "UNKNOWN" $result = $Unknown # The hashtable used to store our mapping of encoding bytes to their # name. For example, "255-254 = Unicode" $encodings = @{} # Find all of the encodings understood by the .NET Framework. For each, # determine the bytes at the start of the file (the preamble) that the .NET # Framework uses to identify that encoding. $encodingMembers = [System.Text.Encoding] | Get-Member -Static -MemberType Property $encodingMembers | ForEach-Object { $encodingBytes = [System.Text.Encoding]::($_.Name).GetPreamble() -join '-' $encodings[$encodingBytes] = $_.Name } # Find out the lengths of all of the preambles. $encodingLengths = $encodings.Keys | Where-Object { $_ } | ForEach-Object { ($_ -split "-").Count } # Go through each of the possible preamble lengths, read that many # bytes from the file, and then see if it matches one of the encodings # we know about. foreach ($encodingLength in $encodingLengths | Sort-Object -Descending) { $bytes = (Get-Content -Path $Path -Encoding byte -ReadCount $encodingLength)[0] $encoding = $encodings[$bytes -join '-'] # If we found an encoding that had the same preamble bytes, # save that output and break. if ($encoding) { $result = $encoding break } } # if encoding determined from BOM, then return it if ($result -ne $Unknown) { [System.Text.Encoding]::$result return } #endregion #region No BOM on file, attempt to determine based on file content #region Determine if Unicode/UTF8 with no BOM algorithm description <# Looking at the content of many code files, most of it is code or spaces. Sure, there are comments/descriptions and there are variable names (which could be double-byte characters) or strings but most of the content is code - represented as single-byte characters. If the file is Unicode but the content is mostly code, the single byte characters will have a null/value 0 byte as either as the first or second byte in each group, depending on Endian type. My algorithm uses the existence of these 0s: - look at the first ByteCountToCheck bytes of the file - if any character is greater than 127, note it (if any are found, the file is at least UTF8) - count the number of 0s found (in every other character) - if a certain percentage (compared to total # of characters) are null/value 0, then assume it is Unicode - if the percentage of 0s is less than we identify as a Unicode file (less than PercentageMatchUnicode) BUT a character greater than 127 was found, assume it is UTF8. - Else assume it's ASCII. Yes, technically speaking, the BOM is really only for identifying the byte order of the file but c'mon already... if your file isn't ASCII and you don't want it's encoding to be confused just put the BOM in there for pete's sake. Note: if you have a huge amount of text at the beginning of your file which is not code and is not single-byte, this algorithm may fail. Again, put a BOM in. #> #endregion $Content = (Get-Content -Path $Path -Encoding byte -ReadCount $ByteCountToCheck -TotalCount $ByteCountToCheck) # get actual count of bytes (in case less than $ByteCountToCheck) $ByteCount = $Content.Count [bool]$NonAsciiFound = $false # yes, the big/little endian sections could be combined in one loop # sorry, crazy busy right now... #region Check if Big Endian # check if big endian Unicode first - even-numbered index bytes will be 0) $ZeroCount = 0 for ($i = 0; $i -lt $ByteCount; $i += 2) { if ($Content[$i] -eq 0) { $ZeroCount++ } if ($Content[$i] -gt 127) { $NonAsciiFound = $true } } if (($ZeroCount / ($ByteCount / 2)) -ge $PercentageMatchUnicode) { # create big-endian Unicode with no BOM New-Object System.Text.UnicodeEncoding $true,$false return } #endregion #region Check if Little Endian # check if little endian Unicode next - odd-numbered index bytes will be 0) $ZeroCount = 0 for ($i = 1; $i -lt $ByteCount; $i += 2) { if ($Content[$i] -eq 0) { $ZeroCount++ } if ($Content[$i] -gt 127) { $NonAsciiFound = $true } } if (($ZeroCount / ($ByteCount / 2)) -ge $PercentageMatchUnicode) { # create little-endian Unicode with no BOM New-Object System.Text.UnicodeEncoding $false,$false return } #endregion #region Doesn't appear to be Unicode; either UTF8 or ASCII # Ok, at this point, it's not a Unicode based on our percentage rules # if not Unicode but non-ASCII character found, call it UTF8 (no BOM, alas) if ($NonAsciiFound -eq $true) { New-Object System.Text.UTF8Encoding $false return } else { # if made it this far, I'm calling it ASCII; done deal pal [System.Text.Encoding]::"ASCII" return } #endregion #endregion } } Export-ModuleMember -Function Get-DTWFileEncoding #endregion
PowerShellCorpus/PoshCode/Create-Sequence.ps1
Create-Sequence.ps1
# Create-Sequence.ps1 # requires -version 1 # # Create a sequence object similar to an Oracle sequence. # # see : http://www.acs.ilstu.edu/docs/oracle/server.101/b10759/statements_6014.htm # # Crée un objet séquence similaire à une séquence Oracle # Version spécifique à PowerShell v1.0 # L'appel de Nextval n'est pas nécessaire CurrVal est accessible dés que l'objet créé #Propriétés en ReadOnly: #----------------------------------------------------------------------------------------- #Tutorial (french) : http://laurent-dardenne.developpez.com/articles/Windows/PowerShell/CreationDeMembresSynthetiquesSousPowerShell/ # Name : Nom de la séquence. # # CurrVal : Contient la valeur courante. # # Increment_By : Spécifie l'interval entre les numéros de la séquence. # Cette valeur entiére peut être n'importe quel nombre entier positif ou négatif de type .NET INT, mais elle ne peut pas être 0. # L'absolu de cette valeur doit être moins (ou égal) que la différence de MAXVALUE et de MINVALUE. # Si cette valeur est négative, alors le séquence est descendante (ordre décroissant). # Si la valeur est positive, alors la séquence est ascendante (ordres croissant). # Si vous omettez ce paramètre la valeur de l'interval est par défaut de 1. # # Start_With : Spécifie le premier nombre de la séquence à produire. # Employez ce paramètre pour démarrer une séquence ascendante à une valeur plus grande que son minimum ou pour # démarrer une séquence descendante à une valeur moindre que son maximum. Pour des séquences ascendantes, # la valeur par défaut est la valeur minimum de la séquence. Pour des séquences descendantes, la valeur par défaut # est la valeur maximum de la séquence. # Note : # Cette valeur n'est pas nécessairement la valeur à laquelle une séquence ascendante cyclique redémarre une fois # sa valeur maximum ou minimum atteinte. # # MaxValue : Spécifie la valeur maximum que la séquence peut produire. # MAXVALUE doit être égal ou plus grand que le valeur du paramètre START_WITH et doit être plus grand que MINVALUE. # # MinValue : Spécifie la valeur minimum de la séquence. # MINVALUE doit être inférieur ou égal à le valeur du paramètre START_WITH et doit être inférieure à MAXVALUE. # # Cycle : Indique que la séquence continue à produire des valeurs une fois atteinte sa valeur maximum ou minimum. # Une fois qu'une séquence ascendante a atteint sa valeur maximum, elle reprend à sa valeur minimum. # Une fois qu'une séquence descendante a atteint sa valeur minimum, elle reprend à sa valeur maximum. # Par défaut une séquence ne produit plus de valeurs une fois atteinte sa valeur maximum ou minimum. # # Comment : Commentaire. # #Méthodes : #----------------------------------------------------------------------------------------- # NextVal: Incrémente la séquence et retourne la nouvelle valeur. # ** Le fonctionnment de cet objet séquence est similaire à celui d'une séquence Oracle sans pour autant être identique. # Si vous ne spécifiez aucun paramètre, autre que le nom obligatoire, alors vous créez une séquence ascendante qui # débute à 1 et est incrémentée de 1 jusqu'à sa limite supérieure ([int]::MaxValue). # Si vous spécifiez seulement INCREMENT_BY -1 vous créez une séquence déscendante qui débute à -1 et # est décrémentée de 1 jusqu'à sa limite inférieure ([int]::MinValue). # Pour créer une séquence ascendante qui incrémente sans limite (autre que celle du type .NET INT), omettez le paramètre MAXVALUE. # Pour créer une séquence descendante qui décrémente sans limite, omettez le paramètre MINVALUE. # Pour créer une séquence ascendante qui s'arrête à une limite prédéfinie, spécifiez une valeur pour le paramètre MAXVALUE. # Pour créer une séquence descendante qui s'arrête à une limite prédéfinie, spécifiez une valeur pour le paramètre MINVALUE. # Si vous ne précisez pas le paramètre -CYCLE, n'importe quelle tentative de produire un numéro de séquence une fois que la séquence # a atteint sa limite déclenchera une erreur. # Pour créer une séquence qui redémarre/boucle après avoir atteint une limite prédéfinie, indiquez le paramètre CYCLE. Dans ce cas # vous devez obligatoirement spécifiez une valeur pour les paramètres MAXVALUE ou MINVALUE. #Valeur par défaut d'une séquence ascendante : # $Sq=Create-Sequence "SEQ_Test" ;$Sq # # Name : SEQ_Test # CurrVal : 1 # Increment_By : 1 # MaxValue : 2147483647 # MinValue : 1 # Start_With : 1 # Cycle : False # Comment : #Valeur par défaut d'une séquence descendante : # $Sq=Create-Sequence "SEQ_Test" -inc -1 ;$Sq # # Name : SEQ_Test # CurrVal : -1 # Increment_By : -1 # MaxValue : -1 # MinValue : -2147483648 # Start_With : -1 # Cycle : False # Comment : #Exemple : # $DebugPreference = "Continue" # $Sq= Create-Sequence "SEQ_Test" # $Sq.Currval # $Sq.NextVal() # $Sq.Currval Function Create-Sequence { #Tous les paramètres sont contraint, i.e. on précise un type. param([String] $Sequence_Name, [String] $Comment, $Increment_By=1, $MaxValue, $MinValue, $Start_With, [switch] $Cycle) function ValidateParameter([string]$Name,$Parameter,[Type] $Type) { # Renvoi True si le type est celui attendu et si le contenu n'est pas $Null ou si on peut caster # la valeur reçue dans le type attendu # Renvoi False si le contenu est à $Null. # Déclenche une exception ArgumentTransformationMetadataException si le type n'est pas celui attendu. Write-Debug "ValidateParameter" Write-debug "$Name" if ($Parameter -ne $null) {Write-debug "$($Parameter.GetType())"} else {Write-debug "`$Parameter est à `$null."} Write-debug "$Parameter" Write-debug "$Type" if (($Parameter -eq $null)) { Write-Debug "Le paramètre $Name est à `$null." return $False } elseif ($Parameter -isNot $Type) { #Peut-on caster la valeur reçue dans le type attendu ? if (!($Parameter -as $Type)) { #récupére le contexte d'appel de l'appelant $Invocation = (Get-Variable MyInvocation -Scope 1).Value throw (new-object System.Management.Automation.ArgumentTransformationMetadataException "$($Invocation.MyCommand).$($MyInvocation.MyCommand) : Impossible de convertir la valeur « $Parameter » en type « $($Type.ToString()) ».") } } return $True } #ValidateParameter write-Debug "[Valeurs des paramètres]" write-Debug "Sequence_Name $Sequence_Name" write-Debug "Comment $Comment" write-Debug "Increment_By $Increment_By" write-Debug "MaxValue $MaxValue" write-Debug "MinValue $MinValue" write-Debug "Start_With $Start_With" write-Debug "Cycle $Cycle" if (($Sequence_Name -eq $null) -or ($Sequence_Name -eq [String]::Empty)) {Throw "Nom de séquence invalide. La valeur de Sequence_Name doit être renseignée."} write-Debug "Test isTypeEqual terminé." if ( (!(ValidateParameter "Increment_By" $Increment_By System.Int32) ) -and ($Increment_By -eq 0) ) {Throw "La valeur de Increment_By doit être un entier différent de zéro."} # Valeur par défaut # Si on ne spécifie aucun paramètre alors on crée une séquence ascendante qui débute à 1 # est incrémentée de 1 sans limite de valeur supérieure (autre que celle du type utilisé) #Si on spécifie seulement -Increment_By -1 on crée une séquence descendante qui débute à -1 # est décrémentée de -1 sans limite de valeur inférieure (autre que celle du type utilisé) write-Debug "" write-Debug "Les valeurs par défaut pour la séquence de type sont :" #Ici si $Increment_By n'est pas renseigné il vaut par défaut 1, on ne peut donc avoir 0 comme valeur renvoyée par la méthode Sign $local:Signe=[System.Math]::Sign($Increment_By) write-Debug "`tIncrement_By $Increment_By" write-Debug "`tSigne $Signe (1= positif -1= négatif)" if ( ($Signe -eq 1) -and #test si les paramètres sont à $null (!(ValidateParameter "Start_With" $Start_With System.Int32)) -and (!(ValidateParameter "MaxValue" $MaxValue System.Int32)) -and (!(ValidateParameter "MinValue" $MinValue System.Int32)) ) { write-Debug "`tSéquence ascendante. Valeur par défaut." $Start_With=1 $MaxValue=[int]::MaxValue $MinValue=1 } elseif ( ($Signe -eq -1) -and (!(ValidateParameter "Start_With" $Start_With System.Int32)) -and (!(ValidateParameter "MaxValue" $MaxValue System.Int32)) -and (!(ValidateParameter "MinValue" $MinValue System.Int32)) ) { write-Debug "`tSéquence descendante. Valeur par défaut." $Start_With=-1 $MaxValue=-1 $MinValue=[int]::MinValue } else { write-Debug "`t* Pas de valeur par défaut. *" # Si MaxValue n'est pas spécifié on indique la valeur maximum pour une séquence ascendante # sinon 1 pour une séquence descendante if (!(ValidateParameter "MaxValue" $MaxValue System.Int32)) { $MaxValue=[int]::MaxValue if ($local:Signe -eq -1) {$MaxValue=-1 } } # Si MinValue n'est pas spécifié on indique la valeur 1 pour une séquence ascendante # sinon la valeur minimum pour une séquence descendante if (!(ValidateParameter "MinValue" $MinValue System.Int32)) { $MinValue=1 if ($Signe -eq -1) {$MinValue=[int]::MinValue } } # Si Start_With n'est pas spécifié on indique, pour une séquence ascendante, la valeur minimum de la séquence # ou pour une séquence descendante la valeur maximum de la séquence. if (!(ValidateParameter "Start_With" $Start_With System.Int32)) { switch ($local:Signe) { 1 {$Start_With=$MinValue} -1 {$Start_With=$MaxValue} }#switch }#If }#else write-Debug "Start_With $Start_With" write-Debug "MaxValue $MaxValue" write-Debug "MinValue $MinValue" if (!(ValidateParameter "Increment_By" $Increment_By System.Int32)) { if ($Cycle.Ispresent) { #Dans ce cas selon le signe du paramètre $Increment_By on doit préciser soit Minvalue soit MaxValue switch ($local:Signe) { 1 { if (!(ValidateParameter "MinValue" $MinValue System.Int32)) { Throw "Séquence ascendante cyclique pour laquelle vous devez spécifier MinValue."} } -1 { if (!(ValidateParameter "MaxValue" $MaxValue System.Int32)) { Throw "Séquence descendante cyclique pour laquelle vous devez spécifier MaxValue."} } default { Throw "Analyse erronée!"} }#switch }#if cycle }#if increment write-Debug "Test de la variable Cycle terminé." write-Debug "[Test de validité de la séquence]" # MINVALUE must be less than or equal to START WITH and must be less than MAXVALUE. if (!($MinValue -le $Start_With )) { Throw "Start_With($Start_With) ne peut pas être inférieur à MinValue($MinValue)."} elseif (!($MinValue -lt $MaxValue)) { Throw "MinValue($MinValue) doit être inférieure à MaxValue($MaxValue)."} # MAXVALUE must be equal to or greater than START WITH and must be greater than MINVALUE. if (!($MaxValue -ge $Start_With)) { Throw "Start_With($Start_With) ne peut pas être supérieur à MaxValue($MaxValue)."} elseif (!($MaxValue -gt $MinValue)) { Throw "MaxValue($MaxValue) doit être supérieure à MinValue($MinValue)."} #On test s'il est possible d'itérer au moins une fois. #La construction suivant est valide mais pour un seul chiffre : # $Sq=Create-Sequence $N $C -inc 1 -min 0 -max 5 -start 5 # $Sq=Create-Sequence $N $C -inc -1 -min 0 -max 2 -start 0 #Start_with n'est pas pris en compte dans ce calcul, on autorise donc un séquence proposant un seul nombre. #Si dans ce cas on précise le switch -Cycle on a bien plusieurs itérations : # $Sq=Create-Sequence $N $C -inc 1 -min 0 -max 5 -start 5 -cycle #On cast $Increment_By car sa valeur peut être égale à [int]::MinValue, d'où une exception lors de l'appel à Abs # La documentation Oracle précise l'opérateur -lt mais dans ce cas la séquence suivante est impossible : # Create-Sequence $N $C -min 1 -max 2 if (!([system.Math]::Abs([Long]$Increment_By) -le ($MaxValue-$MinValue)) ) { Throw "Increment_By($Increment_By) doit être inférieur ou égale à MaxValue($MaxValue) moins MinValue($MinValue)."} #Création de la séquence $Sequence= new-object System.Management.Automation.PsObject # Ajout des propriétés en R/O, le code est créé dynamiquement $MakeReadOnlyMember=@" `$Sequence | add-member ScriptProperty Name -value {"$Sequence_Name"} -Passthru|` add-member ScriptProperty Comment -value {"$Comment"} -Passthru|` add-member ScriptProperty Increment_By -value {[int]$Increment_By} -Passthru|` add-member ScriptProperty MaxValue -value {[int]$MaxValue} -Passthru|` add-member ScriptProperty MinValue -value {[int]$MinValue} -Passthru|` add-member ScriptProperty Start_With -value {[int]$Start_With} -Passthru|` add-member ScriptProperty Cycle -value {`$$Cycle} -Passthru|` add-member ScriptProperty CurrVal -value {[int]$Start_With} "@ Invoke-Expression $MakeReadOnlyMember #La méthode NextVal renvoie en fin de traitement la valeur courante du membre Currval $Sequence | add-member ScriptMethod NextVal { $NewValue=$this.CurrVal + $this.Increment_By write-debug "this $this" write-debug "NewValue $NewValue" #Déclaration paramétrée pour la redéfinition du membre CurrVal #Le paramètre -Force annule et remplace la définition du membre spécifié $RazMember="`$this | add-member -Force ScriptProperty CurrVal -value {0}" switch ([System.Math]::Sign($this.Increment_By)) { #MAXVALUE cannot be made to be less than the current value 1 { if ($NewValue -gt $this.MaxValue) { write-debug "Borne maximum atteinte." if ($this.Cycle -eq $true) #Dans ce cas on recommence { #On construit (par formatage) la définition du membre CurrVal #puis on reconstruit le membre. Invoke-Expression ($RazMember -F "{[int]$this.MinValue}") } else {Throw "La séquence $($this.Name).Nextval a atteint la valeur maximum autorisée."} } else { Invoke-Expression ($RazMember -F "{[int]$NewValue}")} }#Séquence ascendante #MINVALUE cannot be made to exceed the current value -1 { if ($NewValue -lt $this.MinValue) { write-debug "Borne minimum atteinte." if ($this.Cycle -eq $true) {Invoke-Expression ($RazMember -F "{[int]$this.MaxValue}") } else {Throw "La séquence $($this.Name).Nextval a atteint la valeur minimum autorisée."} } else {Invoke-Expression ($RazMember -F "{[int]$NewValue}") } }#Séquence descendante else {Throw "Erreur dans la méthode Nextval."} }#switch #Renvoi la nouvelle valeur $this.CurrVal write-debug "this $this" } write-Debug "[Valeurs de la séquence]" write-Debug "Sequence_Name $Sequence_Name" write-Debug "Comment $Comment" write-Debug "Increment_By $Increment_By" write-Debug "MaxValue $MaxValue" write-Debug "MinValue $MinValue" write-Debug "Start_With $Start_With" write-Debug "Cycle $Cycle" write-Debug "Current $Current" write-Debug "----" write-Debug $Sequence #Spécifie l'affichage des propriétés par défaut #On évite ainsi l'usage d'un fichier de type .ps1xml #From http://poshoholic.com/2008/07/05/essential-powershell-define-default-properties-for-custom-objects/ $DefaultProperties =@( 'Name', 'CurrVal', 'Increment_By', 'MaxValue', 'MinValue', 'Start_With', 'Cycle', 'Comment') $DefaultPropertySet=New System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$DefaultProperties) $PSStandardMembers=[System.Management.Automation.PSMemberInfo[]]@($DefaultPropertySet) $Sequence|Add-Member MemberSet PSStandardMembers $PSStandardMembers return $Sequence } # Examples : # # Valeur pas défaut # #Séquence ascendante # $Sq=Create-Sequence "SEQ_Test" # $Sq=Create-Sequence "SEQ_Test" "" # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" -cycle # #Valeur pas défaut d'une séquence ascendante # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" -min 1 -max ([int32]::MaxValue) -inc 1 -start 1 # #Valeur pas défaut d'une séquence descendante # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" -min ([int32]::MinValue) -max -1 -inc -1 -start -1 # # #Incrément de 2 # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" -inc 2 # #Incrément négatif # $Sq=Create-Sequence "SEQ_Test" "Séquence de test" -inc -1 # # # $N="SEQ_Test" # $C="Séquence de test" # # #Suite ascendante maximum, de [int32]::MinValue à [int32]::MaxValue débutant à [int32]::MinValue # $Sq=Create-Sequence $N $C -min ([int32]::MinValue+1) -start ([int32]::MinValue+1) # #Suite descendante maximum, de [int32]::MinValue à [int32]::MaxValue débutant à [int32]::MaxValue # $Sq=Create-Sequence $N $C -min ([int32]::MinValue+1) -max ([int32]::MaxValue) -start ([int32]::MaxValue) -inc -1 # # #suite ascendante débutant à 0 et finissant à 255 # $Sq=Create-Sequence $N $C -min 0 -max 255 # # # #Valeur minimum # #suite ascendante de 2 nombres # $Sq=Create-Sequence $N $C -minvalue 0 -maxvalue 1 # #suite descendante de 2 nombres # $Sq=Create-Sequence $N $C -minvalue 0 -maxvalue 1 -inc -1 # #suite de 2 nombres positifs avec un pas de 2 # $sq=Create-Sequence $N $C -min 1 -max 3 -inc 2 # # #"suite" de 1 nombre : 2 # $sq=Create-Sequence $N $C -min 1 -max 2 -start 2 # #"suite" de 1 nombre : 5 # $Sq=Create-Sequence $N $C -min 0 -max 5 -inc 1 -start 5 # #"suite" de 1 nombre : 0 # $Sq=Create-Sequence $N $C -min 0 -max 2 -inc -1 -start 0 # # #suite cyclique ascendante débutant à 2, ensuite chaque cycle débutera à 1, c'est à dire la valeur de MinValue # $sq=Create-Sequence $N $C -min 1 -max 2 -start 2 -cycle # #suite cyclique ascendante débutant à 5, ensuite chaque cycle débutera à 0 # $Sq=Create-Sequence $N $C -min 0 -max 5 -inc 1 -start 5 -cycle # #suite cyclique descendante débutant à 0, ensuite chaque cycle débutera aussi à 0 # $Sq=Create-Sequence $N $C -min 0 -max 2 -inc -1 -start 0 -cycle # # #MaxValue à 0, pour une suite descendante uniquement # $Sq=Create-Sequence $N $C -maxvalue 0 -inc -1 # # #suite descendante débutant à -1 jusqu'à [int32]::MinValue # $Sq=Create-Sequence $N $C -maxvalue -1 -inc -1 # #suite ascendante négative débutant [int32]::MinValue jusqu'à -1 # $Sq=Create-Sequence $N $C -min -2147483648 -max -1 -inc 1 -start -2147483648
PowerShellCorpus/PoshCode/SqlProxy.psm1.ps1
SqlProxy.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname, [Parameter(Position=2, Mandatory=$false)] [switch]$force ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } elseif ($force) { $server.Databases | where {$_.IsAccessible -eq $true} } #Skip systems databases else { $server.Databases | where {$_.IsSystemObject -eq $false -and $_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Gets an SMO Login object. .DESCRIPTION The Get-SqlLogin function gets a collection of SMO Login objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlLogin .OUTPUTS Microsoft.SqlServer.Management.Smo.Login Get-SqlLogin returns a Microsoft.SqlServer.Management.Smo.Login object. .EXAMPLE Get-SqlLogin "Z002\\sql2K8" This command gets a collection of SMO Login objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlLogin #> function Get-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlLogin $($server.Name)" foreach ($login in $server.Logins | where {$_.LoginType.ToString() -ne 'Certificate'}) { #Return Login Object $login } } # Get-SqlLogin ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase if ($logintype -eq 'SqlLogin') { $login.LoginType = $logintype if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } try { $login.Create($password) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } elseif ($logintype -eq 'WindowsUser' -or $logintype -eq 'WindowsGroup') { $login.LoginType = $logintype try { $login.Create() $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | % {"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Drop() $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.ChangePassword($password,$true,$false) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Rename("$newName") $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login if ($db.parent.Information.Version.Major -ne '8') { $user.DefaultSchema = $defaultschema } try { $user.Create() $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" $user = $database.Users[$name] try { if ($user) { $user.Drop() $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "User $name does not exist in database $($database.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Gets an SMO ServerRole object. .DESCRIPTION The Get-SqlServerRole function gets a collection of SMO ServerRole objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServerRole .OUTPUTS Microsoft.SqlServer.Management.Smo.ServerRole Get-SqlServerRole returns a Microsoft.SqlServer.Management.Smo.ServerRole object. .EXAMPLE Get-SqlServerRole "Z002\\sql2K8" This command gets a collection of SMO ServerRole objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlServerRole #> function Get-SqlServerRole { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlServerRole:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlServerRole $($server.Name)" foreach ($svrole in $server.Roles) { #Return ServerRole Object $svrole } } #Get-SqlServerRole ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.AddMember($loginame) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.DropMember($loginame) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Returns a SMO DatabaseRole object with additional properties. .DESCRIPTION The Get-SqlDatabaseRole function gets a collection of SMO DatabaseRole objects for the specified SQL Database. .INPUTS Microsoft.SqlServer.Management.Smo.Database You can pipe database objects to Get-SqlDatabaseRole .OUTPUTS Microsoft.SqlServer.Management.Smo.DatabaseRole Get-SqlDatabaseRole returns a Microsoft.SqlServer.Management.Smo.DatabaseRole object. .EXAMPLE Get-SqlDatabaseRole $(Get-SqlDatabase "Z002\\sql2K8" pubs) This command gets a collection of SMO DatabaseRole objects for SQL Server Z002\\SQL2K8, pubs database. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" | Get-SqlDatabaseRole This command gets a collection SMO DatabaseRole objects for all SQL databases on the SQL Server Z002\\SQL2K8. .LINK Get-SqlDatabaseRole #> function Get-SqlDatabaseRole { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [Microsoft.SqlServer.Management.Smo.Database]$database ) process { foreach ($role in $database.Roles) { #Return DatabaseRole Object $role } } } #Get-SqlDatabaseRole ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.AddMember($name) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.DropMember($name) $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $ex = $_.Exception $message = $ex.message $ex = $ex.InnerException while ($ex.InnerException) { $message += "`n$ex.InnerException.message" $ex = $ex.InnerException } $message = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog
PowerShellCorpus/PoshCode/McAfeeAPI_01Connect.ps1
McAfeeAPI_01Connect.ps1
#region << ePO Connection and Initialization >> function McAfee-Connect{ param([String]$script:ServerURL="SERVERNAME:8443") $c = McAfee-Credential $script:wc = McAfee-WebClient -Credential $c } function McAfee-Credential{ $c = Get-Credential -Credential $null return $c } function McAfee-WebClient{ param($Credential) $wc = new-object system.net.webclient $wc.credentials = New-Object System.Net.NetworkCredential -ArgumentList ($Credential.GetNetworkCredential().username,$Credential.GetNetworkCredential().password) return $wc } #endregion
PowerShellCorpus/PoshCode/Get-Scope_2.ps1
Get-Scope_2.ps1
function Get-Scope{ $rtnScope = 0 $global:scope = $false $scope = $true while($($ErrorActionPreference = "silentlycontinue"; switch((get-Variable -Name scope -Scope $rtnScope).value){$null{$true} $true{$true} $false{$ErrorActionPreference = "continue"; return ($rtnScope - 1)}})){ $rtnScope++ } } <#Example. function gg{ Get-Scope }; function iii{ gg }; iii ==> result is 2#>
PowerShellCorpus/PoshCode/set-ipconfigv6.ps1
set-ipconfigv6.ps1
# script parameters param( [Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)] [alias("Name","ComputerName")][string[]]$Computers = @($env:computername), $Domain = "domain.local", $DNSSuffix = @("domain.local,sub.domain.local,domain.com"), $DNSServers = @("10.10.0.1", "10.10.0.2", "10.10.0.3", "10.10.0.4"), $WINSServers = @("10.10.0.5", "10.10.0.6"), $Gateway = @("10.10.255.254"), [switch] $ChangeSettings, [switch] $EnableDHCP, [switch] $IpRelease, [switch] $BatchReport ) process{ foreach ($Computer in $Computers){ If (Test-connection $Computer -quiet -count 1 -EA stop){ Try { [array]$NICs = (Get-WMIObject -Class Win32_NetworkAdapterConfiguration -Computername $Computer -Filter "IPEnabled = TRUE" -EA Stop) } Catch { Write-Warning "$($error[0])" Write-Output "$("INACCESSIBLE: ")$($nl)$($Computer)" Write-Host $nl continue } # Generate selection menu $NICindex = $NICs.count Write-Host "$nl Selection for $($Computer) : $nl" For ($i=0;$i -lt $NICindex; $i++) { Write-Host -ForegroundColor Green "$i --> $($NICs[$i].Description)" Write-Output $(ShowDetails $NICs[$i] $Computer) } $nl # if reporting only then skip menu + processing code if ($BatchReport){continue} Write-Host -ForegroundColor Green "q --> Quit" $nl # Wait for user selection input Do { $SelectIndex = Read-Host "Select connection by number or 'q' (=default) to quit" Switch -regex ($SelectIndex){ "^q.*" {$SelectIndex="quit"; $kip = $true} "\\d" {$SelectIndex = $SelectIndex -as [int];$kip = $false} "^\\s*$" {$SelectIndex="quit"; $kip = $true} } } Until (($SelectIndex -lt $NICindex) -OR $SelectIndex -like "q*") $nl Write-Host "You selected: $SelectIndex" $nl #skip current $computer if $true If ($kip) {continue} Else {ProcessNIC $NICs[$SelectIndex] $Computer} } else { Write-warning "$Computer cannot be reached" } } } begin{ # script variables $nl = [Environment]::NewLine # script functions Function ProcessNIC($NIC, $Computer){ # Change settings for selected network card if option is true and show updated values If ($ChangeSettings){ If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){ Write-Warning "You need Administrator rights to run this script!" Break } If ($IpRelease){ #$NIC.ReleaseDHCPLease $NIC.RenewDHCPLease } Else{ ChangeIPConfig $NIC $Computer } start-sleep -s 2 Write-Host $nl " ====NEW SETTINGS====" $nl $UpdatedNIC = Get-WMIObject -Class Win32_NetworkAdapterConfiguration -Computername $Computer -Filter "Index=$($NIC.Index)" Write-Output $(ShowDetails $UpdatedNIC $Computer)$($nl) } Else{ $nl Write-Warning "For changing settings add -ChangeSettings as parameter, if not this script is output only" $nl } } Function ChangeIPConfig($NIC, $Computer){ if ($EnableDHCP){ $NIC.EnableDHCP() $NIC.SetDNSServerSearchOrder() } else{ $DNSServers = Get-random $DNSservers -Count $DNSServers.Length $NIC.SetDNSServerSearchOrder($DNSServers) | Out-Null #$x = 0 #$IPaddress = @() #$NetMask = @() #$Gateway = @() #$Metric = @() #foreach ($IP in $NIC.IPAddress){ #$IPaddress[$x] = $NIC.IPAddress[$x] #$NetMask[$x] = $NIC.IPSubnet[$x] #$Gateway[$x] = $NIC.DefaultIPGateway[$x] #$Metric[$x] = $NIC.GatewayCostMetric[$x] #$x++ #} #$NIC.EnableStatic($IPaddress, $NetMask) #$NIC.SetGateways($Gateway, $Metric) #$NIC.SetWINSServer($WINSServers) } $NIC.SetDynamicDNSRegistration("TRUE") | Out-Null $NIC.SetDNSDomain("") | Out-Null # remote WMI registry method for updating DNS Suffix SearchOrder $registry = [WMIClass]"\\\\$computer\\root\\default:StdRegProv" $HKLM = [UInt32] "0x80000002" $registry.SetStringValue($HKLM, "SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters", "SearchList", $DNSSuffix) | Out-Null } Function ShowDetails($NIC, $Computer){ Write-Output "$($nl)$(" IP settings on: ")$($Computer)$($nl)$($nl)$(" for") $($NIC.Description)$(":")$($nl)" Write-Output "$("Hostname = ")$($NIC.DNSHostName)" Write-Output "$("DNSDomain= ")$($NIC.DNSDomain)" Write-Output "$("Domain DNS Registration Enabled = ")$($NIC.DomainDNSRegistrationEnabled)" Write-Output "$("Full DNS Registration Enabled = ")$($NIC.FullDNSRegistrationEnabled)" Write-Output "$("DNS Domain Suffix Search Order = ")$($NIC.DNSDomainSuffixSearchOrder)" Write-Output "$("MAC address = ")$($NIC.MACAddress)" Write-Output "$("DHCP enabled = ")$($NIC.DHCPEnabled)" # show all IP adresses on this NIC $x = 0 foreach ($IP in $NIC.IPAddress){ Write-Output "$("IP address $x =")$($NIC.IPAddress[$x])$("/")$($NIC.IPSubnet[$x])" $x++ } Write-Output "$("Default IP Gateway = ")$($NIC.DefaultIPGateway)" Write-Output "$("DNS Server Search Order = ")$($NIC.DNSServerSearchOrder)" } }
PowerShellCorpus/PoshCode/Get-NestedGroups.ps1
Get-NestedGroups.ps1
<# .SYNOPSIS Enumerate all AD group memberships of an account (including nested membership). .DESCRIPTION This script will return all the AD groups an account is member of. .PARAMETER UserName The username whose group membershipts to find. .EXAMPLE .\\Get-NestedGroups.ps1 'johndoe' Name DistinguishedName ---- ----------------- Domain Users CN=Domain Users,CN=Users,DC=contoso,DC=com Finance CN=Finance,OU=Department,OU=Groups,DC=contos... .NOTES ScriptName : Get-NestedGroups Created By : Gilbert van Griensven Date Coded : 06/17/2012 The script iterates through all nested groups and skips circular nested groups. .LINK #> Param ( [Parameter(Mandatory=$true)]$UserName ) Begin { Function LoadADModule { If (!(Get-Module ActiveDirectory)) { If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) { Import-Module ActiveDirectory Return $True } Else { Return $False } } Else { Return $True } } Function GetNestedGroups ($strGroupDN) { $currentGroupmemberships = (Get-ADGroup $strGroupDN –Properties MemberOf | Select-Object MemberOf).MemberOf foreach ($groupDN in $currentGroupmemberships) { if (!(($Script:UserGroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains $groupDN)) { $arrProps = @{ Name = (Get-ADGroup $groupDN).Name DistinguishedName = $groupDN } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups $groupDN } } } Function FindGroupMembership ($strUsername) { $Script:UserGroupMembership = @() $arrProps = @{ Name = "Domain Users" DistinguishedName = (Get-ADGroup "Domain Users").DistinguishedName } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups (Get-ADGroup "Domain Users").DistinguishedName $directMembershipGroups = (Get-ADUser $strUsername –Properties MemberOf | Select-Object MemberOf).MemberOf foreach ($groupDN in $directMembershipGroups) { $arrProps = @{ Name = (Get-ADGroup $groupDN).Name DistinguishedName = $groupDN } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups $groupDN } } } Process { If (!(LoadADModule)) { Write-Host "Could not load module ActiveDirectory!" Return } If ($UserName) { FindGroupMembership $UserName Return $Script:UserGroupMembership } } End { Remove-Module ActiveDirectory -ErrorAction SilentlyContinue }
PowerShellCorpus/PoshCode/Restore-Database.ps1
Restore-Database.ps1
param($sqlserver, $filepath) #Note: Uses Changeset 59378 or higher of SQLPSX SQLServer module http://sqlpsx.codeplex.com/SourceControl/changeset/view/58378#564810 #Added FileListOnly option to Invoke-SqlRestore. The option will be included in releases after 2.3.1 import-module sqlserver -force $server = get-sqlserver $sqlserver $filepath = Resolve-Path $filepath | select -ExpandProperty Path $dbname = Get-ChildItem $filePath | select -ExpandProperty basename $dataPath = Get-SqlDefaultDir -sqlserver $server -dirtype Data $logPath = Get-SqlDefaultDir -sqlserver $server -dirtype Log $relocateFiles = @{} Invoke-SqlRestore -sqlserver $server -filepath $filepath -fileListOnly | foreach { ` if ($_.Type -eq 'L') { $physicalName = "$logPath\\{0}" -f [system.io.path]::GetFileName("$($_.PhysicalName)") } else { $physicalName = "$dataPath\\{0}" -f [system.io.path]::GetFileName("$($_.PhysicalName)") } $relocateFiles.Add("$($_.LogicalName)", "$physicalName") } $server.KillAllProcesses($dbname) Invoke-SqlRestore -sqlserver $server -dbname $dbname -filepath $filepath -relocatefiles $relocateFiles -Verbose -force
PowerShellCorpus/PoshCode/Findup_21.ps1
Findup_21.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"-x", new List<string>()},{"-i",new List<string>()},{"-xf",new List<string>()},{"-if",new List<string>()}, {"-xd",new List<string>()},{"-id",new List<string>()},{"-paths",new List<string>()} }; public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>> { {"-xr", new List<Regex>()},{"-ir",new List<Regex>()},{"-xfr",new List<Regex>()},{"-ifr",new List<Regex>()}, {"-xdr",new List<Regex>()},{"-idr",new List<Regex>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-noerr", false }, {"-delete",false} }; public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files foumd, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes. public static string delconfirm; public static void Main(string[] args) { DateTime startTime = DateTime.Now; Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files."); Console.WriteLine(" "); string optionskey = "-paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem=args[i].ToLower(); if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help message."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -delete - delete each duplicate file with confirmation."); Console.WriteLine(" -x - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used."); Console.WriteLine(" -i - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used."); Console.WriteLine(" -xd - eXcludes all directories (using RegEx if -xdr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories (using RegEx if -idr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files (using RegEx if -xfr) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files (using RegEx if -ifr) following this switch until another switch is used."); Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr."); Console.WriteLine(" -paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -xr \\"(jim)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc -xr \\"[bf]\\" -ir \\"(smith)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); Console.WriteLine(" -xdr,-idr,-xfr,-ifr are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa."); Console.WriteLine(" if for instance you wanted all files that contained the letter \\"d\\" on your D: drive but didn't want the d:\\\\ to cause all files on the d:\\\\ "); Console.WriteLine(" drive to be included, you would specify:"); Console.WriteLine(" findup.exe d:\\\\ -recurse -noerr -regex -ifr \\"[d]\\" "); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionskey = "-paths"; continue; } if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem)) { optionskey = argitem; continue; } if (optionspaths.ContainsKey(optionskey)) optionspaths[optionskey].Add(argitem); else { try { Regex rgx = new Regex(argitem, RegexOptions.Compiled); optionsregex[optionskey].Add(rgx); } catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);} } } if (optionspaths["-paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory."); optionspaths["-paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashName = new Dictionary<long, Dictionary<string,List<FileInfo>>>(); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) { continue; } var breakout = false; while (true) { try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } string SHA512string = ""; foreach (var c in _SHA512.Hash) { SHA512string += String.Format("{0:x2}", c); } if (!SizeHashName.ContainsKey(files[i].Length)) SizeHashName.Add(files[i].Length, new Dictionary<string,List<FileInfo>>()); if (!SizeHashName[files[i].Length].ContainsKey(SHA512string)) SizeHashName[files[i].Length][SHA512string] = new List<FileInfo>() {}; SizeHashName[files[i].Length][SHA512string].Add(files[i]); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } } Console.WriteLine("Completed!"); foreach (var SizeGroup in SizeHashName) { foreach (var HashGroup in SizeGroup.Value) { var SGK = (long)SizeGroup.Key; var HGVC = (int)HashGroup.Value.Count; if (HGVC > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK*HGVC); foreach (var Filenfo in HashGroup.Value) { Console.WriteLine(Filenfo.FullName); numOfDupes++; dupeBytes += Filenfo.Length; if (optionsbools["-delete"]) if (DeleteDupe(Filenfo)) { bytesrecovered += Filenfo.Length; } } } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS. Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); Console.WriteLine("Execution time : " + (DateTime.Now - startTime)); } private static void WriteErr(string Str) { if (!optionsbools["-noerr"]) Console.WriteLine(Str); } private static Boolean DeleteDupe(FileInfo Filenfo) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { Filenfo.Delete(); Console.WriteLine("File Successfully deleted."); deletedfiles++; return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckNames(string fullname) { var filePart = Path.GetFileName(fullname); var dirPart = Path.GetDirectoryName(fullname); if (CheckNamesWorker(fullname,"-x")) return false; if (CheckNamesWorker(filePart,"-xf")) return false; if (CheckNamesWorker(dirPart,"-xd")) return false; if (!CheckNamesWorker(fullname,"-i")) return false; if (!CheckNamesWorker(filePart,"-if")) return false; if (!CheckNamesWorker(dirPart,"-id")) return false; return true; } private static Boolean CheckNamesWorker(string filestr, string key) { foreach (var filepath in optionspaths[key]) { if (filestr.ToLower().StartsWith(filepath)) return true; } foreach (var rgx in optionsregex[key+"r"]) { if (rgx.IsMatch(filestr)) return true; } return (key[1] == 'i' && optionspaths[key].Count == 0 && optionsregex[key + "r"].Count == 0); // If checking [i]ncludes, return true if 0 paths/regex to check, else false } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Parse-ApacheRedirects.ps1
Parse-ApacheRedirects.ps1
<# .SYNOPSIS Parses an Apache redirect file to identify broken entries. .DESCRIPTION All redirects will be followed and the final response code will be processed as follows: 200 - OK 401 - OK 403 - Broken 404 - Broken *** - Optionally remove with -RemoveUnknownErrors switch Only Errors are written to the screen which include 403, 404, and unknown errors. If more verbosity is desired set the $VerbosePreference variable as follows: $VerbosePreference = 'Continue' Written for a Windows 8 system and hasn't been tested on anything else. .PARAMETER RedirectFile Location of the Apache redirect file. .PARAMETER WebsiteDomain Domain name of the website that uses the redirect file. .PARAMETER CreateNewFile Will create a new redirect file by appending ".Broken_Removed" to the file name. Entries which no longer work will be commented out with "### BROKEN ###" Unknown Errors will NOT be removed unless the -RemoveUnknownErrors switch is used. .PARAMETER RemoveUnknownErrors Can only be used if creating a new redirect file as it will comment out Unknown Errors .EXAMPLE PS D:\\> .\\Parse-ApacheRedirects.ps1 -RedirectFile D:\\redirects.conf -WebsiteDomain website.domain.com -CreateNewFile -RemoveUnknownErrors Line 2: ERROR Redirect 301 /somefile http://website.domain.com/newlocation.html Line 3: ERROR Redirect 301 /anotherfile https://website2.domain.com/ Line 18: UNKNWN_ERROR: Redirect 301 /foo http://nothing.domain.com/ Line 18: SVR_RSPND:System.Net.WebException: The remote name could not be resolved: 'nothing.domain.com' Line 18: Removing_From_New_Conf New file available here: D:\\redirects.conf.Broken_Removed Finished .NOTES As mentioned in the Description, setting $VerbosePreference='Continue' will enable all Write-Verbose commands in the script. **This script was written on a Windows 8 system and hasn't been tested on anything else.** #> Param( [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][ValidateScript({Test-Path $_})][string]$RedirectFile, [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][ValidateScript({Resolve-DnsName $_})][string]$WebsiteDomain, [switch]$CreateNewFile, [switch]$RemoveUnknownErrors ) Function Invoke-ResourceRequest($Uri,[switch]$ReturnSC){ $RequestedWebsite = "$WebsiteDomain$Uri" try{ $Response = Invoke-WebRequest -Uri $RequestedWebsite if($Response.StatusCode -eq 200){ if($ReturnSC){ Return 200 } else{ Return 0 } } else{ Return 1 } } Catch { [string]$eResponse = $_.Exception.ToString().split("`n")[0] if($ReturnSC){ Return $eResponse } else{ # allowing 401 and marking 403 & 404 as failed if($eResponse.Contains("(404) Not Found")){ Return 1 } elseif($eResponse.Contains("(403) Forbidden")){ Return 1 } elseif($eResponse.Contains("(401) Unauthorized")){ Return 0 } # all other errors will issue another request to parse error else{ Return 2 } } } } # End Invoke-ResourceRequest Function Function Parse-Uri([string]$LineObject,[int]$LineNumber){ if($LineObject.Contains("`"")){ #Handle line with space(s) $quotes = $LineObject.split("`"").Count if($quotes -eq 3){ #Only one set quoted if($LineObject.IndexOf("`"") -gt 13){ Write-Verbose "Line $LineNumber`: Destination_Url_Quoted " Return $LineObject.Split(" ")[2] } else{ Write-Verbose "Line $LineNumber`: Uri_Quoted " Return $LineObject.Split("`"")[1] } } elseif($quotes -eq 5){ Write-Verbose "Line $LineNumber`: Uri_and_Destination_Url_Quoted " Return $LineObject.Split("`"")[1] } else{ Write-Host "Line $LineNumber`: QUOTE_ERROR_REMOVE_RULE" -ForegroundColor Cyan Write-Verbose "Line $LineNumber`: Should_Only_Have_2_or_4_Quotes" Return "" } } else{ Write-Verbose "Line $LineNumber`: Normal " Return $LineObject.Split(" ")[2] } } # End Parse-Uri Function # Process input parameters $RedirectContent = Get-Content -Path $RedirectFile if($CreateNewFile){ $NewFile = (Get-Item -Path $RedirectFile).FullName+".Broken_Removed" if(Test-Path -Path $NewFile){ if((Read-Host "New conf file exists. Overwrite? [y/n]").ToLower() -eq "y"){ Clear-Content -Path $NewFile } else { Write-Host "`n`tRename $NewFile and launch script again or choose `"y`" to overwrite.`n" Exit } } } if((!($CreateNewFile)) -and ($RemoveUnknownErrors)){ Write-Host "`n`tMust include the `"CreateNewFile`" switch if removing unknown errors.`n`tExiting script.`n" -ForegroundColor Red Exit } #Start main logic $i=1 foreach($line in $RedirectContent){ [string]$RequestUri = "" [int]$Check = 0 if($line.StartsWith("#")){ Write-Verbose "Line $i`: Comment" } else{ if($line.Contains("Redirect")){ if($line.Substring(9,1) -eq "3"){ $RequestUri = Parse-Uri -LineObject $line -LineNumber $i } else{ # Need ficticious redirect number for parsing $RequestUri = Parse-Uri -LineObject $line.tolower().Replace("redirect ","redirect 000 ") -LineNumber $i } if($RequestUri -eq ""){ $Check = 1 } } elseif($line.Length -le 3){ Write-Verbose "Line $i`: Empty" } else{ Write-Verbose "Line $i`: NOT_REDIRECT_OR_EMPTY $line" Write-Verbose "Line $i`: Rule_Was_NOT_Removed " } } if($RequestUri){ Write-Verbose "Line $i`: Uri_found_making_request" $Check = Invoke-ResourceRequest -Uri $RequestUri } if($Check -eq 2){ Write-Verbose "Line $i`: Destination_Returned_an_Error " Write-Verbose "Line $i`: Making_another_request_to_parse_response " $ResponseCode = Invoke-ResourceRequest -Uri $RequestUri -ReturnSC Write-Host "Line $i`: UNKNWN_ERROR`: $line" -ForegroundColor Magenta Write-Host "Line $i`: SVR_RSPND`:$ResponseCode" -ForegroundColor Magenta if($RemoveUnknownErrors -and $CreateNewFile){ Write-Host "Line $i`: Removing_From_New_Conf " -ForegroundColor Magenta $Check = 2 } else{ $Check = $0 } } if($Check -eq 1){ Write-Host "Line $i`: ERROR $line" -ForegroundColor Red } if($NewFile -ne $null){ if($Check -eq 0){ Out-File -FilePath $NewFile -InputObject $line -Append -Encoding ascii } else{ Out-File -FilePath $NewFile -InputObject "### BROKEN ### $line" -Append -Encoding ascii } } $i++ } if($NewFile){ Write-Host "`nNew file available here: "$NewFile -ForegroundColor Green } Write-Host "`nFinished`n" -ForegroundColor Green Exit
PowerShellCorpus/PoshCode/Get-Exchange-Mail_2.ps1
Get-Exchange-Mail_2.ps1
[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft\\Exchange\\Web Services\\1.1\\Microsoft.Exchange.WebServices.dll") | Out-Null $s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1) $s.Credentials = New-Object Net.NetworkCredential('email@domain', 'password') $s.Url = new-object Uri("https://red001.mail.microsoftonline.com/ews/exchange.asmx") $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) $mails = $inbox.FindItems(5) $mails | % {$_.Load()} $mails
PowerShellCorpus/PoshCode/get-netstat 1.3.ps1
get-netstat 1.3.ps1
$netstat = netstat -a -n -o | where-object { $_ -match "(UDP|TCP)" } [regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)' foreach ($net in $netstat) { [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName switch -regex ($net.Trim()) { $regexTCP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = [int]$matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID -EA SilentlyContinue ).ProcessName } $regexUDP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = [int]$matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID -EA SilentlyContinue ).ProcessName } } $process }
PowerShellCorpus/PoshCode/Ring Monitor.ps1
Ring Monitor.ps1
#requires -version 2.0 Import-Module Accelerators # http://poshcode.org/762 Import-Module PowerBoots # http://boots.codeplex.com # http://dynamicdatadisplay.codeplex.com ## You have to get the DynamicDataDisplay control, and put it's DLLs in the PowerBoots folder... ls "$PowerBootsPath\\DynamicDataDisplay*.dll" | Add-BootsFunction ## This sets up all the types, and requires the accelerators and the DynamicDataDisplay.dll Add-Accelerator TimedDouble "System.Collections.Generic.KeyValuePair[DateTime,Double]" Add-Accelerator TimedDoubleRing "Microsoft.Research.DynamicDataDisplay.Common.RingArray[System.Collections.Generic.KeyValuePair[DateTime,Double]]" Add-Accelerator EnumerableDataSource "Microsoft.Research.DynamicDataDisplay.DataSources.EnumerableDataSource``1" function Add-Monitor { #.Synopsis # Create a new monitor line Param( [String]$global:Label="HuddledMasses", [ScriptBlock]$global:Script= { New-Object TimedDouble (Get-Date), ([regex]"time=(\\d+)ms").Match( (ping.exe "HuddledMasses.org" -n 1) ).Groups[1].Value }, $global:XMapping = $([System.Func[TimedDouble, Double]]{ param([TimedDouble]$value); $value.Key.TimeOfDay.TotalSeconds }), $global:YMapping = $([System.Func[TimedDouble, Double]]{ param([TimedDouble]$value); $value.Value }) ) Invoke-BootsWindow $Global:Plotter { $dataSource = New-Object "EnumerableDataSource[System.Collections.Generic.KeyValuePair[DateTime,Double]]" (New-Object TimedDoubleRing $global:RingSize) $dataSource.SetXMapping( $global:XMapping ) $dataSource.SetYMapping( $global:YMapping ) $Global:Plotter.Children.Add( ( LineGraph -Description $(New-Object Microsoft.Research.DynamicDataDisplay.PenDescription $global:Label) ` -DataSource $dataSource -Filters { InclinationFilter; FrequencyFilter } ` -LinePen (Pen -Brush (SolidColorBrush -Color $([Microsoft.Research.DynamicDataDisplay.ColorHelper]::CreateRandomHsbColor())) -Thickness 2.0) ` -Tag {$global:Script} -Name $($global:Label -replace "[^\\p{L}]") )) } } function Remove-Monitor { #.Synopsis # Remove a monitor line Param( [String]$global:Label="HuddledMasses" ) Invoke-BootsWindow $Global:Plotter { $Global:Plotter.Children.Remove( $( $Global:Plotter.Children | Where-Object { ($_ -is [Microsoft.Research.DynamicDataDisplay.LineGraph]) -and ($_.Name -eq $Label) } | Select -First 1 ) ) } } function Global:Update-Ring { #.Synopsis # Internal function for updating all the data lines foreach($graph in $Plotter.Children | ?{$_ -is [Microsoft.Research.DynamicDataDisplay.LineGraph]} ) { $graph.DataSource.Data.Add( (&$graph.Tag) ) } } Function New-RingMonitor { #.Synopsis # Creates a new Ring Monitor graph window, and sets the update interval for it Param( [TimeSpan]$global:Interval = "00:00:02", [Int]$global:RingSize = 200 ) New-BootsWindow { Param($global:w) $w.Tag = DispatcherTimer -Interval $global:Interval -On_Tick Update-Ring $w.Tag.Start() $w.Add_Closed( { $this.Tag.Stop() } ) ChartPlotter | Tee -Var Global:Plotter } -Width 800 -Height 600 -Async -Title "Ring Monitor" } #-WindowStyle None -AllowsTransparency -Background Transparent -On_MouseLeftButtonDown { $this.DragMove() } -ResizeMode CanResizeWithGrip #################################################################################################### ## Examples: Hopefully you get the idea you can graph anything you like.... #################################################################################################### # New-RingMonitor # # Add-Monitor Memory { # New-Object TimedDouble (Get-Date), (gwmi Win32_PerfFormattedData_PerfOS_Memory AvailableBytes).AvailableBytes # } # # Add-Monitor CPU { # New-Object TimedDouble (Get-Date), (gwmi Win32_PerfFormattedData_PerfOS_Processor PercentIdleTime,Name |?{$_.Name -eq "_Total"}).PercentIdleTime # } # ## Yuck. those two numbers won't work together, because they're too far apart. # ## Let's remove the first one and make it percentage based # Remove-Monitor Memory # # Add-Monitor Memory { # New-Object TimedDouble (Get-Date), ((gwmi Win32_PerfFormattedData_PerfOS_Memory AvailableBytes).AvailableBytes / (gwmi Win32_ComputerSystem TotalPhysicalMemory).TotalPhysicalMemory * 100) # } #################################################################################################### # New-RingMonitor # # Add-Monitor Twitter { # New-Object TimedDouble (Get-Date), ([regex]"time=(\\d+)ms").Match( (ping.exe "Twitter.com" -n 1) ).Groups[1].Value # }
PowerShellCorpus/PoshCode/Language.ps1
Language.ps1
## Language.ps1 includes Resolve-Language, Get-English, and Resolve-Anagram ################################################################################################### ## Some language functions, including a language guessing script using a web form ## Xerox Research Center Europe (www.xrce.xerox.com) which may not always be available, ## and the translation functions from Google Translate (google.com/translate_t). ################################################################################################### ## This script uses "ConvertFrom-Html" which is a cmdlet I wrote to parse html as xml ## I've put that cmdlet out there in several places ... #requires -pssnapin Huddled.HtmlSnapin ################################################################################################### ## @Author: Joel Bennnett ## @Usage: ## Resolve-Language "Mon tutoriel avancé sur PowerShell" ## will return "French" ## Get-English "Mon tutoriel avancé sur PowerShell" "French" ## will translate it to "My advanced tutorial on PowerShell" ## Get-English "Mi tutorial avanzado para PowerShell" ## will guess the language and then translate it ## ## Remember that this uses web sites for it's work which are NOT meant to be publically ## queryable web services, and shouldn't be abused -- the Xerox site in particular could ## be removed if they get a huge spike, because there is a commercial implementation ################################################################################################### ## Requires System.Web for UrlEncode [Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null ################################################################################################### ## Deteremine the language of a snippet of text (5 words minimum for best results) function Resolve-Language([string]$text) { return (ConvertFrom-HTML (Post-HTTP "http://www.xrce.xerox.com/cgi-bin/mltt/LanguageGuesser" ( "Text="+[System.Web.HttpUtility]::UrlEncode($text))) ).SelectSingleNode("//font")."#text".Trim() } ################################################################################################### ## Translate text to english ... ## This is obviously reworkable as a general translation tool ## But I don't have much use for that, since I only speak Spanish, English, and code function Get-English([string]$text,[string]$FromLanguage) { if(!$FromLanguage) { $FromLanguage = Resolve-Language $text } switch($FromLanguage) { "Arabic" { $text = "langpair=ar|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Chinese" { $text = "langpair=zh|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Dutch" { $text = "langpair=nl|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "French" { $text = "langpair=fr|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "German" { $text = "langpair=de|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Greek" { $text = "langpair=el|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Italian" { $text = "langpair=it|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Japanese" { $text = "langpair=ja|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Korean" { $text = "langpair=ko|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Portuguese" { $text = "langpair=pt|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Russian" { $text = "langpair=ru|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } "Spanish" { $text = "langpair=es|en&text=" + [System.Web.HttpUtility]::UrlEncode($text) } default { return "Sorry, but I can't translate $language" } } return (ConvertFrom-HTML (Post-HTTP "http://www.google.com/translate_t" $text)).SelectSingleNode("//div[@id='result_box']")."#text".Trim() } ################################################################################################### ## Silly anagram spoiler [regex]$anagram = "^Unscramble ... (.*)$" function Resolve-Anagram($anagram) { ((Post-HTTP "http://www.easypeasy.com/anagrams/results.php" "name=$anagram").Split("`n") | select-string "res 1" ) -replace ".*res 1.*value=""\\s*([^""]*)\\s*"".*",'$1' } ################################################################################################### ## Post as a web-form to do fake submissions function Post-HTTP($url,$bytes) { $request = [System.Net.WebRequest]::Create($url) # $bytes = [Text.Encoding]::UTF8.GetBytes( $bytes ) $request.ContentType = "application/x-www-form-urlencoded" $request.ContentLength = $bytes.Length $request.Method = "POST" $rq = new-object IO.StreamWriter $request.GetRequestStream() $rq.Write($bytes)#,0,$bytes.Length) $rq.Flush() $rq.Close() $response = $request.GetResponse() $reader = new-object IO.StreamReader $response.GetResponseStream(),[Text.Encoding]::UTF8 return $reader.ReadToEnd() }
PowerShellCorpus/PoshCode/PowerShell Template_6.ps1
PowerShell Template_6.ps1
Function new-script { $strName = $env:username $date = get-date -format d $name = Read-Host "Filename" $email = Read-Host "eMail Address" $file = New-Item -type file "c:\\Scripts\\$name.ps1" -force add-content $file "#==========================================================================" add-content $file "#" add-content $file "# NAME: $name.ps1" add-content $file "#" add-content $file "# AUTHOR: $strName" add-content $file "# EMAIL: $email" add-content $file "#" add-content $file "# COMMENT: " add-content $file "#" add-content $file "# You have a royalty-free right to use, modify, reproduce, and" add-content $file "# distribute this script file in any way you find useful, provided that" add-content $file "# you agree that the creator, owner above has no warranty, obligations," add-content $file "# or liability for such use." add-content $file "#" add-content $file "# VERSION HISTORY:" add-content $file "# 1.0 $date - Initial release" add-content $file "#" add-content $file "#==========================================================================" ii $file }
PowerShellCorpus/PoshCode/Search AD Forest.ps1
Search AD Forest.ps1
######################################################################################## ## Search Active Directory Forest ## Search-ADForest ######################################################################################## ## NOTE: You have to have sufficient privileges on the target domain for this to work. ## NOTE: This script requires modification/customization prior to use. ######################################################################################## ## USAGE: ## Search-ADForest DomainA ## * Executes the inserted Active Directory-based script on DomainA only ## Search-ADForest ## * Executes the inserted Active Directory-based script on all domains in the forest ######################################################################################## ## EXAMPLES: ## ## * Script run with no command line parameters. This prompts a search of all domains in ## the current Active Directory Forest. ## ## PoSH C:\\> .\\Search-ADForest.ps1 ## Checking DomainA ## --- script runs and provides normal output for DomainA --- ## ## Checking DomainB ## --- script runs and provides normal output for DomainB --- ## ## Checking DomainC ## --- script runs and provides normal output for DomainC --- ## ## Checking DomainD ## --- script runs and provides normal output for DomainD --- ## ## ## * Script run with a domain name as a command line parameter. This prompts a search of ## all domains in the current Active Directory Forest that are 'like' the input. ## ## PoSH C:\\> .\\Search-ADForest.ps1 DomainB ## Checking DomainB ## --- script runs and provides normal output for DomainB --- ## ## ## * Script run with an FQDN as a command line parameter. This prompts a search of ## all domains in the current Active Directory Forest that are 'like' the input. ## ## PoSH C:\\> .\\Search-ADForest.ps1 DomainC.foo.bar.fabrikam.com ## Checking DomainC.foo.bar.fabrikam.com ## --- script runs and provides normal output for DomainC.foo.bar.fabrikam.com --- ######################################################################################## # Get Domain List [string]$arg = $Args[0] $objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = @($objForest.Domains | Select-Object Name | Where-Object {$_ -like "*$arg*"}) $Domains = $DomainLIst | foreach {$_.Name} # Act on all applicable domains foreach ($Domain in ($Domains)) { Write-Host "Checking $Domain" -foregroundcolor Red Write-Host "" ############################# ## YOUR SCRIPT GOES HERE ## ############################# }
PowerShellCorpus/PoshCode/Exif query script.ps1
Exif query script.ps1
## Selected 'Exif' statistics script is below. There are a number of ways I can improve it: ## Stream output, skip csv file creation (as an interim step) read list with arrays and parameters, ## using regex expressions to best effect. Still, quite a few lessons learned with this and the output can help ## check for errors. The issue is that 'exif' (Cygwin, GNU utility) will sometimes skip fields. I am not checking ## for that or other error conditions in general, but the 'Counts' need to sync up at least. $exif_index = gci *.jpg | %{exif ($_.Name)} $c = $exif_index | Select-String -pattern "EXIF tag" , FNumber , "Focal Length In 35mm" $c1 = ("$c").Split( ) | Select-String -pattern JPG , f/ , mm $c2 = (("$c1").Replace( "'" , "")).Split() $c3 = (("$c2").Replace( " |f/" , ",")).Split() $c4 = (("$c3").Replace( " 35mm|" , ",")).Split() if ((gci PhotoData.csv).Exists -eq "True") {mv PhotoData.csv PhotoData.csv.old -force} else {} "Exif_Tag,FNumber,Focal_Length" | out-file PhotoData.csv $c4 | out-file -append PhotoData.csv $PhotoData = import-csv -path PhotoData.csv $FileName = ( $PhotoData | Measure-Object -Property Exif_Tag ) $FNumber = ( $PhotoData | Measure-Object -Property FNumber -average -maximum -minimum ) $Focal_Length = ( $PhotoData | Measure-Object -Property Focal_Length -average -maximum -minimum ) echo $FileName echo $FNumber echo $Focal_Length
PowerShellCorpus/PoshCode/Get-Payment_1.ps1
Get-Payment_1.ps1
function Get-Payment { param ( $LoanAmount, [double]$InterestRatePerPeriod, $NumberPayments ) $a = $LoanAmount $b = $InterestRatePerPeriod*[math]::Pow(($InterestRatePerPeriod + 1),$NumberPayments) $c = [math]::Pow((1+$InterestRatePerPeriod),$NumberPayments) - 1 $payment = $a*($b/$c) "{0:C}" -f $payment }
PowerShellCorpus/PoshCode/Test-Hash_1.ps1
Test-Hash_1.ps1
function Test-Hash { #.Synopsis # Test the HMAC hash(es) of a file #.Description # Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash #.Example # C:\\PS>ls .\\Bin\\Release -recurse | Test-Hash -BasePath .\\Bin\\Release -Type SHA256 | Export-CSV ~\\Hashes.csv # C:\\Program Files\\MyProduct>Import-CSV ~\\Hashes.csv | Test-Hash # # This example shows how to take the hash of a collection of files and store them in a csv file, and then later verify that the files in a secondary location match the originals exactly. # #.Example # Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5 # # Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name # and take the hash of the file (using the extension of the HashFile as the Type of Hash). # #.Example # Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5 # # Takes the MD5 hash and compares it to the provided hash # #.Example # Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517 # # Tests all of the hashes against the provided (Sha1) hash [CmdletBinding(DefaultParameterSetName="NoExpectation")] PARAM( # The path to the file to hash [Parameter(Position=0,Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [string]$Path, # When hashing many files in folders, use this to convert to relative paths (so you can compare again in a different location) [Parameter(Position=2,Mandatory=$false,ParameterSetName="NoExpectation")] [string]$BasePath, # Supports hashing against a .md5 or .sha1 file such as frequently found on open source servers or torrent sites [Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")] [string]$HashFileName, # Supports passing in the expected hash (particularly useful when piping input from a previous run) [Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)] [Parameter(Position=2,Mandatory=$false,ParameterSetName="FromHashFile")] [ALias("Hash")] [string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $Path)[0].split(" ")[0] }), # The algorithm to use when hashing [Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)] [Parameter(Position=1,Mandatory=$false,ParameterSetName="NoExpectation")] [ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160")] [string[]]$Algorithm = $(if($HashFileName){ [IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1) } else { "SHA256" }) ) begin { $ofs="" if($BasePath) { Push-Location $BasePath } } process { if($BasePath) { $Path = Resolve-Path $Path -Relative } if(Test-Path $Path -Type Container) { # I'd like to support recursing all the files, but for now, just skip Write-Warning "Cannot calculate hash for directories: '$Path'" return } $Hashes = @( foreach($Type in $Algorithm) { # Take the Hash without storing the bytes (ouch) [string]$hash = [Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( [IO.File]::ReadAllBytes( (Convert-Path $Path) ) ) | ForEach { "{0:x2}" -f $_ } # Output an object with the hash, algorithm and path New-Object PSObject -Property @{ Path = $Path; Algorithm = $Type; Hash = $Hash } } ) if($ExpectedHash) { # Check all the hashes to see if any of them match if( $Match = $Hashes | Where { $_.Hash -eq $ExpectedHash } ) { Write-Verbose "Matched hash:`n$($Match | Out-String)" # Output an object with the hash, algorithm and path New-Object PSObject -Property @{ Path = $Match.Path; Algorithm = $Match.Algorithm; Hash = $Match.Hash; Matches = $True } } else { Write-Verbose "Failed to match hash:`n$($PSBoundParameters | Out-String)" # Output an object with the first hash, algorithm and path New-Object PSObject -Property @{ Path = $Hashes[0].Path; Algorithm = $Hashes[0].Algorithm; Hash = $Hashes[0].Hash; Matches = $False } } } else { Write-Output $Hashes } } end { if($BasePath) { Pop-Location } } }
PowerShellCorpus/PoshCode/Set-SecureAutoLogon_1.ps1
Set-SecureAutoLogon_1.ps1
[cmdletbinding()] param ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $Username, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.Security.SecureString] $Password, [string] $Domain, [Int] $AutoLogonCount, [switch] $RemoveLegalPrompt, [System.IO.FileInfo] $BackupFile ) begin { [string] $WinlogonPath = "HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon" [string] $WinlogonBannerPolicyPath = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System" [string] $Enable = 1 [string] $Disable = 0 #region C# Code to P-invoke LSA LsaStorePrivateData function. Add-Type @" using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace ComputerSystem { public class LSAutil { [StructLayout(LayoutKind.Sequential)] private struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential)] private struct LSA_OBJECT_ATTRIBUTES { public int Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public uint Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } private enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L } [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaRetrievePrivateData( IntPtr PolicyHandle, ref LSA_UNICODE_STRING KeyName, out IntPtr PrivateData ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaStorePrivateData( IntPtr policyHandle, ref LSA_UNICODE_STRING KeyName, ref LSA_UNICODE_STRING PrivateData ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaNtStatusToWinError( uint status ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaClose( IntPtr policyHandle ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaFreeMemory( IntPtr buffer ); private LSA_OBJECT_ATTRIBUTES objectAttributes; private LSA_UNICODE_STRING localsystem; private LSA_UNICODE_STRING secretName; public LSAutil(string key) { if (key.Length == 0) { throw new Exception("Key lenght zero"); } objectAttributes = new LSA_OBJECT_ATTRIBUTES(); objectAttributes.Length = 0; objectAttributes.RootDirectory = IntPtr.Zero; objectAttributes.Attributes = 0; objectAttributes.SecurityDescriptor = IntPtr.Zero; objectAttributes.SecurityQualityOfService = IntPtr.Zero; localsystem = new LSA_UNICODE_STRING(); localsystem.Buffer = IntPtr.Zero; localsystem.Length = 0; localsystem.MaximumLength = 0; secretName = new LSA_UNICODE_STRING(); secretName.Buffer = Marshal.StringToHGlobalUni(key); secretName.Length = (UInt16)(key.Length * UnicodeEncoding.CharSize); secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize); } private IntPtr GetLsaPolicy(LSA_AccessPolicy access) { IntPtr LsaPolicyHandle; uint ntsResult = LsaOpenPolicy(ref this.localsystem, ref this.objectAttributes, (uint)access, out LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError(ntsResult); if (winErrorCode != 0) { throw new Exception("LsaOpenPolicy failed: " + winErrorCode); } return LsaPolicyHandle; } private static void ReleaseLsaPolicy(IntPtr LsaPolicyHandle) { uint ntsResult = LsaClose(LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError(ntsResult); if (winErrorCode != 0) { throw new Exception("LsaClose failed: " + winErrorCode); } } public void SetSecret(string value) { LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING(); if (value.Length > 0) { //Create data and key lusSecretData.Buffer = Marshal.StringToHGlobalUni(value); lusSecretData.Length = (UInt16)(value.Length * UnicodeEncoding.CharSize); lusSecretData.MaximumLength = (UInt16)((value.Length + 1) * UnicodeEncoding.CharSize); } else { //Delete data and key lusSecretData.Buffer = IntPtr.Zero; lusSecretData.Length = 0; lusSecretData.MaximumLength = 0; } IntPtr LsaPolicyHandle = GetLsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET); uint result = LsaStorePrivateData(LsaPolicyHandle, ref secretName, ref lusSecretData); ReleaseLsaPolicy(LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError(result); if (winErrorCode != 0) { throw new Exception("StorePrivateData failed: " + winErrorCode); } } } } "@ #endregion } process { try { $ErrorActionPreference = "Stop" $decryptedPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto( [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) ) if ($BackupFile) { # Initialize the hash table with a string comparer to allow case sensitive keys. # This allows differentiation between the winlogon and system policy logon banner strings. $OrigionalSettings = New-Object System.Collections.Hashtable ([system.stringcomparer]::CurrentCulture) $OrigionalSettings.AutoAdminLogon = (Get-ItemProperty $WinlogonPath ).AutoAdminLogon $OrigionalSettings.ForceAutoLogon = (Get-ItemProperty $WinlogonPath).ForceAutoLogon $OrigionalSettings.DefaultUserName = (Get-ItemProperty $WinlogonPath).DefaultUserName $OrigionalSettings.DefaultDomainName = (Get-ItemProperty $WinlogonPath).DefaultDomainName $OrigionalSettings.DefaultPassword = (Get-ItemProperty $WinlogonPath).DefaultPassword $OrigionalSettings.AutoLogonCount = (Get-ItemProperty $WinlogonPath).AutoLogonCount # The winlogon logon banner settings. $OrigionalSettings.LegalNoticeCaption = (Get-ItemProperty $WinlogonPath).LegalNoticeCaption $OrigionalSettings.LegalNoticeText = (Get-ItemProperty $WinlogonPath).LegalNoticeText # The system policy logon banner settings. $OrigionalSettings.legalnoticecaption = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticecaption $OrigionalSettings.legalnoticetext = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticetext $OrigionalSettings | Export-Clixml -Depth 10 -Path $BackupFile } # Store the password securely. $lsaUtil = New-Object ComputerSystem.LSAutil -ArgumentList "DefaultPassword" $lsaUtil.SetSecret($decryptedPass) # Store the autologon registry settings. Set-ItemProperty -Path $WinlogonPath -Name AutoAdminLogon -Value $Enable -Force Set-ItemProperty -Path $WinlogonPath -Name DefaultUserName -Value $Username -Force Set-ItemProperty -Path $WinlogonPath -Name DefaultDomainName -Value $Domain -Force if ($AutoLogonCount) { Set-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -Value $AutoLogonCount -Force } else { Remove-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -ErrorAction SilentlyContinue } if ($RemoveLegalPrompt) { Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeCaption -Value $null -Force Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeText -Value $null -Force Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticecaption -Value $null -Force Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticetext -Value $null -Force } } catch { throw 'Failed to set auto logon. The error was: "{0}".' -f $_ } } <# .SYNOPSIS Enables auto logon using the specified username and password. .PARAMETER Username The username of the user to automatically logon as. .PARAMETER Password The password for the user to automatically logon as. .PARAMETER Domain The domain of the user to automatically logon as. .PARAMETER AutoLogonCount The number of logons that auto logon will be enabled. .PARAMETER RemoveLegalPrompt Removes the system banner to ensure interventionless logon. .PARAMETER BackupFile If specified the existing settings such as the system banner text will be backed up to the specified file. .EXAMPLE PS C:\\> Set-SecureAutoLogon ` -Username $env:USERNAME ` -Password (Read-Host -AsSecureString) ` -AutoLogonCount 2 ` -RemoveLegalPrompt ` -BackupFile "C:\\WinlogonBackup.xml" .INPUTS None. .OUTPUTS None. .NOTES Revision History: 2011-04-19 : Andy Arismendi - Created. 2011-09-29 : Andy Arismendi - Changed to use LSA secrets to store password securely. .LINK http://support.microsoft.com/kb/324737 .LINK http://msdn.microsoft.com/en-us/library/aa378750 #>
PowerShellCorpus/PoshCode/Update Subnet Masks.ps1
Update Subnet Masks.ps1
#config @@#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@#NOTE: Does not support IPv6. If used on a network with static IPv6 addresses, @@#they may be lost. @@#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@$network = "10.200.*" @@$newSubnet = "255.255.240.0" #get WMI for network adapters $nics = Get-WMIObject Win32_NetworkAdapterConfiguration | where { $_.IPEnabled -eq "TRUE" } #loop over each adapter foreach ($nc in $nics) { $addresses = [System.Collections.ArrayList]$nc.IPAddress $smasks = [System.Collections.ArrayList]$nc.IPSubnet $needsChange = $FALSE write-host ("{0} addresses found" -f $addresses.count) #loop over each address for ($i = 0; $i -lt $addresses.count;) { $addy = $addresses[$i] $sm = $smasks[$i] #remove from array all if ($addy -notLike '*.*.*.*') { $addresses.RemoveRange($i, 1) $smasks.RemoveRange($i, 1) } #if the address needs to be updated, change it and flag for update elseif ($addy -like $network -and $sm -ne $newSubnet) { write-host ("Updating address {0}/{1}" -f $addy, $sm) $smasks[$i] = $newSubnet $needsChange = $TRUE $i++; } #otherwise, skip it else { write-host ("Skipping address {0}/{1}" -f $addy, $sm) $i++; } } #if we had any ips that needed to be updated, do so now. if ($needsChange) { write-host ("Updating Addresses...") $res = [int]($nics.EnableStatic($addresses, $smasks).ReturnValue) #a nonzero value indicates failure if ($res -eq 0) { write-host "Updated Successfully!" } else { write-host ("Updating the IP Address failed with error {0}" -f $res) } } #no addresses changed else { write-host "No changes needed" } } write-host 'done '
PowerShellCorpus/PoshCode/Start-RDP.ps1
Start-RDP.ps1
######################################################################################################################## # NAME # Start-RDP # # SYNOPSIS # Opens a remote desktop connection to another computer. # # SYNTAX # Start-RDP [[-Server] <string>] [[-Width] <int>] [[-Height] <int>] # Start-RDP -Path <string> [[-Width] <int>] [[-Height] <int>] # # DETAILED DESCRIPTION # The Start-RDP cmdlet opens a new Remote Desktop connection using the Microsoft Terminal Services Client. # Connection settings can be specified by argument or read from a standard RDP file. # # PARAMETERS # -Server <string> # Specifies the name of the server to connect to. May also include an IP address, domain, and/or port. # # Required? false # Position? 1 # Default value # Accept pipeline input? true # Accept wildcard characters? false # # -Width <int> # Specifies the desired width of the resolution for the connection (for non-full screen connections). # # Required? false # Position? 2 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Height <int> # Specifies the desired height of the resolution for the connection (for non-full screen connections). # # Required? false # Position? 3 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Path <string> # Specifies the path to an RDP file to connect with (resolution settings can be overridden using the # -Width and -Height parameters. # # Required? false # Position? 4 # Default value # Accept pipeline input? true # Accept wildcard characters? false # # -Console <SwitchParameter> # Connect to a Windows Server 2003 console session. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Admin <SwitchParameter> # Connect to a Windows Server 2008 administrator session. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Fullscreen <SwitchParameter> # Open connection in full screen mode. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Public <SwitchParameter> # Run Remote Desktop in public mode. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Span <SwitchParameter> # Span the Remote Desktop connection across multiple monitors. Each monitor must have the same height # and be arranged vertically. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # INPUT TYPE # String,System.IO.FileInfo # # RETURN TYPE # # # NOTES # # -------------------------- EXAMPLE 1 -------------------------- # # C:\\PS>Start-RDP # # # This command opens the Terminal Services Client connection dialog to specify a connection. # # # -------------------------- EXAMPLE 2 -------------------------- # # C:\\PS>Start-RDP -Server myserver -Width 1024 -Height 768 # # # This command opens a new Remote Desktop connection to the server named "myserver" in a window with 1024x768 resolution. # # # -------------------------- EXAMPLE 3 -------------------------- # # C:\\PS>Start-RDP -Server myserver -Fullscreen # # # This command opens a new full screen Remote Desktop connection to the server named "myserver". # # # -------------------------- EXAMPLE 4 -------------------------- # # C:\\PS>Start-RDP -Path C:\\myserver.rdp # # # This command opens a new Remote Desktop connection using the specified RDP file. # # #Function global:Start-RDP { param( [string]$Server = "", [int]$Width = "", [int]$Height = "", [string]$Path = "", [switch]$Console, [switch]$Admin, [switch]$Fullscreen, [switch]$Public, [switch]$Span ) begin { $arguments = "" $dimensions = "" $processed = $false if ($admin) { $arguments += "/admin " } elseif ($console) { $arguments += "/console " } if ($fullscreen) { $arguments += "/f " } if ($public) { $arguments += "/public " } if ($span) { $arguments += "/span " } if ($width -and $height) { $dimensions = "/w:$width /h:$height" } } process { Function script:executePath([string]$path) { Invoke-Expression "mstsc.exe '$path' $dimensions $arguments" } Function script:executeArguments([string]$Server) { Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments" } if ($_) { if ($_ -is [string]) { if ($_ -imatch '\\.rdp$') { if (Test-Path $_) { executePath $_ $processed = $true } else { throw "Path does not exist." } } else { executeArguments $_ $processed = $true } } elseif ($_ -is [System.IO.FileInfo]) { if (Test-Path $_.FullName) { executePath $_.FullName $processed = $true } else { throw "Path does not exist." } } elseif ($_.Path) { if (Test-Path $_.Path) { executePath $_.Path $processed = $true } else { throw "Path does not exist." } } elseif ($_.DnsName) { executeArguments $_.DnsName $processed = $true } elseif ($_.Server) { executeArguments $_.Server $processed = $true } elseif ($_.ServerName) { executeArguments $_.ServerName $processed = $true } elseif ($_.Name) { executeArguments $_.Name $processed = $true } } } end { if ($path) { if (Test-Path $path) { Invoke-Expression "mstsc.exe '$path' $dimensions $arguments" } else { throw "Path does not exist." } } elseif ($server) { Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments" } elseif (-not $processed) { Invoke-Expression "mstsc.exe $dimensions $arguments" } } #}
PowerShellCorpus/PoshCode/Function Run-Script_1.ps1
Function Run-Script_1.ps1
function Run-Script { if ($psISE.CurrentFile.DisplayName.StartsWith("Untitled")) { return } $script = $psISE.CurrentFile.DisplayName $psISE.CurrentFile.Save() $logfile = "$env:programfiles\\Sea Star Development\\" + "Script Monitor Service\\ScriptMon.txt" #Change to suit. if (!(Test-Path env:\\JobCount)) { $env:JobCount = 1 #This will work across multi Tab sessions. } $number = $env:JobCount.PadLeft(4,'0') $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$startTime [$script] start. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$startTime [$script] started." Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PSE$number) started." Invoke-Command -Scriptblock { & "$pwd\\$script" } $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$endTime [$script] ended. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$endTime [$script] ended." Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PSE$number) ended." $env:JobCount = [int]$env:JobCount+1 } $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Run Script",{Run-Script}, "Alt+R") | Out-Null
PowerShellCorpus/PoshCode/ce50f222-81f6-4509-90ad-8904f9331d7c.ps1
ce50f222-81f6-4509-90ad-8904f9331d7c.ps1
# Detect 32 or 64 bits Windows – regardless of WoW64 – with the PowerShell OSArchitecture function # By Vincent Hoogendoorn @@# See http://vincenth.net/blog/archive/2009/11/02/detect-32-or-64-bits-windows-regardless-of-wow64-with-the-powershell-osarchitecture-function.aspx for details. @@# For the used InvokeCSharp function source, see http://vincenth.net/blog/archive/2009/10/27/call-inline-c-from-powershell-with-invokecsharp.aspx @@# or search http://poshcode.org for InvokeCSharp Function global:CurrentProcessIsWOW64 { # Use some inline C# code to call the unmanaged IsWow64Process() function in Kernel32.dll and return its result: $code = @" using System; using System.Runtime.InteropServices; public class Kernel32 { [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo); // This overload returns True if the current process is running on Wow, False otherwise public bool CurrentProcessIsWow64() { bool retVal; if (!(IsWow64Process(System.Diagnostics.Process.GetCurrentProcess().Handle, out retVal))) { throw new Exception("IsWow64Process() failed"); } return retVal; } } "@ InvokeCSharp -code $code -class 'Kernel32' -method 'CurrentProcessIsWow64' } Function global:ProcessArchitecture { switch ([System.IntPtr]::Size) { 4 { 32 } 8 { 64 } default { throw "Unknown Process Architecture: $([System.IntPtr]::Size * 8) bits" } } } Function global:OSArchitecture { if (((ProcessArchitecture) -eq 32) -and (CurrentProcessIsWOW64)) { 64 } else { ProcessArchitecture } # Note that on Vista, W2008 and later Windows versions, we could use (Get-WMIObject win32_operatingsystem).OSArchitecture. # We don't use that because we also support W2003 }
PowerShellCorpus/PoshCode/hex2dec_3.ps1
hex2dec_3.ps1
@echo off ::interactive mode if "%1" equ "" ( if not defined run goto:interactive goto:error ) ::null results for %%i in ("x0" "0x0") do if "%1" equ "%%~i" goto:null ::parsing arguments setlocal enabledelayedexpansion ::only one argument should input set "arg=0" for %%i in (%*) do set /a "arg+=1" if "%arg%" neq "1" if not defined run goto:help if "%arg%" neq "1" if defined run goto:error ::get length of argument set "i=0" set "str=%1" for /l %%i in (0, 1, 255) do ( set "chr=!str:~%%i!" if defined chr set /a "i+=1" ) ::checking first n symbols if !i! equ 1 ( if "%str%" equ "0" goto:null if "%str%" equ "x" goto:error ) if !i! equ 2 ( if "%str:~0,1%" equ "0" goto:error if "%str:~0,1%" equ "x" set "str=0%str%" && goto:check ) if !i! gtr 2 ( if "%str:~0,1%" equ "0" if "%str:~1,1%" neq "x" goto:error if "%str:~0,1%" equ "0" if "%str:~1,1%" equ "x" goto:hex2dec if "%str:~0,1%" equ "x" set "str=0%str%" && goto:check ) for %%i in (a b c d e f) do if "%str:~0,1%" equ "%%i" set "str=0x%str%" && goto:hex2dec :check 2>nul set /a "res=%str%" if "%errorlevel%" equ "0" ( if "%str%" equ "%res%" goto:dec2hex goto:hex2dec ) echo "%str%" | findstr /r [0-9a-f] > nul if "%errorlevel%" equ "0" set "str=0x%str%" && goto:hex2dec goto:error :dec2hex set "map=0123456789ABCDEF" for /l %%i in (1, 1, 8) do ( set /a "res=str & 15, str >>=4" for %%j in (!res!) do set "hex=!map:~%%j,1!!hex!" ) for /f "tokens=* delims=0" %%i in ("!hex!") do set "hex=0x%%i" echo %1 = !hex! & goto:eof :hex2dec 2>nul set /a "res=%str%" if "%errorlevel%" gtr "0" goto:error for /f "tokens=2,3" %%i in ('findstr "# " "%~dpnx0"') do set "str=!str:%%i=%%j!" if "%res%" neq "" if "%res%" neq "0" (echo %str% = %res%) else goto:error endlocal exit /b :error echo =^>err exit /b 1 :null echo =^>nil exit /b 0 :help ::Hex2dec v2.01 - converts hex to decimal and vice versa ::Copyright (C) 2012-2013 greg zakharov :: ::Usage: hex2dec [decimal | hexademical] :: ::Example 1: :: C:\\>hex2dec 0x017a :: 0x017A = 378 :: ::Example 2: :: C:\\>hex2dec 017a :: =>err :: ::Example 3: :: C:\\>hex2dec x017a :: 0x017A = 378 :: ::Example 4: :: C:\\>hex2dec 17a :: 0x17A = 378 :: ::Example 5: :: C:\\>hex2dec 0503 :: =>err :: ::Example 6: :: C:\\>hex2dec x503 :: 0x503 = 1283 :: ::Example 7: :: C:\\>hex2dec 1283 :: 1283 = 0x503 :: ::Example 8: :: C:\\>hex2dec 503 :: 503 = 0x1F7 :: ::Note: hex2dec starts with interactive mode if there is ::no argument. for /f "tokens=* delims=:" %%i in ('findstr "^::" "%~dpnx0"') do echo.%%i exit /b 0 rem :: Upper case chart :: # a A # b B # c C # d D # e E # f F rem :: End of chart :: :interactive ::interactive mode on echo Hex2dec v2.01 - converts hex to decimal and vice versa echo. echo Enter decimal or hexademical number and press Enter to echo take result. Use "exit" or "clear" commands to quit or echo to make host clear. echo. setlocal ::already launched marker set "run=true" :begin set /p "ask=>>> " cmd /c "%~dpnx0" %ask% if "%ask%" equ "clear" cls if "%ask%" equ "exit" cls & goto:eof echo. goto:begin endlocal exit /b
PowerShellCorpus/PoshCode/usr ActiveSync - Exch 07.ps1
usr ActiveSync - Exch 07.ps1
#Sacamos los dispositivos asociados a cada mailbox #Verificamos su ultima conexión o si alguna vez no se han conectado #Autor: Pedro Genil #Fecha:23/11/2012 #Version: 1.0 If ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null) { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin } #Select-Object Identity, DeviceFriendlyName, Devicetype, DeviceUserAgent, FirstSyncTime, LastSuccessSync $mailbox = Get-MailboxServer $fecha = get-date $fecha= $fecha.adddays(-30).ToString("yyyyMMdd") #Recorremos todos los mailbox foreach ($mail in $mailbox) { $a=0 $b=0 echo "Analizando $mail" >> resultado.txt $devices = Get-Mailbox -server $mail -resultsize unlimited| ForEach {Get-ActiveSyncDeviceStatistics -Mailbox:$_.Identity} #Recorremos los dispositivos de cada usuario foreach ($device in $devices) { if($device.LastSuccessSync -ne $NULL) { if ($device.LastSuccessSync.ToString("yyyyMMdd") -gt $fecha) {$a=$a+1} } else {$b=$b+1} } echo "Numero de dispositivos nunca conectados en $mail $b" >> resultado.txt echo "Numero de dispositivos conectados en los ultimos 30 dias en $mail $a" >> resultado.txt }
PowerShellCorpus/PoshCode/Install-ISPackage.ps1
Install-ISPackage.ps1
####################### <# .SYNOPSIS Installs an SSIS package to a SQL Server store. .DESCRIPTION The Install-ISPackage script installs an Dtsx file to a SQL Server store using the command-line utility dtutil. Works for 2005 and higher .EXAMPLE ./install-ispackage.ps1 -DtsxFullName "C:\\Users\\Public\\bin\\SSIS\\sqlpsx1.dtsx" -ServerInstance "Z001\\SQL1" -PackageFullName "SQLPSX\\sqlpsx1" This command install the sqlpsx1.dtsx package to SQL Server instance Z001\\SQL1 under the SQLPSX folder as sqlpsx1. If SQLPSX folder does not exist it will be created. .NOTES Version History v1.0 - Chad Miller - 6/26/2012 - Initial release v1.1 - Chad Miller - 7/05/2012 - Updated to output object. Fixed lastexitcode check in test functions v1.2 - Chad Miller - 7/09/2012 - Added SqlVersion and Dtutil Path logic v1.3 - Chad Miller - 7/10/2012 - Fixed 2005 path logic v1.4 - Chad Miller - 9/25/2012 - Fixed 2012 path logic #> param( [Parameter(Position=0, Mandatory=$true)] [string] $DtsxFullName, [Parameter(Position=1, Mandatory=$true)] [string] $ServerInstance, [Parameter(Position=2, Mandatory=$true)] [string] $PackageFullName ) $ErrorActionPreference = "Stop" $Script:dtutil = $null $exitCode = @{ 0="The utility executed successfully." 1="The utility failed." 4="The utility cannot locate the requested package." 5="The utility cannot load the requested package." 6="The utility cannot resolve the command line because it contains either syntactic or semantic errors"} ####################### function Get-SqlVersion { param($ServerInstance) write-verbose "sqlcmd -S `"$ServerInstance`" -d `"master`" -Q `"SET NOCOUNT ON; SELECT SERVERPROPERTY('ProductVersion')`" -h -1 -W" $SqlVersion = sqlcmd -S "$ServerInstance" -d "master" -Q "SET NOCOUNT ON; SELECT SERVERPROPERTY('ProductVersion')" -h -1 -W if ($lastexitcode -ne 0) { throw $SqlVersion } else { $SqlVersion } } #Get-SqlVersion ####################### function Set-DtutilPath { param($SqlVersion) $paths = [Environment]::GetEnvironmentVariable("Path", "Machine") -split ";" if ($SqlVersion -like "9*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2005 Version of dtutil not found." } } elseif ($SqlVersion -like "10*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2008 or 2008R2 Version of dtutil not found." } } elseif ($SqlVersion -like "11*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\110\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2012 Version of dtutil not found." } } if ($Script:dtutil -eq $null) { throw "Unable to find path to dtutil.exe. Verify dtutil installed." } else { $Script:dtutil += 'dtutil.exe' } } #Set-DtutilPath ####################### function install-package { param($DtsxFullName, $ServerInstance, $PackageFullName) $result = & $Script:dtutil /File "$DtsxFullName" /DestServer "$ServerInstance" /Copy SQL`;"$PackageFullName" /Quiet $result = $result -join "`n" new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /File `"$DtsxFullName`" /DestServer `"$ServerInstance`" /Copy SQL;`"$PackageFullName`" /Quiet" Result = $result Success = ($lastexitcode -eq 0)} if ($lastexitcode -ne 0) { throw $exitcode[$lastexitcode] } } #install-package ####################### function test-path { param($ServerInstance, $FolderPath) write-verbose "$Script:dtutil /SourceServer `"$ServerInstance`" /FExists SQL`;`"$FolderPath`"" $result = & $Script:dtutil /SourceServer "$ServerInstance" /FExists SQL`;"$FolderPath" if ($lastexitcode -gt 1) { $result = $result -join "`n" throw "$result `n $($exitcode[$lastexitcode])" } if ($result -and $result[4] -eq "The specified folder exists.") { $true } else { $false } } #test-path ####################### function test-packagepath { param($ServerInstance, $PackageFullName) write-verbose "$Script:dtutil /SourceServer `"$ServerInstance`" /SQL `"$PackageFullName`" /EXISTS" $result = & $Script:dtutil /SourceServer "$ServerInstance" /SQL "$PackageFullName" /EXISTS if ($lastexitcode -gt 1) { $result = $result -join "`n" throw "$result `n $($exitcode[$lastexitcode])" } new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /SourceServer `"$ServerInstance`" /SQL `"$PackageFullName`" /EXISTS" Result = $result[4] Success = ($lastexitcode -eq 0 -and $result -and $result[4] -eq "The specified package exists.")} } #test-packagepath ####################### function new-folder { param($ServerInstance, $ParentFolderPath, $NewFolderName) $result = & $Script:dtutil /SourceServer "$ServerInstance" /FCreate SQL`;"$ParentFolderPath"`;"$NewFolderName" $result = $result -join "`n" new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /SourceServer `"$ServerInstance`" /FCreate SQL;`"$ParentFolderPath`";`"$NewFolderName`"" Result = $result Success = ($lastexitcode -eq 0)} if ($lastexitcode -ne 0) { throw $exitcode[$lastexitcode] } } #new-folder ####################### function Get-FolderList { param($PackageFullName) if ($PackageFullName -match '\\\\') { $folders = $PackageFullName -split "\\\\" 0..$($folders.Length -2) | foreach { new-object psobject -property @{ Parent=$(if($_-gt 0) { $($folders[0..$($_ -1)] -join "\\") } else { "\\" }) FullPath=$($folders[0..$_] -join "\\") Child=$folders[$_]}} } } #Get-FolderList ####################### ## MAIN ## ####################### try { #1. Get Sql Version $SqlVersion = Get-SqlVersion -ServerInstance $ServerInstance #2. Set Dtutil Path based on Sql Version Set-DtutilPath -SqlVersion $SqlVersion #3. Get SSIS Folder List, verify exists and create missing folders Get-FolderList -PackageFullName $PackageFullName | where { $(test-path -ServerInstance $ServerInstance -FolderPath $_.FullPath) -eq $false } | foreach { new-folder -ServerInstance $ServerInstance -ParentFolderPath $_.Parent -NewFolderName $_.Child } #4. Install SSIS Package install-package -DtsxFullName $DtsxFullName -ServerInstance $ServerInstance -PackageFullName $PackageFullName #5. Verify Package test-packagepath -ServerInstance $ServerInstance -PackageFullName $PackageFullName } catch { write-error "$_ `n $("Failed to install DtsxFullName {0} to ServerInstance {1} PackageFullName {2}" -f $DtsxFullName,$ServerInstance,$PackageFullName)" }
PowerShellCorpus/PoshCode/New-Password 1.1.ps1
New-Password 1.1.ps1
#.Synopsis # Generate pseudo-random passwords based on templates # #.Parameter Template # The template for the password you want to generate. This defines which types of characters are generated for each character in the password. # IMPORTANT: the US English alphabet is hardcoded ... (we make no apologies, but thought you should know that) # # The valid template characters are: # * L - any uppercase letter (A-Z) # * l - any lowercase letter (a-z) # * C - uppercase consonant # * c - lowercase consonant # * V - uppercase vowel # * v - lowercase vowel # * H - uppercase HEX (0123456789ABCDEF) # * h - lowercase HEX (0123456789abcdef) # * . - punctuation # * d - numeric Digit character # * a - any alphabetic character: a-z, A-Z # * A - any alphanumeric character: a-z, A-Z, 0-9 # * * - any character: a-z, A-Z, 0-9 + punctuation # * An actual number modifies the presceding character to allow UP TO that many of that character class # * An escaped character: \\L will be inserted literally... # * Anything else will be inserted literally... # #.Example # New-Password "Cvcvcdd" # Jemad46 # # Description # ----------- # Generates a "pronounceable" 7 character password consisting of alternating consonants and vowels followed by a 2-digit number # #.Example # ("Cvcvcdd," * 8).Split(",") | New-Password # # Description # ----------- # Demonstrates that the function can take pipeline input. Passing multiple templates via the pipeline will generate multiple passwords. # In this case, we generate EIGHT "pronounceable" 7 character password consisting of alternating consonants and vowels followed by a 2-digit number # #.Example # 1..6 | ForEach { New-Password "Cv3c2v3cd4" } # Haavgaef922 # Celboey399 # Mavbaew1 # Voebhit896 # Qeeoddaw34 # Bowaf2 # # Description # ----------- # Generates 6 variable-length, mostly "pronounceable" password. The numbers indicate the maximum counts for each of the character types. # #.Example # New-Password "Cvvc.Cvvcdd" # Ziir-Diud55 # # Description # ----------- # Generates a password which starts with an upper-case consonant, followed by two lower-case vowels, followed by a punctuation mark, followed by an upper-case consonant, followed by two lower-case vowels, followed by two numbers. # #.Example # New-Password "********" # !u($OA:* # # Description # ----------- # Generates a totally random 8 character password # #.Example # New-Password "Get-Cvcvvc" # Get-Wodeaj # # Description # ----------- # Generates a password which looks like a strange PowerShell command, starting with "Get-" and ending with an uppercase consonant, a vowel, a consonant, two vowels, and a final consonant. # #.Notes # On PowerShell 2.0 if you define an alias "rand" to point to Microsoft.PowerShell.Utility\\Get-Random, this script will use the Get-Random cmdlet instead of it's built-in rand function. # Set-Alias rand Microsoft.PowerShell.Utility\\Get-Random -Option AllScope #.Inputs # [String] # A string template for a password #.Outputs # [String] # A password string # History: # v 1.1 - bugfix for the \\ escape character # + added a hex option (H for upper) and (h for lower) # + changed the '#' to 'd' for digits so you can write the patterns without quotes. # v 1.0 - first release # # function New-Password { #[CmdletBinding()] Param ( # [Parameter(ValueFromPipeline=$true,Position=0)] [string]$Template = "************" ) BEGIN { #if($Template.Length -lt 8) { THROW "Passwords less than 8 characters are not allowed." } ## You might consider avoiding the O which is easily confused with 0 except in the Consolas font ;) [char[]]$UpperAlpha = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' [char[]]$LowerAlpha = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' [char[]]$UpperConsonants = 'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z' [char[]]$LowerConsonants = 'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z' [char[]]$LowerVowels = 'a','e','i','o','u' [char[]]$UpperVowels = 'A','E','I','O','U' [char[]]$Numeric = '1','2','3','4','5','6','7','8','9','0' [char[]]$UpperHex = '1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F' [char[]]$LowerHex = '1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f' # In case this is used in a DCPromo answer files, theres a few chars to avoid: Ampersand, Less than, double quote and back slash # And because they're easily confused for ' , let's also avoid the backtick ` ## '&','<','"','\\','``', [char[]]$Punctuation = '!','#','$','%','''','(',')','*','+',',','-','.','/',':',';','=','>','?','@','[',']','^','_' $script:RANDOM = new-object Random function rand { begin { $list = @() } process { $list += $_ } end { $list[$RANDOM.Next(0,$list.Count-1)] } } } PROCESS { if($_) { $Template = $_ } Write-Verbose "Template: $Template" $password = "" $randoms = @() for($c = 0; $c -lt $Template.Length; $c++) { switch -CaseSensitive ($Template[$c]) { 'l' { # Make this character a Lowercase Alpha $password += $LowerAlpha | rand break } 'L' { # Make this character a Uppercase Alpha $password += $UpperAlpha | rand break } 'l' { # Make this character a Lowercase Alpha $password += $LowerAlpha | rand break } 'C' { # Make this character a Uppercase consonant $password += $UpperConsonants | rand break } 'c' { # Make this character a Lowercase consonant $password += $LowerConsonants | rand break } 'V' { # Make this character a Uppercase vowel $password += $UpperVowels | rand break } 'v' { # Make this character a Lowercase vowel $password += $LowerVowels | rand break } 'H' { # Make this character a Uppercase vowel $password += $UpperHex | rand break } 'h' { # Make this character a Lowercase vowel $password += $LowerHex | rand break } '.' { # Make this character punctuation $password += $Punctuation | rand break } 'd' { # Make this character numeric $password += $Numeric | rand break } 'a' { # Make this character any alphabetic $password += $UpperAlpha + $LowerAlpha | rand break } 'A' { # Make this character any alphanumeric $password += $UpperAlpha + $LowerAlpha + $Numeric | rand break } '*' { # Make this character any character $password += $UpperAlpha + $LowerAlpha + $Numeric + $Punctuation | rand break } # For a number, decrement the number, and then go back one... { [bool](([string]$_) -as [int]) } { if($randoms -notcontains $c) { $randoms += $c [int]$count = $(0..([int][string]$_) | rand) } else { [int]$count = $(([int][string]$_) - 1) } if($c -gt 0 -and $count -gt 0) { $Template = $Template.Remove($c,1).Insert($c,$count) $c -= 2 Write-Verbose "ALTER Template: $Template Active: $($Template[$c]) ($c), Generating $count ($_) Password: $password" } break } '\\' { $password += $Template[(++$c)] break } default { $password += $Template[$c] break } } } return $Password } #}
PowerShellCorpus/PoshCode/Send-SMSMessage.ps1
Send-SMSMessage.ps1
#requires -version 2 function Send-SMSMessage { <# .SYNOPSIS Send a Text Message (SMS) using Microsoft Outlook .DESCRIPTION Sends a Text Message (SMS) using the supplied parameters. .PARAMETER To Telephone number to send the text message to. .PARAMETER Message The message to send. .EXAMPLE Send-SMSMessage -To 555-12345 -Message "This is a test message" .NOTES Requires Windows PowerShell v2 and Microsoft Office Outlook 2010. Not tested in Outlook 2003 or 2007, but it should work with the Microsoft Outlook SMS Add-in installed (download from Microsoft). AUTHOR: Jan Egil Ring BLOG: http://blog.powershell.no LASTEDIT: 21.07.2010 #> [CmdletBinding()] param ( [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $To, [parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Message ) #Check if Outlook are running $OutlookState = Get-Process | Where-Object {$_.Name -eq "outlook"} #Check whether Outlook is installed if (-not (Test-Path "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\OUTLOOK.EXE")) { Write-Warning "Outlook are not installed. The message was not sent." break } #Check wheter an Text Messaging (SMS) account are set up in Outlook $outlook = New-Object -ComObject outlook.application if (-not (($outlook.Session.Accounts | Where-Object {$_.AccountType -eq "5"} | Measure-Object).Count -gt 0)) { Write-Warning "Outlook are installed, but no accounts are configured for Text Messaging (SMS). The message was not sent." break } #Send message $NewMessage = $outlook.CreateItem("olMobileItemSMS") $NewMessage.To = $To $NewMessage.Body = $Message $NewMessage.Send($true) #Close outlook.exe if it was not running before executing this function if (-not $OutlookState) { $outlook.Quit() } }
PowerShellCorpus/PoshCode/Start-Verify_2.ps1
Start-Verify_2.ps1
# Author: Steven Murawski http://www.mindofroot.com # This script creates two functions (and a helper function). One starts logging all commands entered, # and the second removes the logging. # This script is similar to the Start-Transcript, but only logs the command line and not the output. # Modified to add the logging at the beginning of the Prompt function, otherwise it appeared to # impact some functions display options. I also added some verification to see that the log directory # exists and to create it if not. function New-ScriptBlock() { param ([string]$scriptblock) $executioncontext.InvokeCommand.NewScriptBlock($scriptblock.trim()) } function Start-Verify () { param ($logfile = 'c:\\scripts\\powershell\\logs\\verify.txt') #if the log folder does not exist, create one if (-not (test-path (split-path $logfile))) { mkdir (Split-Path $logfile) | Out-Null } $lastcmd = 'get-history | select -Last 1 | { $_.CommandLine.ToString() } | Out-File -Append {0};' -f $logfile Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ("$lastcmd`n" + $_.toString()) } | Out-Null } function Stop-Verify () { $lastcmd = '^get-history.*;' Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ($_.tostring() -replace "$lastcmd")} | Out-Null }
PowerShellCorpus/PoshCode/PS2WCF_7.ps1
PS2WCF_7.ps1
<# .SYNOPSIS Functions to call WCF Services With PowerShell. .NOTES Version 1.2 11.02.2012 Requires Powershell v2 and .NET 3.5 Copyright (c) 2008 Christian Glessner Copyright (c) 2012 Justin Dearing 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. Original version by Christian Glessner Blog: http://www.iLoveSharePoint.com Twitter: http://twitter.com/cglessner Codeplex: http://codeplex.com/iLoveSharePoint PowerShell v2.0 modification by Justin Dearing Blog: http://justaprogrammer.net Twitter: http://twitter.com/zippy1981 .LINK Blog describing original version: http://www.ilovesharepoint.com/2008/12/call-wcf-services-with-powershell.html Authoritative version of this fork: https://github.com/justaprogrammer/PowerShellWCF Posted to PoshCode.org http://poshcode.org/?lang=&q=PS2WCF #> # load WCF assemblies Add-Type -AssemblyName "System.ServiceModel" Add-Type -AssemblyName "System.Runtime.Serialization" <# .SYNOPSIS Get metadata of a service .DESCRIPTION Parses a wsdl or mex and generates a WsdlImporter object from it. .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc/mex' .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc' -HttpGet .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc?wsdl' -HttpGet #> function global:Get-WsdlImporter([CmdletBinding()][Parameter(Mandatory=$true, ValueFromPipeline=$true)][string]$WsdlUrl, [switch]$HttpGet) { if($HttpGet) { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet } else { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange } $mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient([Uri]$WsdlUrl, $mode); $mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue $metadataSet = $mexClient.GetMetadata() $wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet) return $wsdlImporter } <# .SYNOPSIS Generate wcf proxy types .DESCRIPTION Examines a web services meta data (wsdl or mex) and generates the types for the client proxy, as well as request and response contracts. .EXAMPLE $proxyType = Get-WcfProxyType $wsdlImporter $endpoints = $wsdlImporter.ImportAllEndpoints(); $proxy = New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address); #> function global:Get-WcfProxyType( [CmdletBinding()] [Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter, [Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl, [string] $proxyPath ) { switch ($PsCmdlet.ParameterSetName) { "WsdlUrl" { $WsdlImporter = Get-WsdlImporter $WsdlUrl trap [Exception] { $WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet continue } break } "WsdlImporter" { break } } $generator = new-object System.ServiceModel.Description.ServiceContractGenerator foreach($contractDescription in $wsdlImporter.ImportAllContracts()) { [void]$generator.GenerateServiceContractType($contractDescription) } $parameters = New-Object System.CodeDom.Compiler.CompilerParameters if($proxyPath -eq $null) { $parameters.GenerateInMemory = $true } else { $parameters.OutputAssembly = $proxyPath } $providerOptions = New-Object "Collections.Generic.Dictionary[String,String]" [void]$providerOptions.Add("CompilerVersion","v3.5") $compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions) $result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit); if($result.Errors.Count -gt 0) { throw "Proxy generation failed" } return $result.CompiledAssembly.GetTypes() | Where-Object {$_.BaseType.IsGenericType -and $_.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" } } <# .SYNOPSIS Generate wcf proxy .DESCRIPTION Generate wcf proxy in a manner similar to a Get-WebServiceProxy .EXAMPLE $proxy = Get-WcfProxy 'http://localhost.fiddler:14232/EchoService.svc/mex' $proxy.Echo("Justin Dearing"); .EXAMPLE $proxy = Get-WcfProxy 'net.tcp://localhost:8732/EchoService/mex' 'net.tcp://localhost:8732/EchoService/' (New-Object System.ServiceModel.NetTcpBinding) $proxy.Echo("Justin Dearing"); #> function global:Get-WcfProxy( [CmdletBinding()] [Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter, [Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl, [Parameter(Position=1, Mandatory=$false)][string] $EndpointAddress = $null, [Parameter(Position=2, Mandatory=$false)][System.ServiceModel.Channels.Binding] $Binding = $null ) { if ($Binding -ne $null -and [string]::IsNullOrEmpty($EndpointAddress)) { throw New-Object ArgumentNullException '$EndPointAddress', 'You cannot set $Binding without setting $EndpointAddress.' } switch ($PsCmdlet.ParameterSetName) { "WsdlUrl" { $WsdlImporter = Get-WsdlImporter $WsdlUrl trap [Exception] { $WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet continue } break } } $proxyType = Get-WcfProxyType $wsdlImporter; if ([string]::IsNullOrEmpty($EndpointAddress)) { $endpoints = $WsdlImporter.ImportAllEndpoints(); $Binding = $endpoints[0].Binding; $EndpointAddress = $endpoints[0].Address; } return New-Object $proxyType($Binding, $EndpointAddress); }
PowerShellCorpus/PoshCode/New-Choice_1.ps1
New-Choice_1.ps1
function New-Choice { <# .SYNOPSIS The New-Choice function is used to provide extended control to a script author who writing code that will prompt a user for information. .PARAMETER Choices An Array of Choices, ie Yes, No and Maybe .PARAMETER Caption Caption to present to end user .EXAMPLE PS C:\\> New-Choice -Choices 'Yes','No' -Caption "PowerShell makes choices easy" .NOTES Author: Andy Schneider Date: 5/6/2011 #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True)] $Choices, [Parameter(Position=1)] $Caption, [Parameter(Position=2)] $Message ) process { $resulthash += @{} for ($i = 0; $i -lt $choices.count; $i++) { $ChoiceDescriptions += @(New-Object System.Management.Automation.Host.ChoiceDescription ("&" + $choices[$i])) $resulthash.$i = $choices[$i] } $AllChoices = [System.Management.Automation.Host.ChoiceDescription[]]($ChoiceDescriptions) $result = $Host.UI.PromptForChoice($Caption,$Message, $AllChoices, 1) $resulthash.$result -replace "&", "" } } new-choice -Choices "yes","no","maybe"
PowerShellCorpus/PoshCode/BufferBox _1.6.ps1
BufferBox _1.6.ps1
#################################################################################################### ## This script is just a demonstration of some of the things you can do with the buffer ## in the default PowerShell host... it serves as a reminder of how much work remains on ## PoshConsole, and as an inspiration to anyone who is thinking about trying to create ## "interactive" PowerShell applications. ## ## Try Test-DisplayBox and then Test-BufferBox (note it has tab completion and everything). #################################################################################################### $global:BoxChars = new-object PSObject -Property @{ 'HorizontalDouble' = ([char]9552).ToString() 'VerticalDouble' = ([char]9553).ToString() 'TopLeftDouble' = ([char]9556).ToString() 'TopRightDouble' = ([char]9559).ToString() 'BottomLeftDouble' = ([char]9562).ToString() 'BottomRightDouble' = ([char]9565).ToString() 'HorizontalDoubleSingleDown' = ([char]9572).ToString() 'HorizontalDoubleSingleUp' = ([char]9575).ToString() 'Horizontal' = ([char]9472).ToString() 'Vertical' = ([char]9474).ToString() 'TopLeft' = ([char]9484).ToString() 'TopRight' = ([char]9488).ToString() 'BottomLeft' = ([char]9492).ToString() 'BottomRight' = ([char]9496).ToString() 'Cross' = ([char]9532).ToString() 'VerticalDoubleRightSingle' = ([char]9567).ToString() 'VerticalDoubleLeftSingle' = ([char]9570).ToString() } $global:RectType = "system.management.automation.host.rectangle" function Show-ConsoleMenu { #.Synopsis # Displays a menu in the console and returns the selection #.Description # Displays a numbered list in the console, accepts a typed number from the user, and returns it. #.Example # ls | Show-ConsoleMenu -Title "Please pick a file to delete:" -Passthru | rm -whatif # # Description # ----------- # Creates a menu showing a line for every file, and outputs the selected file. #.Example # if(Test-Path $Profile) { # switch(Show-ConsoleMenu "Profile exists:" "Delete it!","Rename it with 01","Abort" -Debug) { # 0 { rm $Profile -whatif } # 1 { mv $Profile [IO.Path]::ChangeExtension($Profile,"01.ps1") } # 2 { return } # } # } # # Description # ----------- # Shows how to use the return value without the Passthru switch. # This example would check if you have a profile, and if you do, would offer you the choice of removing or renaming it. param( # The items to be chosen from [Parameter(ValueFromPipeline=$true,Position=2)] [Alias("InputObject")] [PSObject[]]$Choices, # A caption to display before the choices [Parameter(Position=1)] [Alias("Title")] [string]$Caption, # A scriptblock expression for formatting the Choices. [Parameter(Position=3)] [ScriptBlock]$Expression=({$_}), # A prompt to display after the choices [Alias("Footer")] [string]$Prompt, # How much to indent the "center" of the selection menu (Defaults to 8) [int]$indentLeft=8, # If set, Show-ConsoleMenu returns the selected value from $choices, otherwise it returns the index (which is usually easier to use in a switch statement) [Switch]$Passthru, # If set, this function works with my New-BufferBox script by using Out-Buffer [Switch]$UseBufferBox, # If set, allows multiple selection (Press Enter to stop selecting more) [Switch]$MultiSelect ) begin { $allchoices = New-Object System.Collections.Generic.List[PSObject] } process { if($choices) { $allchoices.AddRange($choices) } } end { $Format = "{0:D1}"; $Digits = 1 if($allchoices.Count -gt 10) { $Digits = $allchoices.Count.ToString().Length $Format = "{0:D${Digits}}" } # Make a hashtable with keys for($i=0; $i -lt $allchoices.Count; $i++) { $allchoices[$i] = Add-Member -Input $allchoices[$i] -Type NoteProperty -Name ConsoleMenuKey -Value $($format -f $i) -Passthru } Write-Debug "There are $($allChoices.Count) choices, so we'll use $Digits digits" # output the menu to the screen $menu = $allchoices | Format-Table -HideTableHeader @{E="ConsoleMenuKey";A="Right";W=$indentLeft}, @{E=$Expression;A="Left"} -Force | Out-String $menu = $menu.TrimEnd() + "`n" if($UseBufferBox) { Out-Buffer ("`n" + (" " * ($indentLeft/2)) + $Caption + "`n") -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor Out-Buffer $menu } else { Write-Host ("`n" + (" " * ($indentLeft/2)) + $Caption + "`n") -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor Write-Host $menu } do { if($Prompt) { if($UseBufferBox) { Out-Buffer $Prompt -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor } else { Write-Host $Prompt -ForegroundColor $Host.PrivateData.VerboseForegroundColor -BackgroundColor $Host.PrivateData.VerboseBackgroundColor } } # get a choice from the user [string]$PreviousKeys="" do { $Key = $Host.UI.RawUI.ReadKey("IncludeKeyDown,NoEcho").Character try { [int][string]$choice = "${PreviousKeys}${Key}" $PreviousKeys = "${PreviousKeys}${Key}" } catch { ## The "?" causes us to re-show the menu. Useful for long multi-selects, which might scroll off. if(63 -eq [int][char]$Key) { if($UseBufferBox) { Out-Buffer $menu } else { Write-Host $menu } } elseif(13,27,0 -notcontains [int][char]$Key) { $warning = "You must type only numeric characters (hit Esc to exit)" if($UseBufferBox) { Out-Buffer $warning -ForegroundColor $Host.PrivateData.WarningForegroundColor -BackgroundColor $Host.PrivateData.WarningBackgroundColor } else { Write-Warning $warning } } } } while( $PreviousKeys.Length -lt $Digits -and (13,27 -notcontains [int][char]$Key)) if($PreviousKeys.Length -and $allchoices.Count -gt ([int]$PreviousKeys)) { if($Passthru) { $allchoices[([int]$PreviousKeys)] } else { $choice } } } while($key -ne [char]13 -and $MultiSelect) }} function Reset-Buffer { param( $Position = $Host.UI.RawUI.WindowPosition, [int]$Height = $Host.UI.RawUI.WindowSize.Height, [int]$Width = $Host.UI.RawUI.WindowSize.Width, # Note: all edges are padded by 1 for the box edges, but we also pad each side by this ammount: [int]$Padding = 1, $ForegroundColor = $Host.UI.RawUI.ForegroundColor, $BackgroundColor = $Host.UI.RawUI.BackgroundColor, $BorderColor = "Yellow", [switch]$NoBorder, [switch]$ShowInput, [string]$Title = "" ) $global:BufferHeight = $Height $global:BufferWidth = $Width $global:BufferPadding = $Padding $global:BufferForegroundColor = $ForegroundColor $global:BufferBackgroundColor = $BackgroundColor $global:BufferBorderColor = $BorderColor if($NoBorder) { $global:BufferBoxSides = 0 } else { $global:BufferBoxSides = 2 } if($ShowInput) { $global:BufferHeight -= 2 } $Host.UI.RawUI.SetBufferContents($Position,(New-BufferBox $BufferHeight $BufferWidth -Title:$Title -NoBorder:$NoBorder -ShowInput:$ShowInput -Background $BufferBackgroundColor -Border $BufferBorderColor)) $global:BufferPosition = $Position $global:BufferPosition.X += $global:BufferPadding + ($global:BufferBoxSides/2) # this gets set to the BOTTOM line, because I assume text will flow in from the bottom. $global:BufferPosition.Y += $global:BufferHeight - 2 # and this goes below that ... $global:BufferPromptPosition = $BufferPosition $global:BufferPromptPosition.Y += 2 $global:BufferPromptPosition.X += 2 - $global:BufferPadding # Prompt = "> " } function New-BufferBox { param( [int]$Height = $global:BufferHeight, [int]$Width = $global:BufferWidth, $Title = "", [switch]$NoBorder, [switch]$ShowInput, $BackgroundColor = $global:BufferBackgroundColor, $BorderColor = $global:BufferBorderColor ) $Width = $Width - $global:BufferBoxSides $LineTop =( $global:BoxChars.HorizontalDouble * 2) + $Title ` + $($global:BoxChars.HorizontalDouble * ($Width - ($Title.Length+2))) $LineField = ' ' * $Width $LineBottom = $global:BoxChars.HorizontalDouble * $Width $LineSeparator = $global:BoxChars.Horizontal * $Width $LinePrompt = '> ' + ' ' * ($Width-2) # Prompt = "> " if(!$NoBorder) { $LineField = $global:BoxChars.VerticalDouble + $LineField + $global:BoxChars.VerticalDouble $LinePrompt = $global:BoxChars.VerticalDouble + $LinePrompt + $global:BoxChars.VerticalDouble $LineBottom = $global:BoxChars.BottomLeftDouble + $LineBottom + $global:BoxChars.BottomRightDouble $LineTop = $global:BoxChars.TopLeftDouble + $LineTop + $global:BoxChars.TopRightDouble $LineSeparator = $global:BoxChars.VerticalDoubleRightSingle + $LineSeparator + $global:BoxChars.VerticalDoubleLeftSingle } if($ShowInput) { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineSeparator;$LinePrompt;$LineBottom} } else { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineBottom} } $boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,$BorderColor,$BackgroundColor) return ,$boxBuffer } function Move-Buffer { param( $Position = $global:BufferPosition, [int]$Left = $($global:BufferBoxSides/2), [int]$Top = (2 - $global:BufferHeight), [int]$Width = $global:BufferWidth - $global:BufferBoxSides, [int]$Height = $global:BufferHeight, [int]$Offset = -1 ) $Position.X += $Left $Position.Y += $Top $Rect = New-Object $RectType $Position.X, $Position.Y, ($Position.X + $width), ($Position.Y + $height -1) $Position.Y += $OffSet $Host.UI.RawUI.ScrollBufferContents($Rect, $Position, $Rect, (new-object System.Management.Automation.Host.BufferCell(' ',$global:BufferForegroundColor,$global:BufferBackgroundColor,'complete'))) } function Out-Buffer { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0,Mandatory=$true)] $Message, [Parameter(ValueFromPipelineByPropertyName=$true)] $ForegroundColor = $global:BufferForegroundColor, [Parameter(ValueFromPipelineByPropertyName=$true)] $BackgroundColor = $global:BufferBackgroundColor, [switch]$NoScroll, [Parameter(ValueFromPipelineByPropertyName=$true)] $Position = $global:BufferPosition, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Left = 0, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Top = $(3 - $global:BufferHeight), # Box Edge + New Lines [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Width = ($global:BufferWidth - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Height = ($global:BufferHeight - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Offset = $( 0 - ($Message.Split("`n").Count)) ) process { $lineCount = $Message.Split("`n").Count $Width = $Width - ($global:BufferPadding * 2) if(!$NoScroll){ Move-Buffer $Position $Left $Top $Width $Height $Offset } $MessageBuffer = New-Object "System.Management.Automation.Host.BufferCell[,]" $lineCount, $width $index = 0 foreach( $line in $Message.Split("`n") ) { $Buffer = $Host.UI.RawUI.NewBufferCellArray( @($line.Trim("`r").PadRight($Width)), $ForegroundColor, $BackgroundColor ) for($i = 0; $i -lt $width; $i++) { $MessageBuffer[$index,$i] = $Buffer[0,$i] } $index++ } $Y = $global:BufferPosition.Y $global:BufferPosition.Y -= $lineCount - 1 $Host.UI.RawUI.SetBufferContents($global:BufferPosition,$MessageBuffer) $global:BufferPosition.Y = $Y } } function Set-BufferInputLine { param([String]$Line = "") $PromptText = $line.PadRight(($global:BufferWidth - $line.Length - 3)) # Prompt = "> " $CursorPosition = $BufferPromptPosition $CursorPosition.X += $line.Length $Prompt = $Host.UI.RawUI.NewBufferCellArray( @($PromptText),$global:BufferForegroundColor, $global:BufferBackgroundColor) $Host.UI.RawUI.SetBufferContents( $BufferPromptPosition, $prompt ) $Host.UI.RawUI.CursorPosition = $CursorPosition } function Test-DisplayBox { $Position = $Host.UI.RawUI.WindowPosition $Position.X += 10 $Position.Y += 3 Reset-Buffer $Position 20 66 3 -ForegroundColor 'Gray' -BackgroundColor 'Black' -BorderColor 'Green' Out-Buffer 'Greetings!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer '- - - Thank you for running this simple demo script! - - -' 'Green' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'We are demonstrating how the scroll buffer works: you can add more than one line at a time, but you don''t really need to, since they add almost as fast one at a time.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'That is, as long as you don''t have any delay, you can just' 'white' 'black' Out-Buffer 'write out as many lines as you like, one-at-a-time, like' 'white' 'black' Out-Buffer 'this, and there is really no downside to doing that.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'Right? '.PadRight(58,"-") 'Red' 'black' Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'It''s clearly not as slick to just pop in multiple lines' 'white' 'black' sleep -m 1200 Out-Buffer 'with absolutely no scroll delay, and it makes it a little ' 'white' 'black' sleep -m 1200 Out-Buffer 'hard to tell what you have read already, but that''s ok.' 'white' 'black' sleep -m 1200 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'If you delay between paragraphs.' 'Red' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'But: don''t scroll off-screen faster than I can read!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' } ## Test-BufferBox 3.1 - Now with Tab completion #################################################################################################### ## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the ## chat room you have joined is going on in the background. ## ## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line ## you have to enclose it inside $() braces. #################################################################################################### function Test-BufferBox { param( $title = "PowerShell Interactive Buffer Demo" ) Reset-Buffer -ShowInput -Title $Title ################################################################################################### ##### We only need this for the purposes of the demo... ##### In a real script you would, presumably, be getting stuff from somewhere else to display $noise = $MyInvocation.MyCommand.Definition -split "`n" $index = 0; $random = New-Object "Random" [regex]$chunker = @' [^ \\"']+|([\\"'])[^\\\\1]*?\\\\1[^ \\"']*|([\\"'])[^\\\\1]*$| $ '@ ##### Printing a "How to Exit" message Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " This is just a demo. " -Fore Black -Back Cyan Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan ##### Setting the prompt Set-BufferInputLine ##### And initializing our two variables ... $line="" $exit = $false switch(Show-ConsoleMenu "What would you like to do now?" "Continue the demo","Stop the demo","Exit PowerShell" -UseBuffer) { 0 { <# do nothing, will continue #> } 1 { $exit = $true <#this script exits cleanly below#> } 2 { exit <# stop abruptly #> } } while(!$exit){ while(!$exit -and $Host.UI.RawUI.KeyAvailable) { $char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho"); # we don't want the key up events, but we do want to get rid of them if($char.KeyDown) { switch([int]$char.Character) { 13 { # Enter if($line.Trim() -eq "exit") { $exit = $true; break; } ################################################################################################### ################################################################################################### ############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ############# ############# This executes the user input! ############# ############# Don't use this on, say, content you got from a web page or chat room ############# iex "Out-Buffer `"$line`" -Fore Red"; ############# ################################################################################################### ################################################################################################### $line = ""; Set-BufferInputLine break; } 27 { # Esc $exit = $true; break; } 9 { # Tab if($line.Length -gt 0) { [Array]$words = $chunker.Matches($line) if($words.Count -ge 1) { Out-Buffer ($Words | Out-String) -Fore Black -Back White $lastWord = $words[$($words.Count-1)].Value $trim = $lastWord.TrimEnd("`r","`n") ## This may return more than one ... in which case subsequent tabs should iterate through them ## But for demo purposes, this is more than enough work... $replacement = TabExpansion -Line $line -LastWord ($lastWord.Trim() -replace '"') Out-Buffer ($replacement | Out-String) -Fore Black -Back White $line = $line.SubString(0, $line.Length - $lastWord.Length) + @($replacement)[0] Set-BufferInputLine $line } } break; } 8 { # Backspace if($line.Length -gt 0) { $line = $line.SubString(0,$($line.Length-1)) } # $pos = $Host.UI.RawUI.CursorPosition Set-BufferInputLine $line break; } 0 { # Not actually a key # Out-Buffer $($Char | Out-String) break; } default { $line += $char.Character Set-BufferInputLine $line } } } } # Simulate doing useful things 25% of the time if($random.NextDouble() -gt 0.75) { $noise[($index)..($index++)] | Out-Buffer if($index -ge $noise.Length){$index = 0} } sleep -milli 100 } $CursorPosition = $BufferPromptPosition $CursorPosition.Y += 2 $CursorPosition.X = 0 $Host.UI.RawUI.CursorPosition = $CursorPosition }
PowerShellCorpus/PoshCode/New-FilesystemHardLink.p.ps1
New-FilesystemHardLink.p.ps1
##############################################################################\n##\n## New-FileSystemHardLink\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\nCreate a new hard link, which allows you to create a new name by which you\ncan access an existing file. Windows only deletes the actual file once\nyou delete all hard links that point to it.\n\n.EXAMPLE\n\nPS >"Hello" > test.txt\nPS >dir test* | select name\n\nName\n----\ntest.txt\n\nPS >.\\New-FilesystemHardLink.ps1 test.txt test2.txt\nPS >type test2.txt\nHello\nPS >dir test* | select name\n\nName\n----\ntest.txt\ntest2.txt\n\n#>\n\nparam(\n ## The existing file that you want the new name to point to\n [string] $Path,\n\n ## The new filename you want to create\n [string] $Destination\n)\n\nSet-StrictMode -Version Latest\n\n## Ensure that the provided names are absolute paths\n$filename = $executionContext.SessionState.`\n Path.GetUnresolvedProviderPathFromPSPath($destination)\n$existingFilename = Resolve-Path $path\n\n## Prepare the parameter types and parameters for the CreateHardLink function\n$parameterTypes = [string], [string], [IntPtr]\n$parameters = [string] $filename, [string] $existingFilename, [IntPtr]::Zero\n\n## Call the CreateHardLink method in the Kernel32 DLL\n$currentDirectory = Split-Path $myInvocation.MyCommand.Path\n$invokeWindowsApiCommand = Join-Path $currentDirectory Invoke-WindowsApi.ps1\n$result = & $invokeWindowsApiCommand "kernel32" `\n ([bool]) "CreateHardLink" $parameterTypes $parameters\n\n## Provide an error message if the call fails\nif(-not $result)\n{\n $message = "Could not create hard link of $filename to " +\n "existing file $existingFilename"\n Write-Error $message\n}
PowerShellCorpus/PoshCode/Backup Hyper-V VMs.ps1
Backup Hyper-V VMs.ps1
# Directions for use: # Import this script using the Import-Module cmdlet # All output is logged to the backup directory in the $($BackupDriveLetter):\\VMBackup\\Backup-VMs.log file # Use the Backup-VMs cmdlet to begin the process # Parameter BackupDriveLetter indicates the drive to put this backup onto. It must be mounted to the host running the script. # Parameter VMHost defines the host that contains the VMs you want to back up. If it's blank, then it just targets the host the script is running on # Parameter VMNames defines the specific VMs you wish to backup, otherwise it'll back up all of them on the target host # Switch parameter ShutHostDownWhenFinished will cause the specified host (and any VMs running on it) to shut down upon completion of the backup # Example: # PS> Import-Module D:\\Backup-VMs.ps1 # PS> Backup-VMs -BackupDriveLetter F -VMHost HyperVHost -VMNames mydevmachine,broker77 # ---------------------------------------------------------------------------- # Note that this script requires administrator privileges for proper execution # ---------------------------------------------------------------------------- # Note that this script requires the following: # # PowerShell Management Library for Hyper-V (for the Get-VM and Export-VM cmdlets) # This installs itself wherever you downloaded it - make sure the HyperV folder finds its way to somewhere in $env:PSModulePath # http://pshyperv.codeplex.com/downloads/get/219013 # # Windows PowerShell Pack (for the Copy-ToZip cmdlet) # This installs to $home\\Documents\\WindowsPowerShell\\Modules, make sure that this path is in $env:PSModulePath # http://archive.msdn.microsoft.com/PowerShellPack/Release/ProjectReleases.aspx?ReleaseId=3341 # our one global variable is for logging $Logfile = "" Function Backup-VMs { [CmdletBinding(SupportsShouldProcess=$True)] Param( [parameter(Mandatory = $true)] [string]$BackupDriveLetter, # $BackupDriveLetter:\\VMBackups\\$backupDate [ValidateNotNullOrEmpty()] [string]$VMHost, # the host that holds the vms we wish to back up, otherwise the one running the script [string[]]$VMNames, # if not specified, back up all of them [switch]$ShutHostDownWhenFinished # when set, shuts down the target host, including any vms on it ) process { # first, run a bunch of checks #region checks # check if the PowerShellPack modules are loaded $isPowerShellPackLoaded = Get-Module -Name PowerShellPack if (!$isPowerShellPackLoaded) { Write-Host "Attempting to load PowerShellPack modules..." Import-Module -Name PowerShellPack $isPowerShellPackLoaded = Get-Module -Name PowerShellPack if (!$isPowerShellPackLoaded) { Write-Host -ForegroundColor Red "Cannot load PowerShellPack module - terminating backup script." Break } } # check if the HyperV module is loaded $isHyperVModuleLoaded = Get-Module -Name HyperV if (!$isHyperVModuleLoaded) { Write-Host "Attempting to load HyperV module..." Import-Module -Name HyperV $isHyperVModuleLoaded = Get-Module -Name HyperV if (!$isHyperVModuleLoaded) { Write-Host -ForegroundColor Red "Cannot load HyperV module - terminating backup script." Break } } # sanitize user input (F: will become F) if ($BackupDriveLetter -like "*:") { $BackupDriveLetter = $BackupDriveLetter -replace ".$" } # check to make sure the user specified a valid backup location if ((Test-Path "$($BackupDriveLetter):") -eq $false) { Write-Host -ForegroundColor Red "Drive $($BackupDriveLetter): does not exist - terminating backup script." Break } # if host was not speicified, use the host running the script if ($VMHost -eq "") { $VMHost = Hostname } # check to make sure the specified host is a vmhost if (!(Get-VMHost) -icontains $VMHost) { Write-Host -ForegroundColor Red "Host $($VMHost) is not listed in Get-VMHost - terminating backup script." Break } # check to make sure the specified host has any vms to back up if (!(Get-VM -Server $VMHost)) { Write-Host -ForegroundColor Red "Host $($VMHost) does not appear to have any VMs running on it according to 'Get-VM -Server $($VMHost)'." Write-Host -ForegroundColor Yellow "This can be occur if PowerShell is not running with elevated privileges." Write-Host -ForegroundColor Yellow "Please make sure that you are running PowerShell with Administrator privileges and try again." Write-Host -ForegroundColor Red "Terminating backup script." Break } #endregion #region directory business # make our parent directory if needed if ((Test-Path "$($BackupDriveLetter):\\VMBackup") -eq $false) { $parentDir = New-Item -Path "$($BackupDriveLetter):\\VMBackup" -ItemType "directory" if ((Test-Path $parentDir) -eq $false) { Write-Host -ForegroundColor Red "Problem creating $parentDir - terminating backup script." Break } } # initialize our logfile $Logfile = "$($BackupDriveLetter):\\VMBackup\\Backup-VMs.log" if ((Test-Path $Logfile) -eq $false) { $newFile = New-Item -Path $Logfile -ItemType "file" if ((Test-Path $Logfile) -eq $false) { Write-Host -ForegroundColor Red "Problem creating $Logfile - terminating backup script." Break } } $backupDate = Get-Date -Format "yyyy-MM-dd" $destDir = "$($BackupDriveLetter):\\VMBackup\\$backupDate-$VMHost-backup\\" # make our backup directory if needed if ((Test-Path $destDir) -eq $false) { $childDir = New-Item -Path $destDir -ItemType "directory" if ((Test-Path $childDir) -eq $false) { Write-Host -ForegroundColor Red "Problem creating $childDir - terminating backup script." Break } } #endregion Add-content -LiteralPath $Logfile -value "===================================================================================================" Add-content -LiteralPath $Logfile -value "===================================================================================================" # now that our checks are done, start backing up T -text "Starting Hyper-V virtual machine backup for host $VMHost at:" $dateTimeStart = date T -text "$($dateTimeStart)" T -text "" # export the vms to the destination ExportMyVms -VMHost $VMHost -Destination $destDir -VMNames $VMNames T -text "" T -text "Exporting finished" #region compression # get what we just backed up $sourceDirectory = Get-ChildItem $destDir if ($sourceDirectory) { # get the total size of all of the files we just backed up $sourceDirSize = Get-ChildItem $destDir -Recurse | Measure-Object -property length -sum -ErrorAction SilentlyContinue $sourceDirSize = ($sourceDirSize.sum / 1GB) # get how much free space is left on our backup drive $hostname = Hostname $backupDrive = Get-WmiObject win32_logicaldisk -ComputerName $hostname | Where-Object { $_.DeviceID -eq "$($BackupDriveLetter):" } $backupDriveFreeSpace = ($backupDrive.FreeSpace / 1GB) # tell the user what we've found $formattedBackupDriveFreeSpace = "{0:N2}" -f $backupDriveFreeSpace $formattedSourceDirSize = "{0:N2}" -f $sourceDirSize T -text "Checking free space for compression:" T -text "Drive $($BackupDriveLetter): has $formattedBackupDriveFreeSpace GB free on it, this backup took $formattedSourceDirSize GB" # check if we need to make any room for the next backup $downToOne = $false while (!$downToOne -and $sourceDirSize > $backupDriveFreeSpace) { # clear out the oldest backup if this is the case $backups = Get-ChildItem -Path "$($BackupDriveLetter):\\VMBackup\\" -include "*-backup.zip" -recurse -name $backups = [array]$backups | Sort-Object # make sure we aren't deleting the only directory! if ($backups.length -gt 1) { T -text "Removing the oldest backup [$($backups[0])] to clear up some more room" Remove-Item "$($BackupDriveLetter):\\VMBackup\\$($backups[0])" -Recurse -Force # now check again $backupDrive = Get-WmiObject win32_logicaldisk -ComputerName $hostname | Where-Object { $_.DeviceID -eq "$($BackupDriveLetter):" } $backupDriveFreeSpace = ($backupDrive.FreeSpace / 1GB) $formattedBackupDriveFreeSpace = "{0:N2}" -f $backupDriveFreeSpace T -text "Now we have $formattedBackupDriveFreeSpace GB of room" } else { # we're down to just one backup left, don't delete it! $downToOne = $true } } T -text "Compressing the backup..." # zip up everything we just did ZipFolder -directory $destDir -VMHost $VMHost $zipFileName = $destDir -replace ".$" $zipFileName = $zipFileName + ".zip" T -text "Backup [$($zipFileName)] created successfully" $destZipFileSize = (Get-ChildItem $zipFileName).Length / 1GB $formattedDestSize = "{0:N2}" -f $destZipFileSize T -text "Uncompressed size:`t$formattedSourceDirSize GB" T -text "Compressed size: `t$formattedDestSize GB" } #endregion # delete the non-compressed directory, leaving just the compressed one Remove-Item $destDir -Recurse -Force T -text "" T -text "Finished backup of $VMHost at:" $dateTimeEnd = date T -text "$($dateTimeEnd)" $length = ($dateTimeEnd - $dateTimeStart).TotalMinutes $length = "{0:N2}" -f $length T -text "The operation took $length minutes" if ($ShutHostDownWhenFinished -eq $true) { T -text "Attempting to shut down host machine $VMHost" ShutdownTheHost -HostToShutDown $VMHost } } } ## this function will shut down any vms running on the host executing this script and then shut down said host Function ShutdownTheHost { [CmdletBinding(SupportsShouldProcess=$True)] Param( [string]$HostToShutDown ) process { ## Get a list of all VMs on $HostToShutDown $VMs = Get-VM -Server $HostToShutDown ## only run through the list if there's anything in it if ($VMs) { ## For each VM on Node, Save (if necessary), Export and Restore (if necessary) foreach ($VM in @($VMs)) { $VMName = $VM.ElementName $summofvm = get-vmsummary $VMName $summhb = $summofvm.heartbeat $summes = $summofvm.enabledstate ## Shutdown the VM if HeartBeat Service responds if ($summhb -eq "OK") { T -text "" T -text "HeartBeat Service for $VMName is responding $summhb, saving the machine state" Save-VM -VM $VMName -Server $VMHost -Force -Wait } ## Checks to see if the VM is already stopped elseif (($summes -eq "Stopped") -or ($summes -eq "Suspended")) { T -text "" T -text "$VMName is $summes" } ## If the HeartBeat service is not OK, aborting this VM elseif ($summhb -ne "OK" -and $summes -ne "Stopped") { T -text T -text "HeartBeat Service for $VMName is responding $summhb. Aborting save state." } } T -text "All VMs on $HostToShutDown shut down or suspended." } T -text "Shutting down machine $HostToShutDown..." Stop-Computer -ComputerName $HostToShutDown } } ## the following three functions relating to zipping up a folder come from Jeremy Jameson ## http://www.technologytoolbox.com/blog/jjameson/archive/2012/02/28/zip-a-folder-using-powershell.aspx ## I have modified his approach to suit the multi-gigabyte files we'll be dealing with function IsFileLocked( [string] $path) { [bool] $fileExists = Test-Path $path If ($fileExists -eq $false) { Throw "File does not exist (" + $path + ")" } [bool] $isFileLocked = $true $file = $null Try { $file = [IO.File]::Open( $path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) $isFileLocked = $false } Catch [IO.IOException] { If ($_.Exception.Message.EndsWith("it is being used by another process.") -eq $false) { Throw $_.Exception } } Finally { If ($file -ne $null) { $file.Close() } } return $isFileLocked } function WaitForZipOperationToFinish( [__ComObject] $zipFile, [int] $expectedNumberOfItemsInZipFile) { T -text "Waiting for zip operation to finish on $($zipFile.Self.Path)..." Start-Sleep -Seconds 5 # ensure zip operation had time to start # wait for the operation to finish # the folder is locked while we're zipping stuff up [bool] $isFileLocked = IsFileLocked($zipFile.Self.Path) while($isFileLocked) { Write-Host -NoNewLine "." Start-Sleep -Seconds 5 $isFileLocked = IsFileLocked($zipFile.Self.Path) } T -text "" } function ZipFolder( [IO.DirectoryInfo] $directory) { $backupFullName = $directory.FullName T -text ("Creating zip file for folder ($backupFullName)...") [IO.DirectoryInfo] $parentDir = $directory.Parent [string] $zipFileName If ($parentDir.FullName.EndsWith("\\") -eq $true) { # e.g. $parentDir = "C:\\" $zipFileName = $parentDir.FullName + $directory.Name + ".zip" } Else { $zipFileName = $parentDir.FullName + "\\" + $directory.Name + ".zip" } Set-Content $zipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) $shellApp = New-Object -ComObject Shell.Application $zipFile = $shellApp.NameSpace($zipFileName) If ($zipFile -eq $null) { T -text "Failed to get zip file object." } [int] $expectedCount = (Get-ChildItem $directory -Force -Recurse).Count $expectedCount += 1 # account for the top-level folder T -text "Copying $expectedCount items into file $zipFileName..." $zipFile.CopyHere($directory.FullName) # wait for CopyHere operation to complete WaitForZipOperationToFinish $zipFile $expectedCount T -text "Successfully created zip file for folder ($backupFullName)." } ## Powershell Script to Shutdown and Export Hyper-V 2008 R2 VMs, one at a time. ## Written by Stan Czerno ## http://www.czerno.com/default.asp?inc=/html/windows/hyperv/cluster/HyperV_Export_VMs.asp ## I have modified his approach to suit our purposes Function ExportMyVms { [CmdletBinding(SupportsShouldProcess=$True)] Param( [string]$Destination, [string[]]$VMNames, [string]$VMHost ) process { ## The script requires the PowerShell Management Library for Hyper-V for it to work. ## The PowerShell Management Library for Hyper-V can be downloaded at http://pshyperv.codeplex.com/ ## Be sure to read the documentation before using: ## http://pshyperv.codeplex.com/releases/view/62842 ## http://pshyperv.codeplex.com/releases/view/38769 ## This is how I backup the VMs on my Two-Node Hyper-V Cluster. I can afford for my servers to be down while this is done and ## some of my other resources are clustered so there is minimum down time. ## I also do System State Backups, Exchange Backups and SQL Backups in addition. ## This script can be used on a Stand-Alone Hyper-V Server as well. ## Let me know if you have a better way of doing this as I am not a very good developer and new to Powershell. ## Get a list of all VMs on Node if ($VMNames) { if (($VMNames.Length) -gt 1) { # pass in a multiple-element string array directly $VMs = Get-VM -Name $VMNames -Server $VMHost } else { # turn a single-element string array back into a string $VMNames = [string]$VMNames $VMs = Get-VM -Name "$VMNames" -Server $VMHost } } else { $VMs = Get-VM -Server $VMHost } ## only run through the list if there's anything in it if ($VMs) { foreach ($VM in @($VMs)) { $listOfVmNames += $VM.ElementName + ", " } $listOfVmNames = $listOfVmNames -replace "..$" T -text "Attempting to backup the following VMs:" T -text "$listOfVmNames" T -text "" Write-Host "Do not cancel the export process as it may cause unpredictable VM behavior" -ForegroundColor Yellow ## For each VM on Node, Save (if necessary), Export and Restore (if necessary) foreach ($VM in @($VMs)) { $VMName = $VM.ElementName $summofvm = get-vmsummary $VMName $summhb = $summofvm.heartbeat $summes = $summofvm.enabledstate $restartWhenDone = $false $doexport = "no" ## Shutdown the VM if HeartBeat Service responds if ($summhb -eq "OK") { $doexport = "yes" T -text "" T -text "HeartBeat Service for $VMName is responding $summhb, saving the machine state" $restartWhenDone = $true Save-VM -VM $VMName -Server $VMHost -Force -Wait } ## Checks to see if the VM is already stopped elseif (($summes -eq "Stopped") -or ($summes -eq "Suspended")) { $doexport = "yes" T -text "" T -text "$VMName is $summes, starting export" } ## If the HeartBeat service is not OK, aborting this VM elseif ($summhb -ne "OK" -and $summes -ne "Stopped") { $doexport = "no" T -text T -text "HeartBeat Service for $VMName is responding $summhb. Save state and export aborted for $VMName" } $i = 1 if ($doexport -eq "yes") { $VMState = get-vmsummary $VMName $VMEnabledState = $VMState.enabledstate if ($VMEnabledState -eq "Suspended" -or $VMEnabledState -eq "Stopped") { ## If a folder already exists for the current VM, delete it. if ([IO.Directory]::Exists("$($Destination)\\$($VMName)")) { [IO.Directory]::Delete("$($Destination)\\$($VMName)", $True) } T -text "Exporting $VMName" ## Begin export of the VM export-vm -VM $VMName -Server $VMHost -path $Destination -CopyState -Wait -Force -ErrorAction SilentlyContinue ## check to ensure the export succeeded $exportedCount = (Get-ChildItem $Destination -Force -Recurse).Count ## there should be way more than 5 elements in the destination - this is to account for empty folders if ($exportedCount -lt 5) { T -text "***** Automated export failed for $VMName *****" T -text "***** Manual export advised *****" } if ($restartWhenDone) { T -text "Restarting $VMName..." ## Start the VM and wait for a Heartbeat with a 5 minute time-out Start-VM $VMName -HeartBeatTimeOut 300 -Wait } } else { T -text "Could not properly save state on VM $VMName, skipping this one and moving on." } } } } else { T -text "No VMs found to back up." } } } ## This is just a hand-made wrapper function that mimics the Tee-Object cmdlet with less fuss ## Plus, it makes our log file prettier Function T { [CmdletBinding(SupportsShouldProcess=$True)] Param( [string]$text ) process { Write-Host "$text" $now = date $text = "$now`t: $text" Add-content -LiteralPath $Logfile -value $text } }
PowerShellCorpus/PoshCode/Get-CrystalReportTable.ps1
Get-CrystalReportTable.ps1
function Get-CrystalReportTable() { #Requires -Version 2 <# .Synopsis Examines a Crystal Report and returns the tables used .Description Examines a Crystal Report and returns the tables used by the main report and subreports .Example $reports = Dir *.rpt | Get-CrystalReportTable .Notes Written by Steven Murawski on 11/12/09 http://blog.usepowershell.com Version 0.1 #> [cmdletbinding()] param ( [parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [Alias('FullName')] [string]$Path ) begin { [reflection.assembly]::LoadWithPartialName('CrystalDecisions.Shared') | Out-Null [reflection.assembly]::LoadWithPartialName('CrystalDecisions.CrystalReports.Engine') | Out-Null } process { try { $output = New-Object PSObject | Select-Object Name, Tables, SubReports $output.name = Split-Path $path -Leaf $report = New-Object CrystalDecisions.CrystalReports.Engine.ReportDocument $report.load($path) $output.Tables = $report.Database.Tables | Select-Object -expand Name $subreports = @($report.ReportDefinition.ReportObjects | Where-Object {$_ -is [CrystalDecisions.CrystalReports.Engine.SubreportObject]}) if ($subreports.count -gt 0 ) { $output.subreports = @() foreach ($subreport in $subreports) { $subreportdata = New-Object PSObject | Select-Object Name, Tables $subreportdata.name = $subreport.SubreportName $subreportobject = $report.OpenSubreport($subreport.SubreportName) $subreportdata.Tables = $subreportobject.Database.Tables | Select-Object -expand Name $output.subreports += $subreportdata } } Write-Output $output } finally { $report.dispose() } } }
PowerShellCorpus/PoshCode/SqlProxy_1.psm1.ps1
SqlProxy_1.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 "Set-SqlLoginDefaultDatabase"=10 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname, [Parameter(Position=2, Mandatory=$false)] [switch]$force ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } elseif ($force) { $server.Databases | where {$_.IsAccessible -eq $true} } #Skip systems databases else { $server.Databases | where {$_.IsSystemObject -eq $false -and $_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Gets an SMO Login object. .DESCRIPTION The Get-SqlLogin function gets a collection of SMO Login objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlLogin .OUTPUTS Microsoft.SqlServer.Management.Smo.Login Get-SqlLogin returns a Microsoft.SqlServer.Management.Smo.Login object. .EXAMPLE Get-SqlLogin "Z002\\sql2K8" This command gets a collection of SMO Login objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlLogin #> function Get-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlLogin $($server.Name)" foreach ($login in $server.Logins | where {$_.LoginType.ToString() -ne 'Certificate'}) { #Return Login Object $login } } # Get-SqlLogin ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase if ($logintype -eq 'SqlLogin') { $login.LoginType = $logintype if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } try { $login.Create($password) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } elseif ($logintype -eq 'WindowsUser' -or $logintype -eq 'WindowsGroup') { $login.LoginType = $logintype try { $login.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | % {"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.ChangePassword($password,$true,$false) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLoginDefaultDatabase function changes a SQL Login default database. .INPUTS None You cannot pipe objects to Set-SqlLoginDefaultDatabase .OUTPUTS None This function does not generate any output. .EXAMPLE Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master' This command sets the default database for TestPSUnit login. .LINK Set-SqlLoginDefaultDatabase #> function Set-SqlLoginDefaultDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.DefaultDatabase = $DefaultDatabase $login.Alter() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLoginDefaultDatabase ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Rename("$newName") $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login if ($db.parent.Information.Version.Major -ne '8') { $user.DefaultSchema = $defaultschema } try { $user.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" $user = $database.Users[$name] try { if ($user) { $user.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "User $name does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Gets an SMO ServerRole object. .DESCRIPTION The Get-SqlServerRole function gets a collection of SMO ServerRole objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServerRole .OUTPUTS Microsoft.SqlServer.Management.Smo.ServerRole Get-SqlServerRole returns a Microsoft.SqlServer.Management.Smo.ServerRole object. .EXAMPLE Get-SqlServerRole "Z002\\sql2K8" This command gets a collection of SMO ServerRole objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlServerRole #> function Get-SqlServerRole { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlServerRole:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlServerRole $($server.Name)" foreach ($svrole in $server.Roles) { #Return ServerRole Object $svrole } } #Get-SqlServerRole ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.AddMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.DropMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Returns a SMO DatabaseRole object with additional properties. .DESCRIPTION The Get-SqlDatabaseRole function gets a collection of SMO DatabaseRole objects for the specified SQL Database. .INPUTS Microsoft.SqlServer.Management.Smo.Database You can pipe database objects to Get-SqlDatabaseRole .OUTPUTS Microsoft.SqlServer.Management.Smo.DatabaseRole Get-SqlDatabaseRole returns a Microsoft.SqlServer.Management.Smo.DatabaseRole object. .EXAMPLE Get-SqlDatabaseRole $(Get-SqlDatabase "Z002\\sql2K8" pubs) This command gets a collection of SMO DatabaseRole objects for SQL Server Z002\\SQL2K8, pubs database. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" | Get-SqlDatabaseRole This command gets a collection SMO DatabaseRole objects for all SQL databases on the SQL Server Z002\\SQL2K8. .LINK Get-SqlDatabaseRole #> function Get-SqlDatabaseRole { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [Microsoft.SqlServer.Management.Smo.Database]$database ) process { foreach ($role in $database.Roles) { #Return DatabaseRole Object $role } } } #Get-SqlDatabaseRole ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.AddMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.DropMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog
PowerShellCorpus/PoshCode/e3d743cf-73b0-4cbc-b91e-bf279e52655e.ps1
e3d743cf-73b0-4cbc-b91e-bf279e52655e.ps1
param( [string] $dirRoot = ".", [string] $Spec = "*.*" ) # # Description: # Use the wide unicode versions (FindFirstFileW and FindNextFileW) to report a directory listing of all files, including those that exceed the MAX_PATH ANSI limitations # # Assumptions, this script works on the assumption that: # There's a console to write the output from the compiled VB.Net # # Author: # Wayne Martin, 15/05/2008, http://waynes-world-it.blogspot.com/ # # Usage # PowerShell . .\\FindFiles.ps1 -d c:\\temp -s *.* # # PowerShell . .\\FindFiles.ps1 -d c:\\temp # # References: # http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx # http://blogs.msdn.com/jaredpar/archive/2008/03/14/making-pinvoke-easy.aspx $provider = new-object Microsoft.VisualBasic.VBCodeProvider $params = new-object System.CodeDom.Compiler.CompilerParameters $params.GenerateInMemory = $True $refs = "System.dll","Microsoft.VisualBasic.dll" $params.ReferencedAssemblies.AddRange($refs) $txtCode = @' Imports System Imports System.Runtime.InteropServices Class FindFiles Const ERROR_SUCCESS As Long = 0 Private Const MAX_PREFERRED_LENGTH As Long = -1 <System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet:=System.Runtime.InteropServices.CharSet.[Unicode])> _ Public Structure WIN32_FIND_DATAW '''DWORD->unsigned int Public dwFileAttributes As UInteger '''FILETIME->_FILETIME Public ftCreationTime As FILETIME '''FILETIME->_FILETIME Public ftLastAccessTime As FILETIME '''FILETIME->_FILETIME Public ftLastWriteTime As FILETIME '''DWORD->unsigned int Public nFileSizeHigh As UInteger '''DWORD->unsigned int Public nFileSizeLow As UInteger '''DWORD->unsigned int Public dwReserved0 As UInteger '''DWORD->unsigned int Public dwReserved1 As UInteger '''WCHAR[260] <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=260)> _ Public cFileName As String '''WCHAR[14] <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=14)> _ Public cAlternateFileName As String End Structure <System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)> _ Public Structure FILETIME '''DWORD->unsigned int Public dwLowDateTime As UInteger '''DWORD->unsigned int Public dwHighDateTime As UInteger End Structure Partial Public Class NativeMethods '''Return Type: HANDLE->void* '''lpFileName: LPCWSTR->WCHAR* '''lpFindFileData: LPWIN32_FIND_DATAW->_WIN32_FIND_DATAW* <System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindFirstFileW")> _ Public Shared Function FindFirstFileW(<System.Runtime.InteropServices.InAttribute(), System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)> ByVal lpFileName As String, <System.Runtime.InteropServices.OutAttribute()> ByRef lpFindFileData As WIN32_FIND_DATAW) As System.IntPtr End Function '''Return Type: BOOL->int '''hFindFile: HANDLE->void* '''lpFindFileData: LPWIN32_FIND_DATAW->_WIN32_FIND_DATAW* <System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindNextFileW")> _ Public Shared Function FindNextFileW(<System.Runtime.InteropServices.InAttribute()> ByVal hFindFile As System.IntPtr, <System.Runtime.InteropServices.OutAttribute()> ByRef lpFindFileData As WIN32_FIND_DATAW) As <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean End Function '''Return Type: BOOL->int '''hFindFile: HANDLE->void* <System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="FindClose")> _ Public Shared Function FindClose(ByVal hFindFile As System.IntPtr) As <System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)> Boolean End Function End Class Private Const FILE_ATTRIBUTE_DIRECTORY As Long = &H10 Dim FFW as New NativeMethods Function Main(ByVal dirRoot As String, ByVal sFileSpec As String) As Long Dim result As Long result = FindFiles(dirRoot, sFileSpec) main = result ' Return the result End Function Function FindFiles(ByRef sDir As String, ByVal sFileSpec as String) Dim FindFileData as WIN32_FIND_DATAW Dim hFile As Long Dim sFullPath As String sFullPath = "\\\\?\\" & sDir 'console.writeline(sFullPath & "\\" & sFileSpec) hFile = FFW.FindFirstFileW(sFullPath & "\\" & sFileSpec, FindFileData) ' Find the first object if hFile > 0 Then ' Has something been found? If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) <> FILE_ATTRIBUTE_DIRECTORY Then ' Is this a file? console.writeline(sFullPath & "\\" & FindFileData.cFileName) ' Yes, report the full path and filename End If While FFW.FindNextFileW(hFile, FindFileData) ' For all the items in this directory If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) <> FILE_ATTRIBUTE_DIRECTORY Then ' Is this a file? console.writeline(sFullPath & "\\" & FindFileData.cFileName) ' Yes, report the full path and filename End If End While FFW.FindClose(hFile) ' Close the handle FindFileData = Nothing End If hFile = FFW.FindFirstFileW(sFullPath & "\\" & "*.*", FindFileData) ' Repeat the process looking for sub-directories using *.* if hFile > 0 Then If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) AND _ (FindFileData.cFileName <> ".") AND (FindFileData.cFileName <> "..") Then Call FindFiles(sDir & "\\" & FindFileData.cFileName, sFileSpec) ' Recurse End If While FFW.FindNextFileW(hFile, FindFileData) If (FindFileData.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) AND _ (FindFileData.cFileName <> ".") AND (FindFileData.cFileName <> "..") Then Call FindFiles(sDir & "\\" & FindFileData.cFileName, sFileSpec) ' Recurse End If End While FFW.FindClose(hFile) ' Close the handle FindFileData = Nothing End If End Function end class '@ $cr = $provider.CompileAssemblyFromSource($params, $txtCode) if ($cr.Errors.Count) { $codeLines = $txtCode.Split("`n"); foreach ($ce in $cr.Errors) { write-host "Error: $($codeLines[$($ce.Line - 1)])" write-host $ce #$ce out-default } Throw "INVALID DATA: Errors encountered while compiling code" } $mAssembly = $cr.CompiledAssembly $instance = $mAssembly.CreateInstance("FindFiles") $result = $instance.main($dirRoot, $Spec)
PowerShellCorpus/PoshCode/GPRS Online log_7.ps1
GPRS Online log_7.ps1
<# .SYNOPSIS Get-GprsTime (V4.0 Update for Windows 7 and allow time correction) Check the total connect time of any GPRS devices from a specified date. Use 'Get-Help .\\Get-GprsTime -full' to view Help for this script. .DESCRIPTION Display all the GPRS modem Event Log entries. While applications issued by the mobile phone manufacturers will invariably monitor only their own usage, this will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc. Use the -Verbose switch for some extra information if desired. A default value can be set with the -Monthly switch but can be temporarily overridden with any -Start value and deleted by entering an invalid date. Now uses .NET Parse to use any culture date input. Switches -M and -S cannot be used together. A Balloon prompt will be issued in the Notification area for the 5 days before the nominal month end. NOTE: this can effectively be suppressed by using a value higher than the SIM card term, ie something like -Account 90 for a 30 day card which will override the default setting. Define a function in $profile to set any permanent switches, for example to remove 1hour 15 minutes from the total each time. function GPRS { Invoke-Expression ".\\Get-GprsTime -Adjust 1:15:00- $args" } .EXAMPLE .\\Get-GprsTime.ps1 -Monthly 4/8/2011 This will set the default search date to start from 4/8/2011 and is used to reset the start date each month for the average 30/31 day SIM card. .EXAMPLE .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose Search from 12/07/2011 and also show (Verbose) details for each session. The Account switch will override any balloon prompt near the SIM expiry date. .EXAMPLE .\\Get-GprsTime.ps1 5/9/2011 -v Search one day only and show session details. .EXAMPLE .\\Get-GprsTime.ps1 -Today Show all sessions for today. This always defaults to verbose output. .EXAMPLE .\\Get-GprsTime.ps1 -Debug This shows the first available Event Log record & confirms switch settings. (Note that it will probably not be the first 'RemoteAccess' or 'RasClient' record). .EXAMPLE .\\Get-GprsTime -Adjust 1:20:00 If the same SIM card is used on another computer then such times will have to be added here manually (this should be put in a function in $profile so that it will automatically be included - see example above). To remove an amount of time, just put a '-' sign after the desired figure. .NOTES A shorter total time than that actually used will result if the Event Log does not contain earlier dates; just increase the log size in such a case. The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a (binary compiled) Module version of this procedure is included in the file Gprs3xxx.zip download there; the execution time of the module being about 10 times faster than this script. Use '(measure-Command {.\\Get-GprsTime}).TotalSeconds' to confirm the times. For the Event Log to record connect & disconnect events, the modem software should be set to RAS rather than NDIS if possible. #> Param ([String] $start, [alias("PERIOD")][string] $adjust, [String] $monthly, [Int] $account = 0, [Switch] $today, [Switch] $verbose, [Switch] $debug) Trap [System.Management.Automation.MethodInvocationException] { [Int]$line = $error[0].InvocationInfo.ScriptLineNumber [System.Media.SystemSounds]::Hand.Play() if ($line -eq 205) { Write-Warning "[$name] Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } else { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" } exit 1 } #Establish the Operating System...We only need to confirm XP here. #The result will be written to the 'out' variable '$osv'. function Get-OSVersion($computer,[ref]$osv) { $os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer Switch -regex ($os.Version) { '^5\\.1\\.(\\d{1,4})$' { $osv.value = "xp" } #Find XP & variants. default { $osv.value = "unknown" } } } $osv = $null Get-OSVersion -computer 'localhost' -osv ([ref]$osv) if ($osv -eq 'xp') { $logname = 'System' $connEvent = 20158 $discEvent = 20159 $source = 'RemoteAccess' } else { #Treat As Vista or Windows 7. $logname = 'Application' $connEvent = 20225 $discEvent = 20226 $source = 'RasClient' } $entryType = 'Information' $logEntry = $null $oldest = Get-eventlog -LogName $logname | #Get the earliest Log record. 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 } } $adjustment = $null #Otherwise 'Set-Strictmode -Version latest' will catch. if ($adjust) { $pattern = '^(\\d{1,3}):(\\d{1,2}):(\\d{1,2})-?$' if ($adjust -notmatch $pattern ) { Write-Warning "Invalid format - use <hours>:<minutes>:<seconds>" return } #Now create the 'adjustment' to add later. $adjustment = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] $outString = $adjust.Replace('-','') $outString = interval $outString } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" if ($logEntry) { Write-Debug "$logEntry" } $lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)} if ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log." } else { Write-Output "(There are no events indicated in the System Event Log)" } $lines | ForEach-Object { try { $source = $_.Source } catch { return } if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = Interval $diff Write-Verbose "Disconnect at $convDisc. Online - $period" Write-Verbose " Connect at $convConn." } } #End ForEach if (!$source) { $source = '(Undetermined)' } Write-Verbose "Using local event source - System Event Log [$source]" $period = Interval $total function formatSpan ($timespan) { #Convert returns of '1.11:00:00'. $addHours = $timespan.Days * 24 $addHours+= $timespan.Hours $h = $addHours.ToString().PadLeft(2,'0') + ':' $m = $timespan.Minutes.ToString().PadLeft(2,'0') + ':' $s = $timespan.Seconds.ToString().PadLeft(2,'0') return $h + $m + $s } if ($adjustment -and ($total -match $pattern)) { $outDate = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] if (!$adjust.EndsWith('-')) { $period = $outDate + $adjustment #The '-adjust' value added at start. $show = formatSpan $period $show = interval $show #Get hours,minutes suffix. Write-Output "Total online usage $insert $convert is $show" Write-Output "(Including $($outString.Replace(' ',' ')) adjustment time)" } else { if ($outDate.TotalSeconds -gt $adjustment.TotalSeconds) { $period = $outDate - $adjustment $show = formatSpan $period $show = interval $show Write-Output "Total online usage $insert $convert is $show" Write-Output "(Excluding $($outString.Replace(' ',' ')) adjustment time)" } else { Write-Output "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))." $adjust = $adjust.Replace('-','') Write-Warning "Invalid amount entered ($adjust) - no adjustment performed" } } } else { Write-OutPut "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))." } Write-Output ""
PowerShellCorpus/PoshCode/Select-Alive.ps1
Select-Alive.ps1
filter Select-Alive { param ( [switch]$Verbose ) trap { Write-Verbose "$(get-date -f 's') ping failed: $computer" continue } if ($Verbose) { $VerbosePreference = "continue" $ErrorActionPreference = "continue" } else { $VerbosePreference = "silentlycontinue" $ErrorActionPreference = "silentlycontinue" } Write-Verbose "$(get-date -f 's') ping start" $ping = New-Object System.Net.NetworkInformation.Ping $reply = $null $_ | foreach-object { $obj = $_ # Accomodate different input object types # thx Gaurhoth (http://thepowershellguy.com/blogs/gaurhoth/archive/2007/10/08/an-example-of-how-to-use-new-taskpool.aspx) switch ($obj.psbase.gettype().name) { "DirectoryEntry" { $cn = $obj.dnshostname[0] } "IPHostEntry" { $cn = $obj.HostName } "PSCustomObject" { $cn = $obj.Name } "SearchResult" { $cn = $obj.properties['dnshostname'][0] } "String" { $cn = $obj.trim() } } Write-Verbose "$(get-date -f 's') pinging $cn..." $searchCount++ $reply = $ping.Send($cn) if ($reply.status -eq "Success") { $cn; $pingCount++ } } Write-Verbose "$(get-date -f 's') ping end - $pingCount/$searchCount online" }
PowerShellCorpus/PoshCode/ConvertFrom-FahrenheitWi_1.ps1
ConvertFrom-FahrenheitWi_1.ps1
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nparam([double] $Fahrenheit)\n\nSet-StrictMode -Version Latest\n\n## Convert it to Celsius\n$celsius = $fahrenheit - 32\n$celsius = $celsius / 1.8\n\n## Output the answer\n"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
PowerShellCorpus/PoshCode/Set Logfile length_1.ps1
Set Logfile length_1.ps1
################################################################################ # Set-FileLines.ps1 # This script will maintain the PS Transcript file, or any text file, at a fixed # length and can be used to prevent such files from becoming too large, with the # option of removing any blank lines. Defaults to 10000 lines and can be placed # in $profile. # Setting lines to 0 will just remove any blank lines from the file and, in this # case, the -Blanks switch is not necessary. # Examples: # Set-FileLines 1500 c:\\Scripts\\Logfile.txt # Set-FileLines 0 c:\\scripts\\anyfile.txt # Set-FileLines 3000 -Blanks # The author can be contacted via www.SeaStarDevelopmet.Bravehost.com ################################################################################ Param ([int] $lines = 10000, [String]$file = "$pwd\\Transcript.txt", [Switch]$blanks) If ($file -notlike "*.txt") { [System.Media.SystemSounds]::Hand.Play() Write-Error "This script can only process .txt files" Exit 1 } If (!(Test-Path $file)) { [System.Media.SystemSounds]::Hand.Play() Write-Error "File $file does not exist" Exit 1 } [int]$count = 0 [int]$blankLines = 0 $errorActionPreference = 'SilentlyContinue' $content = (Get-Content $file) If ($lines -eq 0) { #Input 0 lines to have just blank lines removed. [int]$extra = 1 [int]$count = 1 [switch]$blanks = $true #Otherwise no blanks will be deleted below. } Else { $fileLength = ($content | Measure-Object -line) [int]$extra = $fileLength.Lines - $lines #The number of lines to remove. } If ($extra -gt 0) { $tempfile = [IO.Path]::GetTempFileName() Write-Output "Starting maintenance on file <$file>" $content | ForEach-Object { $count += 1 If($count -gt $extra) { #Ignore the first $extra lines. If (($blanks) -and ($_ -match '^\\s*$')) { #Skip blank lines. $blankLines++ } Else { $_ | Out-File $tempfile -Append -Force #Create new file. } } } If ($file -like "*transcript.txt") { Stop-Transcript | Out-Null } Remove-Item $file Move-Item $tempfile -Destination $file If ($lines -eq 0) { #Only interested in blank lines here. $tag = "$blankLines blank lines removed." } ElseIf ($blanks) { $tag = "$extra lines removed (+ $blankLines blank)." } Else { #Not interested in blank lines. $tag = "$extra lines removed." } If ($file -like "*transcript.txt") { Start-Transcript -append -path $file -force | Out-Null } Write-Output "Maintenance of file completed: $tag" } $ErrorActionPreference = 'Continue'
PowerShellCorpus/PoshCode/Check latest BIOS Rev_2.ps1
Check latest BIOS Rev_2.ps1
$BiosRev = Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName -Credential $Credentials # Shortened URL for the Dell Support page, fileid=441102, appears to be the identifier for BIOS downloads # I tested this on a few different models of Dell workstations. $DellBIOSPage = "http://support.dell.com/support/downloads/download.aspx?c=us&cs=RC956904&l=en&s=hied&releaseid=R294848&SystemID=PLX_960&servicetag=$($BiosRev.SerialNumber)&fileid=441102" # This HTML code immediately preceed's the actual service tag, you can see it when you 'view source' on the page $DellPageVersionString = "<span id=`"Version`" class=`"para`">" If ($BiosRev.Manufacturer -match "Dell") { $DellPage = (New-Object -TypeName net.webclient).DownloadString($DellBIOSPage) # Assuming that Dell BIOS rev's remain 3 characters, I find where my string starts and add the length to it # and the substring returns the BIOS rev. $DellCurrentBios = $DellPage.Substring($DellPage.IndexOf($DellPageVersionString)+$DellPageVersionString.Length,3) If (($BiosRev.SMBIOSBIOSVersion -eq $DellCurrentBios) -eq $false) { # Download the latest installer if the Rev's don't match # Assuming Dell continues to use FTP for downloads, find the download URL # This returns just the URL portion of the HTML code $BIOSDownloadURL = $DellPage.Substring($DellPage.IndexOf("http://ftp"),(($DellPage.Substring($DellPage.IndexOf("'http://ftp"),100)).indexof(".EXE"))+3) # Pull the filename from the end of the path, the 12's indicate 8+3 that Dell is using # for filenames, if that changes this should as well. $BIOSFile = $BIOSDownloadURL.Substring(($BIOSDownloadURL.Length)-12,12) If ((Test-Path "C:\\Dell\\") -eq $false) { New-Item -Path "C:\\" -Name "Dell" -ItemType Directory } If ((Test-Path "C:\\Dell\\$($ComputerName)") -eq $false) { New-Item -Path "C:\\Dell" -Name $ComputerName -ItemType Directory } (New-Object -TypeName net.webclient).DownloadFile($BIOSDownloadURL,"C:\\Dell\\$($ComputerName)\\$($BIOSFile)") Write-Host "Latest BIOS for $($ComputerName) downloaded to C:\\Dell\\$($ComputerName)\\$($BIOSFile)" } }
PowerShellCorpus/PoshCode/Get-OleDBPSObject.ps1
Get-OleDBPSObject.ps1
function Get-OleDBPSObject ([string]$ConnectionString, [string]$Query) { $ConnObj = new-object System.Data.OleDb.OleDbConnection $ConnectionString $command = New-Object System.Data.OleDb.OleDbCommand $Query, $ConnObj try { $ConnObj.Open() [System.Data.OleDB.OleDbDataReader]$reader = $command.ExecuteReader() while ($reader.Read()) { $obj = New-Object PSObject for ($i=0; $i -lt $reader.FieldCount; $i++) { $obj | Add-Member -type NoteProperty -name ($reader.GetName($i)) -value ($reader[$i]) } $obj } } catch { throw $_ } finally { $command = $null $reader.Close() $reader = $null $ConnObj.Close() $ConnObj = $null } }
PowerShellCorpus/PoshCode/Create VMKernel on vDS.ps1
Create VMKernel on vDS.ps1
@@ New-VMHostNetworkAdapter -VMHost $myHost -VirtualSwitch "myVDS"-PortGroup "vdPortGroup"
PowerShellCorpus/PoshCode/FuncionInfo_1.types.ps1xml.ps1
FuncionInfo_1.types.ps1xml.ps1
<?xml version="1.0" encoding="utf-8" ?> <Types> <Type> <Name>System.Management.Automation.FunctionInfo</Name> <Members> <ScriptProperty> <Name>Verb</Name> <GetScriptBlock> if ($this.Name.Contains("-")) { $this.Name.Substring(0,$this.Name.Indexof("-")) } else { $null } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>Noun</Name> <GetScriptBlock> if ($this.Name.Contains("-")){ $this.Name.Substring(($this.Name.Indexof("-")+1),($this.Name.length - ($this.Name.Indexof("-")+1))) } else { $this.Name } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>Prefix</Name> <GetScriptBlock> $prefix_val = $((gmo $this.Module).ExportedFunctions.Values + (gcm -mo $this.ModuleName -CommandType "Function") | where { $_.Verb -eq $this.Verb } | group { $_.Definition } | % { $names = $_.Group | Select -Expand Name; $ofs = "-"; $verb,[string]$noun = @($names)[0] -split "-"; foreach($name in $names){ if ( $name.contains("-") ) { $name.substring($name.IndexOf("-") + 1, $name.LastIndexOf($noun) - $name.IndexOf("-") - 1 ) } } } | where {$_} | select -unique | foreach { $_ | where {$this.Noun -match $_ } }) if ( $prefix_val ) { $prefix_val } else { $null } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>InternalName</Name> <GetScriptBlock> $prefix = $this.Prefix if ($prefix) { "$($this.Verb)-$($this.Noun.Replace($prefix, $null))" } else { "$($this.Name)" } </GetScriptBlock> </ScriptProperty> </Members> </Type> </Types>
PowerShellCorpus/PoshCode/Security group monitor_2.ps1
Security group monitor_2.ps1
#Get group membership for a list of security #groups and export to an XML for comparison #against baseline. # $script:WorkingDirectory = split-path $myinvocation.Mycommand.Definition -parent Function Re-Baseline { #First, declare array and hashtable. $securitygroups = @() $table = @{} #Import Security Group list from XML and add to "securitygroups" array. $securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml") $securitygroups += $securitygroupsxml.objs.S #Get membership for each group foreach($securitygroup in $securitygroups){ $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))" $group = $searcher.findone() $table += @{"$securitygroup"= $group.properties.member} } #Export hashtable to XML. So nice. $table | export-clixml $script:WorkingDirectory\\baseline.xml } # #First, declare hashtable. $comparetable = @{} #Import Security Group list from XML and add to "securitygroups" array. $securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml") $securitygroups = $securitygroupsxml.objs.S #Get membership for each group and create a compare table. foreach($securitygroup in $securitygroups){ $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))" $group = $searcher.findone() $comparetable += @{"$securitygroup"= $group.properties.member} } #Export hashtable to XML. So nice. $comparetable | export-clixml "$script:WorkingDirectory\\compare.xml" #Import baseline XML to hashtable. $baselinetable = @{} $baselinetable += import-clixml "$script:WorkingDirectory\\baseline.xml" #Import baseline XML to hashtable. $comparetable = @{} $comparetable += import-clixml "$script:WorkingDirectory\\compare.xml" #Compare respective Keys and Values for $comparetable against #$baselinetable and get differences. $passtoemailsubuser = @() $passtoemailbody = @() foreach($securitygroup in $securitygroups) { If($comparetable."$securitygroup" -eq $NULL) { If($baselinetable."$securitygroup" -eq $NULL) { (get-date).tostring() + " - Security Group $securitygroup is empty in the compare and the baseline" >> $script:WorkingDirectory\\log.txt } Else { foreach($entry in $baselinetable."$securitygroup") {$passtoemailbody += "`r" + $entry + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"} $passtoemailbody += "`r" + $securitygroup + " " + "`r`r" + "in AD contains no more objects" + "`r`r" (get-date).tostring() + " - $securitygroup in AD contains no more objects" >> $script:WorkingDirectory\\log.txt } } Else { $baseline = @($baselinetable."$securitygroup") $compare = @($comparetable."$securitygroup") $results = Compare-Object $baseline $compare foreach($result in $results){ if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "=>")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS ADDED TO***: " + "`r`r" + $securitygroup + "`r`r" $user = $result.inputobject $searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))" $user = $searcher.FindOne() $passtoemailsubuser += $user.properties.samaccountname $mod = $true } if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "<=")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r" $user = $result.inputobject $searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))" $user = $searcher.FindOne() $passtoemailsubuser += $user.properties.samaccountname $mod = $true }} } } if ($mod -eq $true) { $from = New-Object System.Net.Mail.MailAddress "from@address.com" $to = New-Object System.Net.Mail.MailAddress "to@address.com" $message = new-object System.Net.Mail.MailMessage $from, $to $message.Subject = "The following accounts were involved in a security group modification: $passtoemailsubuser" $message.Body = "Note the following security group modification information: `r`r $passtoemailbody" $server = "SMTPSERVERNAME" $client = new-object system.net.mail.smtpclient $server $client.port = 125 $client.Send($message) foreach($entry in $passtoemailbody) {(get-date).tostring() + " - " + $Entry >> $script:WorkingDirectory\\Log.txt} (get-date).tostring() + " - Group Membership compare has been baselined" >> $script:WorkingDirectory\\log.txt re-baseline } else { $from = New-Object System.Net.Mail.MailAddress "from@address.com" $to = New-Object System.Net.Mail.MailAddress "to@address.com" $message = new-object System.Net.Mail.MailMessage $from, $to $message.Subject = "No modifications to the audited security groups have been made." $message.Body = "No modifications to the audited security groups have been made." $server = "SMTPSERVERNAME" $client = new-object system.net.mail.smtpclient $server $client.port = 125 $client.Send($message) "No Changes have been made" }
PowerShellCorpus/PoshCode/Get-User_2.ps1
Get-User_2.ps1
function Get-User($user) { # this function should be passed the CN of the user to be returned $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))" $user = $searcher.FindOne() [System.Collections.Arraylist]$names = $user.Properties.PropertyNames [System.Collections.Arraylist]$props = $user.Properties.Values $userobj = New-Object System.Object for ($i = 0; $i -lt $names.Count) { $userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i]) $i++ } $userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset) $userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp) return $userobj }
PowerShellCorpus/PoshCode/NPS Server Synchronize.ps1
NPS Server Synchronize.ps1
###Network Policy Server Synchronization Script #This script copies the configuration from the NPS Master Server and imports it on this server. #The Account that this script runs under must have Local Administrator rights to the NPS Master. #This was designed to be run as a scheduled task on the NPS Secondary Servers on an hourly,daily, or as-needed basis. #Last Modified 01 Dec 2009 by JGrote <jgrote AT enpointe NOSPAM-DOTCOM> ###Variables #NPSMaster - Your Primary Network Policy Server you want to copy the config from. $NPSMaster = "Server1" #NPSConfigTempFile - A temporary location to store the XML config. Use a UNC path so that the primary can save the XML file across the network. Be sure to set secure permissions on this folder, as the configuration including pre-shared keys is temporarily stored here during the import process. $NPSConfigTempFile = "\\\\server2\\C$\\Temp\\NPSConfigTemp\\NPSConfig-$NPSMaster.xml" #Create an NPS Sync Event Source if it doesn't already exist if (!(get-eventlog -logname "System" -source "NPS-Sync")) {new-eventlog -logname "System" -source "NPS-Sync"} #Write an error and exit the script if an exception is ever thrown trap {write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Error" -Message "An Error occured during NPS Sync: $_. Script run from $($MyInvocation.MyCommand.Definition)"; exit} #Connect to NPS Master and export configuration $configExportResult = invoke-command -ComputerName $NPSMaster -ArgumentList $NPSConfigTempFile -scriptBlock {param ($NPSConfigTempFile) netsh nps export filename = $NPSConfigTempFile exportPSK = yes} #Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script. $NPSConfigTest = Get-Item $NPSConfigTempFile #Clear existing configuration and import new NPS config $configClearResult = netsh nps reset config $configImportResult = netsh nps import filename = $NPSConfigTempFile #Delete Temporary File remove-item -path $NPSConfigTempFile #Compose and Write Success Event $successText = "Network Policy Server Configuration successfully synchronized from $NPSMaster. Export Results: $configExportResult Import Results: $configImportResult Script was run from $($MyInvocation.MyCommand.Definition)" write-eventlog -logname "System" -eventID 1 -source "NPS-Sync" -EntryType "Information" -Message $successText
PowerShellCorpus/PoshCode/Start-Countdown.ps1
Start-Countdown.ps1
function Start-Countdown{ <# .Synopsis Initiates a countdown on your session. Can be used instead of Start-Sleep. Use case is to provide visual countdown progress during "sleep" times .Example Get-Countdown -Seconds 10 This method will clear the screen and display descending seconds .Example Get-Countdown -Seconds 10 -ProgressBar This method will display a progress bar on screen without clearing. .Link http://www.vtesseract.com/ .Description ==================================================================== Author(s): Josh Atwell <josh.c.atwell@gmail.com> File: Start-Countdown.ps1 Date: 2012-04-19 Revision: 1.0 References: www.vtesseract.com ==================================================================== Disclaimer: This script is written as best effort and provides no warranty expressed or implied. Please contact the author(s) if you have questions about this script before running or modifying ==================================================================== #> Param( [INT]$Seconds = (Read-Host "Enter seconds to countdown from"), [Switch]$ProgressBar, [String]$Message = "Blast Off!" ) Clear-Host while ($seconds -ge 1){ If($ProgressBar){ Write-Progress -Activity "Countdown" -SecondsRemaining $Seconds -Status "Time Remaining" Start-Sleep -Seconds 1 }ELSE{ Write-Output $Seconds Start-Sleep -Seconds 1 Clear-Host } $Seconds -- } Write-Output $Message }
PowerShellCorpus/PoshCode/List Object Discoveries.ps1
List Object Discoveries.ps1
# Enumerate OpsMgr 2007 Object Discoveries targeted to Windows Server # Date: 13/10/2008 # Author: Stefan Stranger (help from Jeremy Pavleck and Marco Shaw) get-discovery |? {$_.Target -match (get-monitoringclass | where {$_.Name -eq "Microsoft.Windows.Server.Computer"}).Id} | select Name, DisplayName
PowerShellCorpus/PoshCode/Compare Table & DataRow_1.ps1
Compare Table & DataRow_1.ps1
function Compare-DataRow { param( $a, $b) # @bernd_k http://pauerschell.blogspot.com/ $diff = '' $a_columncount = $a.Table.columns.count $b_columncount = $b.Table.columns.count if ( $a_columncount -ne $b_columncount) { Write-host "Tables have different number of columns" } foreach ( $i in 0..($a_columncount - 1)) { if ($a.item($i) -ne $b.item($i)) { $diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';' } } $diff } function Compare-Table { param( $a, $b) # @bernd_k http://pauerschell.blogspot.com/ $diff = '' $a_rowcount = $a.Rows.count $b_rowcount = $b.Rows.count if ( $a_rowcount -ne $b_rowcount1) { Write-host "Tables have different number of columns" } foreach ( $i in 0..($a_rowcount - 1)) { Compare-DataRow $a.rows[$i] $b.rows[$i] } $diff } Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0] Compare-Table ($a.tables[0]) ($b.tables[0])
PowerShellCorpus/PoshCode/Lock close button.ps1
Lock close button.ps1
$code = @' using System; using System.Runtime.InteropServices; namespace CloseButtonToggle { internal static class WinAPI { [DllImport("kernel32.dll")] internal static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DrawMenuBar(IntPtr hWnd); [DllImport("user32.dll")] internal static extern IntPtr GetSystemMenu(IntPtr hWnd, [MarshalAs(UnmanagedType.Bool)]bool bRevert); const uint SC_CLOSE = 0xf060; const uint MF_BYCOMMAND = 0; internal static void ChangeCurrentState(bool state) { IntPtr hMenu = GetSystemMenu(GetConsoleWindow(), state); DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND); DrawMenuBar(GetConsoleWindow()); } } public static class Status { public static void Disable() { WinAPI.ChangeCurrentState(false); //its 'true' if need to enable } } } '@ Add-Type $code [CloseButtonToggle.Status]::Disable()
PowerShellCorpus/PoshCode/Move-Template.ps1
Move-Template.ps1
#requires -version 2.0 Function Move-Template{ <# .Synopsis Move a VM template .Description Move a VM template either to a new host via vmotion or to a new datastore via svmotion .Parameter Name Name of the VM to be migrated .Parameter VIObject Template to be migrated .Parameter VMHost VMHost to vmotion the template to .Parameter Datastore Datastore to svmotion template to .Example Move-Template -Name W2k8R201 -VMHost (Get-VMHost ESX1) VMotion W2k8R201 template to the ESX1 host. .Example Move-Template -Name W2k8R201 -Datastore (Get-Datastore NFS2) sVMotion W2k8R201 template to the NFS2 Datastore. .Example Get-Template | Move-Template -Datastore (Get-Datastore NFS2) sVMotion all templates onto the NFS2 Datastore .Example Get-Template CentOS_5_2_x64 | Move-Template -Datastore (Get-Datastore NFS2) -VMHost (Get-VMHost ESX03) sVMotion the CentOS_5_2_x64 templates onto the NFS2 Datastore, and then vmotion said template onto ESX03 .link Get-Template New-Template Remove-Template Set-Template #> [CmdletBinding(SupportsShouldProcess=$true,SupportsTransactions=$False,ConfirmImpact="low",DefaultParameterSetName="")] param( [Parameter(Mandatory=$true,Position=0,HelpMessage="Name of template to move", ParameterSetName="vmotionByName")] [Parameter(Mandatory=$true,Position=0,HelpMessage="Name of template to move", ParameterSetName="svmotionByName")] [Parameter(Mandatory=$true,Position=0,HelpMessage="Name of template to move", ParameterSetName="ByName")] [STRING] $Name, [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Managed object of the template to be migrated", ParameterSetName="vmotionByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Managed object of the template to be migrated", ParameterSetName="svmotionByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Managed object of the template to be migrated", ParameterSetName="ByObject")] [VMware.VimAutomation.Client20.TemplateImpl[]] $Template, [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="vmotionByName")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="vmotionByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="ByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="ByName")] [VMware.VimAutomation.Client20.VMHostImpl] $VMHost, [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="svmotionByName")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="svmotionByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="ByObject")] [Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="ByName")] [VMware.VimAutomation.Client20.DatastoreImpl] $Datastore ) Process{ switch ($pscmdlet.parametersetname) { "vmotionByName" { if ($pscmdlet.ShouldProcess($Name,"vmotion Template to $($VMHost.name)")){ $template = Get-Template -Name $Name -verbose:$False $vm = Set-Template -Template $template -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } "vmotionByObject" { Foreach ($tmp in $Template) { if ($pscmdlet.ShouldProcess($tmp.Name,"vmotion Template to $($VMHost.name)")){ $vm = Set-Template -Template $tmp -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } } "svmotionByName" { if ($pscmdlet.ShouldProcess($Name,"svmotion Template to $($Datastore.name)")){ $template = Get-Template -Name $Name -verbose:$False $vm = Set-Template -Template $template -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } "svmotionByObject" { Foreach ($tmp in $Template) { if ($pscmdlet.ShouldProcess($tmp.Name,"svmotion Template to $($Datastore.name)")){ $vm = Set-Template -Template $tmp -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } } "ByName" { if ($pscmdlet.ShouldProcess($Name,"vmotion Template to $($VMHost.name) and svmotion to $($Datastore.name)")){ $template = Get-Template -Name $Name -verbose:$False $vm = Set-Template -Template $template -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } "ByObject" { Foreach ($tmp in $Template) { if ($pscmdlet.ShouldProcess($tmp.Name,"vmotion Template to $($VMHost.name) and svmotion to $($Datastore.name)")){ $vm = Set-Template -Template $tmp -ToVM -verbose:$False -confirm:$False Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false (Get-View -VIObject $VM -verbose:$False).MarkAsTemplate() } } } } } }
PowerShellCorpus/PoshCode/Get-LastBootUpTime.ps1
Get-LastBootUpTime.ps1
<# .SYNOPSIS Gets the start time of the PC .DESCRIPTION The Get-LastBootUpTime function returns an LBUT object that represents the time the computer started. You can use Get-LabstBootUpTime to generate the up time of a PC. By default it uses EventID 6005 from the System log to determine when the PC started. You can also specify to use PSRemoting or WMI commands instead. .PARAMETER ComputerName Vaild input is the name of a computer or a computer object. .PARAMETER WMI Use WMI commands instead of event log. .PARAMETER Remote Will use Invoke-Command instead of -Computer parameter. .EXAMPLE Get-LastBootUpTime beefy-pc The command returns the LastBootUpTime of beefy-pc. .EXAMPLE (Get-ADComputer computer),'anothercomputer' | Get-LastBootUpTime.ps1 -Progress This command gets the LastBootUpTime of "computer" and "anothercomputer." Showing progress up top. Name Value ---- ----- Name computer UpTime 00:33:04.5693916 LastBootUpTime 4/12/2012 12:23:39 AM Name anothercomputer UpTime 2.12:59:59.0814428 LastBootUpTime 4/17/2011 11:56:45 AM .EXAMPLE Get-LastBootUpTime -ComputerName 'Jeff','Don','June',(Get-ADComputer 'Ed') -verbose -Progress -WMI This command uses the Get-WMI cmdlet instead of Get-EventLog to retrieve the last boot up time. .LINK @@http://blogs.msdn.com/b/dmuscett/archive/2009/05/27/get_2d00_wmicustom.aspx http://blogs.msdn.com/b/powershell/archive/2009/08/12/get-systemuptime-and-working-with-the-wmi-date-format.aspx?Redirected=true http://www.microsoft.com/technet/support/ee/transform.aspx?ProdName=Windows+Operating+System&ProdVer=5.2&EvtID=6005&EvtSrc=EventLog&LCID=1033 .NOTES @@It may be undesirable to query the WMI if errors occur or the timeout variable. Author: DVSBOBLOBLAW Date: 4:15:2013 Twitter: https://twitter.com/dvsbobloblaw .INPUTS An array of strings, an array of computer objects (any object that has a name parameter), or a mixture of both. .OUTPUTS An array of custom PSObjects I'll call LBUT objects. Haha, LBUTS. #> [cmdletbinding()] Param( [Parameter(ValueFromPipeline=$true)] [alias('Name','Computer','PCList','ComputerList')] [array]$ComputerName=$env:COMPUTERNAME, [switch]$WMI, [switch]$Remote, [switch]$Progress ) Begin{ $LastButs = @() $total = $ComputerName.Count $index = 0 } Process{ foreach($computer in $ComputerName){ if($computer.name -ne $NULL){ $computer = $computer.name } if($Progress){ Write-Progress -Activity "Getting Last Boot Up Time from $computer" -Status 'Precent Completed' -PercentComplete ((($index++)/$total) * 100) } $communicate = $true $lbut = New-Object psobject -ArgumentList @{'Name'=$computer;'LastBootUpTime'=$NULL;'UpTime'=$NULL} Write-Verbose "Start on $computer" if(!(Test-Connection $computer -Count 1 -Quiet)){ Write-Warning "Cannot Communicate with $computer" $communicate = $false } if($communicate -and !$WMI){ if($Remote){ Write-Verbose 'Invoking {Get-Event Log}' try{ $Events = Invoke-Command -ComputerName $computer -ScriptBlock {Get-EventLog -LogName System | % {if($_.EventID -eq '6005'){$_}} | Select-Object -First 1} -ErrorAction Stop } catch{ Write-Warning "Unable to Invoke {Get-Event Log} on $computer" $communicate = $false } } else{ Write-Verbose 'Get-Event Log' try{ $Events = Get-EventLog -LogName System -ComputerName $computer -ErrorAction Stop | % {if($_.EventID -eq '6005'){$_}} | Select-Object -First 1 } catch{ Write-Warning "Unable to Get-Event Log from $computer" $communicate = $false } } if($communicate){ $lbut.LastBootUpTime = $Events.TimeGenerated } } elseif($communicate){ if($Remote){ Write-Verbose 'Invoking {Get-WMI Query}' try{ $OpSys = Invoke-Command -ComputerName $computer -ScriptBlock {Get-WmiObject -Class Win32_OperatingSystem} -ErrorAction Stop } catch{ Write-Warning "Unable to Invoke {Get-WMI Query} on $computer" $communicate = $false } } else{ Write-Verbose 'Get-WMI Query' try{ $OpSys = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer -ErrorAction Stop } catch{ Write-Warning "Unable to Get-WMI Query from $computer" $communicate = $false } } if($communicate){ $lbut.LastBootUpTime = [Management.ManagementDateTimeConverter]::ToDateTime($OpSys.LastBootUpTime) } } if($communicate){ Write-Verbose 'Calculating UpTime' $lbut.UpTime = (Get-Date)-$lbut.LastBootUpTime } $LastButs += @($lbut) } } End{ Write-Output $LastButs }
PowerShellCorpus/PoshCode/Execute-SQLCommand.ps1
Execute-SQLCommand.ps1
function Execute-SQLCommand {param( [string]$Server, #the host name of the SQL server [string]$Database, #the name of the database [System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure) $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnection.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=ml;Initial Catalog=$Database;Data Source=$Server" $Command.CommandType = 1 # 1 is the 'Text' command type $Command.Connection = $sqlConnection $sqlConnection.Open() $Result = $Command.ExecuteNonQuery() $sqlConnection.Close() if ($Result -gt 0) {return $TRUE} else {return $FALSE} }
PowerShellCorpus/PoshCode/Out-AnsiGraph.ps1
Out-AnsiGraph.ps1
# # Out-AnsiGraph.psm1 # Author: xcud # History: # v0.1 September 21, 2009 initial version # # PS Example> ps | select -first 5 | sort -property VM | Out-AnsiGraph ProcessName, VM # AEADISRV &#9608;&#9608;&#9608; 14508032 # audiodg &#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608; 50757632 # conhost &#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608; 73740288 # AppleMobileDeviceService &#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608; 92061696 # btdna &#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608; 126443520 # function Out-AnsiGraph($Parameter1=$null, $inputObject=$null) { BEGIN { $q = new-object Collections.queue } PROCESS { if($_) { $name = $_.($Parameter1[0]); $val = $_.($Parameter1[1]) if($max -lt $val) { $max = $val} if($namewidth -lt $name.length) { $namewidth = $name.length } $q.enqueue(@($name, $val)) } } END { $q | %{ $graph = ""; 0..($_[1]/$max*20) | %{ $graph += "&#9608;" } $name = "{0,$namewidth}" -f $_[0] "$name $graph " + $_[1] } } } Export-ModuleMember Out-AnsiGraph
PowerShellCorpus/PoshCode/Set-PSODefaultProperties.ps1
Set-PSODefaultProperties.ps1
function Set-PSODefaultProperties { param( [PSObject]$Object, [string[]]$DefaultProperties ) if( $DefaultProperties -ne $null ) { $name = $Object.PSObject.TypeNames[0] $xml = "<?xml version='1.0' encoding='utf-8' ?><Types><Type>" $xml += "<Name>$($name)</Name>" $xml += "<Members><MemberSet><Name>PSStandardMembers</Name><Members>" $xml += "<PropertySet><Name>DefaultDisplayPropertySet</Name><ReferencedProperties>" foreach( $default in $DefaultProperties ) { $xml += "<Name>$($default)</Name>" } $xml += "</ReferencedProperties></PropertySet></Members></MemberSet></Members>" $xml += "</Type></Types>" $file = "$($env:Temp)\\$name.ps1xml" Out-File -FilePath $file -Encoding "UTF8" -InputObject $xml -Force $typeLoaded = $host.Runspace.RunspaceConfiguration.Types | where { $_.FileName -eq $file } if( $typeLoaded -ne $null ) { Update-TypeData } else { Update-TypeData $file } } }
PowerShellCorpus/PoshCode/Services Auto NotRunning.ps1
Services Auto NotRunning.ps1
Get-WmiObject Win32_Service -ComputerName . |` where {($_.startmode -like "*auto*") -and ` ($_.state -notlike "*running*")}|` select DisplayName,Name,StartMode,State|ft -AutoSize
PowerShellCorpus/PoshCode/InkScape utilities.ps1
InkScape utilities.ps1
<# .SYNOPSIS Inkscape utility cmdlets MIT License Copyright (c) 2012-2013 Justin Dearing <zippy1981@gmail.com> 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. #> <# .SYNOPSIS Gets the directory Inkscape is installed to. .DESCRIPTION Returns the directory Inkscape is installed to. .INPUTS None .OUTPUTS System.String #> function Get-InkscapeDir() { if ([IntPtr]::Size -eq 8) { $inkscapeDir = (Get-ItemProperty HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Inkscape InstallDir).InstallDir } else { $inkscapeDir = (Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Inkscape InstallDir).InstallDir } if ([string]::IsNullOrEmpty($inkscapeDir)) { throw (New-Object IO.FileNotFoundException "Inkscape does not appear to be installed") } if (-not (Test-Path -PathType Container $inkscapeDir)) { throw (New-Object IO.FileNotFoundException "InkScape folder $($inkscapeDir) not found", $inkscapeDir) } Write-Verbose "Inkscape install path $($installDir)" $inkscapeDir } <# .SYNOPSIS Gets the path of inkscape.com,inkscapec.exe or inkscape.exe. .DESCRIPTION Returns the full path of the inkscape executable. This is one of three options: * inkscape.com: This is a wrapper to inkscape.exe introduced in Inkscape 0.48 that writes the output of inkscape.exe to the console. * inkscapec.exe: This is a crude first attempt at a wrapper. Source and description is available at http://kaioa.com/node/63. * inkscape.exe: This is the inkscape executable compiled as a windows app. This supports command line options and non-interactive running, but does not write any output to stdout or stderr .INPUTS None .OUTPUTS System.String #> function Get-InkscapeExePath() { param ( [Parameter(Mandatory=$false, Position=0)][AllowEmptyString()][string] $InkscapeDir = $( if ([string]::IsNullOrEmpty($InkscapeDir)) { Get-InkscapeDir } else { $InkscapeDir } ) ) $inkscapeExe = Join-Path $InkscapeDir "inkscape.exe" if (-not (Test-Path -PathType Leaf $inkscapeExe)) { throw (New-Object IO.FileNotFoundException "InkScape.exe not found", $inkscapeExe) } if (Test-Path -PathType Leaf (Join-Path $inkscapeDir "inkscape.com")) { $inkscapeExe = Join-Path $InkscapeDir "inkscape.com" } else { if (Test-Path -PathType Leaf (Join-Path $inkscapeDir "inkscapec.exe")) { Write-Warning "inkscapec.exe found. You should probably upgrade to inkscape 0.48.2 which uses inkscape.com" $inkscapeExe = Join-Path $inkscapeDir "inkscapec.exe" } else { Write-Warning 'inkscape.com not found. Images *should* be generated, but inkscape.exe will not write anything to stdout or stderr' } Write-Warning "`tSee http://inkscape.13.n6.nabble.com/Windows-Console-Options-td2792080.html#a2792083 for details." } Write-Verbose "InkScape executablepath: $inkscapeExe" $inkscapeExe } #iex "start `"$inkscapeExe`""
PowerShellCorpus/PoshCode/SynchronizationScript.ps.ps1
SynchronizationScript.ps.ps1
#------- Get-SPServiceContext function Get-SPServiceContext([Microsoft.SharePoint.Administration.SPServiceApplication]$profileApp) { if($profileApp -eq $null) { #----- Get first User Profile Service Application $profileApp = @(Get-SPServiceApplication | ? { $_.TypeName -eq "User Profile Service Application" })[0] } return [Microsoft.SharePoint.SPServiceContext]::GetContext( $profileApp.ServiceApplicationProxyGroup, [Microsoft.SharePoint.SPSiteSubscriptionIdentifier]::Default) } $serviceContext= Get-SPServiceContext $configManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($serviceContext) if($configManager.IsSynchronizationRunning() -eq $false) { $configManager.StartSynchronization($true) Write-Host "Started Synchronizing" } else { Write-Host "Already Synchronizing" }
PowerShellCorpus/PoshCode/Get-CInfo_1.ps1
Get-CInfo_1.ps1
function Get-CInfo { param($Comp) Function PC-Name{ param ($compname) $ADS = Get-ADComputer -Filter {name -eq $compname} -Properties * | Select-Object -Property name If($ads -eq $null) {$false} ELSE{$True} } $ping = PC-Name $COMP if ($ping -eq $true) { Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } ELSEIF ($ping -eq $false) { do { Write-Host -ForegroundColor yellow "No Match Found, Below Is An AD Search, Try Again (CTRL-C to Exit):" $SEARCH = "*$COMP*" Get-ADComputer -Filter {name -like $SEARCH} | Select-Object -property name,enabled | Format-Table -AutoSize $comp = (read-host "What is the Computer Name? (EX. demersm-l7567)").ToLower() function Ping-Server { Param([string]$srv) $pingresult = Get-WmiObject Win32_PingStatus -Filter "Address='$srv'" if($pingresult.StatusCode -eq 0) {$true} else {$false} } $PING2 = PC-Name $COMP } While ($PING2 -eq $false) } If($ping2 -eq $true){ Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } }
PowerShellCorpus/PoshCode/Get-PrivateKeyPath_1.ps1
Get-PrivateKeyPath_1.ps1
#requires -Version 2.0 # # Example 1: # Get-PrivateKeyPath CN=DO_NOT_TRUST_FiddlerRoot -StoreName My -StoreScope CurrentUser # Example 2: # Get-PrivateKeyPath D359ECDC338CFDDCE86DDDA99BE36286BAE2018A function Get-PrivateKeyPath { param ( [Parameter(Mandatory = $true, Position = 0)] [string] $CertificateInput, [string] [ValidateSet('TrustedPublisher','Remote Desktop','Root','REQUEST','TrustedDevices','CA','Windows Live ID Token Issuer','AuthRoot','TrustedPeople','AddressBook','My','SmartCardRoot','Trust','Disallowed')] $StoreName = 'My', [string] [ValidateSet('LocalMachine','CurrentUser')] $StoreScope = 'CurrentUser' ) begin { Add-Type -AssemblyName System.Security } process { if ($CertificateInput -match "^CN=") { # Common name given # Extract thumbprint(s) of possible certificate(s) with matching common name $MatchingThumbprints = Get-ChildItem cert:\\$StoreScope\\$StoreName | Where-Object { $_.Subject -match "^" + $CertificateInput + ",?" } | Select-Object Thumbprint } else { # Assuming thumbprint # Create array of hashes, similar to output of Select-Object $MatchingThumbprints = @(@{"Thumbprint" = $CertificateInput}) } if ($MatchingThumbprints.count -eq 0) { write-error ("Could not find any matching certificates.") -ErrorAction:Stop } $CertificateStore = new-object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreLocation]$StoreScope) $CertificateStore.open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadOnly") $CertCollection = $CertificateStore.Certificates Foreach ($Thumbprint in $MatchingThumbprints) { $MatchingCertificates = $CertCollection.Find([System.Security.Cryptography.X509Certificates.X509FindType]"FindByThumbprint", $Thumbprint.Thumbprint, $false) $stat = $? if ($stat -eq $false -or $MatchingCertificates.count -eq 0) { write-error ("Internal error: Could not find certificate by thumbprint " + $Thumbprint.Thumbprint) -ErrorAction:Stop } Foreach ($Certificate in $MatchingCertificates) { if ($Certificate.PrivateKey -eq $null) { Write-Error ("Certificate doesn't have Private Key") -ErrorAction:Stop } Switch ($StoreScope) { "LocalMachine" { $PrivateKeysPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::CommonApplicationData) + "\\Microsoft\\Crypto\\RSA\\MachineKeys" } "CurrentUser" { $PrivateKeysPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::ApplicationData) + "\\Microsoft\\Crypto\\RSA" } } $PrivateKeyPath = $PrivateKeysPath + "\\" + $Certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName $PrivateKeyPath } } } end { } }
PowerShellCorpus/PoshCode/BufferBox 3.1.ps1
BufferBox 3.1.ps1
#################################################################################################### ## This script is just a demonstration of some of the things you can do with the buffer ## in the default PowerShell host... it serves as a reminder of how much work remains on ## PoshConsole, and as an inspiration to anyone who is thinking about trying to create ## "interactive" PowerShell applications. ## ## Try Test-DisplayBox and then Test-BufferBox (note it has tab completion and everything). #################################################################################################### $global:BoxChars = new-object PSObject -Property @{ 'HorizontalDouble' = ([char]9552).ToString() 'VerticalDouble' = ([char]9553).ToString() 'TopLeftDouble' = ([char]9556).ToString() 'TopRightDouble' = ([char]9559).ToString() 'BottomLeftDouble' = ([char]9562).ToString() 'BottomRightDouble' = ([char]9565).ToString() 'HorizontalDoubleSingleDown' = ([char]9572).ToString() 'HorizontalDoubleSingleUp' = ([char]9575).ToString() 'Horizontal' = ([char]9472).ToString() 'Vertical' = ([char]9474).ToString() 'TopLeft' = ([char]9484).ToString() 'TopRight' = ([char]9488).ToString() 'BottomLeft' = ([char]9492).ToString() 'BottomRight' = ([char]9496).ToString() 'Cross' = ([char]9532).ToString() 'VerticalDoubleRightSingle' = ([char]9567).ToString() 'VerticalDoubleLeftSingle' = ([char]9570).ToString() } $global:RectType = "system.management.automation.host.rectangle" function Reset-Buffer { param( $Position = $Host.UI.RawUI.WindowPosition, [int]$Height = $Host.UI.RawUI.WindowSize.Height, [int]$Width = $Host.UI.RawUI.WindowSize.Width, # Note: all edges are padded by 1 for the box edges, but we also pad each side by this ammount: [int]$Padding = 1, $ForegroundColor = $Host.UI.RawUI.ForegroundColor, $BackgroundColor = $Host.UI.RawUI.BackgroundColor, $BorderColor = "Yellow", [switch]$NoBorder, [switch]$ShowInput, [string]$Title = "" ) $global:BufferHeight = $Height $global:BufferWidth = $Width $global:BufferPadding = $Padding $global:BufferForegroundColor = $ForegroundColor $global:BufferBackgroundColor = $BackgroundColor $global:BufferBorderColor = $BorderColor if($NoBorder) { $global:BufferBoxSides = 0 } else { $global:BufferBoxSides = 2 } if($ShowInput) { $global:BufferHeight -= 2 } $Host.UI.RawUI.SetBufferContents($Position,(New-BufferBox $BufferHeight $BufferWidth -Title:$Title -NoBorder:$NoBorder -ShowInput:$ShowInput -Background $BufferBackgroundColor -Border $BufferBorderColor)) $global:BufferPosition = $Position $global:BufferPosition.X += $global:BufferPadding + ($global:BufferBoxSides/2) # this gets set to the BOTTOM line, because I assume text will flow in from the bottom. $global:BufferPosition.Y += $global:BufferHeight - 2 # and this goes below that ... $global:BufferPromptPosition = $BufferPosition $global:BufferPromptPosition.Y += 2 $global:BufferPromptPosition.X += 2 - $global:BufferPadding # Prompt = "> " } function New-BufferBox { param( [int]$Height = $global:BufferHeight, [int]$Width = $global:BufferWidth, $Title = "", [switch]$NoBorder, [switch]$ShowInput, $BackgroundColor = $global:BufferBackgroundColor, $BorderColor = $global:BufferBorderColor ) $Width = $Width - $global:BufferBoxSides $LineTop =( $global:BoxChars.HorizontalDouble * 2) + $Title ` + $($global:BoxChars.HorizontalDouble * ($Width - ($Title.Length+2))) $LineField = ' ' * $Width $LineBottom = $global:BoxChars.HorizontalDouble * $Width $LineSeparator = $global:BoxChars.Horizontal * $Width $LinePrompt = '> ' + ' ' * ($Width-2) # Prompt = "> " if(!$NoBorder) { $LineField = $global:BoxChars.VerticalDouble + $LineField + $global:BoxChars.VerticalDouble $LinePrompt = $global:BoxChars.VerticalDouble + $LinePrompt + $global:BoxChars.VerticalDouble $LineBottom = $global:BoxChars.BottomLeftDouble + $LineBottom + $global:BoxChars.BottomRightDouble $LineTop = $global:BoxChars.TopLeftDouble + $LineTop + $global:BoxChars.TopRightDouble $LineSeparator = $global:BoxChars.VerticalDoubleRightSingle + $LineSeparator + $global:BoxChars.VerticalDoubleLeftSingle } if($ShowInput) { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineSeparator;$LinePrompt;$LineBottom} } else { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineBottom} } $boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,$BorderColor,$BackgroundColor) return ,$boxBuffer } function Move-Buffer { param( $Position = $global:BufferPosition, [int]$Left = $($global:BufferBoxSides/2), [int]$Top = (2 - $global:BufferHeight), [int]$Width = $global:BufferWidth - $global:BufferBoxSides, [int]$Height = $global:BufferHeight, [int]$Offset = -1 ) $Position.X += $Left $Position.Y += $Top $Rect = New-Object $RectType $Position.X, $Position.Y, ($Position.X + $width), ($Position.Y + $height -1) $Position.Y += $OffSet $Host.UI.RawUI.ScrollBufferContents($Rect, $Position, $Rect, (new-object System.Management.Automation.Host.BufferCell(' ',$global:BufferForegroundColor,$global:BufferBackgroundColor,'complete'))) } function Out-Buffer { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Message, [Parameter(ValueFromPipelineByPropertyName=$true)] $ForegroundColor = $global:BufferForegroundColor, [Parameter(ValueFromPipelineByPropertyName=$true)] $BackgroundColor = $global:BufferBackgroundColor, [switch]$NoScroll, [Parameter(ValueFromPipelineByPropertyName=$true)] $Position = $global:BufferPosition, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Left = 0, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Top = $(3 - $global:BufferHeight), # Box Edge + New Lines [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Width = ($global:BufferWidth - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Height = ($global:BufferHeight - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Offset = $( 0 - ($Message.Split("`n").Count)) ) process { $lineCount = $Message.Split("`n").Count $Width = $Width - ($global:BufferPadding * 2) if(!$NoScroll){ Move-Buffer $Position $Left $Top $Width $Height $Offset } $MessageBuffer = New-Object "System.Management.Automation.Host.BufferCell[,]" $lineCount, $width $index = 0 foreach( $line in $Message.Split("`n") ) { $Buffer = $Host.UI.RawUI.NewBufferCellArray( @($line.Trim("`r").PadRight($Width)), $ForegroundColor, $BackgroundColor ) for($i = 0; $i -lt $width; $i++) { $MessageBuffer[$index,$i] = $Buffer[0,$i] } $index++ } $Y = $global:BufferPosition.Y $global:BufferPosition.Y -= $lineCount - 1 $Host.UI.RawUI.SetBufferContents($global:BufferPosition,$MessageBuffer) $global:BufferPosition.Y = $Y } } function Set-BufferInputLine { param([String]$Line = "") $PromptText = $line.PadRight(($global:BufferWidth - $line.Length - 3)) # Prompt = "> " $CursorPosition = $BufferPromptPosition $CursorPosition.X += $line.Length $Prompt = $Host.UI.RawUI.NewBufferCellArray( @($PromptText),$global:BufferForegroundColor, $global:BufferBackgroundColor) $Host.UI.RawUI.SetBufferContents( $BufferPromptPosition, $prompt ) $Host.UI.RawUI.CursorPosition = $CursorPosition } function Test-DisplayBox { $Position = $Host.UI.RawUI.WindowPosition $Position.X += 10 $Position.Y += 3 Reset-Buffer $Position 20 66 3 -ForegroundColor 'Gray' -BackgroundColor 'Black' -BorderColor 'Green' Out-Buffer 'Greetings!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer '- - - Thank you for running this simple demo script! - - -' 'Green' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'We are demonstrating how the scroll buffer works: you can add more than one line at a time, but you don''t really need to, since they add almost as fast one at a time.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'That is, as long as you don''t have any delay, you can just' 'white' 'black' Out-Buffer 'write out as many lines as you like, one-at-a-time, like' 'white' 'black' Out-Buffer 'this, and there is really no downside to doing that.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'Right? '.PadRight(58,"-") 'Red' 'black' Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'It''s clearly not as slick to just pop in multiple lines' 'white' 'black' sleep -m 1200 Out-Buffer 'with absolutely no scroll delay, and it makes it a little ' 'white' 'black' sleep -m 1200 Out-Buffer 'hard to tell what you have read already, but that''s ok.' 'white' 'black' sleep -m 1200 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'If you delay between paragraphs.' 'Red' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'But: don''t scroll off-screen faster than I can read!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' } ## Test-BufferBox 3.1 - Now with Tab completion #################################################################################################### ## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the ## chat room you have joined is going on in the background. ## ## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line ## you have to enclose it inside $() braces. #################################################################################################### function Test-BufferBox { param( $title = "PowerShell Interactive Buffer Demo" ) Reset-Buffer -ShowInput -Title $Title ################################################################################################### ##### We only need this for the purposes of the demo... ##### In a real script you would, presumably, be getting stuff from somewhere else to display $noise = $MyInvocation.MyCommand.Definition -split "`n" $index = 0; $random = New-Object "Random" [regex]$chunker = @' [^ \\"']+|([\\"'])[^\\\\1]*?\\\\1[^ \\"']*|([\\"'])[^\\\\1]*$| $ '@ ##### Printing a "How to Exit" message Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " This is just a demo. " -Fore Black -Back Cyan Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan ##### Setting the prompt Set-BufferInputLine ##### And initializing our two variables ... $line="" $exit = $false while(!$exit){ while(!$exit -and $Host.UI.RawUI.KeyAvailable) { $char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho"); # we don't want the key up events, but we do want to get rid of them if($char.KeyDown) { switch([int]$char.Character) { 13 { # Enter if($line.Trim() -eq "exit") { $exit = $true; break; } ################################################################################################### ################################################################################################### ############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ############# ############# This executes the user input! ############# ############# Don't use this on, say, content you got from a web page or chat room ############# iex "Out-Buffer `"$line`" -Fore Red"; ############# ################################################################################################### ################################################################################################### $line = ""; Set-BufferInputLine break; } 27 { # Esc $exit = $true; break; } 9 { # Tab if($line.Length -gt 0) { [Array]$words = $chunker.Matches($line) if($words.Count -ge 1) { Out-Buffer ($Words | Out-String) -Fore Black -Back White $lastWord = $words[$($words.Count-1)].Value $trim = $lastWord.TrimEnd("`r","`n") ## This may return more than one ... in which case subsequent tabs should iterate through them ## But for demo purposes, this is more than enough work... $replacement = TabExpansion -Line $line -LastWord ($lastWord.Trim() -replace '"') Out-Buffer ($replacement | Out-String) -Fore Black -Back White $line = $line.SubString(0, $line.Length - $lastWord.Length) + @($replacement)[0] Set-BufferInputLine $line } } break; } 8 { # Backspace if($line.Length -gt 0) { $line = $line.SubString(0,$($line.Length-1)) } # $pos = $Host.UI.RawUI.CursorPosition Set-BufferInputLine $line break; } 0 { # Not actually a key # Out-Buffer $($Char | Out-String) break; } default { $line += $char.Character Set-BufferInputLine $line } } } } # Simulate doing useful things 25% of the time if($random.NextDouble() -gt 0.75) { $noise[($index)..($index++)] | Out-Buffer if($index -ge $noise.Length){$index = 0} } sleep -milli 100 } $CursorPosition = $BufferPromptPosition $CursorPosition.Y += 2 $CursorPosition.X = 0 $Host.UI.RawUI.CursorPosition = $CursorPosition }
PowerShellCorpus/PoshCode/Roll-Dice_1.ps1
Roll-Dice_1.ps1
# Roll-Dice.ps1 # Cody Bunch # ProfessionalVMware.com Begin { $rand = New-Object System.Random $dice = $rand.next(1,3) } Process { if ( $_ -isnot [VMware.VimAutomation.Types.Snapshot] ) { continue } if ($dice -gt 1) { $_ | Remove-Snapshot -Confirm:$false Write-Host "$_.Name OH NOES! Has been deleted!`n" } else { Write-Host "$_.Name lives to fight again!`n" } }
PowerShellCorpus/PoshCode/Terminate process _ user.ps1
Terminate process _ user.ps1
#Ty Lopes - Calgary - Oct 2012 #(Troy is a huge nerd) #How to kill a process by username #Originally created for a script (running under a sched task) that was not closing excel application after enumerating throught the excel file #Powershell does not seem to close excel properly using the workbook.close function #Note: could not kill the process when I included the extension... example notepad.exe has to be notepad for the $process variable $username = "username" $process= "notepad" $owners = @{} gwmi win32_process |% {$owners[$_.handle] = $_.getowner().user} get-process $process | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}} | where-object {$_.owner -eq $username} | kill -force
PowerShellCorpus/PoshCode/Get-HotFix.ps1
Get-HotFix.ps1
# The Get-HotFix function gets the quick-fix engineering (QFE) updates that have been applied to the local computer or to remote computers and filter those hotfixes named "file 1". # There is Get-HotFix cmdlet in PowerShell V2. This is an attempt to bring similar functionality to V1. function Get-HotFix { param ( [string[]]$ComputerName = ".", [string]$Id = "", [string]$Description = "", $credential ) if ($credential -is [String] ) { $credential = Get-Credential $credential } if ($id -ne "" -and $Description -eq "") { $id = $id.Replace("*","%");$filter = "hotfixid LIKE '$id'" } elseif ($id -eq "" -and $Description -ne "") { $Description = $Description.Replace("*","%");$filter = "description LIKE '$Description'" } elseif ($id -ne "" -and $Description -ne "") { Write-Host "WARNING: Use Id or Description parameter." -foregroundcolor yellow ;break } else { $filter = "" } if ($credential -eq $null) { $HotFixes = get-wmiobject Win32_QuickFixEngineering -computerName $ComputerName -filter $filter | where-object {$_.hotfixid -ne "file 1"} } else { $HotFixes = get-wmiobject Win32_QuickFixEngineering -computerName $ComputerName -filter $filter -credential $credential | where-object {$_.hotfixid -ne "file 1"} } $HotFixes } # Examples: # # C:\\PS>get-hotfix # # C:\\PS>get-hotfix -Id *929* # # C:\\PS>get-hotfix | format-table hotfixid,installedon,servicepackineffect,description -auto -wrap # # C:\\PS>get-hotfix | convertto-html -property hotfixid,description -title "Installed HotFixes" > c:\\temp\\hotfixes.html # # C:\\PS>get-hotfix -description Security* -computername Server01 -credential Server01\\admin01 # # C:\\PS>get-hotfix -description Security* -computername Server01,Server02 | ft __server,desc* # # C:\\PS>$a = get-content servers.txt # $a | foreach { if (!(get-hotfix -id KB958644 -computername $_)) { add-content $_ -path Missing-KB958644.txt }}
PowerShellCorpus/PoshCode/Boots DataGrid Binding.ps1
Boots DataGrid Binding.ps1
#load boots# Import-Module Powerboots function Export-NamedControl { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=1, Mandatory=$true)] $Root = $BootsWindow ) process { Invoke-BootsWindow $Root { $control = $BootsWindow while($control) { $control = $control | ForEach-Object { $Element = $_ if(!$Element) { return } Write-Verbose "This $($Element.GetType().Name) is $Element" if($Element.Name) { Write-Verbose "Defining $($Element.Name) = $Element" Set-Variable "$($Element.Name)" $Element -Scope 2 } ## Return all the child controls ... @($Element.Children) + @($Element.Child) + @($Element.Content) + @($Element.Items) + @($Element.Inlines) + @($Element.Blocks) } } } } } function ConvertFrom-Hashtable { PARAM([HashTable]$hashtable,[switch]$combine) BEGIN { $output = New-Object PSObject } PROCESS { if($_) { $hashtable = $_; if(!$combine) { $output = New-Object PSObject } } $hashtable.GetEnumerator() | ForEach-Object { Add-Member -inputObject $output ` -memberType NoteProperty -name $_.Name -value $_.Value } $output } } #--- Boots ---# $window = New-BootsWindow {} -FileTemplate "C:\\Documents and Settings\\khtruong\\Desktop\\generator\\LATAM\\Submission Tool\\devmgnt.xaml" -async -Passthru -On_Loaded { Export-NamedControl -Root $Args[0] $data = @{ DeviceGroup = "Samsung" Device = "SGH-A887" Platform = "J2ME" }, @{ DeviceGroup = "Motorola" Device = "V3i" Platform = "J2ME" } | ConvertFrom-Hashtable $HadesDevices.ItemsSource = $data }
PowerShellCorpus/PoshCode/Findup_8.ps1
Findup_8.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; namespace Findup { public class FileInfoExt { public FileInfoExt(FileInfo fi) { FI = fi; } public FileInfo FI { get; private set; } public bool Checked { get; set; } public byte[] SHA512_1st1K { get; set; } public byte[] SHA512_All { get; set; } } class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (IE: *.*), and in directories in pathRec, to returnList { public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { Recursive(d, searchPattern, recursiveFlag, returnList); } return; } public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { if (File.Exists(pathRec)) { try { returnList.Add(new FileInfoExt(new FileInfo(pathRec))); } catch (Exception e) { Console.WriteLine("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { returnList.Add(new FileInfoExt(addf)); } } catch (Exception e) { Console.WriteLine("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { try { foreach (string d in (Directory.GetDirectories(pathRec))) { Recursive(d, searchPattern, recursiveFlag, returnList); } } catch (Exception e) { Console.WriteLine("Add Directory error: " + e.Message); } } } else { try { string filePart = Path.GetFileName(pathRec); string dirPart = Path.GetDirectoryName(pathRec); if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { Recursive(dirPart, filePart, recursiveFlag, returnList); } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } catch (Exception e) { Console.WriteLine("Parse error on: " + pathRec); Console.WriteLine("Make sure you don't end a directory with a \\\\ when using quotes. The console arg parser doesn't accept that."); Console.WriteLine("Exception: " + e.Message); return; } } return; } } class Findup { public static void Main(string[] args) { Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile."); Console.WriteLine(" "); string[] paths = new string[0]; System.Boolean recurse = false; System.Boolean delete = false; System.Boolean noprompt = false; System.Boolean b4b = false; List<FileInfoExt> fs = new List<FileInfoExt>(); long bytesInDupes = 0; // bytes in all the duplicates long numOfDupes = 0; // number of duplicate files found. long bytesRec = 0; // number of bytes recovered. long delFiles = 0; // number of files deleted. int c = 0; int i = 0; string deleteConfirm; for (i = 0; i < args.Length; i++) { if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help infomration."); Console.WriteLine(" -recurse - recurses through subdirectories."); Console.WriteLine(" -delete - deletes duplicates with confirmation prompt."); Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt."); Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Might be much slower, but most secure."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse"); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt"); Console.WriteLine(" findup.exe c:\\\\data .\\\\*.txt c:\\\\reports\\\\quarter.doc -recurse -b4b"); Console.WriteLine(" "); return; } if (System.String.Compare(args[i], "-recurse", true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i], "-delete", true) == 0) { delete = true; continue; } if (System.String.Compare(args[i], "-noprompt", true) == 0) { noprompt = true; continue; } if (System.String.Compare(args[i], "-b4b", true) == 0) { b4b = true; continue; } Array.Resize(ref paths, paths.Length + 1); paths[c] = args[i]; c++; } if (paths.Length == 0) { Console.WriteLine("No files specified, try findup.exe -help"); return; } Recurse recurseMe = new Recurse(); recurseMe.Recursive(paths, "*.*", recurse, fs); if (fs.Count < 2) { Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(randomNumber); // get 512-bit SHA-512 salt. for (i = 0; i < fs.Count; i++) { if (fs[i].Checked == true) // If file was already matched, then skip to next. continue; for (c = i + 1; c < fs.Count; c++) { if (fs[c].Checked == true) // skip already matched inner loop files. continue; if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash. continue; if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match. continue; if (fs[i].SHA512_1st1K == null) // check/hash first 1K first. fs[i].SHA512_1st1K = Compute1KHash(fs[i].FI.FullName); if (fs[c].SHA512_1st1K == null) fs[c].SHA512_1st1K = Compute1KHash(fs[c].FI.FullName); if (CompareHash(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash.. continue; if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file. continue; if (b4b == true) // byte for byte comparison specified? { if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function continue; } else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes. { if (fs[i].SHA512_All == null) // check/hash the rest of the files. fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName); if (fs[c].SHA512_All == null) fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName); if (CompareHash(fs[i].SHA512_All, fs[c].SHA512_All) == false) continue; if (fs[i].SHA512_All == null) // check for hash fail before declaring a duplicate. continue; } Console.WriteLine("Match : " + fs[i].FI.FullName); Console.WriteLine("with : " + fs[c].FI.FullName); fs[c].Checked = true; // do not check or match against this file again. numOfDupes++; // increase count of matches. bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. continue; if (noprompt == false) { Console.Write("Delete the duplicate file <Y/n>?"); deleteConfirm = Console.ReadLine(); if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) continue; } try { File.Delete(fs[c].FI.FullName); Console.WriteLine("Deleted: " + fs[c].FI.FullName); bytesRec += fs[c].FI.Length; delFiles++; } catch (Exception e) { Console.WriteLine("File delete error: " + e.Message); } } } Console.WriteLine(" "); Console.WriteLine("Files checked : {0:N0}", fs.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes); Console.WriteLine("Duplicates deleted : {0:N0}", delFiles); Console.WriteLine("Recovered bytes : {0:N0}", bytesRec); return; } private static Boolean B4b(string path1, string path2) { try { using (var stream = File.OpenRead(path1)) { using (var stream2 = File.OpenRead(path2)) { System.Boolean EOF = false; do { var length = stream.Read(largeBuf, 0, largeBuf.Length); var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length); if (length != length2) return false; if (length != largeBuf.Length) EOF = true; int i = 0; while (i < length) { if (largeBuf[i] != largeBuf2[i]) return false; i++; } } while (EOF == false); } } return true; } catch (Exception e) { Console.WriteLine("Byte for Byte comparison failed: " + e.Message); return false; } } private static Boolean CompareHash(byte[] hash1, byte[] hash2) { int i = 0; while (i < hash1.Length) { if (hash1[i] != hash2[i]) return false; i++; } return true ; } private static readonly byte[] readBuf = new byte[1024 + 64]; private static readonly byte[] largeBuf = new byte[10240 + 64]; private static readonly byte[] largeBuf2 = new byte[10240 + 64]; private static readonly byte[] randomNumber = new byte[64]; private static byte[] hash = new byte[64]; private static byte[] Compute1KHash(string path) { Buffer.BlockCopy(randomNumber, 0, readBuf, 0, randomNumber.Length); try { using (var stream = File.OpenRead(path)) { var length = stream.Read(readBuf, hash.Length, readBuf.Length - hash.Length); hash = SHA512.Create().ComputeHash(readBuf, 0, length + hash.Length); return (hash); } } catch (Exception e) { Console.WriteLine("Hash Error: " + e.Message); return (null); } } private static byte[] ComputeFullHash(string path) { Buffer.BlockCopy(randomNumber, 0, largeBuf, 0, randomNumber.Length); try { var _SHA = SHA512.Create(); using (var stream = File.OpenRead(path)) { System.Boolean EOF = false; while (EOF == false) { var length = stream.Read(largeBuf, hash.Length, largeBuf.Length - hash.Length); if (length != (largeBuf.Length - hash.Length)) EOF = true; hash = _SHA.ComputeHash(largeBuf, 0, length + hash.Length); Buffer.BlockCopy(hash, 0, largeBuf, 0, hash.Length); } return (hash); } } catch (Exception e) { Console.WriteLine("Hash error: " + e.Message); return (null); } } } }
PowerShellCorpus/PoshCode/sample format file.ps1
sample format file.ps1
## UI Automation v 1.8 -- REQUIRES the Reflection module (current version: http://poshcode.org/3174 ) ## # WASP 2.0 is getting closer, but this is still just a preview: # -- a lot of the commands have weird names still because they're being generated ignorantly # -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke # v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit # v 1.8 - Fixes .Net version problems: specifying CSharpVersion3 when in PowerShell 2 # IF your PowerShell is running in .Net 4 if($PSVersionTable.CLRVersion -gt "4.0") { $Language = "CSharp" # Version 4 Add-Type -AssemblyName "UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Add-Type -AssemblyName "UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" } else { # In PowerShell 2, we need to use the .Net 3 version $Language = "CSharpVersion3" Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" } $SWA = "System.Windows.Automation" # Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue # Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue # Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue # Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue # Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue # Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue # This is what requires the Reflection module: Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue ##### Conditions Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue ##### IDentifiers Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue ##### Patterns: $patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern #| Where { $_ -ne [System.Windows.Automation.InvokePattern] } Add-Type -Language $Language -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Automation; using System.Runtime.InteropServices; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class StaticFieldAttribute : ArgumentTransformationAttribute { private Type _class; public override string ToString() { return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName); } public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) { if(inputData is string && !string.IsNullOrEmpty(inputData as string)) { System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public); if(field != null) { return field.GetValue(null); } } return inputData; } public StaticFieldAttribute( Type ofClass ) { OfClass = ofClass; } public Type OfClass { get { return _class; } set { _class = value; } } } public static class UIAutomationHelper { [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr FindWindow (string lpClassName, string lpWindowName); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SetForegroundWindow (IntPtr hWnd); public static AutomationElement RootElement { get { return AutomationElement.RootElement; } } ///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis> public static bool SetForeground(this AutomationElement element) { if(element == null) { throw new ArgumentNullException("element"); } // Get handle to the element IntPtr other = FindWindow (null, element.Current.Name); // // Get the Process ID for the element we are trying to // // set as the foreground element // int other_id = GetWindowThreadProcessId (other, IntPtr.Zero); // // // Get the Process ID for the current process // int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero); // // // Attach the current process's input to that of the // // given element. We have to do this otherwise the // // WM_SETFOCUS message will be ignored by the element. // bool success = AttachThreadInput(this_id, other_id, true); // Make the Win32 call IntPtr previous = SetForegroundWindow(other); return !IntPtr.Zero.Equals(previous); } } "@ ## TODO: Write Get-SupportedPatterns or rather ... ## Get-SupportedFunctions (to return the names of the functions for the supported patterns) ## TODO: Support all the "Properties" too ## TODO: Figure out why Notepad doesn't support SetValue ## TODO: Figure out where the menus support went ForEach($pattern in $patterns){ $pattern | Add-Accelerator $PatternFullName = $pattern.FullName $PatternName = $Pattern.Name -Replace "Pattern","." $newline = "`n`t`t" New-Item "Function:ConvertTo-$($Pattern.Name)" -Value " param( [Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject ) process { trap { if(`$_.Exception.Message -like '*Unsupported Pattern.*') { Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue; } } Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current }" $pattern.GetMethods() | Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } | ForEach { $FunctionName = "Function:Invoke-$PatternName$($_.Name)" $Position = 1 if (test-path $FunctionName) { remove-item $FunctionName } $Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+ "$newline[Alias('Parent','Element','Root','AutomationElement')]"+ "$newline[AutomationElement]`$InputObject" ) + @( "[Parameter()]$newline[Switch]`$Passthru" ) + @($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" }) $Parameters = $Parameters -Join "$newline,$newline" $ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $') $definition = @" param( $Parameters ) process { ## trap { Write-Warning "`$(`$_)"; break } `$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues })) } if(`$passthru) { `$InputObject } } "@ trap { Write-Warning $_ Write-Host $definition -fore cyan } New-Item $FunctionName -value $definition } $pattern.GetProperties() | Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} | ForEach { $FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.') if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$pattern.'$($_.Name)' } }" } ## So far this seems to be restricted to Text (DocumentRange) elements $pattern.GetFields() | Where { $_.FieldType.Name -like "*TextAttribute"} | ForEach { $FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name)) }" } $pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } | ForEach { $Name = $_.Name -replace 'Event$' $FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement , [System.Windows.Automation.TreeScope]`$TreeScope = 'Element' , [ScriptBlock]`$EventHandler ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } [Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler ) }" } } $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue $AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties() Set-Alias Invoke-UIElement Invoke-Invoke.Invoke function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Get-ClickablePoint { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject ) process { $InputObject.GetClickablePoint() } } function Show-Window { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { Set-UIFocus $InputObject if($passthru) { $InputObject } } } function Set-UIFocus { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { try { [UIAutomationHelper]::SetForeground( $InputObject ) $InputObject.SetFocus() } catch { Write-Verbose "SetFocus fail, trying SetForeground" } if($passthru) { $InputObject } } } function Send-UIKeys { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Keys , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru , [Parameter()] [Switch]$Async ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } Set-UIFocus $InputObject if($Async) { [SendKeys]::Send( $Keys ) } else { [SendKeys]::SendWait( $Keys ) } if($passthru) { $InputObject } } } function Set-UIText { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Text , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } $valuePattern = $null if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) { Write-Verbose "Set via ValuePattern!" $valuePattern.SetValue( $Text ) } elseif($InputObject.Current.IsKeyboardFocusable) { Set-UIFocus $InputObject [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } if($passthru) { $InputObject } } } function Select-UIElement { [CmdletBinding(DefaultParameterSetName="FromParent")] PARAM ( [Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)] [Alias("MainWindowHandle","hWnd","Handle","Wh")] [IntPtr[]]$WindowHandle=[IntPtr]::Zero , [Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)] [System.Windows.Point[]]$Point , [Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)] [System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement , [Parameter(ParameterSetName="FromParent", Position="0")] [Alias("WindowName")] [String[]]$Name , [Parameter(ParameterSetName="FromParent", Position="1")] [Alias("Type","Ct")] [System.Windows.Automation.ControlType] [StaticField(([System.Windows.Automation.ControlType]))]$ControlType , [Parameter(ParameterSetName="FromParent")] [Alias("UId")] [String[]]$AutomationId , ## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle [Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )] [Alias("Id")] [Int[]]$PID , [Parameter(ParameterSetName="FromParent")] [Alias("Pn")] [String[]]$ProcessName , [Parameter(ParameterSetName="FromParent")] [Alias("Cn")] [String[]]$ClassName , [switch]$Recurse , [switch]$Bare ) process { Write-Debug "Parameters Found" Write-Debug ($PSBoundParameters | Format-Table | Out-String) $search = "Children" if($Recurse) { $search = "Descendants" } $condition = [System.Windows.Automation.Condition]::TrueCondition Write-Verbose $PSCmdlet.ParameterSetName switch -regex ($PSCmdlet.ParameterSetName) { "FromWindowHandle" { Write-Verbose "Finding from Window Handle $HWnd" $Element = $( foreach($hWnd in $WindowHandle) { [System.Windows.Automation.AutomationElement]::FromHandle( $hWnd ) } ) continue } "FromPoint" { Write-Verbose "Finding from Point $Point" $Element = $( foreach($pt in $Point) { [System.Windows.Automation.AutomationElement]::FromPoint( $pt ) } ) continue } "FromParent" { Write-Verbose "Finding from Parent!" ## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition [ScriptBlock[]]$filters = @() if($AutomationId) { [System.Windows.Automation.Condition[]]$current = $( foreach($aid in $AutomationId) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($PID) { [System.Windows.Automation.Condition[]]$current = $( foreach($p in $PID) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($ProcessName) { if($ProcessName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($p in Get-Process -Name $ProcessName) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($Name) { Write-Verbose "Name: $Name" if($Name -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($n in $Name){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ClassName) { if($ClassName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ClassName){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ControlType) { if($ControlType -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ControlType){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($conditions.Length -gt 1) { [System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions } elseif($conditions) { [System.Windows.Automation.Condition]$condition = $conditions[0] } else { [System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition } If($VerbosePreference -gt "SilentlyContinue") { function Write-Condition { param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0) process { Write-Debug ($Condition | fl * | Out-String) if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) { Write-Verbose ((" "*$indent) + $Condition.GetType().Name ) $condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4) } elseif($condition -is [System.Windows.Automation.PropertyCondition]) { Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")") } else { Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")") } } } Write-Verbose "CONDITIONS =============" $global:LastCondition = $condition foreach($c in $condition) { Write-Condition $c } Write-Verbose "============= CONDITIONS" } if($filters.Count -gt 0) { $Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item } } else { $Element = $Parent.FindAll( $search, $condition ) } } } Write-Verbose "Element Count: $(@($Element).Count)" if($Element) { foreach($el in $Element) { if($Bare) { Write-Output $el } else { $e = New-Object PSObject $el foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName) { ## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property $propName = [System.Windows.Automation.Automation]::PropertyName($prop) Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0 } foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName) { Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0 } Write-Output $e } } } } } # [Cmdlet(VerbsCommon.Add, "UIAHandler")] # public class AddUIAHandlerCommand : PSCmdlet # { # private AutomationElement _parent = AutomationElement.RootElement; # private AutomationEvent _event = WindowPattern.WindowOpenedEvent; # private TreeScope _scope = TreeScope.Children; # # [Parameter(ValueFromPipeline = true)] # [Alias("Parent", "Element", "Root")] # public AutomationElement InputObject { set { _parent = value; } get { return _parent; } } # # [Parameter()] # public AutomationEvent Event { set { _event = value; } get { return _event; } } # # [Parameter()] # public AutomationEventHandler ScriptBlock { set; get; } # # [Parameter()] # public SwitchParameter Passthru { set; get; } # # [Parameter()] # public TreeScope Scope { set { _scope = value; } get { return _scope; } } # # protected override void ProcessRecord() # { # Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock); # # if (Passthru.ToBool()) # { # WriteObject(InputObject); # } # # base.ProcessRecord(); # } # } Export-ModuleMember -cmdlet * -Function * -Alias *
PowerShellCorpus/PoshCode/New-RssFeed.ps1
New-RssFeed.ps1
# Creates an RSS feed # Parameter input is for "site": Path, Title, Url, Description # Pipeline input is for feed items: hashtable with Title, Link, Author, Description, and pubDate keys param ( $Path = "$( throw 'Path is a mandatory parameter.' )", $Title = "Site Title", $Url = "http://$( $env:computername )", $Description = "Description of site" ) Begin { # feed metadata $encoding = [System.Text.Encoding]::UTF8 $writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding ) $writer.WriteStartDocument() $writer.WriteStartElement( "rss" ) $writer.WriteAttributeString( "version", "2.0" ) $writer.WriteStartElement( "channel" ) $writer.WriteElementString( "title", $Title ) $writer.WriteElementString( "link", $Url ) $writer.WriteElementString( "description", $Description ) } Process { # Construct feed items $writer.WriteStartElement( "item" ) $writer.WriteElementString( "title", $_.title ) $writer.WriteElementString( "link", $_.link ) $writer.WriteElementString( "author", $_.author ) $writer.WriteStartElement( "description" ) $writer.WriteRaw( "<![CDATA[" ) # desc can contain HTML, so its escaped using SGML escape code $writer.WriteRaw( $_.description ) $writer.WriteRaw( "]]>" ) $writer.WriteEndElement() $writer.WriteElementString( "pubDate", $_.pubDate.toString( 'r' ) ) $writer.WriteElementString( "guid", $homePageUrl + "/" + [guid]::NewGuid() ) $writer.WriteEndElement() } End { $writer.WriteEndElement() $writer.WriteEndElement() $writer.WriteEndDocument() $writer.Close() }
PowerShellCorpus/PoshCode/Sort IE Favorites_1.ps1
Sort IE Favorites_1.ps1
$Results = gci $env:userprofile\\favorites -rec -inc *.url | ? {select-string -inp $_ -quiet "^URL=http"} | select @{Name="Name"; Expression={[IO.Path]::GetFileNameWithoutExtension($_.FullName)}}, @{Name="URL"; Expression={get-content $_ | ? {$_ -match "^URL=http"} | % {$_.Substring(4)}}} New-Item $env:userprofile\\favorites\\sorted -ItemType directory foreach ($Result in $Results |Sort-Object -Property url) { $Url = [System.Uri]$Result.URL if ($Url) { $Folders = $Url.Host.Split(".") if ($url.Host -eq 'agoodman.com.au') { #break } if ($Folders.Count -eq 2) { $RootFolder = $Folders[0] } if ($Folders.Count -eq 3) { $RootFolder = $Folders[1] if (($Folders[$Folders.Count-1]).Length -eq 2) { $RootFolder = $Folders[0] } } if ($Folders.Count -gt 3) { if (($Folders[$Folders.Count-1]).Length -eq 3) { $RootFolder = ($Folders[$Folders.Count-3]) } } New-Item "$($env:userprofile)\\favorites\\sorted\\$($RootFolder)" -ItemType Directory -Force $shell = New-Object -ComObject WScript.Shell $FileName = $Result.Name.Trim() -replace "[^a-zA-Z0-9\\s]","" $path = "$($env:userprofile)\\favorites\\sorted\\$($RootFolder)\\$($FileName).URL" $ShortCut = $shell.CreateShortCut($path) $ShortCut.TargetPath = $Result.URL $ShortCut.Save() } }
PowerShellCorpus/PoshCode/Get_Set Signature (CTP3)_1.ps1
Get_Set Signature (CTP3)_1.ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for CTP 3 #################################################################################################### ## 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-Signed -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-Signed -NotMine -ValidOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 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-Signed ## - Added -MineOnly and -NotMineOnly switches to Select-Signed ## 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: ## F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## OR: ## "Cert:\\CurrentUser\\My\\F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5" ## OR a file name: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## ## The simplest thing is to just create a new PSD1 ## ## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 ` ## -Author "" -Company "" -Copy "" -Desc "" ` ## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() ` ## -PrivateData F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## #################################################################################################### #################################################################################################### 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 bereused without re-querying for the location and/or password ... .RETURNVALUE An X509Certificate2 suitable for code-signing #>################################################################################################## [CmdletBinding()] PARAM () 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-Signed or Test-Signature. 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(!$ExecutionContext.SessionState.Module.PrivateData) { Write-Host $($ExecutionContext | out-string) -Fore Yellow Write-Host $($ExecutionContext.SessionState | out-string) -Fore Yellow Write-Host $($ExecutionContext.SessionState.Module | fl * | out-string) -Fore Yellow Write-Host $($ExecutionContext.SessionState.Module | gm | out-string) -Fore Yellow Write-Host $($ExecutionContext.SessionState.Module.PrivateData | out-string) -Fore Yellow $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 } $ExecutionContext.SessionState.Module.PrivateData = $(Read-Host "Please specify a user certificate") } if($ExecutionContext.SessionState.Module.PrivateData -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { # Write-Host "CertificatePath: $ExecutionContext.SessionState.Module.PrivateData" -fore cyan $ResolvedPath = $Null $ResolvedPath = Resolve-Path $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue" if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore green $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore yellow $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" # Write-Host "ResolvedPath: $ResolvedPath" -fore red } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } Write-Verbose "Certificate: $($Certificate | Out-String)" $ExecutionContext.SessionState.Module.PrivateData = $Certificate } return $ExecutionContext.SessionState.Module.PrivateData } } function Test-Signature { <# .SYNOPSIS Tests a script signature to see if it is valid, or at least unaltered. .DESCRIPTION The Test-Signature function processes the output of Get-AuthenticodeSignature to determine if it is Valid, OR **unaltered** and signed by the user's certificate .NOTES Test-Signature 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-Signature $_} To get the signature reports for all the scripts that we consider safely signed. .EXAMPLE ls | ? { gas $_ | test-signature } 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-Signature $_ -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. .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 , [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) ) PROCESS { Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)" Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $(Resolve-Path $FilePath) } } New-Alias sign Set-AuthenticodeSignature -EA "SilentlyContinue" #################################################################################################### 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-Signature $_ -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-Signed { <#.SYNOPSIS Select files based on the status of their Authenticode Signature. .DESCRIPTION The Select-Signed 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-Signed 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-Signature $_ -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 } # NOTValid returns only things that are SIGNED and Valid 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 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 }} } } Export-ModuleMember Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-Signature, Select-Signed, Get-UserCertificate # SIG # Begin signature block # MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUh2j7Q1a1fQVctEbLvEtM2VHy # HsGgggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL # Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw # Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ # KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx # OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l # dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk # bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs # IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y # ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM # +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ # qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ # /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX # IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05 # 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7 # tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8 # xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx # gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs # VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG # fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1 # JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH # Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG # A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF # BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB # DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF # AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2 # bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q # V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha # vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg # oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1 # jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7 # iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp # Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz # y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp # JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0 # u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB # ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH # EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo # MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE # AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0 # eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo # OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ # KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB # gjcCARUwIwYJKoZIhvcNAQkEMRYEFO9dBNKwVxAMZZ4sU+puzqqXt70lMA0GCSqG # SIb3DQEBAQUABIICABnrY42qvQiGhAyLcPifUIScJt2I4PcPyWXFa2z/xxngOZi+ # Syu1U1ojxOmVj6wP7dXwnBYOforF3uaLqAAfLkAP6NzLfZh3jOkqcyovP5vEyg0M # o1oLv79KrUOq+9Md/UonY01rLkZzZzrzWpiep9vfeYOTQ9J1PjR6CQ0kZDeF6YvN # 0x6QemcFYeum4aksrc+873MjmNXLQXpVsyQxKv4Em4qm+Rc0Lbn9OLKxu9wHXzJu # qyQcE/WSkUoJu8Zm7s1wM6PGnoFq70+S9zkNg0uDh5niLOyUQlHN33NC5QyEGm6I # z658I5uFYgL3LEZeT0zXl5j9YP+ZfDRkRUwn9Xu14losY9WoD9LTgmtvEzo/VdlP # hrSwNE2u3xW6luQBeF9pcKLedgs9J89rWjAVPUQRVLbfd+cd5epJSeGX6UTKNJXS # WMq0SfpztJTf0s0RjPL/JxCy787I/EjWcQDJow/gAaaRFs0ImmFLWzZIci6XnmxO # qMqQxUfea6ZkYjW1RvbKQ7WR3DlUmNE4HL2QT3KdQyf9rbjC5MkF/Kwq7xmcIjrz # OjE81LqqUyybCz8tDbad0bbmzpGmNqKINTowxv+U0Ne8lXRRMuYj6sa+GR96aHSv # RrXB1YksbcYcJq2rxwIldvfnffANQgEObul04Dpbn0KBewNncdyzSkt015Aq # SIG # End signature block
PowerShellCorpus/PoshCode/88c1a7d6-0bf3-48db-bec5-4b21531648c5.ps1
88c1a7d6-0bf3-48db-bec5-4b21531648c5.ps1
Function Get-DiskUsage { <# .SYNOPSIS A tribute to the excellent Unix command DU. .DESCRIPTION This command will output the full path and the size of any object and it's subobjects. Using just the Get-DiskUsage command without any parameters will result in an output of the directory you are currently placed in and it's subfolders. .PARAMETER Path If desired a path can be specified with the Path parameter. In no path is specified $PWD will be used. .PARAMETER h the -h paramater is the same as -h in Unix. It will list the folders and subfolders in the most appropriate unit depending on the size (i.e. Human Readable). .PARAMETER l The -l paramater will add the largest file to the end of the output. .PARAMETER Sort Allows you to sort by Folder or Size. If none i specified the default of Folder will be used. .PARAMETER Depth Depth will allow you to specify a maximum recursion depth. A depth of 1 would return the immediate subfolders under the root. .PARAMETER Force Works the same way as Get-ChildItem -force. .PARAMETER Descending Works the same way as Sort-Object -descending. .LINK http://www.donthaveasite.nu .NOTES Author: Jonas Hallqvist Developed with Powershell v3 #> [CmdletBinding( SupportsShouldProcess=$True )] param ( [String]$Path=$PWD, [Switch]$h, [Switch]$l, [String]$Sort="Folder", [Int]$Depth, [Switch]$Force, [Switch]$Descending ) $ErrorActionPreference = "silentlycontinue" function HumanReadable { param ($size) switch ($size) { {$_ -ge 1PB}{"{0:#'P'}" -f ($size / 1PB); break} {$_ -ge 1TB}{"{0:#'T'}" -f ($size / 1TB); break} {$_ -ge 1GB}{"{0:#'G'}" -f ($size / 1GB); break} {$_ -ge 1MB}{"{0:#'M'}" -f ($size / 1MB); break} {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break} #{$_ -eq $null}{"0B"} default {"{0}" -f ($size) + "B"} } } function LargestFolder { if ($h) { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } else { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } } function Max-Depth { param( [String]$Path = '.', [String]$Filter = '*', [Int]$Level = 0, [Switch]$Force, [Switch]$Descending, [int]$i=0 ) $results=@() $root = (Resolve-Path $Path).Path if ($root -notmatch '\\\\$') {$root += '\\'} if (Test-Path $root -PathType Container) { do { [String[]]$_path += $root + "$Filter" $Filter = '*\\' + $Filter $i++ } until ($i -eq $Level) $dirs=Get-ChildItem -directory $_path -Force:$Force foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.Fullname -recurse | Measure-Object -Property Length -Sum).Sum $results += New-Object psobject -Property @{Folder=$dir.fullname;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } } if ($Depth) { Max-Depth -Path $Path -Level $Depth -Force:$Force -Descending:$Descending } else { $results = @() $dirs=Get-ChildItem -directory $Path -Force:$Force -Recurse foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.FullName -Recurse | Measure-Object -Property Length -Sum).Sum $results+= New-Object psobject -Property @{Folder=$dir.FullName;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } }
PowerShellCorpus/PoshCode/Product key_1.ps1
Product key_1.ps1
from System import Array, Char, Console from System.Collections import ArrayList from Microsoft.Win32 import Registry def DecodeProductKey(digitalProductID): map = ("BCDFGHJKMPQRTVWXY2346789").ToCharArray() key = Array.CreateInstance(Char, 29) raw = ArrayList() i = 52 while i < 67: raw.Add(digitalProductID[i]) i += 1 i = 28 while i >= 0: if (i + 1) % 6 == 0: key[i] = '-' else: k = 0 j = 14 while j >= 0: k = (k * 256) ^ raw[j] raw[j] = (k / 24) k %= 24 key[i] = map[k] j -= 1 i -= 1 return key reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion") val = reg.GetValue("DigitalProductId") Console.WriteLine(DecodeProductKey(val))
PowerShellCorpus/PoshCode/Show-Image.ps1
Show-Image.ps1
function Show-Image { param([string]$file = $(throw "No file specified.")) [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Drawing") #maybe this idea is not good but it can help display big images [Windows.Forms.Screen]::AllScreens | % -p { $maxHeight = ($_.Bounds).Height $maxWidth = ($_.Bounds).Width } if (Test-Path $file) { #loading image $pic = [Drawing.Image]::FromFile((rvpa $file).Path) #window size is equal image $size = $pic.Size #form $frmMain = New-Object Windows.Forms.Form $picArea = New-Object Windows.Forms.PictureBox #picArea $picArea.Dock = "Fill" $picArea.Image = New-Object Drawing.Bitmap((rvpa $file).Path) $picArea.SizeMode = "StretchImage" #frmMain $frmMain.AutoScroll = $true $frmMain.Controls.AddRange(@($picArea)) $frmMain.FormBorderStyle = "None" $frmMain.StartPosition = "CenterScreen" $frmMain.Text = $file $frmMain.Add_KeyDown( { if ($_.KeyCode -eq "Escape") {$frmMain.Close()} } ) #checking sizes if ($size.Height -ge $maxHeight -and $size.Width -ge $maxWidth) { $frmMain.Size = New-Object Drawing.Size($maxWidth, $maxHeight) } else { $frmMain.Size = $size } [void]$frmMain.ShowDialog() #this can escape locking image file with host $pic.Dispose() } }
PowerShellCorpus/PoshCode/Export-PSCredential_4.ps1
Export-PSCredential_4.ps1
# Author: Hal Rottenberg <hal@halr9000.com> # Url: http://halr9000.com/article/tag/lib-authentication.ps1 # Purpose: These functions allow one to easily save network credentials to disk in a relatively # secure manner. The resulting on-disk credential file can only [1] be decrypted # by the same user account which performed the encryption. For more details, see # the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as # MSDN pages about Windows Data Protection API. # [1]: So far as I know today. Next week I'm sure a script kiddie will break it. # # Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>] # Export-PSCredential [-Credential <username>] [-Path <file to export>] # If Credential is not specififed, user is prompted by Get-Credential cmdlet. # If a username is specified, then Get-Credential will prompt for password. # If the Path is not specififed, it will default to "./credentials.enc.xml". # Output: FileInfo object referring to saved credentials # # Import-PSCredential [-Path <file to import>] # # If not specififed, Path is "./credentials.enc.xml". # Output: PSCredential object function Export-PSCredential { param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" ) # Look at the object type of the $Credential parameter to determine how to handle it switch ( $Credential.GetType().Name ) { # It is a credential, so continue PSCredential { continue } # It is a string, so use that as the username and prompt for the password String { $Credential = Get-Credential -credential $Credential } # In all other caess, throw an error and exit default { Throw "You must specify a credential object to export to disk." } } # Create temporary object to be serialized to disk $export = "" | Select-Object Username, EncryptedPassword # Give object a type name which can be identified later $export.PSObject.TypeNames.Insert(0,ĺExportedPSCredentialĺ) $export.Username = $Credential.Username # Encrypt SecureString password using Data Protection API # Only the current user account can decrypt this cipher $export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString # Export using the Export-Clixml cmdlet $export | Export-Clixml $Path Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine # Return FileInfo object referring to saved credentials Get-Item $Path } function Import-PSCredential { param ( $Path = "credentials.enc.xml" ) # Import credential file $import = Import-Clixml $Path # Test for valid import if ( !$import.UserName -or !$import.EncryptedPassword ) { Throw "Input is not a valid ExportedPSCredential object, exiting." } $Username = $import.Username # Decrypt the password and store as a SecureString object for safekeeping $SecurePass = $import.EncryptedPassword | ConvertTo-SecureString # Build the new credential object $Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass Write-Output $Credential }
PowerShellCorpus/PoshCode/Balance-Datastores_1.ps1
Balance-Datastores_1.ps1
<# TODO -Change number of DSTs to is selection of $DSTMostFree to be variable. Also add in logic to select DSTs with lower VMCounts. Total DSTs Select DSTs ---------- ----------- <5 1 5-20 3 >20 5 -For $DSTLeastFree add in logic to select DSTs with higher VMCounts. #> #Parameter- Name of the VMware cluster to work in param($Cluster,$Action) Write-Output "`n$(Get-Date)- Script started" # Validate parameter input If ( ($Action -ne "Move") -and ($Action -ne "Report") ) { Write-Output "$(Get-Date)- Valid values for the parameter ""Action"" are either ""Move"" or ""Report""" Write-Output "$(Get-Date)- Script aborted`n" break } $IsClusterNameInvalid = $true Get-Cluster | % { If ($_.Name -eq $Cluster) {$IsClusterNameInvalid = $false} } If ($IsClusterNameInvalid) { Write-Host "Error- Invalid Cluster Name" -Background Yellow -Foreground Red Write-Host "Valid cluster names for this Virtual Center server." Write-Host "---------------------------------------------------" Get-Cluster | Sort Write-Output "$(Get-Date)- Script aborted`n" break } # Prep $ScriptDir = "\\\\vmscripthost201\\repo" . $ScriptDir\\Get-mDataStoreList.ps1 If ($Cluster -match "Prod") { $DatastoreNumVMsLimit = 15 } Else { $DatastoreNumVMsLimit = 20 } $FreeSpacePercentMoveThreshold = 25 # Get the list of valid datastores and pick the one with the least free space. $DSTs = Get-mDataStoreList $Cluster $DSTInfoAll = $DSTs | Select-Object Name,@{n="CapacityGB";e={[int](($_.CapacityMB/1024))}},@{n="FreeSpaceGB";e={[int](($_.FreeSpaceMB/1024))}},@{n="FreeSpacePercent";e={[int](($_.FreeSpaceMB/$_.CapacityMB*100))}},@{n="ProvisionedGB";e={[int](($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.Freespace + $_.ExtensionData.Summary.Uncommitted)/1024/1024/1024)}},@{n="ProvisionedPercent";e={[int](($_.ExtensionData.Summary.Capacity - $_.ExtensionData.Summary.Freespace + $_.ExtensionData.Summary.Uncommitted)/$_.ExtensionData.Summary.Capacity*100)}},@{n="VMCount";e={(Get-VM -Datastore $_ | Measure-Object).Count}} If ($DSTInfoAll | Where-Object { $_.FreeSpacePercent -lt $FreeSpacePercentMoveThreshold } ) { $DSTInfoLeastCandidates = $DSTInfoAll | Where-Object { $_.FreeSpacePercent -lt 25 } } ElseIf ($DSTInfoAll | Where-Object { $_.VMCount -gt $DatastoreNumVMsLimit } ) { $DSTInfoLeastCandidates = $DSTInfoAll | Where-Object { $_.VMCount -gt $DatastoreNumVMsLimit } } Else { $DSTInfoLeastCandidates = $DSTInfoAll } $DSTLeastFree = $DSTInfoLeastCandidates | Sort-Object FreespacePercent | Select-Object -First 3 | Sort-Object ProvisionedPercent | Select-Object -Last 1 $DSTMostFree = $DSTInfoAll | Where-Object { $_.VMCount -lt $DatastoreNumVMsLimit } | Sort FreeSpacePercent | Select-Object -Last 3 | Sort-Object ProvisionedPercent | Select-Object -First 1 #$DSTInfo | ft -a #$DSTLeastFree | ft -a #$DSTMostFree | ft -a # Get all the VMs on the datastore with the least free space and having less than 16GB of RAM. VMs with high RAM are more likely to fail svMotion. # $SourceVMsInitial = Get-VM -Datastore $DSTLeastFree.Name | Where-Object { $_.MemoryMB -le 16384 } | Sort-Object UsedSpaceGB # cjm 110719- Removing the above restriction to 16GB VMs or lower because there are too many with more than that. $SourceVMsInitial = Get-VM -Datastore $DSTLeastFree.Name | Sort-Object UsedSpaceGB # Remove any VMs that are in the exclusions text file. $SourceVMsNotExcludeded = $SourceVMsInitial | ForEach-Object { $vmtemp = $_.Name $match = $false Get-Content $ScriptDir\\StaticInfo\\sVMotion_ExcludeList.txt | ForEach-Object { If ($vmtemp -eq $_) { $match = $true } } If ($match -eq $false) { $vmtemp } } # $SourceVMs = $SourceVMsNotExcludeded | Where-Object { $_.MemoryMB -le 32768 } # Pick the VM $SourceVMCount = ($SourceVMs | Measure-Object).Count $SourceVMIndex = [int]($SourceVMCount/2) $SourceVMToMove = $SourceVMs[$SourceVMIndex] If ($Action -eq "Report" ) { Write-Output "+++++++ Reporting only +++++++" } $DSTLeastFree | Format-Table -AutoSize $DSTMostFree | Format-Table -AutoSize Get-VM $SourceVMToMove | Select Name,PowerState,VMHost,ResourcePool,NumCpu,MemoryMB,@{n="ProvisionedSpaceGB";e={[int]($_.ProvisionedSpaceGB)}},@{n="UsedSpaceGB";e={[int]($_.UsedSpaceGB)}} | Format-Table -AutoSize If ($Action -eq "Move" ) { # svMotion the VM Write-Output "$(Get-Date)- *** Moving $($SourceVMToMove) from $(($DSTLeastFree).Name) to $(($DSTMostFree).Name)" Move-VM -VM $SourceVMToMove -Datastore ($DSTMostFree).Name -Confirm:$false | Format-Table -AutoSize } Write-Output "$(Get-Date)- Script finished`n"
PowerShellCorpus/PoshCode/Correction.ps1
Correction.ps1
function Convert-ToCHexString { [CmdletBinding()] param ( [Parameter(ValueFromPipeline=$true,Mandatory=$true)][string]$str ) @@ process { ($str.ToCharArray() | %{ "0x{0:X2}" -f [int]$_ }) -join ',' } }
PowerShellCorpus/PoshCode/VM Disk Report_2.ps1
VM Disk Report_2.ps1
$VMs = get-vm $Results = @() foreach ($VM in $VMs) { $Result = new-object PSObject $Result | add-member -membertype NoteProperty -name "Name" -value $VM.Name $Result | add-member -membertype NoteProperty -name "Description" -value $VM.Notes $VMDiskCount = 1 get-harddisk $VM | foreach { $disk = $_ $Result | add-member -name "Disk($VMDiskCount)SizeGB" -value ([math]::Round($disk.CapacityKB / 1MB)) -membertype NoteProperty $Result | add-member -name "Disk($VMDiskCount)Type" -value $disk.DiskType -membertype NoteProperty $VMDiskCount++ } $Results += $Result } $Results | select-object * | export-csv -notypeinformation E:\\VCBDiskReport.csv
PowerShellCorpus/PoshCode/65b30476-81de-4034-8d3c-ef5e8bdd0e43.ps1
65b30476-81de-4034-8d3c-ef5e8bdd0e43.ps1
$url = "http://dougfinke.com/scriptinggames/scriptinggames.html" $web = New-Object System.Net.WebClient foreach($line in ($web.downloadString($url)).split("`n")){ if($line -match "img"){ $line $fileName = $line.substring($line.indexof("title=")+7,(($line.indexof(" src"))-1)-($line.indexof("title=")+7)) $fileName = $fileName.replace(" ","_") $fileName $URLpath = $line.substring($line.indexof("src=")+5,(($line.indexof(">"))-1)-($line.indexof("src=")+5)) $URLpath $web.DownloadFile($URLpath,"C:\\Users\\Public\\Pictures\\Twitter\\$fileName.jpg") } }
PowerShellCorpus/PoshCode/Remove-FTPFile.ps1
Remove-FTPFile.ps1
function Remove-FTPFile ($Source,$UserName,$Password) { #Create FTP Web Request Object to handle connnection to the FTP Server $ftprequest = [System.Net.FtpWebRequest]::Create($Source) # set the request's network credentials for an authenticated connection $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password) $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DeleteFile # send the ftp request to the server $ftpresponse = $ftprequest.GetResponse() $ftpresponse }