full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/RunSSIS_1.ps1
RunSSIS_1.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Executes SSIS package for both server and file system storage types. ### </Description> ### <Usage> ### -------------------------- EXAMPLE 1 -------------------------- ### ./RunSSIS.ps1 -path Z002_SQL1\\sqlpsx -serverName 'Z002\\SQL1' ### ### This command will execute package sqlpsx on the server Z002\\SQL1 ### ### -------------------------- EXAMPLE 2 -------------------------- ### ./RunSSIS.ps1 -path Z002_SQL1\\sqlpsx -serverName Z002\\SQL1 -configFile 'C:\\SSISConfig\\sqlpsx.xml' ### ### This command will execute the package as in Example 1 and process and configuration file ### ### -------------------------- EXAMPLE 3 -------------------------- ### ./RunSSIS.ps1 -path 'C:\\SSIS\\sqlpsx.dtsx' ### ### This command will execute the package sqlpsx.dtsx located on the file system ### ### -------------------------- EXAMPLE 4 -------------------------- ### ./RunSSIS.ps1 -path 'C:\\SSIS\\sqlpsx.dtsx -nolog ### ### This command will execute the package sqlpsx.dtsx located on the file system and skip Windows Event logging ### ### </Usage> ### </Script> # --------------------------------------------------------------------------- param($path=$(throw 'path is required.'), $serverName, $configFile, [switch]$nolog) # Note: SSIS is NOT backwards compatible. At the beginning of the script you’ll need to comment/uncomment the specific assembly # to load 2005 or 2008. Default of the script is set to 2005 [reflection.assembly]::Load("Microsoft.SqlServer.ManagedDTS, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") > $null #[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft SQL Server\\90\\SDK\\Assemblies\\Microsoft.SQLServer.ManagedDTS.dll") > $null #[reflection.assembly]::Load("Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") > $null #[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft SQL Server\\100\\SDK\\Assemblies\\Microsoft.SQLServer.ManagedDTS.dll") > $null #[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ManagedDTS") > $null $myName = 'RunSSIS.ps1' ####################### function New-ISApplication { new-object ("Microsoft.SqlServer.Dts.Runtime.Application") } #New-ISApplication ####################### function Test-ISPath { param([string]$path=$(throw 'path is required.'), [string]$serverName=$(throw 'serverName is required.'), [string]$pathType='Any') #If serverName contains instance i.e. server\\instance, convert to just servername: $serverName = $serverName -replace "\\\\.*" #Note: Don't specify instance name $app = New-ISApplication switch ($pathType) { 'Package' { trap { $false; continue } $app.ExistsOnDtsServer($path,$serverName) } 'Folder' { trap { $false; continue } $app.FolderExistsOnDtsServer($path,$serverName) } 'Any' { $p=Test-ISPath $path $serverName 'Package'; $f=Test-ISPath $path $serverName 'Folder'; [bool]$($p -bor $f)} default { throw 'pathType must be Package, Folder, or Any' } } } #Test-ISPath ####################### function Get-ISPackage { param([string]$path, [string]$serverName) #If serverName contains instance i.e. server\\instance, convert to just servername: $serverName = $serverName -replace "\\\\.*" $app = New-ISApplication #SQL Server Store if ($path -and $serverName) { if (Test-ISPath $path $serverName 'Package') { $app.LoadFromDtsServer($path, $serverName, $null) } else { Write-Error "Package $path does not exist on server $serverName" } } #File Store elseif ($path -and !$serverName) { if (Test-Path -literalPath $path) { $app.LoadPackage($path, $null) } else { Write-Error "Package $path does not exist" } } else { throw 'You must specify a file path or package store path and server name' } } #Get-ISPackage ####################### #MAIN Write-Verbose "$myName path:$path serverName:$serverName configFile:$configFile nolog:$nolog.IsPresent" if (!($nolog.IsPresent)) { $log = Get-EventLog -List | Where-Object { $_.Log -eq "Application" } $log.Source = $myName $log.WriteEntry("Starting:$path",'Information') } $package = Get-ISPackage $path $serverName if ($package) { if ($configFile) { if (test-path -literalPath $configFile) { $package.ImportConfigurationFile("$configFile") } else { $err = "Invalid file path. Verify configFile:$configFile" if (!($nolog.IsPresent)) { $log.WriteEntry("Error:$path:$err",'Error') } throw ($err) break } } $package.Execute() $err = $package.Errors | foreach { $_.Source.ToString() + ':' + $_.Description.ToString() } if ($err) { if (!($nolog.IsPresent)) { $log.WriteEntry("Error:$path:$err",'Error') } throw ($err) break } else { if (!($nolog.IsPresent)) { $log.WriteEntry("Completed:$path",'Information') } } } else { $err = "Cannot Load Package. Verify Path:$path and Server:$serverName" if (!($nolog.IsPresent)) { $log.WriteEntry("Error:$path:$err",'Error') } throw ($err) break } #MAIN #######################
PowerShellCorpus/PoshCode/AS function.ps1
AS function.ps1
#region setup AS function function new-selectexpression { if ($args.count -eq 1) { $theargs = $args[0] } else {$theargs= $args } if ($theargs.count -gt 1) { for($loop=0;$loop -lt ($theargs.count-1);$loop+=2) { @{Name=$theargs[$loop];Expression=$theargs[$loop+1]} } } if (!($theargs.count % 2) -eq 0) {@{Name=$input[$input.count-1];Expression= invoke-Expression "{}" } } } set-Alias as new-selectexpression #endregion #Examples #Select (as theprocess ,name , # "CPU" , {$_.privatememorysize/ 1KB} , # "memory KB" , {$_.privatememorysize/ 1KB} , # "peak KB", {$_.peakworkingset /1KB} ) -first 2
PowerShellCorpus/PoshCode/Basic DNSBL Check for IP.ps1
Basic DNSBL Check for IP.ps1
Function CheckDNSBL { <# .NOTES AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com) WEBSITE: http://tekout.wordpress.com VERSION: 0.1 CREATED: 16th July, 2012 LASTEDIT: 16th July, 2012 Requires: PowerShell v2 or better .DESCRIPTION Basic Proof of Concept DNSBL Check Script You can add your own DNSBL's in the array and expand the list. Please use your Outbound STATIC IP as a parameter. You can run these checks for any version of Exchange [2003,2007,2010] Exchange doesnt need to be installed on the system to run this. Microsoft .Net Framework 3.5 and above required. #> param( $ip ) ## string reverse $reverseIP = ($ip.split("."))[3..0] [string[]]$newIP = [string]::join(".",$reverseIP) ##define hashtable for DNSBL's [string[]]$dnsbl = @( "b.barracudacentral.org"; "bl.deadbeef.com"; "bl.emailbasura.org"; "bl.spamcannibal.org"; "bl.spamcop.net"; "blackholes.five-ten-sg.com"; "blacklist.woody.ch"; "bogons.cymru.com"; "cbl.abuseat.org"; "cdl.anti-spam.org.cn"; "combined.abuse.ch"; "combined.rbl.msrbl.net"; "db.wpbl.info"; "dnsbl-1.uceprotect.net"; "dnsbl-2.uceprotect.net"; "dnsbl-3.uceprotect.net"; "dnsbl.ahbl.org"; "dnsbl.cyberlogic.net"; "dnsbl.inps.de"; "dnsbl.njabl.org"; "dnsbl.sorbs.net"; "drone.abuse.ch"; "drone.abuse.ch"; "duinv.aupads.org"; "dul.dnsbl.sorbs.net"; "dul.ru"; "dyna.spamrats.com"; "dynip.rothen.com"; "http.dnsbl.sorbs.net"; "images.rbl.msrbl.net"; "ips.backscatterer.org"; "ix.dnsbl.manitu.net"; "korea.services.net"; "misc.dnsbl.sorbs.net"; "noptr.spamrats.com"; "ohps.dnsbl.net.au"; "omrs.dnsbl.net.au"; "orvedb.aupads.org"; "osps.dnsbl.net.au"; "osrs.dnsbl.net.au"; "owfs.dnsbl.net.au"; "owps.dnsbl.net.au"; "pbl.spamhaus.org"; "phishing.rbl.msrbl.net"; "probes.dnsbl.net.au"; "proxy.bl.gweep.ca"; "proxy.block.transip.nl"; "psbl.surriel.com"; "rbl.interserver.net"; "rdts.dnsbl.net.au"; "relays.bl.gweep.ca"; "relays.bl.kundenserver.de"; "relays.nether.net"; "residential.block.transip.nl"; "ricn.dnsbl.net.au"; "rmst.dnsbl.net.au"; "sbl.spamhaus.org"; "short.rbl.jp"; "smtp.dnsbl.sorbs.net"; "socks.dnsbl.sorbs.net"; "spam.abuse.ch"; "spam.dnsbl.sorbs.net"; "spam.rbl.msrbl.net"; "spam.spamrats.com"; "spamlist.or.kr"; "spamrbl.imp.ch"; "t3direct.dnsbl.net.au"; "tor.ahbl.org"; "tor.dnsbl.sectoor.de"; "torserver.tor.dnsbl.sectoor.de"; "ubl.lashback.com"; "ubl.unsubscore.com"; "virbl.bit.nl"; "virus.rbl.jp"; "virus.rbl.msrbl.net"; "web.dnsbl.sorbs.net"; "wormrbl.imp.ch"; "xbl.spamhaus.org"; "zen.spamhaus.org"; "zombie.dnsbl.sorbs.net" ) #Compose DNSBL Strings for each member in DNSBL Array [string[]]$newDNSBL =@() foreach ($hash in $dnsbl) { $newDNSBL += [string]$newIP+'.'+$hash } # Enf of ForEach #DNS Lookup Check for 127.0.0.10 for Membership [String]$temp = @() for ($i=1;$i -lt $newDNSBL.Count; $i++) { $temp = [System.Net.Dns]::GetHostAddresses($newDNSBL[$i]) | select-object IPAddressToString -expandproperty IPAddressToString switch($temp){ #127.0.0.10 indicates $IP is listed in DNSBL '127.0.0.10'{ Write-Host "IP $ip is listed in DNSBL " , ($newDNSBL[$i]).Replace("$newIP","") -foregroundcolor "Red" } # End of "127.0.0.10 check #Blank returns not listed in DNSBL ''{ "IP $ip is NOT listed in DNSBL " + ($newDNSBL[$i]).Replace("$newIP","") } # End of "" Check } # End of Switch Block } # End of For Loop to check DNSBL Listing } # End of Function
PowerShellCorpus/PoshCode/Get-WebFile 3.7.3.ps1
Get-WebFile 3.7.3.ps1
## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7.3 - Checks to see if URL is formatted properly (contains http or https) ## v3.7.2 - Puts a try-catch block around $writer = new-object System.IO.FileStream and returns/breaks to ## prevent further execution if fso creation fails (e.g. if path is invalid). Note: known issue -- ## Script hangs if you try to connect to a good FQDN (e.g. www.google.com) with a bad port (e.g. 81). ## It will work fine if you use "http://192.168.1.1:81" but hang/crash if you use ## "http://www.google.com:81". ## v3.7.1 - Puts a try-catch block around the $req.GetResponse() call to prevent further execution if ## the page does not exist, cannot connect to server, can't resolve host, etc. ## v3.7 - [int] to [long] to support files larger than 2.0 GB ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## function Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) if($url.contains("http")) { $req = [System.Net.HttpWebRequest]::Create($url); } else { $URL_Format_Error = [string]"Connection protocol not specified. Recommended action: Try again using protocol (for example 'http://" + $url + "') instead. Function aborting..."; Write-Error $URL_Format_Error; return; } # http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw $req.CookieContainer = New-Object System.Net.CookieContainer try{ $res = $req.GetResponse(); } catch { Write-Error $error[0].Exception.InnerException.Message; return; } if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [long]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { try{ $writer = new-object System.IO.FileStream $fileName, "Create" } catch{ Write-Error $error[0].Exception.InnerException.Message; return; } } [byte[]]$buffer = new-object byte[] 4096 [long]$total = [long]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/Rotate-Right.ps1
Rotate-Right.ps1
function Rotate-Right { <# .SYNOPSIS Performs a binary rotate right operation. Author: Matthew Graeber (@mattifestation) .DESCRIPTION Rather than implementing the logic to perform a binary rotate operation, Rotate-Right wraps the private methods contained within System.Security.Cryptography.SHA256Managed and System.Security.Cryptography.SHA512Managed. .OUTPUTS System.UInt32. Returns a 32-bit unsigned integer System.UInt64. Returns a 64-bit unsigned integer .EXAMPLE PS > Rotate-Right 256 1 128 .EXAMPLE PS > Rotate-Right ([UInt64] 4294967296) 32 1 .LINK http://www.exploit-monday.com/2012/07/finding-powershells-missing-binary.html #> [CmdletBinding(DefaultParameterSetName = '32bit')] Param ( # The 32-bit value to be rotated [Parameter(Mandatory = $True, Position = 0, ParameterSetName = '32bit')] [UInt32] $Value32, # The 64-bit value to be rotated [Parameter(Mandatory = $True, Position = 0, ParameterSetName = '64bit')] [UInt64] $Value64, # The offset by which the value will be rotated [Parameter(Mandatory = $True, Position = 1)] [Int32] $Offset ) $BindingFlags = 'NonPublic, Static' switch ($PsCmdlet.ParameterSetName) { '32bit' { $RorMethodInfo = [System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', $BindingFlags, $null, @([UInt32], [Int32]), $null) $RorMethodInfo.Invoke($null, @($Value32, $Offset)) } '64bit' { $RorMethodInfo = [System.Security.Cryptography.SHA512Managed].GetMethod('RotateRight', $BindingFlags, $null, @([UInt64], [Int32]), $null) $RorMethodInfo.Invoke($null, @($Value64, $Offset)) } } }
PowerShellCorpus/PoshCode/Test-VM.ps1
Test-VM.ps1
Function Test-VM { [cmdletbinding()] Param ( [Parameter(Mandatory=$true,Position=1)] [string[]]$Name, [Parameter(Mandatory=$true,Position=2)] [string[]]$ComputerName ) Process { $results = @() foreach ($cName in $ComputerName) { foreach ($vName in $Name) { $result = New-Object System.Management.Automation.PSObject $result | Add-Member -NotePropertyName ComputerName -NotePropertyValue $cName $result | Add-Member -NotePropertyName Name -NotePropertyValue $vName Try { $vm = Get-VM -ComputerName $cName -Name $vName -ErrorAction SilentlyContinue if ($vm -ne $null) { $Existence = $true } else { $Existence = $false } } Catch { #Display an error message } $result | Add-Member -NotePropertyName Existence -NotePropertyValue $Existence $results += $result } } return $results } }
PowerShellCorpus/PoshCode/playlist_1.com music cache.ps1
playlist_1.com music cache.ps1
function calculateurl ([string]$source) { $encoded = ([byte[]]([regex]::matches($source,'\\w{2}') |% {"0x$_"})) $a = 0 $sbox = 0..255 $seed = "sdf883jsdf22"; $mykey = 0..255 | % { ([byte[]] ($seed.tochararray()))[$_ % $seed.length] } 0..255 | % {$a = ($a + $sbox[$_] + $mykey[$_]) % 256;$b = $sbox[$_];$sbox[$_] = $sbox[$a];$sbox[$a] = $b;} $a = $b = 0;$output = ""; $encoded | % {$a = ($a + 1) % 256;$b = ($b + $sbox[$a]) % 256;$e = $sbox[$a];$sbox[$a] = $sbox[$b];$sbox[$b] = $e; $h = ($sbox[$a] + $sbox[$b]) % 256; $d = $sbox[$h]; $_ -bxor $d } | % { $output += [char]$_ } $output } #function to cache a playlist.com playlist locally. function cacheplaylist([string]$path,[string]$playlistnumber) { ([xml](new-object system.net.webclient).downloadstring("http://pl.playlist.com/pl.php?playlist=$([int]($playlistnumber/256))")).playlist.tracklist.track | % { try { $a= $_.tracktitle;$a;(new-object system.net.webclient).downloadfile((calculateurl $_.location),"$path\\$a.mp3");"$a downloaded" } catch {"$a failed" } } } #example cacheplaylist c:\\musiccache 2952517899
PowerShellCorpus/PoshCode/Get_Set Signature (CTP2).ps1
Get_Set Signature (CTP2).ps1
#requires -version 2.0 CMDLET Set-AuthenticodeSignature -snapin Huddled.BetterDefaults { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path .\\breaking.ps1).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path , $Certificate=$(ls cert:\\CurrentUser\\my\\0DA3A2A2189CD74AE371E6C57504FEB9A59BB22E) ) Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $Path } CMDLET Get-AuthenticodeSignature -snapin Huddled.BetterDefaults { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path .\\breaking.ps1).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path ) Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path } Export-ModuleMember Set-AuthenticodeSignature,Get-AuthenticodeSignature
PowerShellCorpus/PoshCode/New-RandomPassword.ps1
New-RandomPassword.ps1
function New-RandomPassword { [CmdletBinding()] param( [Int16] $Length = 6, [Int16] $NumberOfNonAlphaNumericCharacters = 3, [Switch] $AsSecureString ) Begin { try { # Load required assembly. $assem = [System.Reflection.Assembly]::LoadWithPartialName('System.Web') } catch { throw 'Failed to load required assembly [System.Web.Security]. The error was: "{0}".' -f $_ } } Process { try { $generatedPassword = [System.Web.Security.Membership]::GeneratePassword($Length, $NumberOfNonAlphaNumericCharacters) if ($AsSecureString) { return ConvertTo-SecureString -String $generatedPassword -AsPlainText -Force } else { return $generatedPassword } } catch { throw 'Failed to generate random password. The error was: "{0}".' -f $_ } } End { Get-Variable | Where-Object {$_.Name -eq 'generatedPassword'} | Remove-Variable -Force } <# .SYNOPSIS Generates a random password. .PARAMETER Length The password length. .PARAMETER NumberOfNonAlphaNumericCharacters The number of non-alphanumeric characters to include in the password. .PARAMETER AsSecureString Return the password in the form of a secure string instead of clear text. .EXAMPLE PS C:\\> New-RandomPassword .EXAMPLE PS C:\\> New-RandomPassword -AsSecureString .INPUTS None. .OUTPUTS System.String, System.Security.SecureString .NOTES Revision History 2011-08-26: Andy Arismendi - Created. .LINK http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx #> } New-RandomPassword -Length 14
PowerShellCorpus/PoshCode/PowerWatin 0.1.ps1
PowerWatin 0.1.ps1
## CHANGE this to point to your WatiN.Core.dll $WatinPath = Convert-Path (Resolve-Path "$(Split-Path $Profile)\\Libraries\\Watin2\\WatiN.Core.dll") ## Load the assembly $global:watin = [Reflection.Assembly]::LoadFrom( $WatinPath ) ## initialize the global "Find" functions ... Function Start-Watin { Param([WatiN.Core.IE]$ie) if(!(Get-Command Find-Link -EA0)) { ## Generate Find-Button, Find-TextField, etc: $ie | Get-Member -Type Method | Where-Object { $type = $_.Definition.Split(" ")[0] [WatiN.Core.Element].IsAssignableFrom( ([type]$type) ) } | ForEach-Object { New-Item -Path "Function:global:Find-$($_.Name)" -Value $( iex @" { Param(`$Attribute, [regex]`$value) `$ie.$($_.Name)( ([Watin.Core.Find]::By( `$Attribute, `$value)) ) } "@ ) } } } Function New-Watin { PARAM($URL = "http://www.google.com") ## Create an initial window (I'm creating IE, but WatiN handles Firefox too) $global:ie = new-object WatiN.Core.IE $URL Start-Watin $ie } Function Get-Watin { PARAM($URL = "http://www.google.com") ## Find an existing window (I'm using IE, but WatiN handles Firefox too) $global:ie = [WatiN.Core.IE]::InternetExplorers()[0] Start-Watin $ie Set-WatinUrl $url } function Set-WatinUrl { Param($url) $IE.Goto( $url ) }
PowerShellCorpus/PoshCode/play-note(s).ps1
play-note(s).ps1
function Play-Notes { $defaultduration = 5;if($args[0] -is [int]) {$defaultduration = $args[0]} for($i = 0;$i -lt $args.length;$i++) { $duration = $defaultduration if ($i -lt $args.length-1) { if ($args[$i+1] -is [int]) {$duration = $args[$i+1] } } if ($args[$i] -is [string]) { play-note $args[$i] $duration } } } function Play-Note([string]$note,[int] $duration = 5) { if (!($note -match '(\\d+)')) { $note+='4' };[void]($note -match '([A-G#]{1,2})(\\d+)') [console]::Beep((440 * [math]::Pow([math]::pow(2,(1/12)), (([int] $matches[2]) - 4)* 12 + $( switch($matches[1]) { 'A' { 0 } 'A#' { 1 } 'Bb' { 1 } 'B' { 2 } 'C' { 3 } 'C#' { 4 } 'Db' { 4 } 'D' { 5 } 'D#' { 6 } 'Eb' { 6 } 'E' { 7 } 'F' { 8 } 'F#' { 9 } 'Gb' { 9 } 'G' { 10 } 'G#' { 11 } 'Ab' { 11 } }))),$duration * 100 ) } PLAY-note "C#3" play-notes A B C 20 E 10 B 10 play-notes F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4 F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4 play-notes 2 F5 E5 D5 C5 B5 A5 G 4 F5 E5 D5 C5 B5 A5 G 4 play-notes 4 F5 E5 D5 C5 B5 A5 G F5 E5 D5 C5 B5 A5 G play-notes Db5 Db Eb Gb Ab "C#" 6
PowerShellCorpus/PoshCode/remote helpdesk script.ps1
remote helpdesk script.ps1
Add-PSSnapin quest.activeroles.admanagement $cred = Get-Credential $conn = connect-QADService -service 'x.x.x.x' -credential $cred #region Script Settings #<ScriptSettings xmlns="http://tempuri.org/ScriptSettings.xsd"> # <ScriptPackager> # <process>powershell.exe</process> # <arguments /> # <extractdir>%TEMP%</extractdir> # <files /> # <usedefaulticon>true</usedefaulticon> # <showinsystray>false</showinsystray> # <altcreds>false</altcreds> # <efs>true</efs> # <ntfs>true</ntfs> # <local>false</local> # <abortonfail>true</abortonfail> # <product /> # <version>1.0.0.1</version> # <versionstring /> # <comments /> # <includeinterpreter>false</includeinterpreter> # <forcecomregistration>false</forcecomregistration> # <consolemode>false</consolemode> # <EnableChangelog>false</EnableChangelog> # <AutoBackup>false</AutoBackup> # <snapinforce>false</snapinforce> # <snapinshowprogress>false</snapinshowprogress> # <snapinautoadd>0</snapinautoadd> # <snapinpermanentpath /> # </ScriptPackager> #</ScriptSettings> #endregion #region ScriptForm Designer (Created with Admin Script Editor trial edition) #region Constructor [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") #endregion #region Post-Constructor Custom Code #endregion #region Form Creation #Warning: It is recommended that changes inside this region be handled using the ScriptForm Designer. #When working with the ScriptForm designer this region and any changes within may be overwritten. #~~< Form1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Form1 = New-Object System.Windows.Forms.Form $Form1.ClientSize = New-Object System.Drawing.Size(336, 490) $Form1.Text = "AD Utility - Test Environment" #~~< Label4 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Label4 = New-Object System.Windows.Forms.Label $Label4.Location = New-Object System.Drawing.Point(12, 449) $Label4.Size = New-Object System.Drawing.Size(106, 21) $Label4.TabIndex = 17 $Label4.Text = "Changed Password" #~~< Label3 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Label3 = New-Object System.Windows.Forms.Label $Label3.Location = New-Object System.Drawing.Point(11, 287) $Label3.Size = New-Object System.Drawing.Size(171, 20) $Label3.TabIndex = 16 $Label3.Text = "Username to Change:" $Label3.add_Click({Label3Click($Label3)}) #~~< Label2 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Label2 = New-Object System.Windows.Forms.Label $Label2.Location = New-Object System.Drawing.Point(173, 16) $Label2.Size = New-Object System.Drawing.Size(82, 20) $Label2.TabIndex = 15 $Label2.Text = "Select Domain " $Label2.add_Click({Label2Click($Label2)}) #~~< RichTextBox2 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $RichTextBox2 = New-Object System.Windows.Forms.RichTextBox $RichTextBox2.Location = New-Object System.Drawing.Point(12, 422) $RichTextBox2.Size = New-Object System.Drawing.Size(144, 24) $RichTextBox2.TabIndex = 14 $RichTextBox2.Text = "" #~~< TextBox3 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TextBox3 = New-Object System.Windows.Forms.TextBox $TextBox3.Location = New-Object System.Drawing.Point(11, 310) $TextBox3.Size = New-Object System.Drawing.Size(144, 20) $TextBox3.TabIndex = 13 $TextBox3.Text = "" #~~< ComboBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ComboBox1 = New-Object System.Windows.Forms.ComboBox $ComboBox1.FormattingEnabled = $true $ComboBox1.Location = New-Object System.Drawing.Point(12, 12) $ComboBox1.Size = New-Object System.Drawing.Size(158, 21) $ComboBox1.TabIndex = 12 $ComboBox1.Text = "" $ComboBox1.Items.AddRange([System.Object[]](@("10.153.95.3", "10.153.110.131"))) #~~< Button4 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Button4 = New-Object System.Windows.Forms.Button $Button4.Location = New-Object System.Drawing.Point(212, 345) $Button4.Size = New-Object System.Drawing.Size(78, 22) $Button4.TabIndex = 10 $Button4.Text = "Enable User" $Button4.UseVisualStyleBackColor = $true $Button4.add_Click({Button4Click($Button4)}) #~~< Button3 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Button3 = New-Object System.Windows.Forms.Button $Button3.Location = New-Object System.Drawing.Point(124, 345) $Button3.Size = New-Object System.Drawing.Size(82, 22) $Button3.TabIndex = 9 $Button3.Text = "Unlock User" $Button3.UseVisualStyleBackColor = $true $Button3.add_Click({Button3Click($Button3)}) #~~< Button2 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Button2 = New-Object System.Windows.Forms.Button $Button2.Location = New-Object System.Drawing.Point(12, 345) $Button2.Size = New-Object System.Drawing.Size(106, 24) $Button2.TabIndex = 8 $Button2.Text = "Reset Password" $Button2.UseVisualStyleBackColor = $true $Button2.add_Click({Button2Click($Button2)}) #~~< Label1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Label1 = New-Object System.Windows.Forms.Label $Label1.Location = New-Object System.Drawing.Point(212, 463) $Label1.Size = New-Object System.Drawing.Size(117, 18) $Label1.TabIndex = 7 $Label1.Text = "For Use by: VaforVets" $Label1.add_Click({Label1Click($Label1)}) #~~< Button1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Button1 = New-Object System.Windows.Forms.Button $Button1.Location = New-Object System.Drawing.Point(249, 73) $Button1.Size = New-Object System.Drawing.Size(67, 20) $Button1.TabIndex = 1 $Button1.Text = "Search" $Button1.UseVisualStyleBackColor = $true $Button1.add_Click({ButtonClick($Button1)}) #~~< RadioButton3 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $RadioButton3 = New-Object System.Windows.Forms.RadioButton $RadioButton3.Location = New-Object System.Drawing.Point(152, 48) $RadioButton3.Size = New-Object System.Drawing.Size(82, 24) $RadioButton3.TabIndex = 5 $RadioButton3.TabStop = $true $RadioButton3.Text = "User Name" $RadioButton3.UseVisualStyleBackColor = $true #~~< RadioButton2 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $RadioButton2 = New-Object System.Windows.Forms.RadioButton $RadioButton2.Location = New-Object System.Drawing.Point(72, 48) $RadioButton2.Size = New-Object System.Drawing.Size(104, 24) $RadioButton2.TabIndex = 4 $RadioButton2.TabStop = $true $RadioButton2.Text = "Last Name" $RadioButton2.UseVisualStyleBackColor = $true $RadioButton2.add_CheckedChanged({RadioButton2CheckedChanged($RadioButton2)}) #~~< RadioButton1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $RadioButton1 = New-Object System.Windows.Forms.RadioButton $RadioButton1.Location = New-Object System.Drawing.Point(16, 48) $RadioButton1.Size = New-Object System.Drawing.Size(104, 24) $RadioButton1.TabIndex = 3 $RadioButton1.TabStop = $true $RadioButton1.Text = "Email" $RadioButton1.UseVisualStyleBackColor = $true $RadioButton1.add_CheckedChanged({RadioButton1CheckedChanged($RadioButton1)}) #~~< RichTextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $RichTextBox1 = New-Object System.Windows.Forms.RichTextBox $RichTextBox1.Location = New-Object System.Drawing.Point(11, 99) $RichTextBox1.Size = New-Object System.Drawing.Size(305, 175) $RichTextBox1.TabIndex = 2 $RichTextBox1.Text = "" #~~< TextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TextBox1 = New-Object System.Windows.Forms.TextBox $TextBox1.Location = New-Object System.Drawing.Point(12, 73) $TextBox1.Size = New-Object System.Drawing.Size(219, 20) $TextBox1.TabIndex = 0 $TextBox1.Text = "" $Form1.Controls.Add($Label4) $Form1.Controls.Add($Label3) $Form1.Controls.Add($Label2) $Form1.Controls.Add($RichTextBox2) $Form1.Controls.Add($TextBox3) $Form1.Controls.Add($ComboBox1) $Form1.Controls.Add($Button4) $Form1.Controls.Add($Button3) $Form1.Controls.Add($Button2) $Form1.Controls.Add($Label1) $Form1.Controls.Add($Button1) $Form1.Controls.Add($RadioButton3) $Form1.Controls.Add($RadioButton2) $Form1.Controls.Add($RadioButton1) $Form1.Controls.Add($RichTextBox1) $Form1.Controls.Add($TextBox1) #endregion #region Custom Code #endregion #region Event Loop function Main{ [System.Windows.Forms.Application]::EnableVisualStyles() [System.Windows.Forms.Application]::Run($Form1) } #endregion #endregion #region Event Handlers function ButtonClick( $object ){ $domain = $combobox1.Text $samaccountname = $textbox1.text function Get-UTCAge { #get date time of the last password change Param([int64] $Last = 0) if ($Last -eq 0) { write 0 } else { #clock starts counting from 1/1/1601. [datetime]$utc = "1/1/1601" #calculate the number of days based on the int64 number $i = $Last / 864000000000 #Add the number of days to 1/1/1601 #and write the result to the pipeline write($utc.AddDays($i)) } } # end Get-UTCAge function function Get-PwdAge { Param([int64] $LastSet = 0) if ($LastSet-eq 0) { write "0" } else { #get the date the password was last changed [datetime]$ChangeDate = Get-UTCAge $LastSet #get the current date and time [datetime]$RightNow = Get-Date #write the difference in days write $RightNow.Subtract($ChangeDate).Days } } #end Get-PwdAge function #main code #define some constants #New-Variable ADS_UF_ACCOUNTDISABLE 0 x0002 -Option Constant #New-Variable ADS_UF_PASSWD_CANT_CHANGE 0 x0040 -Option Constant #New-Variable ADS_UF_DONT_EXPIRE_PASSWD 0 x10000 -Option Constant #New-Variable ADS_UF_PASSWD_EXPIRED 0 x800000 -Option Constant #define our searcher object $searchroot = ([ADSI] "LDAP://$domain") $Searcher = New-Object DirectoryServices.DirectorySearcher($SearchRoot) # find the user if ($radiobutton1.checked) {$filter = "(&(objectCategory=person)(objectClass=user)(mail=$samaccountname))"} if ($radiobutton2.checked) {$filter = "(&(objectCategory=person)(objectClass=user)(sn=$samaccountname))"} if ($radiobutton3.checked) {$filter = "(&(objectCategory=person)(objectClass=user)(samaccountname=$samaccountname))"} $searcher.filter = $filter #get the user information $user = $searcher.findOne() if (-not $user.path ) { $RichTextBox1.Text = "Could not find $samaccountname" return } $user | foreach-Object { #get password properties from useraccountcontrol field if ($_.properties.item("useraccountcontrol")[0] -band $ADS_UF_DONT_EXPIRE_PASSWD) { $pwdNeverExpires = $True } else { $pwdNeverExpires = $False } #Password expired should be calculated from a computed UAC value $user = $_.GetDirectoryEntry() $user.psbase.refreshcache("msDS-User-Account-Control-Computed") [int]$computed = $user.psbase.properties.item("msDS-User-Account-Control-Computed").value if ($computed -band $ADS_UF_PASSWD_EXPIRED) { $pwdExpired = $True } else { $pwdExpired = $False } #account disabled if ($_.properties.item("useraccountcontrol")[0] -band $ADS_UF_ACCOUNTDISABLE) { $disabled = $True } else { $disabled = $False } #account lockedout if ($_.properties.item("lockoutTime")[0]) { $lockedout = $True } else { $lockedout = $False } #check if user can change their password if ($_.properties.item("useraccountcontrol")[0] -band $ADS_UF_PASSWD_CANT_CHANGE) { $pwdChangeAllowed = $False } else { $pwdChangeAllowed = $True } # Collect Property Values and write to results box $value = "Name: $($_.properties.item("name")[0]) Description:$($_.properties.item("description")[0]) Email:$($_.properties.item("mail")[0]) AccountCreated:$($_.properties.item("whencreated")[0]) AccountModified:$($_.properties.item("WhenChanged")[0]) LastLogon:$(Get-UTCAge $_.properties.item("lastlogon")[0]) PasswordNeverExpires:$pwdNeverExpires PasswordChangeAllowed:$pwdChangeAllowed Lockout:$lockedout Disabled:$disabled UserName:$($_.properties.item("samaccountname")[0]) "} $RichTextBox1.Text = $value } function Button2Click( $object ){ $username = $textbox3.text function CreatePassword([int]$length) { $specialCharacters = "$@#!" $lowerCase = "abcdefghijklmnopqrstuvwxyz" $upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" $numbers = "1234567890" $res = "" $rnd = New-Object System.Random do { $flag = $rnd.Next(4); if ($flag -eq 0) { $res += $specialCharacters[$rnd.Next($specialCharacters.Length)]; } elseif ($flag -eq 1) { $res += $lowerCase[$rnd.Next($lowerCase.Length)]; } elseif ($flag -eq 2) { $res += $upperCase[$rnd.Next($upperCase.Length)]; } else { $res += $numbers[$rnd.Next($numbers.Length)]; } } while ( 0 -lt $length--) return $res } $Pwd = CreatePassword 8 $RichTextBox2.Text = "$pwd" GET-QADUSER $username | Set-QADUser -userPassword "$pwd" } #Set-QADUser -Identity $samaccountname -UserPassword "$pwd" function Label1Click( $object ){ $RichTextBox1.Text = get-qaduser -SamAccountName $TextBox1.Text } function RadioButton2CheckedChanged( $object ){ } function RadioButton1CheckedChanged( $object ){ } function Button4Click( $object ){ $username = $textbox3.text GET-QADUSER $username | enable-QADUser } function Button3Click( $object ){ $username = $textbox3.text GET-QADUSER $username | UNLOCK-QADUSER } function Label3Click( $object ){ } function Label2Click( $object ){ } Main # This call must remain below all other event functions #endregion
PowerShellCorpus/PoshCode/List AD Users CSV_1.ps1
List AD Users CSV_1.ps1
$NumDays = 0 $LogDir = ".\\User-Accounts.csv" $currentDate = [System.DateTime]::Now $currentDateUtc = $currentDate.ToUniversalTime() $lltstamplimit = $currentDateUtc.AddDays(- $NumDays) $lltIntLimit = $lltstampLimit.ToFileTime() $adobjroot = [adsi]'' $objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot) $objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))" $users = $objstalesearcher.findall() | select ` @{e={$_.properties.cn};n='Display Name'},` @{e={$_.properties.samaccountname};n='Username'},` @{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},` @{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'} $users | Export-CSV -NoType $LogDir
PowerShellCorpus/PoshCode/Out-DataTable_7.ps1
Out-DataTable_7.ps1
####################### function Get-Type { param($type) $types = @( 'System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal', 'System.Double', 'System.Guid', 'System.Int16', 'System.Int32', 'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32', 'System.UInt64') if ( $types -contains $type ) { Write-Output "$type" } else { Write-Output 'System.String' } } #Get-Type ####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-psdrive| Out-DataTable This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties v1.4 - Chad Miller - Corrected issue with DBNull v1.5 - Chad Miller - Updated example v1.6 - Chad Miller - Added column datatype logic with default to string v1.7 - Chad Miller - Fixed issue with IsArray .LINK http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx #> function Out-DataTable { [CmdletBinding()] param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) Begin { $dt = new-object Data.datatable $First = $true } Process { foreach ($object in $InputObject) { $DR = $DT.NewRow() foreach($property in $object.PsObject.get_properties()) { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $property.Name.ToString() if ($property.value) { if ($property.value -isnot [System.DBNull]) { $Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)") } } $DT.Columns.Add($Col) } if ($property.Gettype().IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/Resolve-Aliases.ps1
Resolve-Aliases.ps1
#requires -version 2.0 ## Resolve-Aliases Module ######################################################################################################################## ## Sample Use: ## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1 ## ls *.ps1 | Resolve-Aliases -Inplace ######################################################################################################################## ## Version History ## 1.0 - First Version. "It worked on my sample script" ## 1.1 - Now it parses the $(...) blocks inside strings ## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts) ## 1.3 - I went back to processing the whole script at once (instead of a line at a time) ## Processing a line at a time makes it impossible to handle Here-Strings... ## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it ## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is ## 1.4 - Now resolves parameters too ## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem) ## - Refactored the Resolve-Line filter right out of existence ## - Created a test script for validation, and ######################################################################################################################## function which { PARAM( [string]$command ) # aliases, functions, cmdlets, scripts, executables, normal files $cmds = @(Get-Command $command -EA "SilentlyContinue") if($cmds.Count -gt 1) { $cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0] } else { $cmd = $cmds[0] } if(!$cmd) { $cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0] } if( $cmd.CommandType -eq "Alias" ) { $cmd = which $cmd.Definition } return $cmd } Cmdlet Resolve-Aliases -ConfirmImpact low -DefaultParameterSet Files -snapin Huddled.Tests { Param ( #[ParameterSetName ("Text")] [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")] [string[]]$Line , #[ParameterSetName ("Files")] [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")] #[Alias("FullName","PSChildName","PSPath")] [IO.FileSystemInfo]$File , #[ParameterSetName ("Files")] [Parameter(Position=1, ParameterSetName="Files")] [Switch]$InPlace ) BEGIN { Write-Debug $PSCmdlet.ParameterSetName } PROCESS { if($PSCmdlet.ParameterSetName -eq "Files") { if($File -is [System.IO.FileInfo]){ $Line = ((Get-Content $File) -join "`n") } else { throw "We can't resolve a whole folder at once yet" } } $Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null) for($t = $Tokens.Count; $t -ge 0; $t--) { $token = $Tokens[$t] # DEBUG $token | fl * | out-host switch($token.Type) { "Command" { $cmd = which $token.Content Write-Debug "Command $($token.Content) => $($cmd.Name)" #if($cmd.CommandType -eq "Alias") { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name ) #} } "CommandParameter" { Write-Debug "Parameter $($token.Content)" for($c = $t; $c -ge 0; $c--) { if( $Tokens[$c].Type -eq "Command" ) { $cmd = which $Tokens[$c].Content # if($cmd.CommandType -eq "Alias") { # $cmd = @(which $cmd.Definition)[0] # } Write-Debug "Parameter $($token.Content -replace "^-?","^")" $param = @(($cmd.ParameterSets | % { $_.Parameters | % { $_.Name } } | Sort -Unique) -match ($token.Content -replace "^-?","^")) if($param.Count -eq 1) { $Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" ) } break } } } } } switch($PSCmdlet.ParameterSetName) { "Text" { $Line } "Files" { switch($File.GetType()) { "System.IO.FileInfo" { if($InPlace) { $Line | Set-Content $File } else { $Line } } default { throw "We can't resolve a whole folder at once yet" } } } default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" } } } } # SIG # Begin signature block # MIIK0AYJKoZIhvcNAQcCoIIKwTCCCr0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU6I1SxD5ha/Iq/SiEgWIGlzyK # LtGgggbEMIIGwDCCBKigAwIBAgIJAKpDRVMtv0LqMA0GCSqGSIb3DQEBBQUAMIHG # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEaMBgGA1UEChMRSHVkZGxlZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRp # ZmljYXRlIEF1dGhvcml0eTErMCkGA1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmlj # YXRlIEF1dGhvcml0eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNz # ZXMub3JnMB4XDTA4MDcwMjAzNTA1OVoXDTA5MDcwMjAzNTA1OVowgcAxCzAJBgNV # BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazESMBAGA1UEBxMJUm9jaGVzdGVyMRow # GAYDVQQKExFIdWRkbGVkTWFzc2VzLm9yZzEuMCwGA1UECxMlaHR0cDovL0h1ZGRs # ZWRNYXNzZXMub3JnL0NvZGVDZXJ0LmNydDEVMBMGA1UEAxMMSm9lbCBCZW5uZXR0 # MScwJQYJKoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwggIiMA0G # CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXuceXJZYARJbSTU4hoh91goVp2POx # 6Mz/QZ6D5jcT/JNhdW2GwYQ9YUxNj8jkhXg2Ixbgb1djRGMFC/ekgRkgLxyiuhRh # NrVE1IdV4hT4as3idqnvWOi0S3z2R2EGdebqwm2mrRmq9+DbY+FGxuNwLboWZx8Z # roGlLLHRPzt9pabQq/Nu/FIFO+4JzZ8S5ZnEaKTm4dpD0g6j653OWYVvNXJbS/W4 # Dis5aRkHT1q1Gp02dYHh3NTKrpv1nus9BTDlJRwmU/FgGLNQIvnRwqVoBh+I7tVq # NIRnI1RpDTGyFEohbH8mRlwq3z4ijtb6j9boUJEqd8hQshzUMcALoTIR1tN/5APX # u2j4OqGFESM/OG0i2hLKbnP81u581aZT1BfVfQxvDuWrFiurMxllVGY1NvKkXwc8 # aOZktqMQWbWAs2bxZqERbOILXOmkL/mvPdy+e5yQveriHAhrDONu7a79ylreMHBR # XrmYJTK2G/aHvB5vrXjMPw0TBeph0sM2BN2eVzenAAMsIiGlXPXvtKrpKRiBdx5f # 9SV5dyUG2tR8ANDuc2AMB8FKICuMUd8Sx96p4FOBQhXhvF/RZcWZIW5o+A4sHvYE # /s4oiX7LxGrQK2abNiCVs9BDLI/EcSs/TP+ZskBqu7Qb+AVeevoY3T7skihuyC/l # h7EwqjfNpVQ9UwIDAQABo4G0MIGxMB0GA1UdDgQWBBTgB9XYJV/kJAvnkWmKDHsh # 7Cn3PzAfBgNVHSMEGDAWgBQ+5x4ah0JG0o4iUj0TebNd4MCVxTAJBgNVHRMEAjAA # MBEGCWCGSAGG+EIBAQQEAwIEEDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzALBgNV # HQ8EBAMCBsAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRp # ZmljYXRlMA0GCSqGSIb3DQEBBQUAA4ICAQAw8B6+s48CZZo5h5tUeKV7OWNXKRG7 # xkyavMkXpEi58BSLutmE3O7smc3uvu3TdCXENNUlGrcq/KQ8y2eEI8QkHgT99VgX # r+v5xu2KnJXiOOIxi65EZybRFFFaGJNodTcrK8L/tY6QLF02ilOlEgfcc1sV/Sj/ # r60JS1iXIMth7nYZVjtWeYXOrsd+I+XwJuoVNJlELNdApOU4ZVNrPEuV+QRNMimj # lqIOv2tn9TDdNGUqaOCI0w+a1XQvapEPWETfQK+o9pvYINTswGDjNeb7Xz8ar2JB # 9IVs2xtxDohHB75kyRrlY1hkoY5j12ZhWOlm0L9Ks6XvmMtXJIjj0/m9Z+3s+9p6 # U7IYjz5NnzmDvtNUn2y9zxB/rUx/JqoUO3BWRKiLX0lvGRWJlzFr9978kH2SXxAD # rsKfzB7YZzMh9hZkGNlJf4T+HTB/OXG1jyfkyqQvhNB/tDAaq+ejDtKNBF4hMS7K # Z0B4vagIxFwMuTiei4UaOjrGzeCfT9w1Bmj6uLJme5ydQVM0V7z3Z6jR3LVq4c4s # Y1dfPmYlw62cbyV9Kb/H2hYw5K0OMX60LfLQZOzIPzAeRJ87NufwZnC1afxsSCmU # bvSx4kCMgRZMXw+d1SHRhh7z+06YTQjnUMmtTGt7DtUkU6I8LKEWF/mAzF7sq/7P # AyhPsbu91X5FuzGCA3YwggNyAgEBMIHUMIHGMQswCQYDVQQGEwJVUzERMA8GA1UE # CBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hlc3RlcjEaMBgGA1UEChMRSHVkZGxl # ZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTErMCkG # A1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmljYXRlIEF1dGhvcml0eTEnMCUGCSqG # SIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAqkNFUy2/QuowCQYF # Kw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkD # MQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJ # KoZIhvcNAQkEMRYEFOvLNU6+8DDX82nGYrbW6PQveyjfMA0GCSqGSIb3DQEBAQUA # BIICANMEMm6b38+4XO2OvegDHbZF99B0McYH1yL6AgIgcyOPoSEVzlrsBjgCPIRg # VW5yhhaNO7iEFKnPVwQzk9fxh/59obuzUqNL3Pz+I1YOjRBgNXomABwUKJJu+44Y # qcqxM/4uRWzi2oCidPKEw2wJxK/q+AxkudE6/mcX98qz/P4VMv18/kh3fBhCa+pP # jQsFcxNa2aOCsFYDtkjx0cT51ZKFG9+yeMeamyl1evCvhdwXpqeEKYRj6ZC99zfI # vBtj8gG8adv4WOHvUwo2s/G6RL1zPWNlblm5ZhsiBw98KG7/0KeaVFc3BUZyrOJZ # Wt8QUF/YBUsGpvbvBYfeh2wPne+dyo+TkiCPe45SN50SqVqGqKiKL4bB4vrpv1Qy # n390diw7Z0n71HBFfKulbcu14KjHWS7NRCi7HuIXBmbRWCuX+BFrMAgyj0NWbFbe # NgSaVB9RO8mu1QdgujTxH5CvTEvg64w4glPwCb6/oBKoKsiEXamAPkvpcZ1coW0q # Jn5hbgJMx4i3AkTuDKEl1X7CWlXb3todJ+OgQc2Ss0EPemfm9sRqFaMMctziiGWO # sQy3wWRF8Dz4kVtr27VM/6F7JPPL7a/8aREmTqmvvLhWpjJ6/4bgZ7ihhadzWjoI # g7pJadoPkDDCdH4o5m9sQIOwZf/tlY/BYY6EXVXCxhKnsCFl # SIG # End signature block
PowerShellCorpus/PoshCode/ConvertTo-Hex_8.ps1
ConvertTo-Hex_8.ps1
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx param ( [string]$SidString ) # Create SID .NET object using SID string provided $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring # Create a byte array of the proper length $sidBytes = New-Object byte[] $sid.BinaryLength #Convert to bytes $sid.GetBinaryForm( $sidBytes, 0 ) # Iterate through bytes, converting each to the hexidecimal equivalent $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } # Join the hex array into a single string for output $hexArr -join ''
PowerShellCorpus/PoshCode/Add new smtp_set prmary_3.ps1
Add new smtp_set prmary_3.ps1
#alias,addnewemailaddress import-csv .\\source.csv | foreach { $user = Get-Mailbox $_.alias $user.emailAddresses+= $_.addnewemailaddress $user.primarysmtpaddress = $_.addnewemailaddress Set-Mailbox $user -emailAddresses $user.emailAddresses set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress }
PowerShellCorpus/PoshCode/Generate New Password.ps1
Generate New Password.ps1
function global:GET-NewPassword($PasswordLength, $Complexity) { <# .SYNOPSIS Generates a New password with varying length and Complexity, .DESCRIPTION Generate a New Password for a User. Defaults to 8 Characters with Moderate Complexity. Usage GET-NEWPASSWORD or GET-NEWPASSWORD $Length $Complexity Where $Length is an integer from 1 to as high as you want and $Complexity is an Integer from 1 to 4 .EXAMPLE Create New Password GET-NEWPASSWORD .EXAMPLE Generate a Password of strictly Uppercase letters that is 9 letters long GET-NEWPASSWORD 9 1 .EXAMPLE Generate a Highly Complex password 5 letters long GET-NEWPASSWORD 5 .EXAMPLE Create a new 8 Character Password of Uppercase/Lowercase and store as a Secure.String in Variable called $MYPASSWORD $MYPASSWORD=CONVERTTO-SECURESTRING (GET-NEWPASSWORD 8 2) -asplaintext -force .NOTES The Complexity falls into the following setup for the Complexity level 1 - Pure lowercase Ascii 2 - Mix Uppercase and Lowercase Ascii 3 - Ascii Upper/Lower with Numbers 4 - Ascii Upper/Lower with Numbers and Punctuation #> # Delare an array holding what I need. Here is the format # The first number is a the number of characters (Ie 26 for the alphabet) # The Second Number is WHERE it resides in the Ascii Character set # So 26,97 will pick a random number representing a letter in Asciii # and add it to 97 to produce the ASCII Character # [int32[]]$ArrayofAscii=26,97,26,65,10,48,15,33 # Complexity can be from 1 - 4 with the results being # 1 - Pure lowercase Ascii # 2 - Mix Uppercase and Lowercase Ascii # 3 - Ascii Upper/Lower with Numbers # 4 - Ascii Upper/Lower with Numbers and Punctuation If ($Complexity -eq $NULL) { $Complexity=3 } # Password Length can be from 1 to as Crazy as you want # If ($PasswordLength -eq $NULL) {$PasswordLength=10} # Nullify the Variable holding the password $NewPassword=$NULL # Here is our loop Foreach ($counter in 1..$PasswordLength) { # What we do here is pick a random pair (4 possible) # in the array to generate out random letters / numbers $pickSet=(GET-Random $complexity)*2 # Pick an Ascii Character and add it to the Password # Here is the original line I was testing with # [char] (GET-RANDOM 26) +97 Which generates # Random Lowercase ASCII Characters # [char] (GET-RANDOM 26) +65 Which generates # Random Uppercase ASCII Characters # [char] (GET-RANDOM 10) +48 Which generates # Random Numeric ASCII Characters # [char] (GET-RANDOM 15) +33 Which generates # Random Punctuation ASCII Characters $NewPassword=$NewPassword+[char]((get-random $ArrayOfAscii[$pickset])+$ArrayOfAscii[$pickset+1]) } # When we're done we Return the $NewPassword # BACK to the calling Party Return $NewPassword }
PowerShellCorpus/PoshCode/Prompt Replacement.ps1
Prompt Replacement.ps1
function prompt { $mapped_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=4" | foreach {echo $_.deviceid} $local_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" | foreach {echo $_.deviceid} $removable_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=2" | foreach {echo $_.deviceid} $t = $(get-date -format "HH:mm:ss") $a = (get-location).path $d = (get-location).path.substring(0,$a.indexof(":")+1) $a = $a.substring($a.LastIndexOf("`\\")+1) if ((get-location).path.substring(0,(get-location).path.indexof(":")) -eq "Microsoft.PowerShell.Core\\FileSystem") { $a = (get-location).path $a = $a.substring($a.indexof(":")+2) write-host -fore white -back blue "$t - $a ";"`$`> "} else { if ($a -eq "") {$a = "`\\"} if ($d.length -gt 2) { write-host -ForegroundColor black -backgroundcolor red "[$t] - [$d] $a ";"`$`> "} elseif ($local_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor green "[$t] - [$d] $a ";"`$`> "} elseif ($removable_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor yellow "[$t] - [$d] $a ";"`$`> "} elseif ($mapped_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor magenta "[$t] - [$d] $a ";"`$`> "} } }
PowerShellCorpus/PoshCode/Test-FileLock_1.ps1
Test-FileLock_1.ps1
##################################################################### # Test-FileLock.ps1 # Version 1.0 # # test if file is locked by external program or not # # Vadims Podans (c) 2009 # http://www.sysadmins.lv/ ##################################################################### filter Test-FileLock { if ($args[0]) {$filepath = gi $(Resolve-Path $args[0]) -Force} else {$filepath = gi $_.fullname -Force} if ($filepath.psiscontainer) {return} $locked = $false trap { Set-Variable -name locked -value $true -scope 1 continue } $inputStream = New-Object system.IO.StreamReader $filepath if ($inputStream) {$inputStream.Close()} @{$filepath = $locked} }
PowerShellCorpus/PoshCode/Read Gmail POP .ps1
Read Gmail POP .ps1
<# .AUTHOR Will Steele (wlsteele@gmail.com) .DEPENDENCIES Powershell v2 (for Out-Gridview cmdlet) .DESCRIPTION This script is a proof of concept. Further work needs to be done. It requires the user to enter a valid username and password for a gmail.com account. It then attempts to form an SSL connection with the server, and, retrieve the first email. Unfortunately it returns random results. Perhaps someone can improve upon it. .EXAMPLE Get-Gmail -username 'you@gmail.com' -password '\\/0u|>p@55w0rd' .EXTERNALHELP None. .FORWARDHELPTARGETNAME None. .INPUTS System.Object .LINK http://learningpcs.blogspot.com/2012/01/powershell-v2-read-gmail-more-proof-of.html. .NAME Get-Gmail.ps1 .NOTES The script is further explored to find 'From' addressses in the link above. I have piped the $str variable to Out-Gridview. This can be changed to something more suitable for real processing. .OUTPUTS System.String .PARAMETER username A required parameter for a valid gmail email user. Use the whole string. .PARAMETER password A required parameter for the account password. .SYNOPSIS Read . #> [CmdletBinding()] param( [Parameter( Mandatory = $true, Position = 0, ValueFromPipeline = $true )] [ValidateNotNullOrEmpty()] [String] $username, [Parameter( Mandatory = $true, Position = 1, ValueFromPipeline = $true )] [ValidateNotNullOrEmpty()] [String] $password ) Clear-Host try { Write-Output "Creating new TcpClient." $tcpClient = New-Object -TypeName System.Net.Sockets.TcpClient # Connect to gmail $tcpClient.Connect("pop.gmail.com", 995) if($tcpClient.Connected) { Write-Output "You are connected to the host. Attempting to get SSL stream." # Create new SSL Stream for tcpClient Write-Output "Getting SSL stream." [System.Net.Security.SslStream] $sslStream = $tcpClient.GetStream() # Authenticating as client Write-Output "Authenticating as client." $sslStream.AuthenticateAsClient("pop.gmail.com"); if($sslStream.IsAuthenticated) { Write-Output "You have authenticated. Attempting to login." # Asssigned the writer to stream [System.IO.StreamWriter] $sw = $sslstream # Assigned reader to stream [System.IO.StreamReader] $reader = $sslstream # refer POP rfc command, there very few around 6-9 command $sw.WriteLine("USER $username") # sent to server $sw.Flush() # send pass $sw.WriteLine("PASS $password"); $sw.Flush() # this will retrive your first email $sw.WriteLine("RETR 1") $sw.Flush() $sw.WriteLine("Quit "); $sw.Flush(); [String] $str = [String]::Empty [String] $strTemp = [String]::Empty while (($strTemp = $reader.ReadLine()) -ne $null) { # find the . character in line if($strTemp -eq '.') { break; } if ($strTemp.IndexOf('-ERR') -ne -1) { break; } $str += $strTemp; } # Return raw data Write-Output "`nOutput email" $str | Out-GridView } else { Write-Error "You were not authenticated. Quitting." } } else { Write-Error "You are not connected to the host. Quitting" } } catch { $_ } finally { Write-Output "Script complete." }
PowerShellCorpus/PoshCode/Check Service.ps1
Check Service.ps1
#################################################################################### #PoSH script to check if a server is up and if it is check for a service. #If the service isn't running, start it and send an email # JK - 7/2009 #################################################################################### $erroractionpreference = "SilentlyContinue" $i = "testserver" #Server Name $service = "spooler" #Service to monitor $ping = new-object System.Net.NetworkInformation.Ping $rslt = $ping.send($i) if ($rslt.status.tostring() –eq "Success") { $b = get-wmiobject win32_service -computername $i -Filter "Name = '$service'" If ($b.state -eq "stopped") { $b.startservice() $emailFrom = "services@yourdomain.com" $emailTo = "you@yourdomain.com" $subject = "$service Service has restarted on $i" $body = "The $service service on $i has crashed and been restarted" $smtpServer = "xx.yourdomain.com" $smtp = new-object Net.Mail.SmtpClient($smtpServer) $smtp.Send($emailFrom, $emailTo, $subject, $body) } else {exit} } else {exit}
PowerShellCorpus/PoshCode/Disable-SSLValidation_1.ps1
Disable-SSLValidation_1.ps1
function Disable-SSLValidation { <# .SYNOPSIS Disables SSL certificate validation .DESCRIPTION Disable-SSLValidation disables SSL certificate validation by using reflection to implement the System.Net.ICertificatePolicy class. Author: Matthew Graeber (@mattifestation) License: BSD 3-Clause .NOTES Reflection is ideal in situations when a script executes in an environment in which you cannot call csc.ese to compile source code. If compiling code is an option, then implementing System.Net.ICertificatePolicy in C# and Add-Type is trivial. .LINK http://www.exploit-monday.com #> Set-StrictMode -Version 2 # You have already run this function if ([System.Net.ServicePointManager]::CertificatePolicy.ToString() -eq 'IgnoreCerts') { Return } $Domain = [AppDomain]::CurrentDomain $DynAssembly = New-Object System.Reflection.AssemblyName('IgnoreCerts') $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('IgnoreCerts', $false) $TypeBuilder = $ModuleBuilder.DefineType('IgnoreCerts', 'AutoLayout, AnsiClass, Class, Public, BeforeFieldInit', [System.Object], [System.Net.ICertificatePolicy]) $TypeBuilder.DefineDefaultConstructor('PrivateScope, Public, HideBySig, SpecialName, RTSpecialName') | Out-Null $MethodInfo = [System.Net.ICertificatePolicy].GetMethod('CheckValidationResult') $MethodBuilder = $TypeBuilder.DefineMethod($MethodInfo.Name, 'PrivateScope, Public, Virtual, HideBySig, VtableLayoutMask', $MethodInfo.CallingConvention, $MethodInfo.ReturnType, ([Type[]] ($MethodInfo.GetParameters() | % {$_.ParameterType}))) $ILGen = $MethodBuilder.GetILGenerator() $ILGen.Emit([Reflection.Emit.Opcodes]::Ldc_I4_1) $ILGen.Emit([Reflection.Emit.Opcodes]::Ret) $TypeBuilder.CreateType() | Out-Null # Disable SSL certificate validation [System.Net.ServicePointManager]::CertificatePolicy = New-Object IgnoreCerts }
PowerShellCorpus/PoshCode/ASPX Mailbox (1 of 6).ps1
ASPX Mailbox (1 of 6).ps1
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mailboxTasks.aspx.cs" Inherits="mailboxTasks" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title> Domain Exchange Mailbox Tasks</title> </head> <body> <p> <b>This page is for all domain accounts.</b><br /> <br /> Enter the Logon ID of the user/mailbox that you want to modify.<br /><br /> If you are logged into your workstation with domain credentials, we will use those for security checks.<br /> If you are not logged in with domain credentials, you will see a prompt for them. </p> <form method="Post" action="MailboxConfirm.aspx" runat="server" id ="frmMailboxTasks"> <table> <tr> <td>User's Logon ID:</td> <td><input type="Text" name="txtTargName" /></td> </tr> <tr> <td><input type="radio" name="rdoMailboxAction" value="Create Mailbox" checked="checked" />Create Mailbox</td> <td><input type="radio" name="rdoMailboxAction" value="Delete Mailbox" />Delete Mailboxt</td> <td><input type="radio" name="rdoMailboxAction" value="Change Address" />Change Address</td> </tr> <tr> <td colspan="2"><asp:Button ID="btnNext" Text="Next" Runat="server"></asp:Button></td> </tr> </table> </form> <hr /> <p> <b>Information about Creating Mailboxes</b><br /> <b><span style='color:Red'>IMPORTANT:</span></b> You must create the user object before you can mailbox-enable it.<br /> The user object must have values for the agency and last name fields. If these are blank, you will not be able to create a mailbox for the user.<br /> The agency information should be your agencies three-letter acronym."<br /> You need to set this on the user object in Active Directory; find the user object, open the properties, then click on the Organization tab and put your agency acronym in the Company field.<br /> <br /> Also, please allow several minutes between creating a user object in Active Directory and trying to set up a mailbox. This will give the new user object time to replicate amongst all of the domain controllers.<br /> <br /> Exchange 2007 will automatically assign an internet email address for the user. Typically, this will be in the "standard" form: jdoe@domain.com for Jane Doe.<br /> However, if the "standard" email address is already in use, Exchange will set up a non-standard address such as jdoe2@domain.com.<br /> Please check the email address on the mailbox after it's created to see if it is in the correct format. If not, contact the Customer Support Center at x2000 and we will set the address to our fall-back standard: jadoe@domain.com.<br /> You can check the email address assigned to the user by pulling up the properties of the user object in Active Directory and looking at the E-mail attribute on the General tab.<br /><br /> <b>Information about Deleting Mailboxes</b><br /> There are two possible scenarios related to deleting an Exchange mailbox:<br /> 1) You don't want to keep the mailbox OR the Active Directory user account. In this case, simply delete the user account from Active Directory. This will simultaneously delete the mailbox.<br /> 2) You don't want to keep the mailbox, but you DO want to keep the Active Directory user account. In this case, use this page and select "Delete Mailbox"<br /> </p> </body> </html>
PowerShellCorpus/PoshCode/Compare SQL Tables II.ps1
Compare SQL Tables II.ps1
function Convert-TableToList { param( $t, $colid = 0 ) $t | % {$_.item($colid)} } function Compare-Tables { param( $name, $db1, $db2, $exclude = @() ) # @bernd_k http://pauerschell.blogspot.com/ # requires on sqlise http://sqlpsx.codeplex.com/ $sql = "select name from sys.columns where object_id = object_id('$db1..$name') order by column_id" Invoke-ExecuteSql $sql 'variable' columns $columns = Convert-TableToList $columns | % { if ($exclude -notcontains $_) {$_} } $columnlist = $columns -join ', ' $sql = @" Select 1 [table], $columnlist from $db1..$name except Select 1 [table], $columnlist from $db2..$name union Select 2 [table], $columnlist from $db2..$name except Select 2 [table], $columnlist from $db1..$name ORDER by 2 "@ $sql Invoke-ExecuteSql $sql 'grid' } # Compare-Table2 sometable db1 db2 -ex @('colx', 'coly')
PowerShellCorpus/PoshCode/PurgeFiles script..ps1
PurgeFiles script..ps1
<# .SYNOPSIS PurgeFiles - recursively remove files with given extension and maximum age from a given path. .DESCRIPTION Read the synopsis Example PurgeFiles.psq -path C:\\temp -ext .tmp -max 24 .EXAMPLE PurgeFiles.psq -path C:\\temp -ext .tmp -max 24 #> # HISTORY # 2010/01/29 # rluiten Created param( [Parameter(Mandatory=$true)][string] $path ,[Parameter(Mandatory=$true)][string] $extension ,[Parameter(Mandatory=$true)][int] $maxHours ,[switch] $deleteMode = $false ,[switch] $listMode = $false ) function delete-file([string]$path, [string]$extension, [datetime]$oldestAllowed, [bool] $deleteMode, [bool] $listMode) { $filesToRemove = Get-Childitem $path -recurse | ?{ !$_.PSIsContainer -and ($_.LastWriteTime -lt $oldestAllowed) -and ($_.Extension -eq $extension) } if ($listMode -and $filesToRemove) { $filesToRemove | %{write-host "FILE: $($_.LastWriteTime) ""$($_.FullName)""`r`n"} } if ($deleteMode -and $filesToRemove) { write-host "Removing Files...`r`n" $filesToRemove | remove-item -force } } $oldestAllowed = (get-date).AddHours(-$maxHours) if (-not $deleteMode) { write-host "Running in trial mode, no files will be deleted.`r`n" } delete-file $path $extension $oldestAllowed $deleteMode $listMode
PowerShellCorpus/PoshCode/Get-SQLDatabaseFreespace.ps1
Get-SQLDatabaseFreespace.ps1
###########################################################################" # # NAME: Get-SQLDatabaseFreespace.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: Requires SQL Server 2008 Management Studio Express. The script gets free space from the specified SQL Database # and sends the result to the specified e-mail address. # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 10.05.2009 - Initial release # ###########################################################################" #Add SQL Server 2008 PowerShell snapin Add-Pssnapin SqlServerProviderSnapin100 #Get free space in specified database cd SQLSERVER:\\SQL\\SQL-server-name\\Instance-name\\Databases $DB = Get-Item "Database01" $SpaceAvailable = $DB.SpaceAvailable $formattedresult = $SpaceAvailable $result = "{0:#.00}" -f ($SpaceAvailable/1kb) #Send result to specified e-mail address $smtpServer = "smtp-server-name" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "sender@domain.local" $msg.To.Add("recipient@domain.local") $msg.Subject = "Free space in Database01" $msg.Body = "There are $result MB free space in Database01" $smtp.Send($msg)
PowerShellCorpus/PoshCode/Get-WebFile _1.7.ps1
Get-WebFile _1.7.ps1
## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7 - [int] to [long] to support files larger than 2.0 GB ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## function Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) $req = [System.Net.HttpWebRequest]::Create($url); # http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw $req.CookieContainer = New-Object System.Net.CookieContainer $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [long]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [long]$total = [long]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/Get-InstalledProgram_v3.ps1
Get-InstalledProgram_v3.ps1
param ( [String[]]$Computer, $User ) ############################################################################################# if ($User) {$Connection = Get-Credential -Credential $User} ############################################################################################# if (!$Connection){ foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-Table __SERVER,Name,Version,InstallDate $Install_soft } } else { foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-Table __SERVER,Name,Version,InstallDate $Install_soft } }
PowerShellCorpus/PoshCode/Set-LocalPassword_3.ps1
Set-LocalPassword_3.ps1
param( [switch]$Help , [string] $User , [string] $Password , [string[]] $ComputerNames = @() ) $usage = @' Get-OUComputerNames usage : [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...] returns : Sets local account passwords on one or more computers author : Nathan Hartley '@ if ($help) {Write-Host $usage;break} $ComputerNames += @($input) if (! $ComputerNames) { $ComputerNames = $env:computername } function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) { "*** Setting password for $ChangeComputer/$ChangeUser" & { $ErrorActionPreference="silentlycontinue" ([ADSI] "WinNT://$computer/$user").SetPassword($password) if ($?) { " Success" } else { " Failed: $($error[0])" } } } ForEach ($computer in $ComputerNames) { ChangePassword $computer $user $password }
PowerShellCorpus/PoshCode/HttpRest 2.0.ps1
HttpRest 2.0.ps1
#requires -version 2.0 ## HttpRest module version 2.0 #################################################################################################### ## Still only the initial stages of converting to a full v2 module ## Based on the REST api from MindTouch's Dream SDK ## ## INSTALL: ## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK ## Get MindTouch_Dream_2.1.0.zip (code name Indigo) from http`://sourceforge.net/projects/dekiwiki/files/ ## ## Unpack it, and you can find these dlls in the "dist" folder. ## Make sure to put them in the folder with this script module. ## You also need the PSD1 file. It's in a comment block at the bottom. ## ## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream #################################################################################################### ## Version History ## 1.0 2008-11-30 First Release ## 1.0.1 2009-01-05 Added Get-WebPageContent ## 1.0.2 2009-05-14 Bug fix for Invoke-Http credential issues ## 1.1.0 2009-05-14 First release of a PowerShell 2.0 (CTP3/Windows7) version.... ## 1.1.1 2009-05-15 Added Get-WebPageText and Get-Webfile ... cleaned up options ## 1.2 2009-08-09 Added Hashtable parsing on Get-DreamMessage ## Fixed parsing on Get-DreamPlug so we don't get errors on PowerShell 2 ## Added ParameterSet on Invoke-Http to pass in a plug directly (easier to debug) ## 1.3 2010-07-27 Added a few more aliases to make life easier ## 1.4 2010-07-28 Changed Get-WebPageContent and Get-WebPageText to support pipline input ## Started adding help ... ## 2.0 2010-08-20 Upgrade to Mindtouch Dream 2.1 ## Further Improvements to function behavior and parameter binding. #################################################################################################### ## Usage: ## function Get-Google { ## Invoke-Http GET http`://www.google.com/search @{q=$args} | ## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText ## } ## ######################################################################### ## function Get-WebFile($url,$cred) { ## Invoke-Http GET $url -auth $cred | Receive-Http File ## } ## ######################################################################### ## function Send-Paste { ## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file) ## PROCESS { ## if($_){[IO.FileInfo]$file=$_} ## ## if($file.Exists) { ## $ofs="`n" ## $result = Invoke-Http POST $PastebinURI @{ ## format="posh" # PowerShell ## expiry="d" # (d)ay or (m)onth or (f)orever ## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1]) ## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter. ## paste="Send" ## } -Type FORM_URLENCODED -Wait ## $xml = $result.AsDocument().ToXml() ## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href ## } else { throw "File Not Found" } ## }} ## #################################################################################################### Write-Debug "PSScriptRoot: '$PSScriptRoot'" # This Module depends on MindTouch.Dream $null = Add-Type -Path "$PSScriptRoot\\mindtouch.dream.dll" -ErrorAction Stop # MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll) # This Module also depends on utility functions from System.Web $null = Add-Type -Assembly System.Web -ErrorAction Stop ## Some utility functions are defined at the bottom [uri]$global:url = "" [System.Management.Automation.PSCredential]$global:HttpRestCredential = $null Function Get-DreamMessage { PARAM($Content,$Type) #Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})" if($Type -is [String]) { Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)" $Type = [MindTouch.Dream.MimeType]::$Type } if($Type -is [MindTouch.Dream.MimeType] -and $Content) { Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)" return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content ) } if(!$Content) { Write-Verbose "No Content" return [MindTouch.Dream.DreamMessage]::Ok() } if($Content -is [System.Xml.XmlDocument]) { Write-Verbose "Xml Content" return [MindTouch.Dream.DreamMessage]::Ok( $Content ) } if($Content -is [Hashtable]) { $kvp = $Content.GetEnumerator() | %{ new-object "System.Collections.Generic.KeyValuePair[[String],[String]]" $_.Key, $_.Value } Write-Verbose "Hashtable content: $($kvp | ft -auto | out-string -stream | %{ " $_ ".TrimEnd()} )" return [MindTouch.Dream.DreamMessage]::Ok( $kvp ) } if(Test-Path $Content -EA "SilentlyContinue") { Write-Verbose "File Content" return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content))); } Write-Verbose "Unspecified string content" return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content ) } Function Get-DreamPlug { [CmdletBinding()] PARAM ( $Url, [hashtable]$With, [hashtable]$Headers ) if($Url -is [array]) { Write-Verbose "URL is an array of parts" if($Url[0] -is [hashtable]) { Write-Verbose "URL is an array of hashtable parts" $plug = [MindTouch.Dream.Plug]::New($global:url) foreach($param in $url.GetEnumerator()) { if($param.Value) { $plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)") } else { $plug = $plug.At($param.Key) } } } else { [URI]$uri = Join-Url $global:url $url $plug = [MindTouch.Dream.Plug]::New($uri) } } elseif($url -is [string]) { Write-Verbose "String URL" trap { continue } [URI]$uri = $url if(!$uri.IsAbsoluteUri) { $uri = Join-Url $global:url $url Write-Verbose "Relative URL, appending to $($global:url) to get: $uri" } $plug = [MindTouch.Dream.Plug]::New($uri) } else { Write-Verbose "No URL, using default $($global:url)" $plug = [MindTouch.Dream.Plug]::New($global:url) } if($with) { foreach($w in $with.GetEnumerator()) { if($w.Value) { $plug = $plug.With($w.Key,$w.Value) } } Write-Verbose "Added 'with' params: $plug" } if($headers) { foreach($header in $Headers.GetEnumerator()) { if($header.Value) { $plug = $plug.WithHeader($header.Key,$header.Value) } } Write-Verbose "Added 'with' params: $plug" } return $plug } Function Receive-Http { [CmdletBinding(DefaultParameterSetName="Response")] PARAM( [Parameter(Position=1, Mandatory=$false)] [ValidateSet("Xml", "File", "Text","Bytes")] [Alias("As")] $Output = "Xml" , [Parameter(Position=2, Mandatory=$false)] [AllowEmptyString()] [string]$Path , [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")] [Alias("IO")] [MindTouch.Tasking.Result[MindTouch.Dream.DreamMessage]] $InputObject , [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")] [MindTouch.Dream.DreamMessage] $Response ) PROCESS { if($PSCmdlet.ParameterSetName -eq "Result") { $Response = $InputObject.Wait() } if($Response) { Write-Debug $($response | Out-String) if(!$response.IsSuccessful) { Write-Output $response Write-Host "Hello" -fore Yellow Write-Verbose $($response|gm|out-string) Write-Host "Hello" -fore Yellow Write-Error $($response | Out-String) throw "ERROR: '$($response.Status)' Response Status." } else { switch($Output) { "File" { ## Joel's magic filename guesser ... if(!$Path) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value $Path = $fileName.trim("\\/""'") if(!$Path){ if($response.ResponseUri) { $fileName = $response.ResponseUri.Segments[-1] $Path = $fileName.trim("\\/") if(!([IO.FileInfo]$Path).Extension) { $Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1] } } } } if($Path) { $File = Get-FileName $Path } else { $File = Get-FileName } $null = [MindTouch.IO.StreamUtil]::CopyToFile( $response.AsStream(), $File, $response.ContentLength ) Get-ChildItem $File } "XDoc" { if($Path) { $response.AsDocument()[$Path] } else { $response.AsDocument()#.ToXml() } } "Xml" { if($Path) { $response.AsDocument().ToXml().SelectNodes($Path) } else { $response.AsDocument().ToXml() } } "Text" { if($Path) { $response.AsDocument()[$Path] | % { $_.AsInnerText } } else { $response.AsText() } } "Bytes" { $response.AsBytes() } } } } else { Write-Warning "No Response!" if($InputObject) { Write-Output $InputObject } } } } Function Invoke-Http { #.Synopsis # Invoke an HTTP verb on a URI #.Description # This is the core http rest cmdlet, which does most of the work and allows fetching web pages, files, etc. [CmdletBinding(DefaultParameterSetName="ByPath")] PARAM( ## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html ## Nobody actually uses HEAD or OPTIONS, right? ## And nobody's even heard of TRACE or CONNECT ;) [Parameter(Position=0, Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] ## There are other verbs, but we need a list to make sure you don't screw up [string]$Verb = "GET" , [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="WithPlug")] [MindTouch.Dream.Plug] $Plug , [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByPath")] [string] $Path , [Parameter(Position=2, Mandatory=$false, ParameterSetName="ByPath")] [hashtable]$With , [Parameter(Position=3, Mandatory=$false, ParameterSetName="ByPath")] [hashtable]$Headers , [Parameter(Mandatory=$false)] $Content , [Parameter(Mandatory=$false)] [System.Collections.Generic.IEnumerable[MindTouch.Web.DreamCookie]]$Cookies , [Parameter(Mandatory=$false)] $Type # Of Content , [Parameter(Mandatory=$false)] [switch]$authenticate , [Parameter(Mandatory=$false)] $credentials , [Parameter(Mandatory=$false)] [switch]$Persistent ## Note this ALSO causes WaitForResponse , [switch]$waitForResponse ) PROCESS { if($PSCmdlet.ParameterSetName -eq "ByPath") { $Plug = Get-DreamPlug $Path $With $Headers } ## Special Handling for FORM_URLENCODED if($Type -like "Form*" -and !$Content) { $dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri ) $Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath ) Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)" } else { $dream = Get-DreamMessage $Content $Type Write-Verbose "Created Dream with Content: $($dream.AsText() |out-String)" } if(!$plug -or !$dream) { throw "Can't come up with a request!" } if($Persistent -and $global:HttpRestCookies) { $dream.Cookies.AddRange( $global:HttpRestCookies ) } if($Cookies) { $dream.Cookies.AddRange( $Cookies ) } if($authenticate -or $credentials){ if($credentials -is [System.Management.Automation.PSCredential]) { Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)" $plug = $plug.WithCredentials($credentials.GetNetworkCredential()) } elseif($credentials -is [System.Net.ICredentials]) { Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)" $plug = $plug.WithCredentials($credentials.GetNetworkCredential()) } else { if($credentials) { Write-Error "Credential must be a PSCredential or a System.Net.ICredentials" } $null = Get-HttpCredential # Make sure they have global credentials Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)" $plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential()) } } Write-Verbose $plug.Uri ## DEBUG: Write-Debug "URI: $($Plug.Uri)" Write-Debug "Verb: $($Verb.ToUpper())" Write-Debug $($dream | gm | Out-String) $result = $plug.InvokeAsync( $Verb.ToUpper(), $dream ) Write-Debug $($result | Out-String) # if($DebugPreference -eq "Continue") { # Write-Debug $($result.Wait() | Out-String) # } if($waitForResponse -or $Persistent) { $result = $result.Wait() $global:HttpRestCookies = $result.Cookies } write-output $result trap [MindTouch.Dream.DreamResponseException] { Write-Error @" TRAPPED DreamResponseException $($_.Exception.Response | Out-String) $($_.Exception.Response.Headers | Out-String) "@ break; } } } Function Get-WebPageContent { #.Synopsis # A wrapper for http get | rcv xml [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)] [string]$url , [Parameter(Mandatory=$false)] [string]$xpath="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) PROCESS { invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http xml $xpath | select -expand outerxml } } Function Get-WebPageText { #.Synopsis # A wrapper for http get | rcv text [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)] [string]$url , [Parameter(Mandatory=$false)] [string]$xpath="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) PROCESS { invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http text $xpath } } Function Get-WebFile { #.Synopsis # Download a file from a URI to the local computer [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)] [string]$url , [Parameter(Mandatory=$false)] [Alias("output")] [string]$path="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) PROCESS { Invoke-Http GET $url $with -Authenticate:$Authenticate -Persist:$Persist | Receive-Http File $path } } Function Set-HttpDefaultUrl { #.Synopsis # Set the base URI for making lots of calls to a single webservice without re-entering the full URL each time PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service")) $global:url = $baseUri } Function Set-HttpCredential { #.Synopsis # Set the default credentials for making lots of calls to a single webservice without re-entering credentials param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" ` -Message "Your login for $($global:url.Host)" ` -Domain $($global:url.Host)) ) if($Credential -is [System.Management.Automation.PSCredential]) { $global:HttpRestCredential = $Credential } elseif($Credential -is [System.Net.NetworkCredential]) { $global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password) } } Function Get-HttpCredential { #.Synopsis # Retrieves the default credentials for making lots of calls to a single webservice without re-entering credentials if(!$global:url) { Set-HttpDefaultUrl } if(!$global:HttpRestCredential) { Set-HttpCredential } if(!$Secure) { return $global:HttpRestCredential.GetNetworkCredential(); } else { return $global:HttpRestCredential } } Function ConvertTo-UrlDoubleEncode { #.Synopsis # Encode URLs twice for use with mindtouch APIs param([string]$text) return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) ) } Function Join-Url { #.Synopsis # Like Join-Path, but for URIs [CmdletBinding()] param( [Parameter()] [uri]$baseUri=$global:url , [Parameter(ValueFromRemainingArguments=$true)] [string[]]$path ) $ofs="/";$BaseUrl = "" if($BaseUri -and $baseUri.AbsoluteUri) { $BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/" } return [URI]"$BaseUrl$([string]::join("/",@($path)).TrimStart('/'))" } Function ConvertTo-SecureString { #.Synopsis # Helper function which converts a string to a SecureString Param([string]$input) $result = new-object System.Security.SecureString foreach($c in $input.ToCharArray()) { $result.AppendChar($c) } $result.MakeReadOnly() return $result } Function Get-FileName { #.Synopsis # Helper function to get a VALID filesystem path param($fileName=$([IO.Path]::GetRandomFileName()), $path) $fileName = $fileName.trim("\\/""'") ## if the $Path has a file name, and it's folder exists: if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) { $path ## if the $Path is just a folder (and it exists) } elseif($Path -and (Test-Path $path -Type Container)) { $fileName = Split-Path $fileName -leaf Join-Path $path $fileName ## If there's no valid $Path, and the $FileName has a folder... } elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) { $fileName } else { Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf) } } Function Get-UtcTime { Param($Format="yyyyMMddhhmmss") [DateTime]::Now.ToUniversalTime().ToString($Format) } Function Get-CredentialBetter { ## .Synopsis ## Gets a credential object based on a user name and password. ## .Description ## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations. ## ## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically. ## ## .Parameter UserName ## A default user name for the credential prompt, or a pre-existing credential (would skip all prompting) ## .Parameter Title ## Allows you to override the default window title of the credential dialog/prompt ## ## You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it. ## .Parameter Message ## Allows you to override the text displayed inside the credential dialog/prompt. ## ## You can use this for things like presenting an explanation of what you need the credentials for. ## .Parameter Domain ## Specifies the default domain to use if the user doesn't provide one (by default, this is null) ## .Parameter GenericCredentials ## The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\". ## .Parameter Inline ## Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE) ## [CmdletBinding(DefaultParameterSetName="Better")] PARAM( [Parameter(Position=1,Mandatory=$false)] [Alias("Credential")] [PSObject]$UserName=$null, [Parameter(Position=2,Mandatory=$false)] [string]$Title=$null, [Parameter(Position=3,Mandatory=$false)] [string]$Message=$null, [Parameter(Position=4,Mandatory=$false)] [string]$Domain=$null, [Parameter(Mandatory=$false)] [switch]$GenericCredentials, [Parameter(Mandatory=$false)] [switch]$Inline ) PROCESS { if( $UserName -is [System.Management.Automation.PSCredential]) { return $UserName } elseif($UserName -ne $null) { $UserName = $UserName.ToString() } if($Inline) { if($Title) { Write-Host $Title } if($Message) { Write-Host $Message } if($Domain) { if($UserName -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } if(!$UserName) { $UserName = Read-Host "User" if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } return New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString) } if($GenericCredentials) { $Credential = "Generic" } else { $Credential = "Domain" } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. ## BugBug? PowerShell.exe disregards the last parameter $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Credential,"Default") } } New-Alias Encode-Twice ConvertTo-UrlDoubleEncode new-alias gwpc Get-WebPageContent -EA "SilentlyContinue" new-alias gwpt Get-WebPageText -EA "SilentlyContinue" new-alias http Invoke-Http -EA "SilentlyContinue" new-alias rcv Receive-Http -EA "SilentlyContinue" Export-ModuleMember -Function Invoke-Http, Receive-Http, Get-WebPageContent, Get-WebPageText, Get-WebFile, ConvertTo-UrlDoubleEncode, Get-HttpCredential, Set-HttpCredential, Set-HttpDefaultUrl -Alias * ########################################################################################## ##### HttpRest.psd1 ########################################################################################## ## # ## # Module manifest for module 'HttpRest' ## # Generated by: Joel Bennett ## # Generated on: 3/19/2009 ## # ## ## @{ ## ## # These modules will be processed when the module manifest is loaded. ## ModuleToProcess = 'HttpRest.psm1' ## ## # This GUID is used to uniquely identify this module. ## GUID = '49fc4e2a-0270-467d-a652-a9ba8f82e97b' ## ## # The author of this module. ## Author = 'Joel Bennett' ## ## # The company or vendor for this module. ## CompanyName = 'http://HuddledMasses.org' ## ## # The copyright statement for this module. ## Copyright = 'Copyright (c) 2008, Joel Bennett. Released under Ms-PL license.' ## ## # The version of this module. ## ModuleVersion = '2.0' ## ## # A description of this module. ## Description = 'This module provides functions for working Http services. Everything from downloading web pages, posting forms, and parsing HTML as XML, to downloading images and files, to interacting with REST web APIs' ## ## # The minimum version of PowerShell needed to use this module. ## PowerShellVersion = '2.0' ## ## # The CLR version required to use this module. ## CLRVersion = '2.0' ## ## # Functions to export from this manifest. ## FunctionsToExport = '*' ## ## # Aliases to export from this manifest. ## AliasesToExport = '*' ## ## # Variables to export from this manifest. ## VariablesToExport = '*' ## ## # Cmdlets to export from this manifest. ## CmdletsToExport = '*' ## ## # This is a list of other modules that must be loaded before this module. ## RequiredModules = @() ## ## # The script files (.ps1) that are loaded before this module. ## ScriptsToProcess = @() ## ## # The type files (.ps1xml) loaded by this module. ## TypesToProcess = @() ## ## # The format files (.ps1xml) loaded by this module. ## FormatsToProcess = @() ## ## # A list of assemblies that must be loaded before this module can work. ## RequiredAssemblies = 'autofac.dll', 'log4net.dll', 'mindtouch.core.dll', 'SgmlReaderDll.dll', 'mindtouch.dream.dll' ## ## # Module specific private data can be passed via this member. ## PrivateData = '' ## ## }
PowerShellCorpus/PoshCode/RichCopyMyProfile.ps1
RichCopyMyProfile.ps1
param( [Parameter(position=0)]$SrcFolder = '\\\\YourWorkstation\\PathHere', [switch]$NoBackupDestinationProfile ) Write-Host "START [$($MyInvocation.MyCommand.Name)] $(get-date -f yyyyMMdd.HHmmss)" $global:dirPSProfile = (Split-Path -Parent $profile) filter DirHelper( [Parameter(Position=0)]$Path, [Parameter(Position=1)][Scriptblock]$DirExistsScriptBlock ) { [bool]$backupProfile = !(Test-Path -PathType Container $Path) if (!(Test-Path -PathType Container $Path)) { md $Path -Verbose } else { if ($DirExistsScriptBlock -ne $null) { & $DirExistsScriptBlock } } cd $Path } DirHelper $dirPSProfile { $back = Join-Path (Split-Path $Path -Parent) '_GetCTBackup' Write-Warning "Found profile directory. Attempting backup before continuing. [$back]" Write-Host ('xcopy /iy "{0}" "{1}"' -f $path,$back) xcopy /iy "$Path" "$back" } if (Get-Command robocopy.exe -ErrorAction SilentlyContinue) { robocopy $SrcFolder $dirPSProfile /S } else { $proc = &{ if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") { "64" } else { "" } } xcopy /d/y/i "$SrcFolder\\bin\\RichCopy*" "$dirPSProfile\\bin" $cmd = '"{0}\\bin\\RichCopy{1}.exe"'-f $dirPSProfile,$proc $cmdArgs = ( $SrcFolder,'"{0}"','/TD','64','/TS','32','/SC','64','/FEF','_Scratch.ps1;*.7z' | %{ $_ -f $dirPSProfile }) echo 'running command: {0} {1}' -f $cmd,($cmdArgs -join ' ') Start-Process -Wait $cmd $cmdArgs } Write-Host "END [$($MyInvocation.MyCommand.Name)] $(get-date -f yyyyMMdd.HHmmss)"
PowerShellCorpus/PoshCode/W8 PseudoStartMenu.ps1
W8 PseudoStartMenu.ps1
function Update-FakeWindow8Startmenu { $StartMenu = "C:\\Startmenu" remove-item $StartMenu -Recurse -Force $path1 = "$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs" gci $path1 -rec | % { cp $_.fullname "$StartMenu\\$($_.fullname.substring($path1.Length + 1))" } $path2 = "$env:AppData\\Microsoft\\Windows\\Start Menu\\Programs" gci "$env:AppData\\Microsoft\\Windows\\Start Menu\\Programs" -Recurse | % { cp $_.fullname "$StartMenu\\$($_.fullname.substring($path2.Length + 1))" -ea SilentlyContinue } }
PowerShellCorpus/PoshCode/VMware Host Network Info_2.ps1
VMware Host Network Info_2.ps1
# Set the VI Server and Filename before running Connect-VIServer MYVISERVER $filename = "C:\\DetailedNetworkInfo.csv" Write "Gathering VMHost objects" $vmhosts = Get-VMHost | Sort Name | Where-Object {$_.State -eq "Connected"} | Get-View $MyCol = @() foreach ($vmhost in $vmhosts){ $ESXHost = $vmhost.Name Write "Collating information for $ESXHost" $networkSystem = Get-view $vmhost.ConfigManager.NetworkSystem foreach($pnic in $networkSystem.NetworkConfig.Pnic){ $pnicInfo = $networkSystem.QueryNetworkHint($pnic.Device) foreach($Hint in $pnicInfo){ $NetworkInfo = "" | select-Object Host, vSwitch, vSwitchPorts, vSwitchPrtInUse, PNic, Speed, MAC, DeviceID, PortID, Observed, VLAN $NetworkInfo.Host = $vmhost.Name $NetworkInfo.vSwitch = Get-Virtualswitch -VMHost (Get-VMHost ($vmhost.Name)) | where {$_.Nic -eq ($Hint.Device)} $NetworkInfo.vSwitchPorts = $NetworkInfo.vSwitch.NumPorts $NetworkInfo.vSwitchPrtInUse = ($NetworkInfo.vSwitch.NumPorts - $NetworkInfo.vSwitch.NumPortsAvailable) $NetworkInfo.PNic = $Hint.Device $NetworkInfo.DeviceID = $Hint.connectedSwitchPort.DevId $NetworkInfo.PortID = $Hint.connectedSwitchPort.PortId $record = 0 Do{ If ($Hint.Device -eq $vmhost.Config.Network.Pnic[$record].Device){ $NetworkInfo.Speed = $vmhost.Config.Network.Pnic[$record].LinkSpeed.SpeedMb $NetworkInfo.MAC = $vmhost.Config.Network.Pnic[$record].Mac } $record ++ } Until ($record -eq ($vmhost.Config.Network.Pnic.Length)) foreach ($obs in $Hint.Subnet){ $NetworkInfo.Observed += $obs.IpSubnet + " " Foreach ($VLAN in $obs.VlanId){ If ($VLAN -eq $null){ } Else{ $strVLAN = $VLAN.ToString() $NetworkInfo.VLAN += $strVLAN + " " } } } $MyCol += $NetworkInfo } } } $Mycol | Sort Host, PNic | Export-Csv $filename -NoTypeInformation
PowerShellCorpus/PoshCode/Split-TextToLines Demo_1.ps1
Split-TextToLines Demo_1.ps1
function Show-LineArrayStructure ($lines) { $len = $lines.length "Type is: $($lines.gettype().Name)" "Number of lines: $len" for ($i = 0; $i -lt $len; $i++) { "$($i + 1). Line: length $($lines[$i].length) >$($lines[$i])<" } '' } $text = "abc`r`nefg`r`n" # $text # $text.length $lines = $text.Split("`n") Show-LineArrayStructure $lines $lines2 = $text.Split("`r`n") Show-LineArrayStructure $lines2 $lines3 = $([Regex]::Split($text,"`r`n" )) Show-LineArrayStructure $lines3 $lines4 = $text -split "`n" Show-LineArrayStructure $lines4 # best method $lines5 = $text -split "`r`n" Show-LineArrayStructure $lines5 # even better proposed by Jaycul in comment on # http://pauerschell.blogspot.com/2009/02/ise-extension-basics-splitting-text-to.html $lines6 =$text.Split([string[]]"`r`n", [StringSplitOptions]::None) Show-LineArrayStructure $lines6
PowerShellCorpus/PoshCode/DotSource.psm1.ps1
DotSource.psm1.ps1
#requires -version 3 $accelerators = [psobject].Assembly.GetType( 'System.Management.Automation.TypeAccelerators' ) foreach ($Type in 'Parser', 'FunctionDefinitionAst', 'AssignmentStatementAst', 'VariableExpressionAst', 'TokenKind') { $accelerators::Add( $Type, "System.Management.Automation.Language.$Type" ) } function Import-Script { param ( $Path, [ValidateSet( 'Script', 'Global', 'Local' )] $Scope = 'Global', [switch]$IncludeVariables ) $fullName = (Resolve-Path $Path).ProviderPath $ast = [Parser]::ParseFile( $fullName, [ref]$null, [ref]$null ) foreach ($function in $ast.FindAll({ $args[0] -is [FunctionDefinitionAst] }, $false)) { $define = $false switch -Regex ($function.Name) { '^(?!.*:)' { $define = $true $name = $function.Name break } '(Global|Script|Local):' { $define = $true $name = $function.Name -replace '.*:' } default { $define = $false } } if ($define) { & ([scriptblock]::Create(" function $Scope`:$name $($function.Body) " )) } } if ($IncludeVariables) { foreach ($variable in $ast.FindAll({ $args[0] -is [AssignmentStatementAst] -and $args[0].Operator -eq [TokenKind]::Equals -and $args[0].Left -is [VariableExpressionAst] }, $false)) { $define = $false switch -Regex ($variable.Left.VariablePath) { '^(?!.*:)' { $define = $true $name = $variable.Left.VariablePath break } '(Global|Script|Local):' { $define = $true $name = $variable.Left.VariablePath -replace '.*:' } default { $define = $false } } if ($define) { & ([scriptblock]::Create( "`$$Scope`:$name = $( $variable.Right.Extent.Text )" )) } } } } New-Alias -Name .. -Value Import-Script -Force Export-ModuleMember -Function * -Alias *
PowerShellCorpus/PoshCode/Boots DataGrid Binding_1.ps1
Boots DataGrid Binding_1.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 "[your_path to xaml_file.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/Updated CloneVM from CSV_1.ps1
Updated CloneVM from CSV_1.ps1
Param ($servercsv) # $servercsv is the input file <# .SYNOPSIS Mass cloning of virtual machines .DESCRIPTION Mass cloning of virtual machines from a template using a CSV file as a source. .NOTES 1- Assumes template only has a C: drive and that only a D: will be added from the CSV file. Additional drives will have to be done manually. 2- Input CSV file format is at the bottom of this file. 3- When testing use this command to mass delete the VMs created with the script. import-csv inputfile.csv | % { Remove-VM -DeleteFromDisk -VM $_.Name -RunAsync -Confirm:$false } 4- Folder is not set due to the likelihood of duplicate folder names in large environment. There's no good, consistent, and easy way that I could figure out to handle that. 5- Creating the additional disk fails with PowerCLI 4.0 U1. Reference URLs on the next two lines: http://blog.vmpros.nl/2009/08/21/vmware-number-of-virtual-devices-exceeds-the-maximum-for-a-given-controller/ http://communities.vmware.com/thread/251601 6- Setting the guest network fails with PowerCLI 4.0 U1. I've posted the issue. http://communities.vmware.com/thread/262855 ** UPDATE- Issue with dvSwitches not supported in PowerCli yet. Workaround here- http://www.lucd.info/2010/03/04/dvswitch-scripting-part-8-get-and-set-network-adapters/ Todos- 1- Set the guest network config. with either Copy-VMGuestfile and Invoke-VMScript, or Set-VMGuestNetworkInterface. 2- Check/update vmware tools. (May not be advisable, my conflict with sysprep reboot(s).) 3- Create script to validate CSV file. Possibly to be run by Project Managers. 4- Create Excel spreadsheet with dropdown lists of cluster locations and other info to assist Project Managers. .LINK http://netops.ma.monster.com/virtech/VMware%20Wiki%20Library/Home.aspx .EXAMPLE C:\\Temp> C:\\ops\\posh\\VMware\\Clone_Template_fromCSV.ps1 inputfile.csv #> Write-Output "`n++ $(Get-Date) - Starting Script." # Prep $OrginalVIServer = $global:DefaultVIServer # Saving the Virtual Center that the shell session was connected to. $ScriptDir = "\\\\vmscripthost201\\repo" $VMTargets = Import-CSV $servercsv Write-Output "`n++ $(Get-Date) - Verifying server names are unique." $DupeNames = $false $AllVMs = Get-VM | Sort $i = 0; If ( ($VMTargets | Measure-Object).Count -eq 1) { # only one VM in the CSV to deploy $j = 0 while ($AllVMs[$j]) { If ($VMTargets.Name -eq $AllVMs[$j].Name) { $DupeNames = $true $DupeNames Write-Host "Requested VM name" $VMTargets.Name "is in use. `n" } # end If $j++ } # end while } Else { # more than one VM in the CSV to deploy while ($VMTargets[$i]) { $j = 0 while ($AllVMs[$j]) { If ($VMTargets[$i].Name -eq $AllVMs[$j].Name) { $DupeNames = $true $DupeNames Write-Host "Requested VM name" $VMTargets[$i].Name "is in use. `n" } # end If $j++ } # end while $i++ } # end while } If ($dupenames -eq $false) { Write-Output "`n++ $(Get-Date) - Starting deploying." $serverlist = Import-CSV $servercsv # ** Clone new VM $serverlist | % { $_.VC Connect-VIServer $_.VC | Select-Object Name If ($_.VC -match "ukvcenter101") { If ($_.Template -match "std") { $GuestIDs_mapto_OSCustSpec = Import-Csv $ScriptDir\\StaticInfo\\guestids_list_UK_Win2K8Std.csv } ElseIf ($_.Template -match "ent") { $GuestIDs_mapto_OSCustSpec = Import-Csv $ScriptDir\\StaticInfo\\guestids_list_UK_Win2K8Ent.csv } Else { Write-Host "No matching UK template name to pick OSCustSpec"; break; } } Else { $GuestIDs_mapto_OSCustSpec = Import-Csv $ScriptDir\\StaticInfo\\guestids_list.csv } $TemplateGuestId = (((Get-Template $_.Template).ExtensionData).Guest).GuestId Write-Output "$($_.Template) and $($TemplateGuestId)" $OSCustSpec = ($GuestIDs_mapto_OSCustSpec | ? { $_.guestid -eq $TemplateGuestId }).OSCustSpec Write-Output "$($OSCustSpec)" $respool = $_.ResourcePool $RPTarget = (Get-ResourcePool -location $_.Cluster | Where { $_.Name -match $respool } | get-random) $VMHostTarget = (Get-VMHost -Location $_.Cluster | Where-Object { $_.ConnectionState -eq "Connected" } | Select Name,@{n="Lightest";e={ ( ($_.CpuUsageMhz/$_.CpuTotalMhz) + ($_.MemoryUsageMB/$_.MemoryTotalMB) )/2 }} | sort Lightest | select -first 1).Name $DSTTarget = (.$ScriptDir\\Get-DatastoreMostFree.ps1 $_.Cluster).Name If ($DSTTarget -eq $null) { Write-Output "No datatstore returned for cluster $($_.Cluster). Exiting script." break } Write-Output "`n++ $(Get-Date) `t- Creating VM:`t $(($_.Name).ToLower())`t$($_.Cluster)`t$($VMHostTarget)`t$($DSTTarget)`t$($RPTarget)`t$($OSCustSpec)" New-VM -Confirm:$False ` -Name ($_.Name).ToLower() ` -Template $_.Template ` -OSCustomizationSpec $OSCustSpec ` -DiskStorageFormat Thin ` -ResourcePool $RPTarget ` -Description $_.Notes ` -VMHost $VMHostTarget ` -Datastore $DSTTarget Start-Sleep 5 # Giving the VM time to appear in the Virtual Center inventory. Set-VM -Confirm:$false ` -VM $_.Name ` -NumCpu $_.NumCpu ` -MemoryMB ([int]$_.RAMSizeGB * 1024) If ( $_.Template -match "w2k8" ) { $SCSIControllerType = "VirtualLsiLogicSAS" } else { $SCSIControllerType = "VirtualLsiLogic" } (Get-VM -Name $_.Name).Guest.OSFullName $_.Template $SCSIControllerType New-HardDisk -VM $_.Name -CapacityKB ([int]$_.D_DriveSizeGB * 1024 * 1024) -DiskType Flat -StorageFormat Thin -Confirm:$false | New-ScsiController -Type $SCSIControllerType Get-NetworkAdapter -VM $_.Name | Set-NetworkAdapter -NetworkName $_.VLAN -Confirm:$false Set-Annotation -Entity $_.Name -CustomAttribute Application -value $_.Application Set-Annotation -Entity $_.Name -CustomAttribute "Business Unit" -value $_.BusinessUnit Set-Annotation -Entity $_.Name -CustomAttribute Category -value $_.Category Set-Annotation -Entity $_.Name -CustomAttribute Support -value $_.Support Get-FloppyDrive -VM $_.Name | Remove-FloppyDrive -Confirm:$false Get-UsbDevice -VM $_.Name | Remove-UsbDevice -Confirm:$false Get-VM -Name $_.Name | Get-VMResourceConfiguration | Set-VMResourceConfiguration -CPUReservationMhz 0 -CPULimitMhz $null Get-VM -Name $_.Name | Get-VMResourceConfiguration | Set-VMResourceConfiguration -MemReservationMB 0 -MemLimitMB $null If (Get-Folder $_.Description) { Move-VM -VM $_.Name -Destination $_.Description } ElseIf (Get-Folder Staging) { Move-VM -VM $_.Name -Destination Staging } Else { "`n++ $(Get-Date) - Folder ""Staging"" does not exist. The VM will be in the Datacenter root folder." } } # end % Write-Output "`n++ $(Get-Date) - Finished deploying." # Dump list of VMs, check Resource Pool $serverlist | % { Get-VM $_.Name } | Select-Object @{n="Cluster";e={$_.VMHost.Parent.Name}},Name,ResourcePool,Folder,NumCpu,MemoryMB,@{n="ProvisionedSpaceGB";e={[int]$_.ProvisionedSpaceGB}},@{n="UsedSpaceGB";e={[int]$_.UsedSpaceGB}} } #end If # Reconnecting to the Virtual Center that the shell session was connected to before running the script. Connect-VIServer $OrginalVIServer.Name # Input file format <# VC,Cluster,Name,Template,ResourcePool,NumCPU,RAMSizeGB,D_DriveSizeGB,VLAN,Application,BusinessUnit,Category,Support,Notes vcenterxxx.fqdn.com,Bed-QADevIntv35,QA-DBHYPESS201,w2k8_std_x64_r2_tmpl,Normal,1,3,50,VLAN350,ESS,Hyperion,QA,Finance,"DEV00nnnnnn- For testing blah blah" #> Write-Output "`n++ $(Get-Date) - Finished Script."
PowerShellCorpus/PoshCode/Debug Regex match.ps1
Debug Regex match.ps1
<# .SYNOPSIS A very simple function to debug a Regex search operation and show any 'Match' results. .DESCRIPTION Sometimes it is easier to correct any regex usage if each match can be shown in context. This function will show each successful result in a separate colour, including the strings both before and after the match. Using the -F switch will allow only the first of any matches to be returned. .EXAMPLE Debug-Regex '\\b[A-Z]\\w+' 'Find capitalised Words in This string' -first Use the -F switch to return only the first match. MATCHES ---------------<match>-------------------- 1 [<Find> capitalised Words in This string] .EXAMPLE Debug-Regex '\\b[0-9]+\\b' 'We have to find numbers like 123 and 456 in this' MATCHES ---------------<match>-------------------- 1 [We have to find numbers like <123> and 456 in this] 2 [We have to find numbers like 123 and <456> in this] .NOTES Based on an idea from the book 'Mastering Regular Expressions' by J.Friedl, page 429. #> function Debug-Regex { param ([Parameter(mandatory=$true)][regex]$regex, [Parameter(mandatory=$true)][string]$string, [switch]$first) $m = $regex.match($string) if (!$m.Success) { Write-Host "No Match using Regex '$regex'" -Fore Yellow return } $count = 1 Write-Host "MATCHES ---------------<" -Fore Yellow -NoNewLine Write-Host "match" -Fore White -NoNewLine Write-Host ">--------------------" -Fore Yellow while ($m.Success) { Write-Host "$count $($m.result('[$`<'))" -Fore Yellow -NoNewLine Write-Host "$($m.result('$&'))" -Fore White -NoNewLine Write-Host "$($m.result('>$'']'))" -Fore Yellow if ($first) { return } $count++ $m = $m.NextMatch() } }
PowerShellCorpus/PoshCode/PowerShell_ISE Profile.ps1
PowerShell_ISE Profile.ps1
#-------------------------------------------------------------------------------------------------------------- #Convert Untitled1.ps1 to ASCII encoding $psise.CurrentPowerShellTab.Files | % { # set private field which holds default encoding to ASCII $_.gettype().getfield("encoding","nonpublic,instance").setvalue($_, [text.encoding]::ascii) } # watch for changes to the Files collection of the current Tab register-objectevent $psise.CurrentPowerShellTab.Files collectionchanged -action { # iterate ISEFile objects $event.sender | % { # set private field which holds default encoding to ASCII $_.gettype().getfield("encoding","nonpublic,instance").setvalue($_, [text.encoding]::ascii) } } #--------------------------------------------------------------------------------------------------------------
PowerShellCorpus/PoshCode/Get-Parameter 1.21.ps1
Get-Parameter 1.21.ps1
function Get-Parameter { [OutputType('System.String')] [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String]$Command, [Parameter(Position=1)] [String[]]$Name=@('*'), [Parameter()] [ValidateSet('Name','Type','Pos','BV','BP','DV','Aliases','Mandatory','Dynamic')] [String]$SortBy='Name', [Parameter()] [switch]$Descending, [Parameter()] [ValidateSet('Filter','Cmdlet','Function','Alias','ExternalScript')] [String]$CommandType, [switch]$IncludeCommonParameters ) Process { if($CommandType) { switch($CommandType) { "function" { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType} } "filter" { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType} } default { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue } } } else { $cmd = Get-Command -Name $Command -CommandType Cmdlet,Function,Alias,ExternalScript -ErrorAction SilentlyContinue } if(!$cmd) { Throw "'$Name' is not a Cmdlet,Function,Filter,Alias or ExternalScript" } if($cmd.length -gt 1) { $types = $cmd | Select-Object -ExpandProperty CommandType -Unique Throw "'$Command' is ambiguous and matches one of $($types -join ","). Use -CommandType to get only a specified type of command." } if($cmd.CommandType -eq 'Alias') { Write-Verbose "'$Name' refers to an Alias, reolving command." $cmd = Get-Command -Name $cmd.ResolvedCommandName } foreach($set in $cmd.ParameterSets) { if($IncludeCommonParameters) { [array]$p = $set.Parameters | Select-Object * } else { # Get a list of common parameters $cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name [array]$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object * } if($p.count -le 0 -and !$IncludeCommonParameters) { Write-Warning "The specified cmdlet ('$cmd') has no parameters." return } $params = $p | Foreach-Object {$_.Name} for($i=0;$i -le $p.length;$i++) { $flag=$false for($x=0;$x -le $params[$i].length -and !($flag);$x++) { $regex = "^" + $params[$i].substring(0,$x) if(($params -match $regex).count -eq 1) { $flag=$true $p[$i].Aliases += $regex.substring(1).ToLower() } } } $p | Where-Object {$_.Name -like $Name} | Foreach-Object { $PropertyName = $_.Name $psn = $_.Attributes | Where-Object {$_.ParameterSetName} if($psn.ParameterSetName -notmatch '__AllParameterSets') { $PropertyName="*$PropertyName" } New-Object PSObject -Property @{ ParameterSet = $(if ($set.IsDefault) { $set.Name + ' *' } else { $set.Name }) Name = $PropertyName BV = $_.ValueFromPipeline BP = $_.ValueFromPipelineByPropertyName Type = $_.ParameterType.Name Aliases = $_.Aliases Pos = if($_.Position -lt 0) {'Named'} else {$_.Position+1} Mandatory = $_.IsMandatory Dynamic = $_.IsDynamic } } | Sort-Object -Descending:$Descending {$_.$SortBy -replace '\\*'} | Format-Table Name,Type,Pos,BV,BP,Aliases,Mandatory,Dynamic -AutoSize -GroupBy ParameterSet | Out-String } } } Set-Alias -Name gprm -Value Get-Parameter
PowerShellCorpus/PoshCode/Get-App 1.1.ps1
Get-App 1.1.ps1
## Get-App ## Attempt to resolve the path to an executable using Get-Command and the AppPaths registry key ################################################################################################## ## Example Usage: ## Get-App Notepad ## Finds notepad.exe using Get-Command ## Get-App pbrush ## Finds mspaint.exe using the "App Paths" registry key ## &(Get-App WinWord) ## Finds, and launches, Word (if it's installed) using the "App Paths" registry key ################################################################################################## ## Revision History ## 1.0 - initial release ## 1.1 - strip quotes from results... ## - NOTE: should be used with the "which" script to return the correct item in the case ## where you're calling an app that would show up in the normal Get-Command... ## http://powershellcentral.com/scripts/173 ################################################################################################## #function Get-App { param( [string]$cmd ) $command = $null $eap = $ErrorActionPreference $ErrorActionPreference = "SilentlyContinue" $command = Get-Command $cmd | Select -First 1 $ErrorActionPreference = $eap if($command -eq $null) { $AppPaths = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths" if(!(Test-Path $AppPaths\\$cmd)) { $cmd = [IO.Path]::GetFileNameWithoutExtension($cmd) if(!(Test-Path $AppPaths\\$cmd)){ $cmd += ".exe" } } if(Test-Path $AppPaths\\$cmd) { $default = (Get-ItemProperty $AppPaths\\$cmd)."(default)" if($default) { Get-Command $default.Trim("""'") } } } #}
PowerShellCorpus/PoshCode/Invert-MouseWheel.ps1
Invert-MouseWheel.ps1
Get-ItemProperty HKLM:\\SYSTEM\\CurrentControlSet\\Enum\\HID\\*\\*\\Device` Parameters FlipFlopWheel -EA 0 | ForEach-Object { Set-ItemProperty $_.PSPath FlipFlopWheel 1 }
PowerShellCorpus/PoshCode/Write-Log_6.ps1
Write-Log_6.ps1
function Write-Log { #region Parameters [cmdletbinding()] Param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $Message, [Parameter()] [ValidateSet(ōErrorö, ōWarnö, ōInfoö)] [string] $Level = ōInfoö, [Parameter()] [Switch] $NoConsoleOut, [Parameter()] [ValidateSet("Black", "DarkMagenta", "DarkRed", "DarkBlue", "DarkGreen", "DarkCyan", "DarkYellow", "Red", "Blue", "Green", "Cyan", "Magenta", "Yellow", "DarkGray", "Gray", "White")] [String] $ConsoleForeground = 'White', [Parameter()] [ValidateRange(1,30)] [Int16] $Indent = 0, [Parameter()] [IO.FileInfo] $Path = ö$env:temp\\PowerShellLog.txtö, [Parameter()] [Switch] $Clobber, [Parameter()] [ValidateSet("Application","System","Security")] [String] $EventLogName, [Parameter()] [String] $EventSource, [Parameter()] [Int32] $EventID = 1, [Parameter()] [String] $LogEncoding = "ASCII" ) #endregion Begin {} Process { try { $msg = "{0}`t{1}`t{2}{3}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level.ToUpper(), (" " * $Indent), $Message if ($NoConsoleOut -eq $false) { switch ($Level) { 'Error' { Write-Error $Message } 'Warn' { Write-Warning $Message } 'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground} } } if (-not $Path.Exists) { New-Item -Path $Path.FullName -ItemType File -Force | Out-Null } if ($Clobber) { $msg | Out-File -FilePath $Path -Encoding $LogEncoding -Force } else { $msg | Out-File -FilePath $Path -Encoding $LogEncoding -Append } if ($EventLogName) { if (-not $EventSource) { $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name } if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) } $log = New-Object System.Diagnostics.EventLog $log.set_log($EventLogName) $log.set_source($EventSource) switch ($Level) { ōErrorö { $log.WriteEntry($Message, 'Error', $EventID) } ōWarnö { $log.WriteEntry($Message, 'Warning', $EventID) } ōInfoö { $log.WriteEntry($Message, 'Information', $EventID) } } } } catch { throw ōFailed to create log entry in: æ$PathÆ. The error was: æ$_Æ.ö } } End {} <# .SYNOPSIS Writes logging information to screen and log file simultaneously. .DESCRIPTION Writes logging information to screen and log file simultaneously. Supports multiple log levels. .PARAMETER Message The message to be logged. .PARAMETER Level The type of message to be logged. .PARAMETER NoConsoleOut Specifies to not display the message to the console. .PARAMETER ConsoleForeground Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified. .PARAMETER Indent The number of spaces to indent the line in the log file. .PARAMETER Path The log file path. .PARAMETER Clobber Existing log file is deleted when this is specified. .PARAMETER EventLogName The name of the system event log, e.g. 'Application'. .PARAMETER EventSource The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER EventID The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER LogEncoding The text encoding for the log file. Default is ASCII. .EXAMPLE PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application' .EXAMPLE PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script" .INPUTS System.String .OUTPUTS No output. .NOTES Revision History: 2011-03-10 : Andy Arismendi - Created. 2011-07-23 : Will Steele - Updated. 2011-07-23 : Andy Arismendi - Added missing comma in param block. - Added support for creating missing directories in log file path. 2012-03-10 : Pat Richard - Added validation sets to $ConsoleForeground and $EventLogName - Changed formatting of $msg so that only $message is indented instead of entire line (looks cleaner) - suppressed output when creating path/file #> }
PowerShellCorpus/PoshCode/7511f2db-9f71-4daf-8971-f1ab6eb2a6af.ps1
7511f2db-9f71-4daf-8971-f1ab6eb2a6af.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/Write-ProgressForm.ps1
Write-ProgressForm.ps1
function Write-ProgressForm { <# .SYNOPSIS Write-ProgressForm V1.0 GUI Replacement for PowerShell's Write-Progress command .DESCRIPTION GUI Replacement for PowerShell's Write-Progress command Uses same named parameters for drop-in replacement CAVEATS: You can't close the Form by clicking on it, must call Write-ProgressForm -Completed Therefore decided to hide Close button (why tease people?) .INPUTS Same as Write-Progress command BONUS: -ICOpath <path to your ICO> -FormTitle <Title of the Write-progress form> (Only needs to be mentioned when 1st called then it sticks around) .OUTPUTS Nothing but a GUI .NOTES Uses Global variables extensively License: GPL v3.0 or greater / BSD (Latest version) Form Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 Generated On: 30/01/2013 12:38 PM Generated By: Denis St-Pierre, Ottawa, Canada #> param( #parameters with default values assigned [String]$Activity="Activity", [String]$CurrentOperation="CurrentOperation", [String]$status="Status", [Int]$PercentComplete=0, [switch]$Completed=$false, [int]$FontSize = 10, [String]$ICOpath="", #yes, you can use your *OWN* icon file in the form [String]$FormTitle="" ) $HideUselessCloseButton=$true #Change to false if you can fix it, pls $UselessAutoSize=$false #Useless because it doesn't work as expected #If WriteProgressForm variable exists, use it. If ( Get-Variable -Name WriteProgressForm -Scope Global -ErrorAction SilentlyContinue ) { If ( $Completed){ #If asked to close, do it $progressBar1.Value=100 $StatusLabel.Text = "Complete" Start-Sleep -Seconds 1 $WriteProgressForm.close() Return } else { #otherwise, Update it $progressBar1.Value = $PercentComplete #To update Progress bar position $ActivityLabel.Text = "$Activity" $CurrentOperationLabel.Text = "$CurrentOperation" $StatusLabel.Text = "$status" Return } } #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $global:WriteProgressForm = New-Object System.Windows.Forms.Form $global:StatusLabel = New-Object System.Windows.Forms.Label $CloseButton = New-Object System.Windows.Forms.Button $global:progressBar1 = New-Object System.Windows.Forms.ProgressBar $global:CurrentOperationLabel = New-Object System.Windows.Forms.Label $global:ActivityLabel = New-Object System.Windows.Forms.Label $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. # $WriteProgressForm.close()= # { #TODO: Place custom script here # } $CloseButton_OnClick= { #TODO: Place custom script here } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $WriteProgressForm.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $WriteProgressForm.AccessibleDescription = "WriteProgressFormDesc" $WriteProgressForm.AccessibleName = "WriteProgressForm" $WriteProgressForm.AccessibleRole = 48 $WriteProgressForm.AutoSize = $true #works on forms, labels not so much $WriteProgressForm.AutoSizeMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 170 # $System_Drawing_Size.Width = 505 # $WriteProgressForm.ClientSize = $System_Drawing_Size $WriteProgressForm.DataBindings.DefaultDataSourceUpdateMode = 0 $WriteProgressForm.StartPosition = 1 #Center of the Screen #add Icon to dialog, if possible If ( ($ICOpath -ne "") -and (Test-Path "$ICOpath") ) { Try { #If the ICO file is NFG, ignore and move on $WriteProgressForm.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon("$ICOpath") } catch { } #use default ICO } $WriteProgressForm.Name = "WriteProgressForm" $WriteProgressForm.Text = "$FormTitle" # $WriteProgressForm.add_FormClosing($WriteProgressForm.close()) #failed attempt to make CloseButton work w/o PS code # ** $StatusLabel $StatusLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 33 $StatusLabel.Location = $System_Drawing_Point $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 475 $StatusLabel.MinimumSize = $System_Drawing_Size $StatusLabel.AutoSize = $UselessAutoSize $StatusLabel.Name = "StatusLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $StatusLabel.Padding = $System_Windows_Forms_Padding # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 475 # $StatusLabel.Size = $System_Drawing_Size $StatusLabel.TabIndex = 4 $StatusLabel.Text = "$status" $WriteProgressForm.Controls.Add($StatusLabel) # ** $CloseButton $CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 400 $System_Drawing_Point.Y = 134 $CloseButton.Location = $System_Drawing_Point $CloseButton.Name = "CloseButton" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 25 $System_Drawing_Size.Width = 90 $CloseButton.Size = $System_Drawing_Size $CloseButton.TabIndex = 3 $CloseButton.Text = "Close" $CloseButton.UseVisualStyleBackColor = $True $CloseButton.add_Click($CloseButton_OnClick) # $CloseButton.add_MouseClick($WriteProgressForm.close()) #failed attempt #2 to make CloseButton work w/o PS code If ($HideUselessCloseButton) { #dont add button to form } else { $WriteProgressForm.Controls.Add($CloseButton) } # ** $progressBar1 $progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 10 $System_Drawing_Point.Y = 57 $progressBar1.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 5 $System_Windows_Forms_Padding.Bottom = 5 $System_Windows_Forms_Padding.Left = 5 $System_Windows_Forms_Padding.Right = 5 $System_Windows_Forms_Padding.Top = 5 $progressBar1.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 30 $System_Drawing_Size.Width = 480 $progressBar1.MinimumSize = $System_Drawing_Size $progressBar1.AutoSize = $UselessAutoSize #doesn't work, stays the same size $progressBar1.Name = "progressBar1" # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 30 # $System_Drawing_Size.Width = 480 # $progressBar1.Size = $System_Drawing_Size $progressBar1.Step = 1 $progressBar1.Style = 1 $progressBar1.TabIndex = 2 $progressBar1.Value = $PercentComplete #Progress bar position $WriteProgressForm.Controls.Add($progressBar1) # ** $CurrentOperationLabel $CurrentOperationLabel.AccessibleDescription = "CurrentOperationDesc" $CurrentOperationLabel.AccessibleName = "CurrentOperation" $CurrentOperationLabel.AccessibleRole = 0 $CurrentOperationLabel.CausesValidation = $False $CurrentOperationLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 100 $CurrentOperationLabel.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $CurrentOperationLabel.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 475 $CurrentOperationLabel.MinimumSize = $System_Drawing_Size $CurrentOperationLabel.AutoSize = $UselessAutoSize $CurrentOperationLabel.Name = "CurrentOperationLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $CurrentOperationLabel.Padding = $System_Windows_Forms_Padding # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 475 # $CurrentOperationLabel.Size = $System_Drawing_Size $CurrentOperationLabel.TabIndex = 1 $CurrentOperationLabel.Text = "$CurrentOperation" $WriteProgressForm.Controls.Add($CurrentOperationLabel) # ** $ActivityLabel # $ActivityLabel.CausesValidation = $False $ActivityLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 10 $System_Drawing_Point.Y = 10 $ActivityLabel.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $ActivityLabel.Margin = $System_Windows_Forms_Padding $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 480 $ActivityLabel.MinimumSize = $System_Drawing_Size $ActivityLabel.Name = "ActivityLabel" $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 1 $System_Windows_Forms_Padding.Bottom = 1 $System_Windows_Forms_Padding.Left = 1 $System_Windows_Forms_Padding.Right = 1 $System_Windows_Forms_Padding.Top = 1 $ActivityLabel.Padding = $System_Windows_Forms_Padding $ActivityLabel.AutoSize = $UselessAutoSize # $System_Drawing_Size = New-Object System.Drawing.Size # $System_Drawing_Size.Height = 20 # $System_Drawing_Size.Width = 480 # $ActivityLabel.Size = $System_Drawing_Size $ActivityLabel.TabIndex = 0 $ActivityLabel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",$FontSize,1,3,1) $ActivityLabel.Text = "$Activity" $WriteProgressForm.Controls.Add($ActivityLabel) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $WriteProgressForm.WindowState #Init the OnLoad event to correct the initial state of the form $WriteProgressForm.add_Load($OnLoadForm_StateCorrection) #Show the Form # $WriteProgressForm.ShowDialog()| Out-Null #ShowDialog waits until it is closed $WriteProgressForm.Show() #show form and keep on going $WriteProgressForm.activate() #Make sure its on top Start-sleep -Milliseconds 500 #was needed to give time for form to fully draw itself } #End Function #Clean up global WriteProgressForm variables before try { $WriteProgressForm.close() Remove-Variable StatusLabel | Out-Null Remove-Variable CurrentOperationLabel | Out-Null Remove-Variable progressBar1 | Out-Null Remove-Variable ActivityLabel | Out-Null Remove-Variable WriteProgressForm } catch { #go on } $ScopeNum=0 $Scope=0 $TotalNumScopes=100 #Foreach ($DHCPScope in $ObjDHCPscopes){ for ($PCcomplete=1; $PCcomplete -lt 100; $PCcomplete++) { $ScopeName="ScopeName" $Scope=$Scope+1 #increment $CurrentOperation="*CurOp*Getting Leases from scope $ScopeName" $Status="*Status*$PCcomplete% complete. ($Scope of $TotalNumScopes)" # Write-Progress -Activity "*Act*Building list from DHCP server ..." -status $status -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" Write-ProgressForm -Activity "*Act*Building list from DHCP server ... Building list from DHCP server... Building list from DHCP server ..." -status $status -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" Start-sleep -Milliseconds 050 } $PCcomplete=100 $CurrentOperation="complete" #Write-Progress -Activity "Building list from DHCP server ..." -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" -Status "$PCcomplete% complete." Write-ProgressForm -Activity "Building list from DHCP server ..." -PercentComplete $PCcomplete -CurrentOperation "$CurrentOperation" -Status "$PCcomplete% complete." Start-sleep -seconds 1 #Write-Progress -Activity "Complete" -Completed -Status "Complete" Write-ProgressForm -Activity "Complete" -Completed -Status "Complete"
PowerShellCorpus/PoshCode/Compare-Agents.ps1
Compare-Agents.ps1
#This scripts compares the agents that are installed in two zones and #gives the agents that are not common. #Usage: #Compare-Agents.ps1 -server1 RMSServer1.contoso.com -server2 RMSServer2.contoso.com -output c:\\Temp.txt #RMSServer1 is the one whose agents are to be moved. param([string] $Server1,$Server2,$output) Function Mainone { write-host $Server1 write-host $Server2 $Temp1 = $Server1 $Temp2 = $Server2 $outfilepath = $output New-Managementgroupconnection $Temp1 set-location monitoring:\\$Temp1 $AllServer1Agents = get-agent $RMSServer1 = get-RootManagementServer write-host "Got all the agents for the first group" $RMS1name = $RMSServer1.Computername $data1 = "All the agents on " + $RMS1name New-Managementgroupconnection $Temp2 set-location monitoring:\\$Temp2 $AllServer2Agents = get-agent $RMSServer2 = get-RootManagementServer write-host "Got all the agents for the second group" #Write-data $RMSServer.ManagementGroup.name $RMS2name = $RMSServer2.Computername $data2 = "All the agents on " + $RMS2name #write-data $data2 #foreach($Agent in $AllServer2Agents) { write-data $Agent.computername} write-host "Calling the function to compare Agents" CheckAgent $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name } Function CheckAgent($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name) { write-host "Calling function to get all agents in an array" Get-Agentnames $AllServer1Agents $AllServer2Agents $RMS1name $RMS2name } Function Get-Agentnames($AllServer1Agents,$AllServer2Agents,$RMS1name,$RMS2name) { $Server1Agent = @() $Server2Agent = @() foreach($A in $AllServer1Agents) { $Server1Agent = $Server1Agent + $A.Computername } foreach($B in $AllServer2Agents) { $Server2Agent = $Server2Agent + $B.Computername } Compare-theAgents $Server1Agent $Server2Agent } function Compare-theAgents($Server1Agent,$Server2Agent) { $FoundAgent = @() $NotFoundAgent = @() for($i=0; $i -lt $Server1Agent.count; $i++) { $Temp1 = $Server1Agent[$i] $Data = "Comparing element " + $Server1Agent[$i] write-host $Data for($j=0; $j -lt $Server2Agent.count; $j++) { $Temp2 = $Server2Agent[$j] #write-host $Temp2 if($Temp1 -match $Temp2) { $FoundAgent = $FoundAgent + $Temp1 $Server1Agent[$i] = "Present" } } } for($k=0; $k -lt $Server1Agent.count; $k++) { if($Server1Agent[$k] -notmatch "Present") { $NotfoundAgent = $NotFoundAgent + $Server1Agent[$k] } } write-data "These are the agents that are found common" for($k=0;$k -lt $FoundAgent.count;$k++){write-data $FoundAgent[$k]} write-data "These are the agents that are not found" for($l=0;$l -lt $NotFoundAgent.count;$l++){write-data $NotFoundAgent[$l]} } function write-data($Writedata) { out-file -filepath $outfilepath -inputobject $Writedata -append -encoding ASCII } Mainone
PowerShellCorpus/PoshCode/PowerOAuth 1.0.ps1
PowerOAuth 1.0.ps1
#requires -Version 2.0 #requires -Module HttpRest -Version 1.2 # http`://poshcode.org/1262 Set-StrictMode -Version 2.0 $null = [Reflection.Assembly]::LoadWithPartialName('System.Web') $safeChars = [char[]]'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~' function Get-OAuthBase { #.Synopsis # Get the basic OAuth Authorization values #.Parameter ConsumerKey # The OAuth Consumer Key #.Parameter AccessToken # The OAuth Access token #.ReturnValue # A HashTable containing the key-value pairs needed for further requests, including the oauth_consumer_key, oauth_signature_method, oauth_timestamp, oauth_nonce, oauth_version, and optionally, the oauth_token. PARAM( [Parameter(Mandatory=$true)]$ConsumerKey , [Parameter(Mandatory=$false)]$AccessToken ) END { @{ oauth_consumer_key = Format-OAuth $ConsumerKey oauth_signature_method = 'HMAC-SHA1' # The signature method the Consumer used to sign the request oauth_timestamp = [int]((Get-Date).ToUniversalTime() - (Get-Date 1/1/1970)).TotalSeconds oauth_nonce = [guid]::NewGuid().GUID -replace '-' oauth_version = '1.0' # OPTIONAL: If present, value MUST be 1.0 } + $(if($AccessToken){ @{oauth_token = $AccessToken } } else { @{} }) # $FFAccessToken.oauth_token }} function Format-OAuth { #.Synopsis # UrlEncode, but with upper-case hex #.Parameter value # The text to encode PARAM([Parameter(ValueFromPipeline=$true)][string]$value) PROCESS { $result = New-Object System.Text.StringBuilder foreach($c in $value.ToCharArray()){ if($safeChars -notcontains $c) { $null = $result.Append( ('%{0:X2}' -f [int]$c) ) } else { $null = $result.Append($c) } } write-output $result.ToString() }} function ConvertTo-Hashtable { #.Synopsis # Convert a query string into a hashtable #.Parameter string # The query string to convert #.Parameter PairSeparator # The string separating each set of key=value pairs #.Parameter KeyValueSeparator # The string separating the keys from the values #.ReturnValue # The hashtable created from reading the query string PARAM( [Parameter(ValueFromPipeline=$true, Position=0, Mandatory=$true)] [String] $string , [Parameter(Position=1)] [String] $PairSeparator = '&' , [Parameter(Position=2)] [String] $KeyValueSeparator = '=' ) PROCESS { $result = @{} foreach($w in $string.split($pairSeparator) ) { $k,$v = $w.split($KeyValueSeparator,2) $result.Add($k,$v) } write-output $result } } function ConvertFrom-Hashtable { #.Synopsis # Convert a hashtable into a query string #.Description # Converts a hashtable into a query string by joining the keys to the values, and then joining all the pairs together #.Parameter values # The hashtable to convert #.Parameter PairSeparator # The string used to concatenate the sets of key=value pairs, defaults to "&" #.Parameter KeyValueSeparator # The string used to concatenate the keys to the values, defaults to "=" #.ReturnValue # The query string created by joining keys to values and then joining them all together into a single string PARAM( [Parameter(ValueFromPipeline=$true, Position=0, Mandatory=$true)] [Hashtable] $Values , [Parameter(Position=1)] [String] $pairSeparator = '&' , [Parameter(Position=2)] [String] $KeyValueSeparator = '=' , [string[]]$Sort ) PROCESS { [string]::join($pairSeparator, @( if($Sort) { foreach( $kv in $Values.GetEnumerator() | Sort $Sort) { if($kv.Name) { '{0}{1}{2}' -f $kv.Name, $KeyValueSeparator, $kv.Value } } } else { foreach( $kv in $Values.GetEnumerator()) { if($kv.Name) { '{0}{1}{2}' -f $kv.Name, $KeyValueSeparator, $kv.Value } } } )) }} function ConvertTo-OAuthSignatureBase { #.Synopsis # An internal function to build up the string needed for the OAuth Signature PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [hashtable] $Parameters =@{} , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" # , # [System.Management.Automation.PSCredential] # $Credential ) BEGIN { trap { continue } if(!$Uri.IsAbsoluteUri) { $Uri= Join-Url $global:url $Uri Write-Verbose "Relative URL, appending to $($global:url) to get: $Uri" } } END { $normalizedUrl = ("{0}://{1}" -f $Uri.Scheme, $Uri.Host).ToLower() if (!(($Uri.Scheme -eq "http" -and $Uri.Port -eq 80) -or ($Uri.Scheme -eq "https" -and $Uri.Port -eq 443))) { $normalizedUrl += ":" + $Uri.Port } $normalizedUrl += $Uri.AbsolutePath write-output $normalizedUrl if($Uri.Query) { $Parameters += $(ConvertTo-Hashtable $Uri.Query.trim("?")) } $normalizedRequestParameters = Format-OAuth (ConvertFrom-Hashtable $Parameters -Sort "Name","Value") ## DEBUG Write-Host $normalizedRequestParameters -fore yellow write-output $normalizedRequestParameters $result = New-Object System.Text.StringBuilder $null = $result.AppendFormat("{0}&", $verb.ToUpper() ) $null = $result.AppendFormat("{0}&", $(Format-OAuth $normalizedUrl) ) $null = $result.AppendFormat("{0}", $normalizedRequestParameters) ## DEBUG Write-Host $result.ToString() -fore cyan write-output $result.ToString(); } } function Get-OAuthSignature { #.Synopsis # An internal function to calculate the OAuth Signature using the HMAC-SHA1 algorithm #.Parameter Verb # The HTTP verb which will be invoked is the first part of the OAuth Signature string (defaults to GET) #.Parameter Uri # The URI which will be queried is the second part of the OAuth Signature string #.Parameter Parameters # All of the parameters which will be passed (regardless of how they will be passed) in hashtable format. The OAuth Base Authorization parameters are not included here, they will be set by this function #.Parameter ConsumerKey # The OAuth Consumer Key (a key specific to the application requesting access) #.Parameter ConsumerSecret # The OAuth Consumer Secret (the secret part of the application's consumer key shouldn't be given to end users) #.Parameter AccessToken # The OAuth Access Token (if you're already authenticated) #.Parameter ConsumerSecret # The OAuth Access Secret (the secret part of the access token, if you're already authenticated) PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [hashtable] $Parameters =@{} , [Parameter(Mandatory=$true)] [string] $ConsumerKey = "key" , [Parameter(Mandatory=$true)] [string] $ConsumerSecret = "secret" , [Parameter(Mandatory=$false)] [string] $AccessToken = "" , [Parameter(Mandatory=$false)] [string] $AccessSecret = "" , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" # , # [System.Management.Automation.PSCredential] # $Credential ) END { @($Parameters.Keys) | % { $Parameters.$_ = @($Parameters.$_) | %{ Format-OAuth $_ } } $Parameters += Get-OAuthBase $ConsumerKey $AccessToken $url, $query, $sigbase = ConvertTo-OAuthSignatureBase -Uri $Uri -Parameters $Parameters -Verb $Verb Write-Verbose $sigbase Write-Output $url, $Parameters $sha = new-object System.Security.Cryptography.HMACSHA1 $sha.Key = [System.Text.Encoding]::Ascii.GetBytes( ('{0}&{1}' -f $(Format-OAuth $ConsumerSecret),$(Format-OAuth $AccessSecret)) ) Write-Output $([Convert]::ToBase64String( $sha.ComputeHash( [System.Text.Encoding]::Ascii.GetBytes( $sigbase ) ) )) }} function Invoke-OAuthHttp { #.Synopsis # The primary OAuth function #.Parameter Uri # The URI which will be invoked against #.Parameter Parameters # All of the additional parameters which will be passed (regardless of how they will be passed) in hashtable format. Obviously the OAuth Base access parameters are not included here, they will be set by this function #.Parameter ConsumerKey # The OAuth Consumer Key (a key specific to the application requesting access) #.Parameter ConsumerSecret # The OAuth Consumer Secret (the secret part of the application's consumer key shouldn't be given to end users) #.Parameter AccessToken # The OAuth Access Token (if you're already authenticated) #.Parameter ConsumerSecret # The OAuth Access Secret (the secret part of the access token, if you're already authenticated) #.Parameter Verb # The HTTP verb which will be invoked (defaults to GET) PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [HashTable] $Parameters =@{} , [Parameter(Mandatory=$true)] [string] $ConsumerKey = "key" , [Parameter(Mandatory=$true)] [string] $ConsumerSecret = "secret" , [Parameter(Mandatory=$false)] [string] $AccessToken = "" , [Parameter(Mandatory=$false)] [string] $AccessSecret = "" , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" ) END { $parameters.format = "xml" if($AccessToken -and $AccessSecret) { $script:url, $script:Headers, $script:sig = Get-OAuthSignature -Uri $Uri -Parameters $Parameters ` -ConsumerKey $ConsumerKey ` -ConsumerSecret $ConsumerSecret ` -AccessToken $AccessToken ` -AccessSecret $AccessSecret ` -Verb $Verb.ToUpper() } else { $script:url, $script:Headers, $script:sig = Get-OAuthSignature -Uri $Uri -Parameters $Parameters ` -ConsumerKey $ConsumerKey ` -ConsumerSecret $ConsumerSecret ` -Verb $Verb.ToUpper() } $Headers += @{ oauth_signature = Format-OAuth $sig } $Parameters.Keys | %{ $Headers.Remove($_) } $WithHeader = @{ Authorization="OAuth {0}`"" -f $(ConvertFrom-Hashtable $Headers "`", " "=`"") } switch($Verb) { "POST" { $plug = Get-DreamPlug $Uri.AbsoluteUri -Headers $WithHeader $script:result = Invoke-Http "POST" -Plug $plug -Content ([HashTable]$Parameters) | Receive-Http Xml } "GET" { $plug = Get-DreamPlug $Uri.AbsoluteUri -Headers $WithHeader -With $Parameters $script:result = Invoke-Http "GET" -Plug $plug | Receive-Http Xml } } ## Freakydeaky magic pulls an access hashtable out of it's hat if(!$AccessToken -and $result.html -and $result.html -match "oauth_token_secret") { $result.html | ConvertTo-Hashtable } else { $result } } } # http`://oauth.net/core/1.0#auth_step3 # # A good place to practice: http`://term.ie/oauth/example/ # # The reason I started playing: http`://friendfeed.com/api/documentation # http`://friendfeed.com/api/applications/6a3c26fe1af047bb9553b3098bee5867 # # One other resource I found helpful (I had to make a few enhancements to HttpRest): # http`://blog.developer.mindtouch.com/2009/08/05/async-io-dream-vs-parallel-extensions/ # And thanks to http`://oauth.googlecode.com/svn/code/csharp/ # And thanks to http`://oauth.googlecode.com/svn/code/python/oauth/
PowerShellCorpus/PoshCode/get-ipinformation.ps1
get-ipinformation.ps1
function get-ipinformation { process { (Get-WmiObject Win32_NetworkAdapterConfiguration -computer $_ ) | ? { $_.IPenabled } | select (AS Server , __server, DNSHostName , DNSHostName , Mac , Macaddress, Description, Description, DNSDomain , DNSDomain, FirstIPAddress ,{ ($_.IPAddress) | select -first 1 }, IPAddressAll , { [string] $_.IPAddress} , IPSubnet , {($_.IPSubnet) | select -first 1 } , IPSubnetall , { [string] $_.IPSubnet }, DefaultIPGateway, { ($_.DefaultIPGateway) | select -first 1 } , DefaultIPGatewayALL, { [string] $_.DefaultIPGateway }, DHCPEnabled , { [bool] $_.DHCPEnabled }, DHCPServer, DHCPServer, PrimaryDNSServer , { ( $_.DNSServerSearchOrder)[0] }, SecondaryDNSServer , { ( $_.DNSServerSearchOrder)[1] }, AllDNSServer , { [string] $_.DNSServerSearchOrder }, WINSPrimaryServer , WINSPrimaryServer, WINSSecondaryServer , WINSSecondaryServer, #random ones DomainDNSRegistrationEnabled , DomainDNSRegistrationEnabled, FullDNSRegistrationEnabled , FullDNSRegistrationEnabled, DNSDomainSuffixSearchOrder, DNSDomainSuffixSearchOrder, WINSEnableLMHostsLookup , WINSEnableLMHostsLookup ) } } #requires the follow function function new-selectexpression { if ($args.count -eq 1) { $theargs = $args[0] } else {$theargs= $args } if ($theargs.count -gt 1) { for($loop=0;$loop -lt ($theargs.count-1);$loop+=2) { @{Name=$theargs[$loop];Expression=$theargs[$loop+1]} } } if (!($theargs.count % 2) -eq 0) {@{Name=$input[$input.count-1];Expression= invoke-Expression "{}" } } }
PowerShellCorpus/PoshCode/Set-Writable.ps1
Set-Writable.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author>Keith Hill</Author> ### <Description> ### This filter can be used to change a file's read only status. ### </Description> ### <Usage> ### Set-Writable foo.txt ### Set-Writable [a-h]*.txt -passthru ### Get-ChildItem bar[0-9].txt | Set-Writable ### </Usage> ### </Script> # --------------------------------------------------------------------------- param($Path, [switch]$PassThru, [switch]$Verbose) begin { if ($args -eq '-?') { "" "Usage: Set-Writable [[-Path] <object>] [[-PassThru] <switch>] [[-Verbose] <switch>]" "" "Parameters:" " -Path : Path of files or FileInfo objects to make writable" " -PassThru : Pass the input object down the pipeline" " -Verbose : Display verbose information" " -? : Display this usage information" "" return } if ($verbose) { $VerbosePreference = 'Continue' } function MakeFileWritable($files) { foreach ($file in @($files)) { if ($file -is [System.IO.FileInfo]) { if ($verbose) { Write-Verbose "Set-Writable processing $file" } $file.IsReadOnly = $false if ($passThru) { $file } } elseif ($file -is [string]) { $rpaths = @(Resolve-Path $file -ea SilentlyContinue) foreach ($rpath in $rpaths) { if ($verbose) { Write-Verbose "Set-Writable processing $rpath" } $fileInfo = New-Object System.IO.FileInfo $rpath $fileInfo.IsReadOnly = $false if ($passThru) { $file } } } else { Write-Error "Expected type FileInfo or String, got $($file.psobject.typenames[0]) instead." } } } } process { if ($_) { MakeFileWritable $_ } } end { if ($Path) { MakeFileWritable $Path } }
PowerShellCorpus/PoshCode/Enable-MailboxJunkEmail_1..ps1
Enable-MailboxJunkEmail_1..ps1
# Author: Jon Webster # Name: Enable-MailboxJunkEmail # Created: 1/27/2009 # # Version: 1.0 # History: 1.0 01/27/2009 Initial version param( $Identity, [string]$CasURL, [string]$User, [string]$Password, $DomainController, [switch]$help ) BEGIN { Function Usage { Write-Host @' Enable Server Side Junk E-mail filtering through Outlook Web Access `n Usage: Enable-MailboxJunkEmail -Identity <string> -CasURL <string> -User <string> -Password <string> -DomainController <string> `n Parameters: Identity: The Identity of mailbox who's server side Junk E-mail you want to enable. CasURL: The (OWA) Client Access Server Address of the exchange server you want to use. User: The fullaccess user's 'username' connecting to the mailbox that you want to change. Password: The fullaccess user's 'password' connecting to the mailbox that you want to change. DomainController: The fully qualified domain name (FQDN) of the domain controller that you want to use. `n Example: Enable-MailboxJunkEmail -Identity "john.doe@consoto.com" -CasURL "mail.consoto.com" -User "CONSOTO\\Administrator" -Password "AdminPassword!" '@ } if($help -or $args -contains "-?") { Usage return } Function ValidateParams { # These required parameters are not passed via pipeline # $Identity $ErrorMessage = "" if(!$CasURL) { $ErrorMessage += "Missing parameter: The -CasURL parameter is required. Please pass a valid Client Access Server Url`n" } if(!$User) { $ErrorMessage += "Missing parameter: The -User parameter is required. Please pass a valid Username for OWA mailbox authentication`n" } if(!$Password) { $ErrorMessage += "Missing parameter: The -Password parameter is required. Please pass a valid password for OWA mailbox authentication`n" } if($ErrorMessage) { throw $ErrorMessage break } } Function ValidatePipeline { if($_) { $ErrorMessage = "" if(!$_.Identity) { $ErrorMessage += "Missing Pipeline property: The Identity property is required." } else { Set-Variable -Name Identity -Scope 1 -Value $_.Identity } if($ErrorMessage) { throw $ErrorMessage break } } } Function UpdateJunk { param ([string]$mbMailbox) $xmlstr = "<params><fEnbl>1</fEnbl></params>" $req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/ev.owa?oeh=1&ns=JunkEmail&ev=Enable", $False) $req.setRequestHeader("Content-Type", "text/xml; charset=""UTF-8""") $req.setRequestHeader("Content-Length", $xmlstr.Length) $req.Send($xmlstr) Write-Debug $req.status Write-Debug $req.GetAllResponseHeaders() if($req.status -ne 200) { Write-Error $req.responsetext return } if($req.responsetext -match "name=lngFrm") { Write-Host "Mailbox has not been logged onto before via OWA" $pattern = "<option selected value=""(.*?)"">" $matches = [regex]::Matches($req.responsetext,$pattern) if($matches.count -eq 2) { $lcidarry = $matches[0].Groups[1].Value Write-Debug $lcidarry $tzidarry = $matches[1].Groups[1].Value Write-Debug $tzidarry $pstring = "lcid=" + $lcidarry + "&tzid=" + $tzidarry $req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/lang.owa", $False) $req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") $req.setRequestHeader("Content-Length", $pstring.Length) # not required? #$req.setRequestHeader("cookie", $reqCadata) # Error here $req.send($pstring) if($req.responsetext -match "errMsg") { # Permission Error Write-Error "Authentication Error" } else { Write-Debug $req.status if($req.status -eq 200 -and $req.responsetext -notmatch "errMsg") { Write-Host "Trying to update the Junk E-mail setting again." UpdateJunk($mbMailbox) Write-Host "Removing OWA Language and Timezone settings..." &{ # We'll get a warning if no properties were modified. # That warning means replication hasn't occurred yet. $warningPreference = "Stop" $script:count = 0 $loop = $true while($loop) { $loop = $false Set-Mailbox $mbMailbox -Languages $null -DomainController $DomainController trap { if($script:count -lt 5) { # Try for up to 20 seconds Write-Debug "Unable to Reset Languages trying again in 5 seconds." Sleep 5 Set-Variable -Name loop -Scope 1 -Value $true $script:count++ } else { Write-Debug "Failed." } continue } } $warningPreference = "Continue" } } else { Write-Warning "Failed to set Default OWA settings" } } } else { Write-Warning "Script failed to retrieve default values" } Write-Host "Junk E-Mail setting Changed Successfully" } } ValidateParams } PROCESS { ValidatePipeline $mbx = Get-Mailbox -Identity $Identity -DomainController $DomainController -ErrorAction SilentlyContinue if(!$mbx) {throw "Invalid Mailbox specified: $Identity"} $szXml = "destination=https://" + $CasURL + "/owa/&flags=0&username=" + $User $szXml = $szXml + "&password=" + $Password + "&SubmitCreds=Log On&forcedownlevel=0&trusted=0" $req = New-Object -COMObject "MSXML2.ServerXMLHTTP.6.0" $req.Open("POST", "https://" + $CasURL + "/owa/auth/owaauth.dll", $False) $req.SetOption(2, 13056) $req.Send($szXml) Write-Debug $req.GetAllResponseHeaders() if($req.responsetext -match "wrng") { Write-Error "The user name or password that you entered is not valid. Try entering it again." return; } UpdateJunk($mbx.PrimarySMTPAddress) }
PowerShellCorpus/PoshCode/ConvertFrom-CliXml.ps1
ConvertFrom-CliXml.ps1
function ConvertFrom-CliXml { param( [parameter(position=0,mandatory=$true,valuefrompipeline=$true)] [validatenotnull()] [string]$string ) begin { $inputstring = "" } process { $inputstring += $string } end { $type = [type]::gettype("System.Management.Automation.Deserializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null) $sr = new-object io.stringreader $inputstring $xr = new-object xml.xmltextreader $sr $deserializer = $ctor.invoke($xr) $method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1] $done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance") while (!$done.invoke($deserializer, @())) { try { $method.invoke($deserializer, "") } catch { write-warning "Could not deserialize $string: $_" } } } }
PowerShellCorpus/PoshCode/Set-WinSchedule_1.ps1
Set-WinSchedule_1.ps1
# Set-WinSchedule # Written by Tome Tanasovski # http://powertoe.wordpress.com # version 1.0 # Created March 2010 # # Please read through the synopsis->Description to see the list of features that I hope to get # in a final release. If you choose to work on any of the issues by all means, but please contact # me to let me know so that no effort is duplicated # Winform Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null function Set-WinSchedule { <# .Synopsis Creates a winform to select a schedule and creates a scheduled task .Description Set-Computer gives a GUI to select a schedule and schedules a task using schtasks This is a beta. There are still a lot of features to implement: Need to have more scheduling options. I expect to have all options available in a recurring outlook calendar item Need to have methods for scheduling with all 3 providers: schtasks, wmi, and at. Currently it only uses schtasks Need to design the return object properties: Should contain the text paths for each provider type Should contain a date/time for start time Need to provide a method to overwrite an existing task if it has the same name and the user confirms that it is ok to overwrite. Should also provide a -force parameter for this option. Need to ensure that files piped from get-item will be scheduled Need a parameter to override ok box at the end .Example Set-Schedule c:\\windows\\notepad.exe .Parameter TaskRun The name of the command to be scheduled .Parameter ScheduleName The name that the scheduled task will be given. .Notes NAME: Set-Schedule AUTHOR: Tome Tanasovski LASTEDIT: 3/11/2010 KEYWORDS: .Link http://powertoe.wordpress.com #> param( [Parameter(Position=1,Mandatory=$true)] [string] $taskrun, [Parameter(Position=2,Mandatory=$true)] [string] $taskname ) $command = "& schtasks.exe /query /tn $taskname" $job = start-job $ExecutionContext.InvokeCommand.NewScriptBlock($command) Wait-Job $job if ($job.ChildJobs[0].output -ne "") { [System.windows.forms.messagebox]::show("A task named $taskname already exists. You must delete this task before you can use the name.") return } $SchedulePickerForm = New-Object System.Windows.Forms.Form $comboTime = New-Object System.Windows.Forms.ComboBox $label4 = New-Object System.Windows.Forms.Label $buttonCancel = New-Object System.Windows.Forms.Button $buttonOK = New-Object System.Windows.Forms.Button $group = New-Object System.Windows.Forms.GroupBox $checkSaturday = New-Object System.Windows.Forms.CheckBox $checkFriday = New-Object System.Windows.Forms.CheckBox $checkThursday = New-Object System.Windows.Forms.CheckBox $checkWednesday = New-Object System.Windows.Forms.CheckBox $checkTuesday = New-Object System.Windows.Forms.CheckBox $checkMonday = New-Object System.Windows.Forms.CheckBox $checkSunday = New-Object System.Windows.Forms.CheckBox $labelDays = New-Object System.Windows.Forms.Label $labelHours = New-Object System.Windows.Forms.Label $boxHourlyDaily = New-Object System.Windows.Forms.TextBox $labelEvery = New-Object System.Windows.Forms.Label $radioHourly = New-Object System.Windows.Forms.RadioButton $radioWeekly = New-Object System.Windows.Forms.RadioButton $radioDaily = New-Object System.Windows.Forms.RadioButton $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState $checkboxes = ($checkMonday,$checkTuesday,$checkWednesday,$checkThursday,$checkFriday,$checkSaturday,$checkSunday) function VisibleInvisibleCheckBoxes { Write-Host $checkboxes $checkboxes |foreach {$_.visible = -not $_.visible} } # Events $handler_radioButtonChanged = { switch ($true) { ($radioHourly.Checked) { $labelHours.Visible = $true $labelDays.Visible = $false $boxHourlyDaily.Visible = $true $checkboxes |foreach {$_.visible = $false} } ($radioDaily.Checked) { $labelHours.Visible = $false $labelDays.Visible = $true $boxHourlyDaily.Visible = $true $checkboxes |foreach {$_.visible = $false} } ($radioWeekly.Checked) { $labelHours.Visible = $false $labelDays.Visible = $false $boxHourlyDaily.Visible = $false $checkboxes |foreach {$_.visible = $true} } } } $buttonCancel_OnClick = { $SchedulePickerForm.Close() return $null } $buttonOK_OnClick = { $doit = $false switch ($true) { ($radioHourly.Checked -or $radioDaily.Checked) { try { $recurrence = [Convert]::ToInt32($boxHourlyDaily.Text) if ($recurrence -gt 0) { try { switch ($true) { ($radiohourly.checked) { if ($recurence -gt 23) { [System.windows.forms.messagebox]::show("Hourly recurrence must be 1-23 hours") $boxHourlyDaily.Focus() } else { & schtasks /create /tn $taskname /tr "$taskrun" /sc hourly /mo $boxHourlyDaily.Text /st $comboTime.Text /f [System.Windows.Forms.Messagebox]::show("Task has been scheduled") $SchedulePickerForm.Close() } } ($radioDaily.checked) { if ($recurence -gt 365) { [System.windows.forms.messagebox]::show("Hourly recurrence must be 1-365 hours") $boxhourlydaily.focus() } else { & schtasks /create /tn $taskname /tr $taskrun /sc daily /mo $boxHourlyDaily.Text /st $comboTime.Text /f $SchedulePickerForm.Close() } } } } catch { [System.windows.forms.messagebox]::show($error[0]) } } else { [System.windows.forms.messagebox]::show("Recurrence must be greater than 0") $boxHourlyDaily.Focus() } } catch { [System.windows.forms.messagebox]::show("You must enter a valid integer recurrence") $boxHourlyDaily.Focus() } } ($radioWeekly.Checked) { $dflag = "" $checkboxes|foreach { if ($_.checked) { $dflag += $_.text.substring(0,3) + "," } } if ($dflag -ne "") { $dflag = $dflag.substring(0,$dflag.length-1) & schtasks /create /tn $taskname /tr $taskrun /sc weekly /st $comboTime.Text /d "$dflag" /f $SchedulePickerForm.Close() } else { [System.windows.forms.messagebox]::show("You must select at least one day for weekly recurrence") } } } } $OnLoadForm_StateCorrection={ #Correct the initial state of the form to prevent the .Net maximized form issue $SchedulePickerForm.WindowState = $InitialFormWindowState } $SchedulePickerForm.Text = "Schedule Picker" $SchedulePickerForm.MaximizeBox = $False $SchedulePickerForm.Name = "SchedulePickerForm" $SchedulePickerForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 476 $System_Drawing_Size.Height = 157 $SchedulePickerForm.ClientSize = $System_Drawing_Size $SchedulePickerForm.FormBorderStyle = 5 $comboTime.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 121 $System_Drawing_Size.Height = 21 $comboTime.Size = $System_Drawing_Size $comboTime.DataBindings.DefaultDataSourceUpdateMode = 0 $comboTime.Name = "comboTime" $comboTime.Items.Add("00:00")|Out-Null $comboTime.Items.Add("00:30")|Out-Null $comboTime.Items.Add("01:00")|Out-Null $comboTime.Items.Add("01:30")|Out-Null $comboTime.Items.Add("02:00")|Out-Null $comboTime.Items.Add("02:30")|Out-Null $comboTime.Items.Add("03:00")|Out-Null $comboTime.Items.Add("03:30")|Out-Null $comboTime.Items.Add("04:00")|Out-Null $comboTime.Items.Add("04:30")|Out-Null $comboTime.Items.Add("05:00")|Out-Null $comboTime.Items.Add("05:30")|Out-Null $comboTime.Items.Add("06:00")|Out-Null $comboTime.Items.Add("06:30")|Out-Null $comboTime.Items.Add("07:00")|Out-Null $comboTime.Items.Add("07:30")|Out-Null $comboTime.Items.Add("08:00")|Out-Null $comboTime.Items.Add("08:30")|Out-Null $comboTime.Items.Add("09:00")|Out-Null $comboTime.Items.Add("09:30")|Out-Null $comboTime.Items.Add("10:00")|Out-Null $comboTime.Items.Add("10:30")|Out-Null $comboTime.Items.Add("11:00")|Out-Null $comboTime.Items.Add("11:30")|Out-Null $comboTime.Items.Add("12:00")|Out-Null $comboTime.Items.Add("12:30")|Out-Null $comboTime.Items.Add("13:00")|Out-Null $comboTime.Items.Add("13:30")|Out-Null $comboTime.Items.Add("14:00")|Out-Null $comboTime.Items.Add("14:30")|Out-Null $comboTime.Items.Add("15:00")|Out-Null $comboTime.Items.Add("15:30")|Out-Null $comboTime.Items.Add("16:00")|Out-Null $comboTime.Items.Add("16:30")|Out-Null $comboTime.Items.Add("17:00")|Out-Null $comboTime.Items.Add("17:30")|Out-Null $comboTime.Items.Add("18:00")|Out-Null $comboTime.Items.Add("18:30")|Out-Null $comboTime.Items.Add("19:00")|Out-Null $comboTime.Items.Add("19:30")|Out-Null $comboTime.Items.Add("20:00")|Out-Null $comboTime.Items.Add("20:30")|Out-Null $comboTime.Items.Add("21:00")|Out-Null $comboTime.Items.Add("21:30")|Out-Null $comboTime.Items.Add("22:00")|Out-Null $comboTime.Items.Add("22:30")|Out-Null $comboTime.Items.Add("23:00")|Out-Null $comboTime.Items.Add("23:30")|Out-Null $comboTime.Text = "08:00" $comboTime.DropDownStyle = "DropDownList" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 53 $System_Drawing_Point.Y = 119 $comboTime.Location = $System_Drawing_Point $comboTime.TabIndex = 1 $SchedulePickerForm.Controls.Add($comboTime) $label4.TabIndex = 3 $label4.TextAlign = 16 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 35 $System_Drawing_Size.Height = 23 $label4.Size = $System_Drawing_Size $label4.Text = "Start:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 116 $label4.Location = $System_Drawing_Point $label4.DataBindings.DefaultDataSourceUpdateMode = 0 $label4.Name = "label4" $SchedulePickerForm.Controls.Add($label4) $buttonCancel.TabIndex = 3 $buttonCancel.Name = "buttonCancel" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $buttonCancel.Size = $System_Drawing_Size $buttonCancel.UseVisualStyleBackColor = $True $buttonCancel.Text = "Cancel" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 368 $System_Drawing_Point.Y = 119 $buttonCancel.Location = $System_Drawing_Point $buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonCancel.add_Click($buttonCancel_OnClick) $SchedulePickerForm.Controls.Add($buttonCancel) $buttonOK.TabIndex = 2 $buttonOK.Name = "buttonOK" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $buttonOK.Size = $System_Drawing_Size $buttonOK.UseVisualStyleBackColor = $True $buttonOK.Text = "OK" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 287 $System_Drawing_Point.Y = 119 $buttonOK.Location = $System_Drawing_Point $buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonOK.add_Click($buttonOK_OnClick) $SchedulePickerForm.Controls.Add($buttonOK) $group.Name = "group" $group.Text = "Recurrence pattern" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 431 $System_Drawing_Size.Height = 101 $group.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 12 $group.Location = $System_Drawing_Point $group.TabStop = $False $group.TabIndex = 0 $group.DataBindings.DefaultDataSourceUpdateMode = 0 $SchedulePickerForm.Controls.Add($group) $checkSaturday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 73 $System_Drawing_Size.Height = 24 $checkSaturday.Size = $System_Drawing_Size $checkSaturday.TabIndex = 13 $checkSaturday.Text = "Saturday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 274 $System_Drawing_Point.Y = 64 $checkSaturday.Location = $System_Drawing_Point $checkSaturday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkSaturday.Name = "checkSaturday" $checkSaturday.Visible = $False $group.Controls.Add($checkSaturday) $checkFriday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 24 $checkFriday.Size = $System_Drawing_Size $checkFriday.TabIndex = 12 $checkFriday.Text = "Friday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 204 $System_Drawing_Point.Y = 64 $checkFriday.Location = $System_Drawing_Point $checkFriday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkFriday.Name = "checkFriday" $checkFriday.Visible = $False $group.Controls.Add($checkFriday) $checkThursday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 70 $System_Drawing_Size.Height = 24 $checkThursday.Size = $System_Drawing_Size $checkThursday.TabIndex = 11 $checkThursday.Text = "Thursday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 129 $System_Drawing_Point.Y = 64 $checkThursday.Location = $System_Drawing_Point $checkThursday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkThursday.Name = "checkThursday" $checkThursday.Visible = $False $group.Controls.Add($checkThursday) $checkWednesday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 83 $System_Drawing_Size.Height = 24 $checkWednesday.Size = $System_Drawing_Size $checkWednesday.TabIndex = 10 $checkWednesday.Text = "Wednesday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 342 $System_Drawing_Point.Y = 44 $checkWednesday.Location = $System_Drawing_Point $checkWednesday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkWednesday.Name = "checkWednesday" $checkWednesday.Visible = $False $group.Controls.Add($checkWednesday) $checkTuesday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 68 $System_Drawing_Size.Height = 24 $checkTuesday.Size = $System_Drawing_Size $checkTuesday.TabIndex = 9 $checkTuesday.Text = "Tuesday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 274 $System_Drawing_Point.Y = 44 $checkTuesday.Location = $System_Drawing_Point $checkTuesday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkTuesday.Name = "checkTuesday" $checkTuesday.Visible = $False $group.Controls.Add($checkTuesday) $checkMonday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 24 $checkMonday.Size = $System_Drawing_Size $checkMonday.TabIndex = 8 $checkMonday.Text = "Monday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 204 $System_Drawing_Point.Y = 44 $checkMonday.Location = $System_Drawing_Point $checkMonday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkMonday.Name = "checkMonday" $checkMonday.Visible = $False $group.Controls.Add($checkMonday) $checkSunday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $checkSunday.Size = $System_Drawing_Size $checkSunday.TabIndex = 7 $checkSunday.Text = "Sunday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 129 $System_Drawing_Point.Y = 44 $checkSunday.Location = $System_Drawing_Point $checkSunday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkSunday.Name = "checkSunday" $checkSunday.Visible = $False $group.Controls.Add($checkSunday) $labelDays.TabIndex = 6 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 18 $labelDays.Size = $System_Drawing_Size $labelDays.Visible = $False $labelDays.Text = "day(s)" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 189 $System_Drawing_Point.Y = 23 $labelDays.Location = $System_Drawing_Point $labelDays.DataBindings.DefaultDataSourceUpdateMode = 0 $labelDays.Name = "labelDays" $group.Controls.Add($labelDays) $labelHours.TabIndex = 5 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $labelHours.Size = $System_Drawing_Size $labelHours.Text = "hour(s)" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 189 $System_Drawing_Point.Y = 23 $labelHours.Location = $System_Drawing_Point $labelHours.DataBindings.DefaultDataSourceUpdateMode = 0 $labelHours.Name = "labelHours" $group.Controls.Add($labelHours) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 28 $System_Drawing_Size.Height = 20 $boxHourlyDaily.Size = $System_Drawing_Size $boxHourlyDaily.DataBindings.DefaultDataSourceUpdateMode = 0 $boxHourlyDaily.Text = "1" $boxHourlyDaily.Name = "boxHourlyDaily" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 155 $System_Drawing_Point.Y = 20 $boxHourlyDaily.Location = $System_Drawing_Point $boxHourlyDaily.TabIndex = 4 $group.Controls.Add($boxHourlyDaily) $labelEvery.TabIndex = 3 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 67 $System_Drawing_Size.Height = 23 $labelEvery.Size = $System_Drawing_Size $labelEvery.Text = "Every" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 116 $System_Drawing_Point.Y = 23 $labelEvery.Location = $System_Drawing_Point $labelEvery.DataBindings.DefaultDataSourceUpdateMode = 0 $labelEvery.Name = "labelEvery" $group.Controls.Add($labelEvery) $radioHourly.TabIndex = 0 $radioHourly.Name = "radioHourly" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioHourly.Size = $System_Drawing_Size $radioHourly.UseVisualStyleBackColor = $True $radioHourly.Text = "Hourly" $radioHourly.Checked = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 17 $radioHourly.Location = $System_Drawing_Point $radioHourly.DataBindings.DefaultDataSourceUpdateMode = 0 $radioHourly.TabStop = $True $radioHourly.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioHourly) $radioWeekly.TabIndex = 2 $radioWeekly.Name = "radioWeekly" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioWeekly.Size = $System_Drawing_Size $radioWeekly.UseVisualStyleBackColor = $True $radioWeekly.Text = "Weekly" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 56 $radioWeekly.Location = $System_Drawing_Point $radioWeekly.DataBindings.DefaultDataSourceUpdateMode = 0 $radioWeekly.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioWeekly) $radioDaily.TabIndex = 1 $radioDaily.Name = "radioDaily" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioDaily.Size = $System_Drawing_Size $radioDaily.UseVisualStyleBackColor = $True $radioDaily.Text = "Daily" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 37 $radioDaily.Location = $System_Drawing_Point $radioDaily.DataBindings.DefaultDataSourceUpdateMode = 0 $radioDaily.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioDaily) $SchedulePickerForm.CancelButton = $buttonCancel $SchedulePickerForm.AcceptButton = $buttonOK #Save the initial state of the form $InitialFormWindowState = $SchedulePickerForm.WindowState #Init the OnLoad event to correct the initial state of the form $SchedulePickerForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $SchedulePickerForm.ShowDialog() |out-null }
PowerShellCorpus/PoshCode/Get-PasswordExpiredUser_1.ps1
Get-PasswordExpiredUser_1.ps1
Param($ou) if($ou){$root = [ADSI]"LDAP://$ou"}else{$root=[adsi]""} $filter = "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=65536))" $ds = new-object directoryservices.directorysearcher($root,$filter) $users = $ds.findall() $users | format-table @{l="User";e={$_.properties.item('cn')}}, @{l="sAMAccountName";e={$_.properties.item('sAMAccountName')}}, @{l="Path";e={$_.path}}
PowerShellCorpus/PoshCode/938222df-0908-4ad3-86aa-24bb9510af6f.ps1
938222df-0908-4ad3-86aa-24bb9510af6f.ps1
## Update all fast running (1 minute) timerjobs to run onece every 30+ minutes instead ## Jos Verlinde ## Version 1 - Sharepoint 2010 B2 $Jobs = @(Get-SPTimerJob | Where-Object { $_.Schedule.Interval -le 5 -and $_.Schedule.Description -eq "Minutes" }) if ( $Jobs.count -GT 0 ) { ## Add 30 mintues to all these timerjobs foreach ($job in $Jobs) { Write-Host -foregroundcolor green $job.name $Sched = $job.Schedule $Sched.Interval= $Sched.Interval+30 $job.Schedule=$Sched $job.Update() } Get-SPTimerJob | Where-Object { $_.Schedule.Description -eq "Minutes" } } else { Write-Host -foregroundcolor green "No fast running timerjobs found" }
PowerShellCorpus/PoshCode/Get-DellWarranty_3.ps1
Get-DellWarranty_3.ps1
function Get-DellWarranty { <# .Synopsis Provides warranty information for one or more Dell service tags. .Description Queries the Dell Website for a list of service tags and returns the warranty information as a custom object. If a service tag has multiple warranties, they are returned as multiple separate objects. If no service tag is specified, it will attempt to retrieve and lookup the local system's service tag. The service tag can be provided to the command in several ways: 1. Using the -servicetag parameter 2. By passing one or more Service Tags via the pipeline 3. By passing objects that have either servicetag or serialnumber defined as a property, such as win32_bios WMI objects See examples for details. .Parameter ServiceTag ALIAS: serialnumber The Dell service tag you wish to query. Example: XYZ12A3 .Example C:\\PS> Get-DellWarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- If no service tags are provided, the script retrieves the local computer's serial number from WMI and queries for it. .Example C:\\PS> Get-DellWarranty -ServiceTag XXXX123 Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- You can pass the service tag as a parameter, or as the first positional parameter (e.g. Get-DellWarranty XXXX123) .Example C:\\PS> "XXXX123","XXXX124","XXXX125" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can pass serial numbers via the pipeline either directly or as a variable. .Example C:\\PS> get-wmiobject win32_bios -computername "computer1","computer2","1.2.3.4" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can also pass any object that has a "serialnumber" or "servicetag" property. In this example, we query computers directly for their serial numbers, and pass those results (which are WMI objects that have a serialnumber property) via pipeline directly to the command to obtain warranty information. .Notes AUTHOR: Justin Grote <jgrote NOSPAM-AT allieddigital NOSPAM-DOT net> WARNING: Since Dell does not provide a formal API, this script works by screen-scraping the HTML from the Dell product support site. Any future change to the layout or logic of this site will break the script or cause unpredictable results. HISTORY: v1.0 [31 Jan 2011] - Initial Module Creatio .Link http://support.dell.com/support/topics/global.aspx/support/my_systems_info #> [CmdletBinding()] param( [Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] [alias("serialnumber")] [string[]]$ServiceTag ) PROCESS { # If nothing was passed, retrieve the local system service tag if ($ServiceTag -eq $null) { write-verbose "No Service Tags provided. Using Local Computer's Service Tag" write-verbose "START Obtaining Serial number via WMI for localhost" $ServiceTag = (get-wmiobject win32_bios).SerialNumber write-verbose "SUCCESS Obtaining Serial number via WMI for localhost - $ServiceTag" } # Detect if an array of service tags were passed via parameter and unwind them. foreach ($strServicetag in $servicetag) { write-verbose "START Querying Dell for Service Tag $_" Get-DellWarrantyWorker $strServicetag write-verbose "SUCCESS Querying Dell for Service Tag $_" } } } Function Get-DellWarrantyWorker { Param( [String]$serviceTag ) #Dell Warranty URL Path $URL = "http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=$serviceTag" trap [System.FormatException] { write-error -category invalidresult "The service tag $serviceTag was not found. This is either because you entered the tag incorrectly, it is not present in Dell's database, or Dell changed the format of their website causing this search to fail." -recommendedaction "Please check that you entered the service tag correctly" return; } #Screenscrape the HTML for the warranty Table $HTML = (New-Object Net.WebClient).DownloadString($URL) If ($HTML -Match '<table[\\w\\s\\d"=%]*contract_table">.+?</table>') { $htmltable = $Matches[0] } else { throw (New-Object System.FormatException) } $HtmlLines = $htmltable -Split "<tr" | Where-Object { $_ -Match '<td' } $Header = ($HtmlLines[0] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*' | Where-Object { $_ -ne '' } #Convert the warranty table fields into a powershell object For ($i = 1; $i -lt $HtmlLines.Count; $i++) { $Output = New-Object PSObject $Output | Add-Member NoteProperty "Service Tag" -value $serviceTag $Values = ($HtmlLines[$i] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*|<a.+?>' For ($j = 1; $j -lt $Values.Count; $j++) { $Output | Add-Member NoteProperty $Header[$j - 1] -Value $Values[$j] } #Minor formatting fix if days remaining on warranty is zero if ($output.'Days Left' -match '<<0') {write-host -fore darkgreen "match!";$output.'Days Left' = 0} return $Output } }
PowerShellCorpus/PoshCode/Get-Parameter 2.3.ps1
Get-Parameter 2.3.ps1
#Requires -version 2.0 #.Synopsis # Enumerates the parameters of one or more commands #.Notes # With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy # Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186 # Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255 # Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445 # Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446 # Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549 # - Added resolving aliases and avoided empty output # Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344 # Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592 # - Merged Oisin and Hal's code with my own implementation # - Added calculation of dynamic paramters # Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005 # - Now uses FormatData so the output is objects # - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation) # Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007 # - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line) # - Fleshed out and added dates to this version history after Bergle's criticism ;) # Version 2.2 - July 29, 2010 - By Joel Bennett (This Version) # - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo # Version 2.3 - July 29, 2010 - By Joel Bennett (This Version) # - Added a ToString ScriptMethod which allows queries like: # $parameters = Get-Parameter Get-Process; $parameters -match "Name" # #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter Name # The name of the command to get parameters for #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] ##This is just script-file nesting stuff, so that you can call the SCRIPT, and after it defines the global function, it will call it. param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) Function global:Get-Parameter { #.Synopsis # Enumerates the parameters of one or more commands #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter Name # The name of the command to get parameters for #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$Name , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) begin { $PropertySet = @( "Name", @{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}}, "Aliases", @{n="Short";e={$_.Name}}, @{n="Type";e={$_.ParameterType.Name}}, @{n="ParameterSet";e={$paramset}}, @{n="Command";e={$command}}, @{n="Mandatory";e={$_.IsMandatory}}, @{n="Provider";e={$_.DynamicProvider}}, @{n="ValueFromPipeline";e={$_.ValueFromPipeline}}, @{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}} ) function Join-Object { Param( [Parameter(Position=0)] $First , [Parameter(ValueFromPipeline=$true,Position=1)] $Second ) begin { [string[]] $p1 = $First | gm -type Properties | select -expand Name } process { $Output = $First | Select $p1 foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) { Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p" } $Output } } } process{ foreach($cmd in $Name) { if($ModuleName) { $cmd = "$ModuleName\\$cmd" } $commands = @(Get-Command $cmd) foreach($command in $commands) { # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = @(Get-Command ($command.definition))[0] } if (-not $command) { continue } $Parameters = @{} foreach($provider in Get-PSProvider) { $drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters") [Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values [Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic } foreach($p in $MoreParameters | Where { $Dynamic -notcontains $_ } ){ $Parameters.($p.Name) = $p } # Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)" if($dynamic) { foreach($d in $dynamic) { if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) { Write-Debug ("ADD:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name).DynamicProvider += $provider.Name } else { Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru } } } } ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else. foreach($p in $($Parameters.Keys)) { $shortest="^" foreach($char in [char[]]$p) { $shortest += $char $Matches = ($Parameters.Keys -match $Shortest).Count Write-Debug "$($shortest.SubString(1)) $Matches" if($Matches -eq 1) { $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru break } } } Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)" foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){ foreach($parameter in $Parameters.Keys | Sort) { Write-Verbose "Parameter: $Parameter" if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue } if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) { if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet } else { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets } Write-Output $Output | Select-Object $PropertySet | ForEach { $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata") $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx") Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")" $_ } | Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru } } } } } } } # Since you can't update format data without a file that has a ps1xml ending, let's make one up... $tempFile = "$([IO.Path]::GetTempFileName()).ps1xml" Set-Content $tempFile @' <?xml version="1.0" encoding="utf-8" ?> <Configuration> <Controls> <Control> <Name>ParameterGroupingFormat</Name> <CustomControl> <CustomEntries> <CustomEntry> <CustomItem> <Frame> <LeftIndent>4</LeftIndent> <CustomItem> <Text>Command: </Text> <ExpressionBinding> <ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock> </ExpressionBinding> <NewLine/> <Text>Set: </Text> <ExpressionBinding> <ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock> </ExpressionBinding> <NewLine/> </CustomItem> </Frame> </CustomItem> </CustomEntry> </CustomEntries> </CustomControl> </Control> </Controls> <ViewDefinitions> <View> <Name>ParameterMetadataEx</Name> <ViewSelectedBy> <TypeName>System.Management.Automation.ParameterMetadataEx</TypeName> </ViewSelectedBy> <GroupBy> <PropertyName>ParameterSet</PropertyName> <CustomControlName>ParameterGroupingFormat</CustomControlName> </GroupBy> <TableControl> <TableHeaders> <TableColumnHeader> <Label>Name</Label> <Width>22</Width> </TableColumnHeader> <TableColumnHeader> <Label>Aliases</Label> <Width>12</Width> </TableColumnHeader> <TableColumnHeader> <Label>Position</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>Mandatory</Label> <Width>9</Width> </TableColumnHeader> <TableColumnHeader> <Label>Pipeline</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>ByName</Label> <Width>6</Width> </TableColumnHeader> <TableColumnHeader> <Label>Provider</Label> <Width>15</Width> </TableColumnHeader> <TableColumnHeader> <Label>Type</Label> </TableColumnHeader> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Aliases</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Position</PropertyName--> <ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Mandatory</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipeline</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipelineByPropertyName</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Provider</PropertyName--> <ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Type</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> </ViewDefinitions> </Configuration> '@ Update-FormatData -Append $tempFile # This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that. Get-Parameter @PSBoundParameters
PowerShellCorpus/PoshCode/Create random strings.ps1
Create random strings.ps1
# =============================================================== # / Author: Marcus L. Farmer # / Script: createRandomStrings.ps1 # / Date: 2-04-2009 # / Purpose: generate psedorandomly generated strings for passwords or other uses # / Usage: ./createRandomStrings.ps1 # / Reqs.: none # / Output: text file containing output - default file is # / Comments: none # =============================================================== function createRandomString($charset) { $lblResults.text = "Hello now!" [string]$outputString = "" for ($i=1; $i -lt ([int]$txtGenerateThisManyNumbers.text + 1); $i++) { $lblResults.text = "in the first loop enumerating i" for ($x=1; $x -lt ([int]$txtLengthOfEachNumber.text + 1); $x++) { $lblResults.text = "in the second loop enumerating x" $outputString = $outputString + $charset.substring((get-random $charset.length), 1) } # $lblResults.text = $outputString Add-Content -Path $txtFileName.text -Value $outputString $outputString = "" } $lblResults.text = "Your really cool and super randomly generated strings can be found in " + $txtFileName.text } $btnGenerateNumbers_OnClick= { #TODO: Place custom script here createRandomString($txtCreateCharacterSet.Text) } $btnResetCharacterSet_OnClick= { #TODO: Place custom script here $txtCreateCharacterSet.Text = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' } #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms v1.0.1.0 # Generated On: 2/3/2009 4:55 PM # Generated By: Marcus L. Farmer ######################################################################## #region Import the Assembles [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null #endregion #region Generated Form Objects $frmMain = New-Object System.Windows.Forms.Form $btnGenerateNumbers = New-Object System.Windows.Forms.Button $txtFileName = New-Object System.Windows.Forms.TextBox $lblSaveAsFile = New-Object System.Windows.Forms.Label $txtGenerateThisManyNumbers = New-Object System.Windows.Forms.TextBox $lblGenerateThisManyNumbers = New-Object System.Windows.Forms.Label $txtLengthOfEachNumber = New-Object System.Windows.Forms.TextBox $lblLengthOfEachNumber = New-Object System.Windows.Forms.Label $btnResetCharacterSet = New-Object System.Windows.Forms.Button $txtCreateCharacterSet = New-Object System.Windows.Forms.TextBox $lblCreateCharacterSet = New-Object System.Windows.Forms.Label $lblResults = New-Object System.Windows.Forms.Label #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. #---------------------------------------------- #region Generated Form Code $frmMain.BackColor = [System.Drawing.Color]::FromArgb(255,40,46,34) $frmMain.Text = 'Random Number Generator' $frmMain.Name = 'frmMain' $frmMain.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 326 $System_Drawing_Size.Height = 299 $frmMain.ClientSize = $System_Drawing_Size $btnGenerateNumbers.TabIndex = 10 $btnGenerateNumbers.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200) $btnGenerateNumbers.Name = 'btnGenerateNumbers' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 142 $System_Drawing_Size.Height = 23 $btnGenerateNumbers.Size = $System_Drawing_Size $btnGenerateNumbers.UseVisualStyleBackColor = $False $btnGenerateNumbers.Text = 'Generate Numbers' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 169 $System_Drawing_Point.Y = 191 $btnGenerateNumbers.Location = $System_Drawing_Point $btnGenerateNumbers.DataBindings.DefaultDataSourceUpdateMode = 0 $btnGenerateNumbers.add_Click($btnGenerateNumbers_OnClick) $frmMain.Controls.Add($btnGenerateNumbers) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 142 $System_Drawing_Size.Height = 20 $txtFileName.Size = $System_Drawing_Size $txtFileName.DataBindings.DefaultDataSourceUpdateMode = 0 $txtFileName.Text = 'randomStrings.txt' $txtFileName.Name = 'textBox4' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 169 $System_Drawing_Point.Y = 164 $txtFileName.Location = $System_Drawing_Point $txtFileName.TabIndex = 9 $frmMain.Controls.Add($txtFileName) $lblSaveAsFile.TabIndex = 8 $lblSaveAsFile.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblSaveAsFile.Size = $System_Drawing_Size $lblSaveAsFile.Text = 'Save as file' $lblSaveAsFile.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 61 $System_Drawing_Point.Y = 162 $lblSaveAsFile.Location = $System_Drawing_Point $lblSaveAsFile.DataBindings.DefaultDataSourceUpdateMode = 0 $lblSaveAsFile.Name = 'lblSaveAsFile' $frmMain.Controls.Add($lblSaveAsFile) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 142 $System_Drawing_Size.Height = 20 $txtGenerateThisManyNumbers.Size = $System_Drawing_Size $txtGenerateThisManyNumbers.DataBindings.DefaultDataSourceUpdateMode = 0 $txtGenerateThisManyNumbers.Text = '10' $txtGenerateThisManyNumbers.Name = 'txtGenerateThisManyNumbers' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 169 $System_Drawing_Point.Y = 137 $txtGenerateThisManyNumbers.Location = $System_Drawing_Point $txtGenerateThisManyNumbers.TabIndex = 7 $frmMain.Controls.Add($txtGenerateThisManyNumbers) $lblGenerateThisManyNumbers.TabIndex = 6 $lblGenerateThisManyNumbers.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 154 $System_Drawing_Size.Height = 23 $lblGenerateThisManyNumbers.Size = $System_Drawing_Size $lblGenerateThisManyNumbers.Text = 'Generate this many numbers' $lblGenerateThisManyNumbers.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 135 $lblGenerateThisManyNumbers.Location = $System_Drawing_Point $lblGenerateThisManyNumbers.DataBindings.DefaultDataSourceUpdateMode = 0 $lblGenerateThisManyNumbers.Name = 'lblGenerateThisManyNumbers' $frmMain.Controls.Add($lblGenerateThisManyNumbers) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 141 $System_Drawing_Size.Height = 20 $txtLengthOfEachNumber.Size = $System_Drawing_Size $txtLengthOfEachNumber.DataBindings.DefaultDataSourceUpdateMode = 0 $txtLengthOfEachNumber.Text = '9' $txtLengthOfEachNumber.Name = 'txtLengthOfEachNumber' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 170 $System_Drawing_Point.Y = 108 $txtLengthOfEachNumber.Location = $System_Drawing_Point $txtLengthOfEachNumber.TabIndex = 5 $frmMain.Controls.Add($txtLengthOfEachNumber) $lblLengthOfEachNumber.TabIndex = 4 $lblLengthOfEachNumber.BackColor = [System.Drawing.Color]::FromArgb(255,40,46,34) $lblLengthOfEachNumber.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 155 $System_Drawing_Size.Height = 23 $lblLengthOfEachNumber.Size = $System_Drawing_Size $lblLengthOfEachNumber.Text = 'Length of each number' $lblLengthOfEachNumber.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 108 $lblLengthOfEachNumber.Location = $System_Drawing_Point $lblLengthOfEachNumber.DataBindings.DefaultDataSourceUpdateMode = 0 $lblLengthOfEachNumber.Name = 'lblLengthOfEachNumber' $frmMain.Controls.Add($lblLengthOfEachNumber) $btnResetCharacterSet.TabIndex = 3 $btnResetCharacterSet.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200) $btnResetCharacterSet.Name = 'btnResetCharacterSet' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 141 $System_Drawing_Size.Height = 23 $btnResetCharacterSet.Size = $System_Drawing_Size $btnResetCharacterSet.UseVisualStyleBackColor = $False $btnResetCharacterSet.Text = 'Reset Character Set' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 170 $System_Drawing_Point.Y = 66 $btnResetCharacterSet.Location = $System_Drawing_Point $btnResetCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0 $btnResetCharacterSet.add_Click($btnResetCharacterSet_OnClick) $frmMain.Controls.Add($btnResetCharacterSet) $txtCreateCharacterSet.Multiline = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 141 $System_Drawing_Size.Height = 44 $txtCreateCharacterSet.Size = $System_Drawing_Size $txtCreateCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0 $txtCreateCharacterSet.Text = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' $txtCreateCharacterSet.Name = 'txtCreateCharacterSet' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 170 $System_Drawing_Point.Y = 15 $txtCreateCharacterSet.Location = $System_Drawing_Point $txtCreateCharacterSet.TabIndex = 2 $frmMain.Controls.Add($txtCreateCharacterSet) $lblCreateCharacterSet.TabIndex = 1 $lblCreateCharacterSet.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 156 $System_Drawing_Size.Height = 23 $lblCreateCharacterSet.Size = $System_Drawing_Size $lblCreateCharacterSet.Text = 'Create Character Set' $lblCreateCharacterSet.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 15 $lblCreateCharacterSet.Location = $System_Drawing_Point $lblCreateCharacterSet.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCreateCharacterSet.Name = 'lblCreateCharacterSet' $lblCreateCharacterSet.add_Click($handler_label2_Click) $lblCreateCharacterSet.add_MouseHover($CreateCharacterSet_onhover) $frmMain.Controls.Add($lblCreateCharacterSet) $lblResults.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 327 $System_Drawing_Size.Height = 51 $lblResults.Size = $System_Drawing_Size $lblResults.ForeColor = [System.Drawing.Color]::FromArgb(255,240,221,22) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = -1 $System_Drawing_Point.Y = 249 $lblResults.Location = $System_Drawing_Point $lblResults.DataBindings.DefaultDataSourceUpdateMode = 0 $lblResults.Name = 'lblResults' $frmMain.Controls.Add($lblResults) #endregion Generated Form Code #Show the Form $frmMain.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/Import-CmdEnvironment_1.ps1
Import-CmdEnvironment_1.ps1
# .SYNOPSIS # Import environment variables from cmd to PowerShell # .DESCRIPTION # Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell # .EXAMPLE # Import-CmdEnvironment Import-CmdEnvironment ${Env:VS90COMNTOOLS}\\vsvars32.bat x86 # # Imports the x86 Visual Studio 2008 Command Tools environment # .EXAMPLE # Import-CmdEnvironment Import-CmdEnvironment ${Env:VS100COMNTOOLS}\\vsvars32.bat x86_amd64 # # Imports the x64 Cross Tools Visual Studio 2010 Command environment #function Import-CmdEnvironment { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [string]$Command = "echo" , [Parameter(Position=0,Mandatory=$False,ValueFromRemainingArguments=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Parameters ) ## If it's an actual file, then we should quote it: if(Test-Path $Command) { $Command = "`"$(Resolve-Path $Command)`"" } $setRE = new-Object System.Text.RegularExpressions.Regex '^(?<var>.*?)=(?<val>.*)$', "Compiled,ExplicitCapture,MultiLine" $OFS = " " [string]$Parameters = $Parameters $OFS = "`n" ## Execute the command, with parameters. Write-Verbose "EXECUTING: cmd.exe /c `"$Command $Parameters > nul && set`"" ## For each line of output that matches, set the local environment variable foreach($match in $setRE.Matches((cmd.exe /c "$Command $Parameters > nul && set")) | Select Groups) { Set-Content Env:\\$($match.Groups["var"]) $match.Groups["val"] -Verbose } #}
PowerShellCorpus/PoshCode/Select-EnumeratedType.ps1
Select-EnumeratedType.ps1
#requires -version 2 if (-not(test-path variable:script:_helpcache)) { $SCRIPT:_helpCache = @{} } function Select-EnumeratedType { <# .SYNOPSIS Visually create an instance of an enum. .DESCRIPTION Visually create an instance of an enum with an easy to use menu system. Supports both single value enumerated types and bitmask (flags) enums. Also supports inline help for enumerated values (powershell.exe only) .PARAMETER EnumeratedType The enum type to provide choices for. Pass as a string or Type. .PARAMETER IncludeHelp Allows the caller to view help for the enumerated type, including all values. This help is pulled from the local .NET installation and does not require online access. .PARAMETER DefaultValue A dynamic parameter that is added and typed to the provided enum. Use this to provide default values should the caller press <enter> without choosing a value or value(s). This parameter will absorb all trailing arguments. (ValueFromRemainingArguments = $true) .EXAMPLE $rights = Select-EnumeratedType System.Security.AccessControl.CryptoKeyRights Delete,Synchronize .EXAMPLE $access = Select-EnumeratedType System.IO.FileAccess Read -IncludeHelp #> [cmdletbinding()] param( [parameter(position=0, mandatory=$true)] [validatescript({ $_.isenum })] [validatenotnull()] [type]$EnumeratedType, [parameter()] [switch]$IncludeHelp ) dynamicparam { # only create dynamic parameter if enum provided if ($PSCmdlet.MyInvocation.BoundParameters["EnumeratedType"]) { write-verbose "Adding DefaultValue ($enumeratedType) parameter." # dynamically create -Default parameter with the correct enum type for easy validation $dict = new-object management.automation.RuntimeDefinedParameterDictionary $defaultParam = new-object System.Management.Automation.RuntimeDefinedParameter $defaultParam.Name = "DefaultValue" $defaultParam.ParameterType = $enumeratedType # create parameter attribute for positional info etc. $p = new-object System.Management.Automation.ParameterAttribute $p.ParameterSetName = $PSCmdlet.ParameterSetName $p.ValueFromRemainingArguments = $true $p.Position = 1 $p.Mandatory = $false $defaultParam.Attributes.Add($p) $dict.Add("DefaultValue", $defaultParam) $dict } } end { # ugly. why doesn't $defaultvalue just work? $default = $pscmdlet.MyInvocation.BoundParameters["DefaultValue"] $help = @{} if ($IncludeHelp) { $xmldoc = Get-XmlDocumentation -type $enumeratedType if ($xmlDoc) { # use readallines over get-content - 10x faster. $f = [xml][io.file]::readAllLines($xmlDoc) $selector = "F:$($enumeratedType.fullName)" foreach ($node in $f.doc.members.selectnodes("member[starts-with(@name,'$selector')]")) { if ($node.summary) { $help[$node.name] = $node.summary.trim() } } } } $choices = new-object collections.generic.list[System.Management.Automation.Host.ChoiceDescription] $names = [enum]::getnames($enumeratedType) [double[]]$values = [enum]::getvalues($enumeratedType)|%{[double]$_} # compute hotkeys for enum choices $hot = new-hotkeytable $names # insert ampersand (&) for hotkey hints $names | % { $i = $_.indexof([string]$hot[$_], [stringcomparison]::ordinalignorecase) if ($i -ne -1) { # hotkey exists in word $name = $_.insert($i, "&") } else { # hotkey is not part of word - need to append (blech) $name = "$_ (&$($hot[$_]))" } $helpKey = "F:$($enumeratedType.fullname).$_" if ($includehelp -and $help[$helpKey]) { # doesn't work in ISE - never renders the '?' $choiceParams = @($name, $help[$helpKey]) } else { $choiceParams = $name } $choices.add((new-object Management.Automation.Host.ChoiceDescription -Args $choiceParams)) } # are we a flags enum? $isFlags = $enumeratedType.GetCustomAttributes([FlagsAttribute], $false) # does this host support multiple choice? $supportsMultipleChoice = $host.ui -is [Management.Automation.Host.IHostUISupportsMultipleChoiceSelection] if ($isFlags -and (-not $supportsMultipleChoice)) { throw ("{0} enum is flags decorated and this host ({1}) does not support multiple choice selections. Sorry!" -f $enumeratedType.name, $host.name) } $title = $enumeratedType.name if ($isFlags) { if (-not $default) { # no default provided $default = [int[]]@() } else { # need to parse default [int[]]$defaults = @() $limit = [math]::log([enum]::GetUnderlyingType($enumeratedType)::maxvalue + 1, 2) # cast to [int] required or else we get non-zero result # as we approach limit (double trouble) for ($index = [int]$limit; $index -ge 0; $index--) { $bit = [math]::pow(2,$index) # double if (([int]$default) -band $bit) { $defaults += [array]::indexof($values, $bit) } } $default = $defaults } $message = "Choose one or more values for mask:" $title += " (Flags)" } else { if (-not $default) { # this is menu position, not enum value $default = -1 } else { # convert to index $default = [array]::indexof($values, [double]$default) } $message = "Choose single value:" } $result = @() # invoke host support for multiple choice $host.ui.promptforchoice($title, $message, $choices, $default) | % { $result += $names[$_] } # cast back to enum $result -as $enumeratedtype } } function Get-HelpSummary { [CmdletBinding()] param ( [string]$file, [reflection.assembly]$assembly, [string]$selector ) if ($helpCache.ContainsKey($assembly)) { $xml = $helpCache[$assembly] } else { # cache it Write-Progress -id 1 "Caching Help Documentation" $assembly.getname().name # cache this for future lookups. It's a giant pig. Oink. $xml = [xml](gc $file) $helpCache.Add($assembly, $xml) Write-Progress -id 1 "Caching Help Documentation" $assembly.getname().name -completed } # TODO: support overloads $summary = $xml.doc.members.SelectSingleNode("member[@name='$selector' or starts-with(@name,'$selector(')]").summary $summary } function New-HotKeyTable { param([string[]]$names) $hot = @{} # assign hot keys $names | % { $c = [char]::toupper($_[0]) # prioritize first letter if (-not $hot.containsvalue($c)) { $hot[$_] = $c write-debug "1) assigned $c to $_" } } $names | ? { # unallocated? -not $hot.containskey($_) } | % { # try camel humps for ($i=1; $i -lt $_.length; $i++) { $c = $_[$i] if ([char]::IsUpper($c) -and (-not $hot.containsvalue($c))) { $hot[$_] = $c write-debug "2) assigned $c to $_" break } } } $names | ? { # unallocated? -not $hot.containskey($_) } | % { # try sequential from pos 1 for ($i=1; $i -lt $_.length; $i++) { $c = [char]::toupper($_[$i]) # available? if (-not $hot.containsvalue($c)) { $hot[$_] = $c write-debug "3) assigned $c to $_" break } } } # alphabetic search $names | ? { # unallocated? -not $hot.containskey($_) } | % { $word = $_ write-host "processing $word" $s = [int]"A"[0] for ($i = $s; $i -lt ($s + 26); $i++) { $c = [char]$i if (-not $hot.containsvalue($c)) { $hot[$word] = $c write-debug "4) assigned $c to $word" break } } } # todo: if the above fails, use 0-9? $hot } function Get-XmlDocumentation { [cmdletbinding()] param([type]$type) $docFilename = [io.path]::changeextension([io.path]::getfilename($type.assembly.location), ".xml") $location = [io.path]::getdirectoryname($type.assembly.location) $codebase = (new-object uri $type.assembly.codebase).localpath # try localized location (typically newer than base framework dir) $frameworkDir = "${env:windir}\\Microsoft.NET\\framework\\v2.0.50727" $lang = [system.globalization.cultureinfo]::CurrentUICulture.parent.name switch ( "${frameworkdir}\\${lang}\\$docFilename", "${frameworkdir}\\$docFilename", "$location\\$docFilename", "$codebase\\$docFilename" ) { { test-path $_ } { $_; return; } default { # try next path continue; } } }
PowerShellCorpus/PoshCode/Add-SqlTable_2.ps1
Add-SqlTable_2.ps1
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"} ####################### function Get-SqlType { param([string]$TypeName) switch ($TypeName) { 'Boolean' {[Data.SqlDbType]::Bit} 'Byte[]' {[Data.SqlDbType]::VarBinary} 'Byte' {[Data.SQLDbType]::VarBinary} 'Datetime' {[Data.SQLDbType]::DateTime} 'Decimal' {[Data.SqlDbType]::Decimal} 'Double' {[Data.SqlDbType]::Float} 'Guid' {[Data.SqlDbType]::UniqueIdentifier} 'Int16' {[Data.SQLDbType]::SmallInt} 'Int32' {[Data.SQLDbType]::Int} 'Int64' {[Data.SqlDbType]::BigInt} default {[Data.SqlDbType]::VarChar} } } #Get-SqlType ####################### <# .SYNOPSIS Creates a SQL Server table from a DataTable .DESCRIPTION Creates a SQL Server table from a DataTable using SMO. .EXAMPLE $dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table .EXAMPLE $dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table. .NOTES Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52 Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Updated documentation v1.2 - Chad Miller - Add loading Microsoft.SqlServer.ConnectionInfo #> function Add-SqlTable { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [String]$TableName, [Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable, [Parameter(Position=4, Mandatory=$false)] [string]$Username, [Parameter(Position=5, Mandatory=$false)] [string]$Password, [ValidateRange(1,8000)] [Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000 ) if($Username) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance } $con.Connect() $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con $db = $server.Databases[$Database] $table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName foreach ($column in $DataTable.Columns) { $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)" if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength } else { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType } $col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType $col.Nullable = $column.AllowDBNull $table.Columns.Add($col) } $table.Create() } #Add-SqlTable
PowerShellCorpus/PoshCode/PShellExec.ps1
PShellExec.ps1
:20000000504B03041400000008001783273DD0F4E663770F0000002400000E0000005053BC :2000200068656C6C457865632E657865ED597D6C1CC7757FBB77BC3B1EC9238F9429C932A6 :20004000ADD5C94A28C93C91126531B265F153326D51A27594182536A4E57144AEB4777BAA :20006000DE5D7E5C93D267040894B4B11D18289AC2CD1752032E5A44019CC4ADDB5A819385 :20008000D609E0C2469AD6296A5B6882A02A925A0950C44E525D7F6F76F73E282A5680F4CC :2000A0009F22739C37F3DEBC795FF366667739F1A12729444461D47299E879F2CA20BD774A :2000C00029A12636FF75829E6B7C65CBF3CA9157B64CCD1B8E56B0AD395BCF69593D9FB7C7 :2000E0005C6D4668F6425E33F2DAE8B18C96B36645BAA5257E872F63728CE88812A2BF7867 :20010000FAE34702B99729A1342931A24E20CD1EEDB3FD001AF9860D7A7DD5B39B4BD04A54 :20012000A354AFABD26003519BFCABB695469651C89DE6CE20F436D2F5E54CC584DFAC6897 :2001400044B11A3406FCBE1A3CED8A6517ED97D679BCD25795EA0AC867D2B66367C9B76DA4 :2001600010358EBAA19E0FE4C1B42D4C2BEBDB7A863C59A9EBF886695529F57B2DDBA652E3 :20018000035DDD463495205248D6C86AFEF72A9B7AC37458957393B4825589C7256C521F16 :2001A00037D65F0B775E533AA2C9684F2B75AB2CBDB3BB41BAB4AEB9B3853A3BC203DF67D4 :2001C000216A32FC271654C73B1A920D56141D1BF20A16021A0F2434AD2F61203CF005F065 :2001E000074CD1D54C6730B4D16A0C244151FCF6AA11DBA9BBA986B9C36EC57CFB6180CE82 :20020000CD6DDD8864FC7DB7B4BCF111A85E813161086801AD1BD1899764EAED7C7FB2C14D :20022000FEC86AA5AD814EC9B433946C885332BCFE831DE1641851B81666AEFDEBCBE572BC :20024000A4BBB5665EC28F09744639F49E4F1F63F16DB56C91EE249B815D1B69DA19F5B05F :20026000A6150E46C0B2F7BAC992BC912292D2DD0E4AB41BCB12E9EE90E17FE38F10C56EC1 :20028000A462BC3916B56E61CF635627378DFE02BD797747A43E5CDBEC4F4156A47B3D68B3 :2002A000C988B5816DDAC84ABF5C1F407A13B3072876E78698752B48D62606B7016CB8A68E :2002C00040D84E65BD94D7EC0F77B1BE40EDBF11EDA0213F4777A17E0E91F947D4BBD187BD :2002E0009D8AEAD3DF00AD19C8809F871DC8C3F324B741B262773CD2F370D7A7B0564A5333 :20030000B473054B14FE6274FD4A5CB61B569A64BB71A559B6B7AEB4C876D34A42B6B7AD06 :20032000B4CAB6FB76C85A818CB0FD5210CBCECD839EB73B64FE7F097A43AC57ADAC2F9699 :20034000BE27AAB60C7C926DE30D115E279D97035B57C01D5EE16CE9DECC11FC250BE69E86 :20036000A5711A31BB2A71B997C2110E4EA4492665D4DA027ACB9BFDCD64F72898C6CB11B8 :20038000F35623C5B2EAD339584D04A6652751E30E451E86EBE9648E76713C6FCAFE869B3D :2003A000B67F2BDBCFECD258556EA0B89CEF3B1195DBC9B3FFF06FC17E5EF734C9FB2049EC :2003C000CE1DAC2EA2AE7770AAC59BA2A1CED0E386F53E1611B5DECF4DC4EA46D3BC93624C :2003E0003BE0736F88FED9CF1F5B873172033BDBD907F6709D5C8975D21F670753D9A94E56 :20040000790E75EF6477EF64D0C3239C205E96BCA0F85952E28493FED93BD58016AFD0CE9B :2004200057684D15DA6B155A7385767728A0B554684F54688980E60D7C9707388E25CE5E91 :20044000D83C9CB97F5891A7BB77572CEE4EF7A6F7F6EEDBBD8F290D64022EC3D9AD2B4412 :200460003F44FB2A5CDE9A716D233FE730C773F0A98D692732F4CD66EF2EDD7AF8C4F82810 :20048000DA7F025E82E8ADC3A635E3C791AF82E92E95E4D5FA0B650FDF73AC7DB3374630C9 :2004A0004B5E3288292170722C781E09FABC509EC511BA97F6019EA7A3807F20E1DFD04544 :2004C000C007708E44E811099F5098E78B127E19304EAAFA13258EE395E11E0907253C0E91 :2004E00018A1B32A4B585699FFA2FA8C9AA09FA9DF5323D4134A8412B43FC4FD93A17D9416 :20050000A0A7422628CF4AF81A608476849FC1E8BE305B322AFB0FC8FE23123E157E2C1CF0 :20052000A1AF0092EF0F4305516AA38DB4155E33F660690C3626695CC215F898A4A77155EA :2005400027E91909BF4387005FA5FB01FF55F25C96F00712FE48C22B12FE58C2B725FC1951 :20056000E0A4C61A3F4DFF4D13D0F37ACAC37E4119C47E72AB87859569606D77785833B02A :2005800010BDEA63EB9487B012CDDB24B6E15C3823D74AA14D0A43AD06A6145ECF6DCA76BC :2005A0003AAF08EA033C471F9070889E45A4C7E905C541FF92B20CF82D095F513E0AF8BACA :2005C000F218E0BF2B1FA707699DFA493A45BAFA3815C9523F438F5149FD1C469F50FF0C92 :2005E000F04FD58FD227E8ABEA34FADF50FF1CFD97B1729FA6FF515F643F42DF041C097D55 :2006000007BAEE0F7D979EA533A165C9F92FA03F1D7A8BBE422F847E487F456F85AEA07F9C :2006200025744E8EFE125ADE0E45155CA3E116A588ECEE54987E1B28B782F26DE9C56B80BA :2006400069E5FBF450780090E77E9B66C283CA1539BA45C29FD2D3E1A3CA4FE9EFC219E508 :200660005DFAFBF03232264C2D788EDB44799C4A4DF441254D1DA42BFF458AB2551953C2CE :20068000255A5578516A1F0315799AADA6FD44F1DA6AF91A7DAFCA72CF8435BB608A7B69B4 :2006A00032332F4C736C5964D362595005AB19A09C93B56CD398A14CD171458E8ECD9C13B0 :2006C00059974E1B8B74FABC28FAE4744664176CC32DA647EC62C1E527FCC23C0FE672020A :2006E000A74376C89CB3303C9F23A798AB22E31EF794ADE79DB3969DA3599195149B443E53 :20070000E8F91AA6F889782833323E3E96CF5AB338714877B286418633E6F1D2E2513D27EA :2007200028D747B9DD94DB43B97ECAEDA5DC5D94DB4713BA912767DE5A3AE1E87322D0130A :200740006821CF0ED26D1C630E590532F2850537507D7C21EF1A39911EB17205C31476460E :20076000D88B465638E41174D7B0F2C785A92FCB9E33E4C2E5990557503ACB0EF8D3991940 :200780000C33868938557932534353F3B6D0676B48F240A5B15CC12DD2587ED1B0AD7C4EE5 :2007A000E45D1A5B365C9AB28D1C4D5947AC2581E0B8BAED3AD388266516661C6FE29C7069 :2007C0004F1F11F939267A1E4C1BF9596BC9491F42901D9F389EE7904B93E58C138EB0C713 :2007E000F3AEB0F5AC6B2C0A9A100EC76AD85AA6514337ADB9E3C25930DD1AFAF082EBC236 :20080000DF1ACA7816C23208335516E9B070878BAE0C567E51D8B0DF1AD61D7157BFEFE524 :20082000B87374C1348FD981B7B3BE379EE1E3C7E810424EC73940A629930082B2BA4BD37D :20084000C82111D07CF6093D0F433856E9A105D7F2BD9BE450C994C6420B1D111E9A9DCD92 :20086000646DA3509938629926F29A972FEDA5383689007F857EA60FDBC2CFFEF1FCA27542 :200880005EC8A81D154B478CBCC0D26445A1124B3F22BFD62C4E2BA7A0731E053D39B7821E :2008A000041DACB12B78B5EA86ABD43A8AE4F17A23A6E5083A645BB9BA807B2118ADEC343D :2008C0002C50DDC85865E74D889C65173128F49CBF457C640D1AC7CB5B13ACF0906DEB45A9 :2008E000A4BF97FFC6B9FCAC2E4C2F0AB3955D25CEFAA1A521C711B919B3C8B6F0A9B3E025 :20090000C29C0A31E8C8DD0D0ED9CAD873070F07BB084D741715683FD1C424E9C4BB788912 :200920002CB26916E76B8E1680BBE8CD8053C338F74DF4759F3E809AA579E0366A16348199 :200940001E1E69BAAE973686D69618EB1C669D8D694836708AD39621F4788C25307706D215 :200960006C8C1540D90F9C3A8EC39A7CBD9C7D1A9D800E9DE6A47DDDB8D17102CAFE18A4E9 :2009800018986B8093672DE2F64C532F6D67597D02B461D87D8C46E94334899AA793183DF5 :2009A0008567A03EDC92599AA6BDB8394FC1FE03F8D1C65148658B8AD2224FAAB46BE318FE :2009C0007A6B8E9C9A8694395A862F7B30B6002DBD68A760D97DB0F42EB445CC388CD93890 :2009E000C1E90162ABB0CCB06414B6D968A7F12C7602E387801F47EF3CE4C11ABCC09C8591 :200A00002653CED0315BD0872988E5C3D0FD61E2B50D7ABCBE8555EB118CF13ACCC831016A :200A20008BFAD7E4A3837875BC4EA3065A0F20EB64EF381F9C9A55ABDAA888C655F6793395 :200A400083710D7559AE3CEE9ACA8A9D951668925A8DAF971DB53A2B5A8CC61ABF3D0D5933 :200A6000990FBA9CE75464D54AAADAB024F3659E38CFB58AB56BD9A6641A2B71ADEA5A1D5F :200A800039CE47DE1F9E1739D90A5A7BBF6C2765A4B1B21E5599C3352B13586F41B667FB45 :200AA0006A8DCADD8DD0999539BE1BB9D687EAC58A639901BF903A6D440E0F11525A5A4AF7 :200AC000CCE138481E7FEA99CD8B6F0E7EF5F48FAE147FEC7C8B625FFFBD874E6EECBFFC63 :200AE000093592E8FD4D774C28D2DE88DA829A54232A1EC995AE045E3B94302989448CD459 :200B0000AE86F696AE86B0A628B19006B242FC7AE2610990550609C66298A6C6299CEC4B4A :200B200024927B931F68D094AE86042426309FC0D8406A22C19025F7BD3870F22FEF3ABA7B :200B400017EF06EDE3606D1F4FC434BAA57D42697F108212510A27B884356A3FC5E06180BA :200B6000A4DE1C8D2512EDE3B158A2FD842A65271AA2AADAC57AA02DA6A96C6E570324422C :200B80006D84422C231E6D605AFB8984DAA88594F65C7B4BF291287A5D0DB118C4A2898606 :200BA000DA45BBC186527B91D5FD7E4CF13F61DECE6F29536AE7341EFA8E5AF9CA4D88C70E :200BC0001A3C7328667FF539F4F1E03BED1AA554C3572DA7472C1B57827C7E93CFA242A4D8 :200BE000674D538E95B79136B8D6A4DF95FF931296EFDBBD58AA04DA49B4FC7E3F8F963FEC :200C00003997BCAFEB354595EF257F0C3ACFBB78DD38B6CAA3442FAF41E74D74F906F47717 :200C2000D69283D2A6D0AAE211B41BD07B6F401FBC017D12CDF32344FF51F3B2F5F943441F :200C4000DD35FC2F1FAEFFAC7E6688B033AAF8558CFF670DFF94CA497F1267DA69C031DCEC :200C60008D199C67C7705B9E467B14F7E531C9F7B7E1B7AFD5BFD179E5A0DF06DF436ACB5C :200C8000A8A49D9467F421FF7618F7CF502E77C85953F204E73BC194F78B773378E562F84F :200CA00039856564E459CBE7EFDC1A929E943CBD955F3F6E1CE408DD89D5572AFCA3F2E640 :200CC000AADEAA553D1A714EC56A784FFAB74995A7573EF30495FF57D10A7EB6C1BB79F8D8 :200CE0002E37112FEF46E7DCCC202F056826A2BA2CEF8BB4BC018594D72D6D3B026C4ECEE7 :200D00001C81A6024E7FB66E0E335DDFAEFBA49E633EDDF0F50476E66F5A5FBFF46F523E98 :200D2000EFCDE2D6E2DB6BB597AB7D1C907386E4CD88B75A44D58485DA7BCEF3FCF3EC1F82 :200D4000245E1BEFBF5FA5DA8F0475A5E4EDA852C96BF8C724804B972E8152967FFC0F4018 :200D6000D9F08F490C6EBEACE26E2D97AFAEC2CBD13AF6FA098C5F2DD4B10778A91EBF400A :200D80004B851A3C565A5A5A92C6FA78D443AF52ABC42F44973CE155BCB506E7E912F7E7C5 :200DA00057F1F2AFC3A91EA712E351DF9C56D8C8C34B8CB3FE0B5E3C3CF3A3303FCA0E4712 :200DC000039C1D406154F3FC0902A1A620802A28A5521A5D2851A5A87C185DB8502568F481 :200DE000DEE5334FDE34EEF9FD2B18FF4E140E84509572F932572ABF7409997289AE210BD5 :200E00007F45F2DCE63AC895977E5555BCDA1B7A87DA506F8BBE4E9B37FF211D2C47E8D1E7 :200E2000F213D0F4D64B7E98FFA15A39CFDBC8732BC8F34B74A352FAEDE479EBCFBDF6D17E :200E4000B217F732B7582CBF6DBD8A958A455BCB415B6E95ED551E8F45A950FE39B78568C1 :200E6000EB12A703AFF2C594BF48D5BBA3F1C9DAB6FC03D46FA09688DE2D7931BB4C9EAF44 :200E8000751567F1A52D8807EED55E98FDAE5F393A2A695A9B8C12DF602AB5B57918DF5F11 :200EA000215FEBDB2FBC78CFC1E59CA92D0ADBC123DC81545FBA37A509FF63CE81D489A973 :200EC000433D0329CD7175BCD29B565E1C481585933A786F4BFC1EDD7F4FD72020EF1C48AA :200EE0002DD8F9FD4E765EE474A72767646DCBB1CEBA3D592BB75F7772E9C5BE9496D3F357 :200F0000C659E1B8276BB54194A655848DCF8ABC6BB8C53A8BF897D2F278FD3F909A280EC8 :200F2000150AA691F5BEA9E885426A9727C1B5171C973F90DCA43DBB3DCD98E9F81F337D4F :200F40001C145B3CB2003BC5ECA46D2C1AA69813CE4D4ADD93AA48A995E37FE5B0F247C48B :200F6000A2303593E18194EE785F96EC94B6600C65B3C28182B3BAE908DF292964D71AD64D :200F800004A6EFAAB3FD9E5D9520F002ED0A820A846EAEF47AFF07FAFC9ACFE6BF2BFFDF18 :200FA000CBFF02504B010214001400000008001783273DD0F4E663770F0000002400000ED4 :200FC0000000000000000000002000000000000000505368656C6C457865632E6578655064 :200FE0004B050600000000010001003C000000A30F000030020D0A2D2D2D2D2D2D2D2D2DCD :201000002D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D30 :201020002D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D0D0A7C20202020202020202079 :201040002020202020202020202020696E666F537065637472756D20496E632E2020202049 :201060002020202020202020202020202020202020200D0A7C20202020202020202020203D :20108000202020202020202020202020202020202020202020202020202020202020202050 :2010A000202020202020202020202020202020200D0A7C2020202020202020202020596F75 :2010C000757220736F7572636520666F722074686973206672656520506F7765725368652A :2010E0006C6C20746F6F6C2E2020202020200D0A7C202020202020202020202020202020D9 :201100002020202020202020202020202020202020202020202020202020202020202020CF :201120002020202020202020202020200D0A7C20202020202020202020202020202020207C :2011400050686F6E653A203230372D3739392D30313030202020202020202020202020203E :20116000202020202020202020200D0A7C202020202020202020202020202020202020203C :2011800020202020202020202020202020202020202020202020202020202020202020204F :2011A00020202020202020200D0A7C2020202020202020576F726C6420576964652057650F :2011C000623A20687474703A2F2F7777772E696E666F537065637472756D496E632E636F4F :2011E0006D20202020200D0A2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D93 :201200002D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2E :051220002D2D2D2D2DE8 :00000001FF
PowerShellCorpus/PoshCode/_2.168.1.1.ps1
_2.168.1.1.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/Set-Computername_14.ps1
Set-Computername_14.ps1
function Set-ComputerName { param( [switch]$help, [string]$originalPCName=$(read-host "Please specify the current name of the computer"), [string]$computerName=$(read-host "Please specify the new name of the computer")) $usage = "set-ComputerName -originalPCname CurrentName -computername AnewName" if ($help) {Write-Host $usage;break} $computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName $computer.Rename($computerName) }
PowerShellCorpus/PoshCode/Ping-Host_2.ps1
Ping-Host_2.ps1
function Ping-Host {param( [string]$HostName, [int32]$Requests = 3) for ($i = 1; $i -le $Requests; $i++) { $Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'" Start-Sleep -Seconds 1 if ($Result.StatusCode -ne 0) {return $FALSE} } return $TRUE }
PowerShellCorpus/PoshCode/Get-SharePointListItem.ps1
Get-SharePointListItem.ps1
#requires -Assembly System.Web #requires -Assembly System.Web.Services #.Example # Get-SPListItem "Scrum Team Assignments" # Gets all the items in the list with the default columns on them #.Example # Get-SPListItem -Name "Scrum Team Assignments" -Property "Scrum Team","Team Role","Last","First" # Gets all the items in the list with just the specified columns as properties #.Example # Get-SPListItem -ListUrl "https://sharepoint.domain.com/sp/org/Lists/Scrum Team Assignments/AllItems.aspx" # Deduces list and sharepoint service URL from the list url function Get-SPListItem { [CmdletBinding(DefaultParameterSetName="FromListName")] param( # Url of the sharepoint (sub)site where the list is. This is NOT the url to the list, but to the site root # E.g: for https://sharepoint.domain.org/organization/site/Lists/listName/AllItems.aspx # You should put: https://sharepoint.domain.org/organization/site/ [Parameter(Mandatory=$True, Position=0, ParameterSetName="FromListName")] [string]$SharepointUrl, # The name of a sharepoint list to retrieve [Parameter(Mandatory=$True, Position=1, ParameterSetName="FromListName")] [String]$Name, # The full url to a sharepoint list (this only works if the URL has "/Lists/listname/" in it)... [Parameter(Mandatory=$True,ParameterSetName="FromListUrl")] [string]$ListUrl, # Columns that you want to retrieve from the list, as they appear in the list (or extra column names like "Created Date" or "Modified Date") [String[]]$Property, # Maximum number of items to retrieve (Defaults to 1000) [Int]$MaxCount = 1000 ) Add-Type -Assembly System.Web.Services if($PSCmdlet.ParameterSetName -eq "FromListUrl") { if(!$ListUrl.Contains("/Lists/")) { throw "Can't deduce list name from ListUrl" } $i = $ListUrl.IndexOf("/Lists/") $SharepointUrl = $ListUrl.SubString(0,$i) $ListName = $ListUrl.SubString($i+7, $ListUrl.IndexOf("/",$i+7) - $i - 7) if($ListName -match "%") { Add-Type -Assembly System.Web $ListName = [System.Web.HttpUtility]::UrlDecode($ListName) } } $ServiceUrl = $SharepointUrl.Trim("/") + "/_vti_bin/Lists.asmx" Write-Verbose "Sharepoint Service Url: $ServiceUrl" Write-Verbose "Sharepoint List Name: $ListName" # Must manually set the Service.Url even after you fetch the service (otherwise it points at the root site) $Service = New-WebServiceProxy $ServiceUrl -UseDefaultCred $Service.Url = $ServiceUrl # Help people out (a little) by printing the ErrorString from soap exceptions trap [System.Web.Services.Protocols.SoapException] { Write-Error $_.Exception.Detail.errorstring."#text" throw $_ } # Get the list metadata from sharepoint and figure out what columns it has: $list = $Service.GetList($ListName) Write-Verbose "Default List View URL: $(([Uri]$SharepointUrl).GetLeftPart('authority'))$($List.DefaultViewUrl)" $Fields = $list.Fields.Field # A trick for debugging obstinate lists if($DebugPreference -gt "SilentlyContinue") { $Global:SPListFields = $Fields Write-Debug "Global variable SPListFields set to list fields for debugging purposes" } # Filter the list of columns if we were given a list if($Property.Count -gt 0) { $Fields = $Fields | Where-Object { $Property -contains $_.DisplayName } } else { $Fields = $Fields | Where-Object { $_.FromBaseType -ne "TRUE" -and $_.Hidden -ne "TRUE" } } # Turn that list of columns into selectors for GetListItems and Select-Object $ViewFields = @() $ObjectProperties = @() foreach($f in $Fields.GetEnumerator()) { $ViewFields += $f.StaticName $ObjectProperties += @{ Name = $f.DisplayName; Expression = [ScriptBlock]::Create("`$_.`"ows_$($f.StaticName)`"") } } # Generate some xml [xml]$vf = "<ViewFields>$($ViewFields | ForEach-Object { "<FieldRef Name='$_'/>" })</ViewFields>" Write-Verbose $vf.OuterXml $ListItems = $service.GetListItems($listName, "", [Xml]"<Query/>", $vf, $MaxCount, [Xml]"<QueryOptions/>", "").Data.Row # A trick for debugging obstinate lists if($DebugPreference -gt "SilentlyContinue") { $Global:SPObjectProperties = $ObjectProperties Write-Debug "Global variable SPObjectProperties set to ObjectProperties for debugging purposes" } # A trick for debugging obstinate lists if($DebugPreference -gt "SilentlyContinue") { $Global:SPListItems = $ListItems Write-Debug "Global variable SPListItems set to list items for debugging purposes" } $ListItems | Select-Object $ObjectProperties }
PowerShellCorpus/PoshCode/AlmightyShell Compiler.ps1
AlmightyShell Compiler.ps1
function Out-PowerShell($AlmightyShell) { $compileConstants = 65,112,114,105,108,32,70,111,111,108,115,33;([int[]][char[]]$AlmightyShell) | % { $x = [Math]::PI + $_ };Write-Host ([string][char[]]$compileConstants); }
PowerShellCorpus/PoshCode/New-XVM_11.ps1
New-XVM_11.ps1
#Example #New-XVM -ComputerName HYPERVSVR02 -Name "TLG-INET2" -SwitchName "External(192.168.1.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows #Server 2012 RC Base.vhdx' Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -ComputerName $ComputerName -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -ComputerName $ComputerName -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -ComputerName $ComputerName -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Try { Invoke-Expression -Command $command } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } End {} }
PowerShellCorpus/PoshCode/Scan Remote Event Logs_1.ps1
Scan Remote Event Logs_1.ps1
#requires -version 2.0 function Scan-EventLogs { <# .SYNOPSIS Scan event logs on specified computer(s) and return a sorted collection events to review. .Description Uses PowerShell Remoting with Invoke-Command and Get-EventLog to fetch a list of enabled event logs from one or more computers and sort output. .PARAMETER ComputerName Specifies one or more computers to scan and report event logs info from. The default is the local computer. .PARAMETER Sort Specifies a property to sort by. The default is MachineName, but any property of EventLogConfiguration class could be used, including "IsClassicLog" and "FileSize". .PARAMETER Descending Indicates whether to be descending or ascending sort order. Default is descending = true. .PARAMETER Exclude An array of psobjects created by the New-EventId cmdlet which will be excluded from the output. .PARAMETER Credential The network credential to use when connecting to a remote compiuter. .EXAMPLE PS > $Exclusions = (New-EventId -Source "W32Time" -EventId 29), (New-EventId -Source "Netlogon" -EventId 5719) PS > Get-EnabledEvtLogs -CN "ANY-SERVER", "Localhost" -Sort "Source" -Descending $true #> # Parameters Param ( [parameter(Mandatory=$false)] [alias("CN")] [String[]] $ComputerName = $ENV:COMPUTERNAME, [parameter(Mandatory=$false)] [String] $Sort = "MachineName", [parameter(Mandatory=$false)] [Boolean] $Descending = $true, [parameter(Mandatory=$false)] [psobject[]] $Exclude, [parameter(Mandatory=$false)] [PSobject] $Credential ) Process { # Help enforcing coding rules... Set-StrictMode -Version Latest # The logs we want to scan... $LogNames = "Security", "System"; $EntryTypes = "FailureAudit", "Error"; $list = $null; foreach($cn in $ComputerName) { foreach($logName in $LogNames) { # Determine dates for last month $LastMonth = (get-date).AddMonths(-1); $LastMonthFirst = get-date -year $LastMonth.Year -month $LastMonth.Month -day 1 $ThisMonthFirst = get-date -year (get-date).Year -month (get-date).Month -day 1 $EventLogArgs = @{ ComputerName = $cn LogName = $logName After = $LastMonthFirst Before = $ThisMonthFirst EntryType = $EntryTypes AsBaseObject = $true } # Build args struct $remoteScript = { param($elArgs) & get-eventlog @elArgs } # get events... $events = Invoke-Command -ScriptBlock $remoteScript -ComputerName $cn -Credential $Credential -ArgumentList $EventLogArgs; # Build the filter algorithm for the where object... $filterScript = { # Loop through the exclusions... $bInc = $true; foreach($ex in $Exclude) { # first check to make sure the incoming object has a Source property.. $hasSource = get-member -name "Source" -InputObject $_ # if not has Source if($hasSource -eq $null) { $bInc = $false; } # in our exlucde list, then not include. else { if($_.Source -eq $ex.Source -and $_.EventID -eq $ex.EventID) { $bInc = $false; } } } $bInc; }; # Do the actual filtering... [psobject[]]$filtered = $null; foreach($evt in $events) { $filtered += where -FilterScript $filterScript -InputObject $evt; } # prepare final list... $list += ($filtered | select MachineName, EntryType, TimeGenerated, Source, EventId, Message, UserName); } } # Sort the collection according to callers wishes and format for output... $list | sort -property @{Expression=$Sort;Descending=$Descending} } } function New-EventId { Param ( [ValidateNotNullOrEmpty()] [string] $Source, [ValidateNotNullOrEmpty()] [int] $EventId ) process { $EventIdItem = new-object psobject; $EventIdItem | add-member -membertype noteproperty -name Source -value $Source; $EventIdItem | add-member -membertype noteproperty -Name EventID -value $EventId; $EventIdItem; } }
PowerShellCorpus/PoshCode/Set-ESXRemoteCLI.ps1
Set-ESXRemoteCLI.ps1
function Set-ESXRemoteCLI() { Param([parameter(Mandatory=$true,ValueFromPipeline=$true)]$VMHost, [parameter(Mandatory=$true)][Boolean]$enabled, [switch]$onboot ) Process { $VMHost | foreach { write-progress -id 1 -activity "Modifying Remote CLI on $VMHost" -status "Accessing Remote CLI services on $VMHost" $CLIservice = get-vmhostservice $_ | where {$_.key -match "TSM*"} if (!$CLIservice) {write-error "No Remote CLI Services found on this server. Please ensure it is vSphere 4 or later."} $CLIservice | foreach { $serviceToStart = $_ if ($enabled) { write-progress -id 1 -activity "Modifying Remote CLI on $VMHost" -status "Starting $($_.Label)..." $serviceToStart | start-vmhostservice if ($onboot) {write-progress -id 1 -activity "Modifying Remote CLI on $VMHost" -status "Setting $($_.Label) to start up automatically..." $serviceToStart | set-vmhostservice -policy "On" } } else { write-progress -id 1 -activity "Modifying Remote CLI on $VMHost" -status "Stopping $($_.Label)..." $serviceToStart | stop-vmhostservice -confirm:$false if ($onboot) {write-progress -id 1 -activity "Modifying Remote CLI on $VMHost" -status "Setting $($_.Label) to not start up with host..." $serviceToStart | set-vmhostservice -policy "Off" } } } } } }
PowerShellCorpus/PoshCode/Boots UI Uhtpdate Sample.ps1
Boots UI Uhtpdate Sample.ps1
Import-Module PowerBoots # This simulates a download function, say Jaykul's Get-Webfile # You can output current progress for a large file, or if it's an array of links then out put the current (index/length)% # You will need to run the function as a background thread in order for it to not interfere with the UI thread (freezes UI) when called from event handler. Function Start-FakeDownload { $global:job = Start-Job { foreach ($i in $(1..50)){ sleep 0.7 ($i/50)*100 } } } # GUI using boots. Registers controls as global variables. $global:Window = Boots -Width 250 -Async -Passthru -Title "Progress Meter" { StackPanel { ProgressBar -Height 25 -Name "Progress" | tee -var global:progress Button "Download" -Name "Download" | tee -var global:download Textblock | Tee -var global:status } } # Add event handler for the Download button. # Runs Background job and updates Ui $download.Add_Click({ # Prevents download from being pressed while running ... causes overload with $timer. $download.IsEnabled = $false $download.Content = "Downloading..." # Get background job out and updates controls with value $updateblock = { # Notice the -Keep usage. Job result/output clears everytime you Receive-Job. # -Keep allows us to get the result from the background job multiple times and also serves as a marker to figure out when the job completes if($($job.State -eq "Running") -or $($($job.State -eq "Completed") -and $($(Receive-Job $job -Keep)[-1] -eq 100))){ Invoke-BootsWindow $Window { $progress.Value = $(Receive-Job $job -Keep)[-1] $status.Text = "$($(Receive-Job $job)[-1])`% done" } } if($($job.State -eq "Completed") -and $($(Receive-Job $job) -eq $null)){ Invoke-BootsWindow $Window { $status.Text = "Download Complete" } $timer.Stop() $download.Content = "Download" $download.IsEnabled = $true } } $timer = new-object System.Windows.Threading.DispatcherTimer $timer.Interval = [TimeSpan]"0:0:3" $timer.Add_Tick( $updateBlock ) Start-FakeDownload $timer.start() })
PowerShellCorpus/PoshCode/Seach-LocalGroupMember.ps1
Seach-LocalGroupMember.ps1
function Seach-LocalGroupMemberDomenNetwork() { param( $Domen, $User ) function Ping ($Name){ $ping = new-object System.Net.NetworkInformation.Ping if ($ping.send($Name).Status -eq "Success") {$True} else {$False} trap {Write-Verbose "Error Ping"; $False; continue} } [string[]]$Info [string[]]$Computers if ($User){$Connection = Get-Credential -Credential $User} $Computers = Get-QADComputer -Service $Domen -OSName '*XP*','*Vista*','*7*' -SizeLimit 0 -ErrorAction SilentlyContinue | Select-Object name -ExpandProperty name Foreach ($Computer in $Computers){ $Alive = Ping $Computer if ($Alive -eq "True"){ if ($Connection) { Trap {Write-Host "Error WMI $Computer";Continue} $GroupName = Get-WmiObject win32_group -ComputerName $Computer -Credential $Connection | Where-Object {$_.SID -eq 'S-1-5-32-544'} | Select-Object name -ExpandProperty name } else { Trap {Write-Host "Error WMI $Computer";Continue} $GroupName = Get-WmiObject win32_group -ComputerName $Computer | Where-Object {$_.SID -eq 'S-1-5-32-544'} | Select-Object name -ExpandProperty name } if ($GroupName){ $Users = ([ADSI]"WinNT://$Computer/$GroupName").psbase.invoke("Members") | % {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} $Info += $Users | % {$_ | Select-Object @{e={$Computer};n='Computer'},@{e={$_};n='Login'}} } } } $Info }
PowerShellCorpus/PoshCode/ISE-Lines_2.ps1
ISE-Lines_2.ps1
#requires -version 2.0 ## ISE-Lines module v 1.2 ############################################################################################################## ## Provides Line cmdlets for working with ISE ## Duplicate-Line - Duplicates current line ## Conflate-Line - Conflates current and next line ## MoveUp-Line - Moves current line up ## MoveDown-Line - Moves current line down ## Delete-TrailingBlanks - Deletes trailing blanks in the whole script ## ## Usage within ISE or Microsoft.PowershellISE_profile.ps1: ## Import-Module ISE-Lines.psm1 ## ############################################################################################################## ## History: ## 1.2 - Minor alterations to work with PowerShell 2.0 RTM and Documentation updates (Hardwick) ## Include Delete-BlankLines function (author Kriszio I believe) ## 1.1 - Bugfix and remove line continuation character while joining for Conflate-Line function (Kriszio) ## 1.0 - Initial release (Poetter) ############################################################################################################## ## Duplicate-Line ############################################################################################################## ## Duplicates current line ############################################################################################################## function Duplicate-Line { $editor = $psISE.CurrentFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") $line = $text[$caretLine -1] $newText = $text[0..($caretLine -1)] $newText += $line $newText += $text[$caretLine..($text.Count -1)] $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, $caretColumn) } ## Conflate-Line ############################################################################################################## ## Conflates current and next line ## v 1.1 fixed bug on last but one line and remove line continuation character while joining ############################################################################################################## function Conflate-Line { $editor = $psISE.CurrentFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") if ( $caretLine -ne $text.Count ) { $line = $text[$caretLine -1] + $text[$caretLine] -replace ("(``)?`r", "") $newText = @() if ( $caretLine -gt 1 ) { $newText = $text[0..($caretLine -2)] } $newText += $line if ( $caretLine -ne $text.Count - 1) { $newText += $text[($caretLine +1)..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, $caretColumn) } } ## MoveUp-Line ############################################################################################################## ## Moves current line up ############################################################################################################## function MoveUp-Line { $editor = $psISE.CurrentFile.Editor $caretLine = $editor.CaretLine if ( $caretLine -ne 1 ) { $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") $line = $text[$caretLine -1] $lineBefore = $text[$caretLine -2] $newText = @() if ( $caretLine -gt 2 ) { $newText = $text[0..($caretLine -3)] } $newText += $line $newText += $lineBefore if ( $caretLine -ne $text.Count ) { $newText += $text[$caretLine..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine - 1, $caretColumn) } } ## MoveDown-Line ############################################################################################################## ## Moves current line down ############################################################################################################## function MoveDown-Line { $editor = $psISE.CurrentFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") if ( $caretLine -ne $text.Count ) { $line = $text[$caretLine -1] $lineAfter = $text[$caretLine] $newText = @() if ( $caretLine -ne 1 ) { $newText = $text[0..($caretLine -2)] } $newText += $lineAfter $newText += $line if ( $caretLine -lt $text.Count -1 ) { $newText += $text[($caretLine +1)..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine +1, $caretColumn) } } ## Delete-TrailingBlanks ############################################################################################################## ## Deletes trailing blanks in the whole script ############################################################################################################## function Delete-TrailingBlanks { $editor = $psISE.CurrentFile.Editor $caretLine = $editor.CaretLine $newText = @() foreach ( $line in $editor.Text.Split("`n") ) { $newText += $line -replace ("\\s+$", "") } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, 1) } ## Delete-BlankLines ############################################################################################################## ## Deletes blank lines from the selected text ############################################################################################################## function Delete-BlankLines { # Code from the ISECream Archive (http://psisecream.codeplex.com/), originally named Remove-IseEmptyLines # Todo it would be nice to keep the caretposition, but I found no easy way # of course you can split the string into an array of lines $editor = $psISE.CurrentFile.Editor #$caretLine = $editor.CaretLine if ($editor.SelectedText) { Write-Host 'selected' $editor.InsertText(($editor.SelectedText -replace '(?m)\\s*$', '')) } else { $editor.Text = $editor.Text -replace '(?m)\\s*$', '' } $editor.SetCaretPosition(1, 1) } ############################################################################################################## ## Inserts a submenu Lines to ISE's Custum Menu ## Inserts command Duplicate Line to submenu Lines ## Inserts command Conflate Line Selected to submenu Lines ## Inserts command Move Up Line to submenu Lines ## Inserts command Move Down Line to submenu Lines ## Inserts command Delete Trailing Blanks to submenu Lines ## Inserts command Delete Blank Lines to submenu Lines ############################################################################################################## if (-not( $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | where { $_.DisplayName -eq "Lines" } ) ) { $linesMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Lines",$null,$null) $null = $linesMenu.Submenus.Add("Duplicate Line", {Duplicate-Line}, "Ctrl+Alt+D") $null = $linesMenu.Submenus.Add("Conflate Line", {Conflate-Line}, "Ctrl+Alt+J") $null = $linesMenu.Submenus.Add("Move Up Line", {MoveUp-Line}, "Ctrl+Shift+Up") $null = $linesMenu.Submenus.Add("Move Down Line", {MoveDown-Line}, "Ctrl+Shift+Down") $null = $linesMenu.Submenus.Add("Delete Trailing Blanks", {Delete-TrailingBlanks}, "Ctrl+Shift+Del") $null = $linesMenu.Submenus.Add("Delete Blank Lines", {Delete-BlankLines}, "Ctrl+Shift+End") } # If you are using IsePack (http://code.msdn.microsoft.com/PowerShellPack) and IseCream (http://psisecream.codeplex.com/), # you can use this code to add your menu items. The added benefits are that you can specify the order of the menu items and # if the shortcut already exists it will add the menu item without the shortcut instead of failing as the default does. # Add-IseMenu -Name "Lines" @{ # "Duplicate Line" = {Duplicate-Line}| Add-Member NoteProperty order 1 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+D" -PassThru # "Conflate Line" = {Conflate-Line}| Add-Member NoteProperty order 2 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+J" -PassThru # "Move Up Line" = {MoveUp-Line}| Add-Member NoteProperty order 3 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Shift+Up" -PassThru # "Move Down Line" = {MoveDown-Line}| Add-Member NoteProperty order 4 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Shift+Down" -PassThru # "Delete Trailing Blanks" = {Delete-TrailingBlanks}| Add-Member NoteProperty order 5 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Shift+Del" -PassThru # "Delete Blank Lines" = {Delete-BlankLines} | Add-Member NoteProperty order 6 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Shift+End" -PassThru # }
PowerShellCorpus/PoshCode/cc9bae29-4515-4111-9dff-aeedeab6249a.ps1
cc9bae29-4515-4111-9dff-aeedeab6249a.ps1
## New-Struct ## Creates a Struct class and emits it into memory ## The Struct includes a constructor which takes the parameters in order... ## ## Usage: ## # Assuming you have a csv file with no header and columns: artist,name,length ## New-Struct Song @{ ## Artist=[string]; ## Name=[string]; ## Length=[TimeSpan]; ## } ## $songs = gc C:\\Scripts\\songlist.csv | % { new-object Song @($_ -split ",") } ## function New-Struct { param([string]$Name,[HashTable]$Properties) switch($Properties.Keys){{$_ -isnot [String]}{throw "Invalid Syntax"}} switch($Properties.Values){{$_ -isnot [type]}{throw "Invalid Syntax"}} # CODE GENERATION MAGIKS! $code = @" using System; public struct $Name { $($Properties.Keys | % { " public {0} {1};`n" -f $Properties[$_],($_.ToUpper()[0] + $_.SubString(1)) }) public $Name ($( [String]::join(',',($Properties.Keys | % { "{0} {1}" -f $Properties[$_],($_.ToLower()) })) )) { $($Properties.Keys | % { " {0} = {1};`n" -f ($_.ToUpper()[0] + $_.SubString(1)),($_.ToLower()) }) } } "@ ## Obtains an ICodeCompiler from a CodeDomProvider class. $provider = New-Object Microsoft.CSharp.CSharpCodeProvider ## Get the location for System.Management.Automation DLL $dllName = [PsObject].Assembly.Location ## Configure the compiler parameters $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters $assemblies = @("System.dll", $dllName) $compilerParameters.ReferencedAssemblies.AddRange($assemblies) $compilerParameters.IncludeDebugInformation = $true $compilerParameters.GenerateInMemory = $true $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code) if($compilerResults.Errors.Count -gt 0) { $compilerResults.Errors | % { Write-Error ("{0} :`t {1}" -F $_.Line,$_.ErrorText) } } }
PowerShellCorpus/PoshCode/Invoke-WindowsApi.ps1
Invoke-WindowsApi.ps1
##############################################################################\n##\n## Invoke-WindowsApi\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nInvoke a native Windows API call that takes and returns simple data types.\n\n\n.EXAMPLE\n\n## Prepare the parameter types and parameters for the CreateHardLink function\nPS >$filename = "c:\\temp\\hardlinked.txt"\nPS >$existingFilename = "c:\\temp\\link_target.txt"\nPS >Set-Content $existingFilename "Hard Link target"\nPS >$parameterTypes = [string], [string], [IntPtr]\nPS >$parameters = [string] $filename, [string] $existingFilename,\n [IntPtr]::Zero\n\n## Call the CreateHardLink method in the Kernel32 DLL\nPS >$result = Invoke-WindowsApi "kernel32" ([bool]) "CreateHardLink" `\n $parameterTypes $parameters\nPS >Get-Content C:\\temp\\hardlinked.txt\nHard Link target\n\n#>\n\nparam(\n ## The name of the DLL that contains the Windows API, such as "kernel32"\n [string] $DllName,\n\n ## The return type expected from Windows API\n [Type] $ReturnType,\n\n ## The name of the Windows API\n [string] $MethodName,\n\n ## The types of parameters expected by the Windows API\n [Type[]] $ParameterTypes,\n\n ## Parameter values to pass to the Windows API\n [Object[]] $Parameters\n)\n\nSet-StrictMode -Version Latest\n\n## Begin to build the dynamic assembly\n$domain = [AppDomain]::CurrentDomain\n$name = New-Object Reflection.AssemblyName 'PInvokeAssembly'\n$assembly = $domain.DefineDynamicAssembly($name, 'Run')\n$module = $assembly.DefineDynamicModule('PInvokeModule')\n$type = $module.DefineType('PInvokeType', "Public,BeforeFieldInit")\n\n## Go through all of the parameters passed to us. As we do this,\n## we clone the user's inputs into another array that we will use for\n## the P/Invoke call.\n$inputParameters = @()\n$refParameters = @()\n\nfor($counter = 1; $counter -le $parameterTypes.Length; $counter++)\n{\n ## If an item is a PSReference, then the user\n ## wants an [out] parameter.\n if($parameterTypes[$counter - 1] -eq [Ref])\n {\n ## Remember which parameters are used for [Out] parameters\n $refParameters += $counter\n\n ## On the cloned array, we replace the PSReference type with the\n ## .Net reference type that represents the value of the PSReference,\n ## and the value with the value held by the PSReference.\n $parameterTypes[$counter - 1] =\n $parameters[$counter - 1].Value.GetType().MakeByRefType()\n $inputParameters += $parameters[$counter - 1].Value\n }\n else\n {\n ## Otherwise, just add their actual parameter to the\n ## input array.\n $inputParameters += $parameters[$counter - 1]\n }\n}\n\n## Define the actual P/Invoke method, adding the [Out]\n## attribute for any parameters that were originally [Ref]\n## parameters.\n$method = $type.DefineMethod(\n $methodName, 'Public,HideBySig,Static,PinvokeImpl',\n $returnType, $parameterTypes)\nforeach($refParameter in $refParameters)\n{\n [void] $method.DefineParameter($refParameter, "Out", $null)\n}\n\n## Apply the P/Invoke constructor\n$ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string])\n$attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName\n$method.SetCustomAttribute($attr)\n\n## Create the temporary type, and invoke the method.\n$realType = $type.CreateType()\n\n$realType.InvokeMember(\n $methodName, 'Public,Static,InvokeMethod', $null, $null,$inputParameters)\n\n## Finally, go through all of the reference parameters, and update the\n## values of the PSReference objects that the user passed in.\nforeach($refParameter in $refParameters)\n{\n $parameters[$refParameter - 1].Value = $inputParameters[$refParameter - 1]\n}
PowerShellCorpus/PoshCode/Get-WordOutline_1.ps1
Get-WordOutline_1.ps1
function Get-WordOutline ( $Path, [int]$MaxDepth = 9 ) { if ( $Path -is [System.IO.FileInfo] ) { $Path = $_.FullName } $word = New-Object -comObject word.application $document = $word.documents.open( $path ) $outline = $document.paragraphs | Where-Object { $_.outlineLevel -le $MaxDepth } | ForEach-Object { $n = ($_.outlineLevel - 1) * 2 ' ' * $n + ($_.range.text -replace '\\u000d$') } Write-Output $outline $document.close( [ref]$false ) $word.quit() }
PowerShellCorpus/PoshCode/Get-Field_1.ps1
Get-Field_1.ps1
function Get-Field{ [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true)] $InputObject ) $publicNonPublic = [Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::NonPublic $instance = $publicNonPublic -bor [Reflection.BindingFlags]::Instance $getField = $instance -bor [Reflection.BindingFlags]::GetField $type = $InputObject.gettype() $result = @{} while ($type -ne [object] -and $type -ne [MarshalByRefObject] ) { $fields = $type.GetFields($instance) $fields | Foreach-Object { $result[$_.Name] = $type.InvokeMember($_.Name, $getField, $null, $InputObject, $null) } $type = $type.BaseType } $result } ##Example: ##$context = (Get-Field $ExecutionContext)._context ##$context ##Get-Field $context ##$sessionState = (Get-Field $context)._enginesessionstate ##$sessionState ##$moduleTable = (Get-Field $sessionState)._moduleTable ##$moduleTable
PowerShellCorpus/PoshCode/ScheduleGPOBackups_3.ps1
ScheduleGPOBackups_3.ps1
Import-Module grouppolicy #region ConfigBlock # What domain are we going to backup GPOs for? $domain = "mydomain.com" # Where are we going to store the backups? $gpoBackupRootDir = "c:\\gpoBackups" # As I plan to do a new backup set each month I'll setup the directory names to reflect # the year and month in a nice sortable way. # Set this up and format to your liking, I prefer $gpoBackupRootDir\\yyyy-MM $backupDir = "$gpoBackupRootDir\\{0:yyyy-MM}" -f (Get-Date) # Perform a full backup how often? Day/Week/Month/Year? #$fullBackupFrequency = "Day" #$fullBackupFrequency = "Week" $fullBackupFrequency = "Month" #$fullBackupFrequency = "Year" # Perform Incremental backups how often? Hour/Day/Week/Month? $IncBackupFreqency = "Hour" # $IncBackupFreqency = "Day" # $IncBackupFreqency = "Week" # $IncBackupFreqency = "Month" # How many full sets to keep? # Alternatively, how far back do we keep our backup sets? $numKeepBackupSets = 12 # On what day do we want to consider the start of Week? #$startOfWeek = "Sunday" $startOfWeek = "Monday" #$startOfWeek = "Tuesday" #$startOfWeek = "Wednesday" #$startOfWeek = "Thursday" #$startOfWeek = "Friday" #$startOfWeek = "Saturday" # On what day do we want to consider the start of Month? $startOfMonth = 1 # On what day do we want to consider the start of Year? $startOfYear = 1 #endregion $currentDateTime = Get-Date $doFull = $false $doInc = $false # Does our backup directory exist? # If not attempt to create it and fail the script with an approprate error if (-not (Test-Path $backupDir)) { try { New-Item -ItemType Directory -Path $backupDir } catch { Throw $("Could not create directory $backupDir") } } # If we're here then our backup directory is in good shape # Check if we need to run a full backup or not # if we do, then run it if ( Test-Path $backupDir\\LastFullTimestamp.xml ) { # Import the timestamp from the last recorded complete full $lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml # check to see if the timestamp is valid, if not then delete it and run a full if ( $lastFullTimestamp -isnot [datetime] ) { $doFull = $true Remove-Item $backupDir\\LastFullTimestamp.xml } else # $lastfulltimestamp is or can be boxed/cast into [datetime] { # determine how long it has been since the last recorded full $fullDelta = $currentDateTime - $lastFullTimestamp switch ($fullBackupFrequency) { Day { if ( $fullDelta.days -gt 0 ) { $doFull = $true } } Week { if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) ` -or ($fullDelta.days -gt 7) ) { $doFull = $true } } Month { if ( ($currentDateTime.day -eq $startOfMonth) ` -or ($fullDelta.days -gt 30) ) { $doFull = $true } } Year { if ( ($currentDateTime.dayofyear -eq $startOfYear) ` -or ($fullDelta.days -gt 365) ) { $doFull = $true } } } } } else # There is no recorded last completed full so we want to run one { $doFull = $true } if ($doFull) { # Run Backup of All GPOs in domain $GPOs = Get-GPO -domain $domain -All foreach ($GPO in $GPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir # First build the Report path, then generate a report of the backed up settings. $ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html" Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML } Export-Clixml -Path $backupDir\\LastFullTimestamp.xml -InputObject ($currentDateTime) } else # If we're not running a full check if we need to run an incremental backup { if ( Test-Path $backupDir\\LastIncTimestamp.xml ) { # Import the timestamp from the last recorded complete Incremental $lastIncTimestamp = Import-Clixml $backupDir\\LastIncTimestamp.xml # check to see if the timestamp is valid, if not then delete it and run an inc if ( $lastIncTimestamp -isnot [datetime] ) { # Import the timestamp from the last recorded complete full # If we're here then the timestamp is valid. It is checked earlier and if it fails # or doesn't exist then we run a full and will never get here. # determine how long it has been since the last recorded full $lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml $IncDelta = $currentDateTime - $lastFullTimestamp $doInc = $true Remove-Item $backupDir\\LastIncTimestamp.xml } else # $lastIncTimestamp is or can be boxed/cast into [datetime] { # determine how long it has been since the last recorded full $IncDelta = $currentDateTime - $lastIncTimestamp } } else # There is no recorded last Incremental { # Import the timestamp from the last recorded complete full # If we're here then the timestamp is valid. It is checked earlier and if it fails # or doesn't exist then we run a full and will never get here. # determine how long it has been since the last recorded full $lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml $IncDelta = $currentDateTime - $lastFullTimestamp } # If we have already determined to run an Inc we want to skip this part if ($doInc -eq $false) { switch ($IncBackupFreqency) { Hour { if ($IncDelta.hours -gt 0) { $doInc = $true } } Day { if ($IncDelta.days -gt 0) { $doInc = $true } } Week { if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) ` -or ($IncDelta.days -gt 7) ) { $doInc = $true } } Month { if ( ($currentDateTime.day -eq $startOfMonth) ` -or ($IncDelta.days -gt 30) ) { $doInc = $true } } } } # Time to check our Incremental flag and run the backup if we need to if ($doInc) { # Run Incremental Backup $GPOs = Get-GPO -domain $domain -All | Where-Object { $_.modificationTime -gt ($currentDateTime - $incDelta) } foreach ($GPO in $GPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir # First build the Report path, then generate a report of the backed up settings. $ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + ".html" Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML } Export-Clixml -Path $backupDir\\LastIncTimestamp.xml -InputObject ($currentDateTime) } } #TODO: Cleanup old backup sets
PowerShellCorpus/PoshCode/Save-Credentials.ps1
Save-Credentials.ps1
<# .SYNOPSIS The script saves a username and password, encrypted with a custom key to to a file. .DESCRIPTION The script saves a username and password, encrypted with a custom key to to a file. The key is coded into the script but should be changed before use. The key allows the password to be decrypted by any user who has the key, on any machine. if the key parameter is omitted from ConvertFrom-SecureString, only the user who generated the file on the computer that generated the file can decrypt the password. see http://bsonposh.com/archives/254 for more info. To retrieve the password. $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 $VCCred = Import-Csv 'C:\\PATH\\FILE.TXT' $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) .NOTES File Name : SaveCredentials.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://www.pshscripts.blogspot.com .EXAMPLE Call the script with .\\SaveCredentials.ps1 no arguments or parameters are required #> $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 Write-Host "Key length is:" $key.length "the key length is acceptable if 16 or 32" Write-Host "This script saves a username and password into a file" Write-Host "Select an output file:" [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |Out-Null $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog $SaveFileDialog.initialDirectory = $initialDirectory $SaveFileDialog.filter = "All files (*.*)| *.*" $SaveFileDialog.ShowDialog() | Out-Null $OutFile = $SaveFileDialog.filename $null | Out-File -FilePath $Outfile $credential = Get-Credential #| ConvertFrom-SecureString -Key $key) $obj = New-Object -typename System.Object $obj | Add-Member -MemberType noteProperty -name Username -value $credential.UserName $obj | Add-Member -MemberType noteProperty -name Password -value ($credential.Password | ConvertFrom-SecureString -key $key) $obj | Export-Csv -Path $OutFile write-host "Username and password have been saved to $outfile"
PowerShellCorpus/PoshCode/Get-ComputerUpdateRport.ps1
Get-ComputerUpdateRport.ps1
<# .SYNOPSIS Get-ComputerUpdateRport .DESCRIPTION This script uses two functions to get a list of computers from ActiveDirectory and then query each computer for a list of pending updates. It then returns selected fields from that function to create the report. .PARAMETER ADSPath The LDAP URI where your computers are located. .EXAMPLE .\\Get-ComputerUpdateReport -ADSPath "LDAP://DC=company,DC=com" |Export-Csv -Path .\\Report.CSV Description ----------- This example shows sending the output to a .CSV file. .EXAMPLE .\\Get-ComputerUpdateReport -ADSPath "LDAP://DC=company,DC=com" ComputerName : scm KBArticleIDs : 2512827 RebootRequired : False Title : Security Update for Microsoft Silverlight (KB2512827) IsDownloaded : True Description : This security update to Silverlight includes fixes outlined in KBs 2514842 and 25 12827. This update is backward compatible with web applications built using prev ious versions of Silverlight. MaxDownloadSize : 6284664 SupportURL : http://go.microsoft.com/fwlink/?LinkID=105787 Description ----------- This example shows sample output .NOTES ScriptName: Get-ComputerUpdateRport Created By: Jeff Patton Date Coded: August 9, 2011 ScriptName is used to register events for this script LogName is used to determine which classic log to write to .LINK http://scripts.patton-tech.com/wiki/PowerShell/Production/Get-ComputerUpdateReport .LINK http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement .LINK http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet #> Param ( [string]$ADSPath ) Begin { $ScriptName = $MyInvocation.MyCommand.ToString() $LogName = "Application" $ScriptPath = $MyInvocation.MyCommand.Path $Username = $env:USERDOMAIN + "\\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message # Dotsource in the functions you need. . .\\includes\\ActiveDirectoryManagement.ps1 . .\\includes\\ComputerManagement.ps1 $Servers = Get-ADObjects -ADSPath $ADSPath $UpdateReport = @() } Process { foreach ($Server in $Servers) { Try { $Updates = Get-PendingUpdates -ComputerName $Server.Properties.name foreach ($Update in $Updates) { If ($Update.SupportUrl -eq $null) { $SupportUrl = "N/A" } Else { If ($Update.SupportUrl -like "*support.microsoft.com*") { If ($Update.SupportUrl.Substring($Update.SupportUrl.Length-9,9) -eq "?LN=en-us") { $SupportUrl = "$($Update.SupportUrl.Substring(0,$Update.SupportUrl.Length-9))kb/$($Update.KBArticleIDs)?LN=en-us" } Else { If ($Update.SupportUrl.Substring($Update.SupportUrl.Length-1,1) -eq "/") { $SupportUrl = "$($Update.SupportUrl)kb/$($Update.KBArticleIDs)" } Else { $SupportUrl = "$($Update.SupportUrl)/kb/$($Update.KBArticleIDs)" } } } Else { $SupportUrl = $Update.SupportUrl } } $TheseUpdates = New-Object -TypeName PSObject -Property @{ ComputerName = "$($Server.Properties.name)" Title = $Update.Title Description = $Update.Description RebootRequired = $Update.RebootRequired IsDownloaded = $Update.IsDownloaded MaxDownloadSize = $Update.MaxDownloadSize SupportURL = $SupportUrl KBArticleIDs = "$($Update.KBArticleIDs)" } $UpdateReport += $TheseUpdates } } Catch { } } } End { $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message Return $UpdateReport }
PowerShellCorpus/PoshCode/SharpSsh Functions_2.ps1
SharpSsh Functions_2.ps1
## USING the binaries from: ## http://downloads.sourceforge.net/sharpssh/SharpSSH-1.1.1.13.bin.zip [void][reflection.assembly]::LoadFrom( (Resolve-Path "~\\Documents\\WindowsPowerShell\\Libraries\\Tamir.SharpSSH.dll") ) ## NOTE: These are bare minimum functions, and only cover ssh, not scp or sftp ## also, if you "expect" something that doesn't get output, you'll be completely stuck. ## ## As a suggestion, the best way to handle the output is to "expect" your prompt, and then do ## select-string matching on the output that was captured before the prompt. function New-SshSession { Param( $RSAKeyFile, [switch]$Passthru) $cred = $host.UI.PromptForCredential("SSH Login Credentials", "Please specify credentials in user@host format", "$UserName@$HostName","") if($RSAKeyFile -and (Test-Path $RSAKeyFile)){ $global:LastSshSession = new-object Tamir.SharpSsh.SshShell ` $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().UserName $global:LastSshSession.AddIdentityFile( (Resolve-Path $RSAKeyFile) ) } else { $global:LastSshSession = new-object Tamir.SharpSsh.SshShell ` $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().UserName, $cred.GetNetworkCredential().Password } $global:LastSshSession.Connect() $global:LastSshSession.RemoveTerminalEmulationCharacters = $true if($Passthru) { return $global:LastSshSession } $global:LastSshSession.WriteLine("") sleep -milli 500 $global:defaultPrompt = [regex]::Escape( $global:LastSshSession.Expect().Split("`n")[-1] ) } function Remove-SshSession { Param([Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession) $SshShell.WriteLine( "exit" ) sleep -milli 500 if($SshShell.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." } $SshShell.Close() $SshShell = $null } function Invoke-Ssh { Param( [string]$command , [regex]$expect = $global:defaultPrompt## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } } function Send-Ssh { Param( [string]$command , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) } else { throw "The ssh shell isn't open!" } } function Receive-Ssh { Param( [RegEx]$expect ## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } }
PowerShellCorpus/PoshCode/Get-SophosScanTime.ps1
Get-SophosScanTime.ps1
####################### <# .SYNOPSIS Gets the Scan time information for Sophos .DESCRIPTION The Get-SophosScanTime function gets the Sophos weekly scan time information. .EXAMPLE Get-SophosScanTime "Z002" This command gets information for computername Z002. .EXAMPLE Get-Content ./servers.txt | Get-SophosScanTime This command gets information for a list of servers stored in servers.txt. .EXAMPLE Get-SophosScanTime (get-content ./servers.txt) This command gets information for a list of servers stored in servers.txt. .NOTES Version History v1.0 - Chad Miller - Initial release #> function Get-SophosScanTime { [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullorEmpty()] [string[]]$ComputerName ) BEGIN {} PROCESS { foreach ($computer in $computername) { Get-WMIObject -ComputerName $computer -Query "SELECT * FROM CIM_DataFile WHERE Drive ='C:' AND Path='\\\\ProgramData\\\\Sophos\\\\Sophos Anti-Virus\\\\Logs\\\\' AND FileName LIKE 'Week%' AND Extension='txt'" | Select CSName,@{n="StartTime";e={($_.ConvertToDateTime($_.creationdate)).ToString("f")}},@{n="EndTime";e={($_.ConvertToDateTime($_.lastmodified)).ToString("f")}}, @{n="RunDuration";e={(($_.ConvertToDateTime($_.lastmodified)).Subtract(($_.ConvertToDateTime($_.creationdate)))).ToString()}} } } END {} }
PowerShellCorpus/PoshCode/Copy__Paste__Clear.ps1
Copy__Paste__Clear.ps1
using System; using System.Text; using System.Threading; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("2.0.0.0")] namespace Clip { internal static class WinAPI { [DllImport("kernel32.dll")] internal static extern IntPtr GetConsoleWindow(); [DllImport("kernel32.dll")] internal static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); [DllImport("kernel32.dll")] internal static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll", BestFitMapping = false, ThrowOnUnmappableChar = true)] internal static extern IntPtr lstrcpy(IntPtr lpString1, string lpString2); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseClipboard(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EmptyClipboard(); [DllImport("user32.dll")] internal static extern IntPtr GetOpenClipboardWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] internal static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); internal static void CopyToClipboard(string text) { IntPtr mem = GlobalAlloc((uint)0x0042, (UIntPtr)(text.Length + 1)); //GHND = 0x0042; IntPtr lck = GlobalLock(mem); lstrcpy(lck, text); GlobalUnlock(mem); OpenClipboard(GetOpenClipboardWindow()); EmptyClipboard(); SetClipboardData((uint)1, mem); //CF_TEXT = 1; CloseClipboard(); } internal static void PasteFromClipboard() { IntPtr hndl = GetConsoleWindow(); SendMessage(hndl, 0x0111, (IntPtr)0xfff1, IntPtr.Zero); //WM_COMMAND = 0x0111, 0xfff1 is console pointer } internal static void ClearClipboardData() { OpenClipboard(GetOpenClipboardWindow()); EmptyClipboard(); CloseClipboard(); } } internal sealed class Program { static void Main() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) sb.Append("test, "); //copy to clipboard test WinAPI.CopyToClipboard(sb.ToString()); Thread.Sleep(1500); //paste to console text test WinAPI.PasteFromClipboard(); Thread.Sleep(1500); //clear clipboard test WinAPI.ClearClipboardData(); } } }
PowerShellCorpus/PoshCode/Get-TheVillageChurchPod.ps1
Get-TheVillageChurchPod.ps1
function Get-TheVillageChurchPodCast { <# .SYNOPSIS Gets The Village Church sermon podcasts. .DESCRIPTION The Get-TheVillageChurchPodcast function returns objects of all the available sermon podcasts from The Village Church. The objects can be filtered by speaker, series, title, or date and optionally downloaded to a specified folder. .PARAMETER Speaker Specifies the name of the podcast speaker. The wildcard '*' is allowed. .PARAMETER Series Specifies the series of the podcast. The wildcard '*' is allowed. .PARAMETER Title Specifies the title of the podcast. The wildcard '*' is allowed. .PARAMETER Date Specifies the date or date range of the podcast(s). .PARAMETER DownloadPath Specifies the download folder path to save the podcast files. .EXAMPLE Get-TheVillageChurchPodcast Gets all the available sermon podcasts from The Village Church. .EXAMPLE Get-TheVillageChurchPodcast -Speaker MattChandler -Series Habakkuk Gets all the sermon podcasts where Matt Chandler is the speaker and the series is Habakkuk. .EXAMPLE Get-TheVillageChurchPodcast -Speaker MattChandler -Date 1/1/2003,3/31/2003 Gets all the sermon podcasts where Matt Chandler is the speaker and the podcasts are in the date ranage 1/1/2003 - 3/31/2003. .EXAMPLE Get-TheVillageChurchPodcast -Speaker MattChandler -Date 1/1/2003,3/31/2003 -DownloadPath C:\\temp\\TheVillage Gets all the sermon podcasts where Matt Chandler is the speaker and the podcasts are in the date ranage 1/1/2003 - 3/31/2003 and downloads the podcast files to the folder path C:\\temp\\TheVillage. .INPUTS System.String .OUTPUTS PSObject .NOTES Name: Get-TheVillageChurchPodCast Author: Rich Kusak Created: 2011-06-14 LastEdit: 2011-09-12 11:07 Version: 1.2.0.0 .LINK http://fm.thevillagechurch.net/sermons .LINK about_regular_expressions #> [CmdletBinding()] param ( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [string]$Speaker = '*', [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [string]$Series = '*', [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [string]$Title = '*', [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateCount(1,2)] [datetime[]]$Date = ([datetime]::MinValue,[datetime]::MaxValue), [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateScript({ if ($_) { if (Test-Path $_ -IsValid) {$true} else { throw "The download path '$_' is not valid." } } else {$true} })] [string]$DownloadPath ) begin { $sermonsUri = 'http://fm.thevillagechurch.net/sermons' $studiesSeminarsUri = 'http://fm.thevillagechurch.net/studies-seminars' $resourceFilesAudioUri = 'http://fm.thevillagechurch.net/resource_files/audio/' $partRegex = "href='/resource_files/audio/(?<file>(?<date>\\d{8}).*_(?<speaker>\\w+)_(?<series>\\w+)Pt(?<part>\\d+)-(?<title>\\w+)\\.mp3)'" $noPartRegex = "href='/resource_files/audio/(?<file>(?<date>\\d{8}).*_(?<speaker>\\w+)_(?<series>\\w+)-(?<title>\\w+)\\.mp3)'" $webClient = New-Object System.Net.WebClient if ([System.Net.WebProxy]::GetDefaultProxy().Address) { $webClient.UseDefaultCredentials = $true $webClient.Proxy.Credentials = $webClient.Credentials } } # begin process { try { Write-Debug "Performing operation 'DownloadString' on target '$sermonsUri'." $reference = $webClient.DownloadString($sermonsUri) $pages = [regex]::Matches($reference, 'page=(\\d+)&') | ForEach {$_.Groups[1].Value} | Sort -Unique $pages | ForEach -Begin {$sermons = @()} -Process { $sermonsPageUri = "http://fm.thevillagechurch.net/sermons?type=sermons&page=$_&match=any&kw=&topic=&sb=date&sd=desc" Write-Debug "Performing operation 'DownloadString' on target '$sermonsPageUri'." $sermons += $webClient.DownloadString($sermonsPageUri) } } catch { return Write-Error $_ } $obj = foreach ($line in $sermons -split '(?m)\\s*$') { if ($line -match $partRegex) { New-Object PSObject -Property @{ 'File' = $matches['file'] 'Date' = "{0:####-##-##}" -f [int]$matches['date'] 'Speaker' = $matches['speaker'] 'Series' = $matches['series'] 'Part' = "{0:d2}" -f [int]$matches['part'] 'Title' = $matches['title'] } } elseif ($line -match $noPartRegex) { New-Object PSObject -Property @{ 'File' = $matches['file'] 'Date' = "{0:####-##-##}" -f [int]$matches['date'] 'Speaker' = $matches['speaker'] 'Series' = $matches['series'] 'Part' = '00' 'Title' = $matches['title'] } } } # foreach ($line in $sermons -split '(?m)\\s*$') if ($PSBoundParameters['Date']) { switch ($Date.Length) { 1 {$Date += $Date ; break} 2 { if ($Date[0] -gt $Date[1]) { [array]::Reverse($Date) } } } # switch } # if ($PSBoundParameters['Date']) if ($DownloadPath) { try { if (-not (Test-Path $DownloadPath -PathType Container)) { New-Item $DownloadPath -ItemType Directory -Force -ErrorAction Stop | Out-Null } } catch { return Write-Error $_ } [PSObject[]]$filter = $obj | Where { $_.Speaker -like $Speaker -and $_.Series -like $Series -and ([datetime]$_.Date -ge $Date[0]) -and ([datetime]$_.Date -le $Date[1]) } $count = $filter.Length $i = 0 foreach ($podcast in $filter) { $fullPath = Join-Path $DownloadPath $podcast.File if (Test-Path $fullPath) { Write-Warning "File '$fullPath' already exists." continue } try { Write-Debug "Performing operation 'DownloadFile' on target '$($podcast.File)'." Write-Progress -Activity 'Downloading PodCast' -Status $podcast.File -PercentComplete $(($i/$count)*100 ; $i++) -CurrentOperation "$i of $count" $webClient.DownloadFile($resourceFilesAudioUri + $podcast.File, $fullPath) } catch { Write-Error $_ continue } } # foreach ($podcast in $filter) Write-Progress -Activity 'Downloading PodCast' -Status 'Complete' -PercentComplete 100 Sleep -Seconds 1 } else { $obj | Where { $_.Speaker -like $Speaker -and $_.Series -like $Series -and $_.Title -like $Title -and ([datetime]$_.Date -ge $Date[0]) -and ([datetime]$_.Date -le $Date[1]) } | Select Date, Speaker, Series, Part, Title | Sort Date } } # process } # function Get-TheVillageChurchPodCast {
PowerShellCorpus/PoshCode/Disconnect-VMHost.ps1
Disconnect-VMHost.ps1
#requires -version 2 -pssnapin VMware.VimAutomation.Core Function Disconnect-VMHost { <# .Summary Used to Disconnect a Connected host from vCenter. .Parameter VMHost VMHost to Disconnect to virtual center .Example Get-VMHost | Where-Object {$_.state -eq "Connected"} | Disconnect-VMHost Will Attempt to Disconnect any host that are currently Connected. .Example Disconnect-VMHost -Name ESX1.get-admin.local Will Disconnect ESX1 From vCenter #> [CmdletBinding( SupportsShouldProcess=$True, SupportsTransactions=$False, ConfirmImpact="low", DefaultParameterSetName="ByString" )] Param( [Parameter( Mandatory=$True, Valuefrompipeline=$true, ParameterSetName="ByObj" )] [VMware.VimAutomation.Client20.VMHostImpl[]] $VMHost, [Parameter( Mandatory=$True, Position=0, ParameterSetName="ByString" )] [string[]] $Name ) Begin { IF ($Name) { $VMHost = $Name|%{ Get-VMHost -Name $_ } } } process { Foreach ($VMHostImpl in ($VMHost|Get-View)) { if ($pscmdlet.ShouldProcess($VMHostImpl.name)) { $VMHostImpl.DisconnectHost_Task() } } } }
PowerShellCorpus/PoshCode/Get-MWSOrder_1.ps1
Get-MWSOrder_1.ps1
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GetOrderCmdlet.cs" company="Huddled Masses"> // Copyright (c) 2011 Joel Bennett // </copyright> // <summary> // Defines the Get-Order Cmdlet for Amazon Marketplace Orders WebService. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace PoshOrders { using System; using System.Management.Automation; // I'm using Amazon's MarketplaceWebServiceOrders Apache-licensed web-service access code. using MarketplaceWebServiceOrders; using MarketplaceWebServiceOrders.Model; /// <summary> /// Get Amazon Marketplace Orders from the WebService /// </summary> [Cmdlet(VerbsCommon.Get, "Order")] public class GetOrderCmdlet : Cmdlet { // Access Key ID and Secret Access Key ID for the Amazon MWS /// <summary>The Amazon Access Key ID</summary> private const string AccessKeyId = "INSERT YOUR MWS ACCESS KEY HERE"; /// <summary>The Amazon Secret Key</summary> private const string SecretAccessKey = "INSERT YOUR MWS SECRET ACCESS KEY HERE"; /// <summary>The Application Name is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationName = "INSERT YOUR APPLICATION NAME HERE"; /// <summary>The Application Version is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationVersion = "1.0"; /// <summary>Default value for the service URL is for the USA</summary> private string serviceUrl = "https://mws.amazonservices.com/Orders/2011-01-01"; /// <summary>The web service client</summary> private MarketplaceWebServiceOrdersClient marketplaceWebServiceOrdersClient; /// <summary>Default value for "Created After" is 1 day ago.</summary> private DateTime createdAfter = DateTime.MinValue; /// <summary>Default value for "Created Before" is infinitely in the future</summary> private DateTime createdBefore = DateTime.MaxValue; /// <summary>The Default order status is Unshipped or PartiallyShipped</summary> private OrderStatusEnum[] orderStatus = new[] { OrderStatusEnum.Unshipped, OrderStatusEnum.PartiallyShipped }; /// <summary> /// Gets or sets the merchant id. /// </summary> /// <value> /// The merchant id. /// </value> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] public string MerchantId { get; set; } /// <summary> /// Gets or sets the marketplace id. /// </summary> /// <value> /// The marketplace id. /// </value> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Marketplace { get; set; } /// <summary> /// Gets or sets the service URL. /// Defaults to the USA service URL. /// </summary> /// <value> /// The service URL. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string ServiceUrl { get { return this.serviceUrl; } set { this.serviceUrl = value; } } /// <summary> /// Gets or sets a date orders must prescede. /// </summary> /// <value> /// The date. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedBefore { get { return this.createdBefore; } set { this.createdBefore = value; } } /// <summary> /// Gets or sets a date the orders must come aftercreated after. /// </summary> /// <value> /// The created after. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedAfter { get { return this.createdAfter; } set { this.createdAfter = value; } } /// <summary> /// Gets or sets the order status. /// </summary> /// <value> /// The order status. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public OrderStatusEnum[] OrderStatus { get { return orderStatus; } set { orderStatus = value; } } /// <summary> /// Gets or sets the buyer email. /// </summary> /// <value> /// The buyer email. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string BuyerEmail { get; set; } /// <summary> /// Gets or sets the seller order id. /// </summary> /// <value> /// The seller order id. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SellerOrderId { get; set; } /// <summary> /// Gets or sets whether to include the Order Items /// </summary> /// <value> /// True to included the Order Items /// </value> [Parameter(Mandatory = false)] public SwitchParameter IncludeItems { get; set; } /// <summary> /// Implement the Begin step for PowerShell Cmdlets /// </summary> protected override void BeginProcessing() { base.BeginProcessing(); var config = new MarketplaceWebServiceOrdersConfig { ServiceURL = "https://mws.amazonservices.com/Orders/2011-01-01" }; this.marketplaceWebServiceOrdersClient = new MarketplaceWebServiceOrdersClient( ApplicationName, ApplicationVersion, AccessKeyId, SecretAccessKey, config); } /// <summary> /// Implement the Process step for PowerShell Cmdlets /// </summary> protected override void ProcessRecord() { base.ProcessRecord(); /* // If no dates are specificied, start a day ago ... if (CreatedBefore == DateTime.MaxValue && CreatedAfter == DateTime.MinValue) { CreatedAfter = DateTime.UtcNow.AddDays(-1); } */ // Amazon's policy doesn't allow calling with a CreatedBefore after two minutes before the request time if (CreatedBefore == DateTime.MaxValue) { CreatedBefore = DateTime.Now.AddMinutes(-2); } var orderRequest = new ListOrdersRequest { MarketplaceId = new MarketplaceIdList(), OrderStatus = new OrderStatusList(), BuyerEmail = this.BuyerEmail, SellerId = this.MerchantId, SellerOrderId = this.SellerOrderId, CreatedAfter = this.CreatedAfter, CreatedBefore = this.CreatedBefore }; orderRequest.OrderStatus.Status.AddRange(OrderStatus); orderRequest.MarketplaceId.Id.AddRange(Marketplace); var response = marketplaceWebServiceOrdersClient.ListOrders(orderRequest); foreach (var order in response.ListOrdersResult.Orders.Order) { var output = new PSObject(order); if (IncludeItems.ToBool()) { var itemRequest = new ListOrderItemsRequest { AmazonOrderId = order.AmazonOrderId, SellerId = this.MerchantId, }; var items = marketplaceWebServiceOrdersClient.ListOrderItems(itemRequest); output.Properties.Add(new PSNoteProperty("Items", items.ListOrderItemsResult.OrderItems.OrderItem)); } WriteObject(output); } } } }
PowerShellCorpus/PoshCode/Set-Keydelay.ps1
Set-Keydelay.ps1
Begin { $key = "keyboard.typematicMinDelay" $value = "2000000" } Process { #Make Sure it's a VM if ( $_ -isnot [VMware.VimAutomation.Client20.VirtualMachineImpl] ) { continue } #Setup our Object $vm = Get-View $_.Id $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig[0].Key=$key $vmConfigSpec.extraconfig[0].Value=$value #Run the change $vm.ReconfigVM($vmConfigSpec) }
PowerShellCorpus/PoshCode/LibraryChart_3.ps1
LibraryChart_3.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Defines functions for wokring with Microsoft Chart Control for .NET 3.5 Framework ### Pipe output of Powershell command to Out-Chart function and specify chart type ### Chart will display in form or save to image file ### Real-time charts are supported by passing in a script block ### My thanks to Richard MacDonald for his wonderful post on Charting with PowerShell ### http://blogs.technet.com/richard_macdonald/archive/2009/04/28/3231887.aspx ### Note: Requires NET Framework 3.5 and Microsoft Chart Controls for Microsoft .NET Framework 3.5 ### </Description> ### <Usage> ### . ./LibraryChart.ps1 ### -------------------------- EXAMPLE 1 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' ### ### This command will produce a default column chart ### ### -------------------------- EXAMPLE 2 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -filename 'c:\\users\\u00\\documents\\process.png' ### This command will output the chart to a file ### ### -------------------------- EXAMPLE 3 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -chartType 'Pie' ### ### This command will produce a pie chart ### ### -------------------------- EXAMPLE 4 -------------------------- ### out-chart -xField 'name' -yField 'WS' -scriptBlock {Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 1} -chartType 'line' ### ### This command will produce a real-time line chart ### ### </Usage> ### </Script> # -------------------------------------------------------------------------- [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") ####################### function New-Chart { param ([int]$width,[int]$height,[int]$left,[int]$top,$chartTitle) # create chart object $global:Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart $global:Chart.Width = $width $global:Chart.Height = $height $global:Chart.Left = $left $global:Chart.Top = $top # create a chartarea to draw on and add to chart $chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea $global:chart.ChartAreas.Add($chartArea) [void]$global:Chart.Titles.Add($chartTitle) # change chart area colour $global:Chart.BackColor = [System.Drawing.Color]::Transparent } #New-Chart ####################### function New-BarColumnChart { param ([hashtable]$ht, $chartType='Column', $chartTitle,$xTitle,$yTitle, [int]$width,[int]$height,[int]$left,[int]$top,[bool]$asc) @@ New-Chart -width $width -height $height -left $left -top $top -chartTitle $chartTitle $chart.ChartAreas[0].AxisX.Title = $xTitle $chart.ChartAreas[0].AxisY.Title = $yTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::$chartType if ($asc) { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Ascending, "Y") } else { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") } $global:Chart.Series["Data"]["DrawingStyle"] = "Cylinder" $global:chart.Series["Data"].IsValueShownAsLabel = $true $global:chart.Series["Data"]["LabelStyle"] = "Top" } #New-BarColumnChart ####################### function New-LineChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) @@ New-Chart -width $width -height $height -left $left -top $top -chartTitle $chartTitle [void]$global:Chart.Series.Add("Data") # $global:Chart.Series["Data"].Points.AddXY($(get-date), $($ht.Values)) $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys,$ht.Values) #$global:Chart.Series["Data"].XValueType = [System.Windows.Forms.DataVisualization.Charting.ChartValueType]::Time #$global:Chart.chartAreas[0].AxisX.LabelStyle.Format = "hh:mm:ss" #$global:Chart.chartAreas[0].AxisX.LabelStyle.Interval = 1 #$global:Chart.chartAreas[0].AxisX.LabelStyle.IntervalType = [System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType]::Seconds $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line #$global:chart.Series["Data"].IsValueShownAsLabel = $false } #New-LineChart ####################### function New-PieChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) @@ New-Chart -width $width -height $height -left $left -top $top -chartTitle $chartTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie $global:Chart.Series["Data"]["PieLabelStyle"] = "Outside" $global:Chart.Series["Data"]["PieLineColor"] = "Black" #$global:chart.Series["Data"].IsValueShownAsLabel = $true #$global:chart.series["Data"].Label = "#PERCENT{P1}" #$legend = New-object System.Windows.Forms.DataVisualization.Charting.Legend #$global:Chart.Legends.Add($legend) #$Legend.Name = "Default" } #New-PieChart ####################### function Remove-Points { param($name='Data',[int]$maxPoints=200) while ( $global:chart.Series["$name"].Points.Count > $maxPoints ) { $global:chart.Series["$name"].Points.RemoveAT(0) } } #Add-Series ####################### function Out-Form { param($interval,$scriptBlock,$xField,$yField) # display the chart on a form $global:Chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = 'PowerCharts' $Form.Width = 600 $Form.Height = 600 $Form.controls.add($global:Chart) if ($scriptBlock -is [ScriptBlock]) { if (!($xField -or $yField)) { throw 'xField and yField required with scriptBlock parameter.' } $timer = New-Object System.Windows.Forms.Timer $timer.Interval = $interval $timer.add_Tick({ $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField if ($global:Chart.Series["Data"].ChartTypeName -eq 'Line') { Remove-Points $ht | foreach { $global:Chart.Series["Data"].Points.AddXY($($_.Keys), $($_.Values)) } } else { $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) } $global:chart.ResetAutoValues() $global:chart.Invalidate() }) $timer.Enabled = $true $timer.Start() } $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog() } #Out-Form ####################### function Out-ImageFile { param($fileName,$fileformat) $global:Chart.SaveImage($fileName,$fileformat) } ####################### ### ConvertTo-Hashtable function based on code by Jeffery Snover ### http://blogs.msdn.com/powershell/archive/2008/11/23/poshboard-and-convertto-hashtable.aspx ####################### function ConvertTo-Hashtable { param([string]$key, $value) Begin { $hash = @{} } Process { $thisKey = $_.$Key $hash.$thisKey = $_.$Value } End { Write-Output $hash } } #ConvertTo-Hashtable ####################### function Out-Chart { param( $xField=$(throw 'Out-Chart:xField is required'), $yField=$(throw 'Out-Chart:yField is required'), $chartType='Column',$chartTitle, [int]$width=500, [int]$height=400, [int]$left=40, [int]$top=30, $filename, $fileformat='png', [int]$interval=1000, $scriptBlock, [switch]$asc ) Begin { $ht = @{} } Process { if ($_) { $thisKey = $_.$xField $ht.$thisKey = $_.$yField } } End { if ($scriptBlock) { $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField } switch ($chartType) { 'Bar' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Column' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Pie' {New-PieChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } 'Line' {New-LineChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } } if ($filename) { Out-ImageFile $filename $fileformat } elseif ($scriptBlock ) { Out-Form $interval $scriptBlock $xField $yField } else { Out-Form } } } #Out-Chart
PowerShellCorpus/PoshCode/99425dd4-2c85-40f1-9cc8-39300a810b7a.ps1
99425dd4-2c85-40f1-9cc8-39300a810b7a.ps1
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null #NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired # to something that more suits your reality. $crawlFreshnessDayThreshhold = 2 $crawlDurationHourThreshhold = 4 $successRatioThreshhold = 0.9 function Calculate-CrawlDuration( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) { return "Green - no current crawl" } $timespan = [datetime]::Now - $contentSource.CrawlStarted $timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days" + "($($timespan.TotalHours.ToString('0.0')) hours)" if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) { return "Green - $timespanFormatted" } elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-CrawlFreshness( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { $timespan = [datetime]::Now - $contentSource.CrawlCompleted $timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago" if ($timespan.Days -le 0) { return "Green - $timespanFormatted" } elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-IndexHealth( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource, $successCount, $warningCount, $errorCount) { $formatted = "($($successCount)/$($warningCount)/$($errorCount))" if ($errorCount -eq 1) { return "Red - exactly 1 error, usually indicates permissions/config error - $formatted" } $successRatio = ([double]$successCount)/([double]($warningCount + $errorCount)) $successRatioMidpointToPerfection = (1.0 - ((1.0 - $successRatioThreshhold)/2.0)) if ($successRatio -ge $successRatioMidpointToPerfection) { return "Green - $formatted" } elseif ($successRatio -ge $successRatioThreshhold) { return "Yellow - $formatted" } else { return "Red - $formatted" } } function Get-CrawlHealth { $serverContext = [Microsoft.Office.Server.ServerContext]::Default $searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext) $content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext $history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext $contentSources = $content.ContentSources | foreach { $_ } $contentSources | foreach { #unroll DataTable object into more useful DataRow object $crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ } add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value ( Calculate-CrawlDuration $_) add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value ( Calculate-CrawlFreshness $_) add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value ( Calculate-IndexHealth -contentSource $_ -successCount $crawlHistory.SuccessCount -warningCount ( $crawlHistory.WarningCount) -errorCount $crawlHistory.ErrorCount) } $contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth | fl } #USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials # (specifically, with access to the SSP - usually the SharePoint farm account) # -Tweak the threshholds (they may be too ambitious for your environment) # -Paste this text into an open PowerShell window and type (without the # mark) # Get-CrawlHealth
PowerShellCorpus/PoshCode/Findup_23.ps1
Findup_23.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 found, 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 - minus drive/files - (using RegEx if -xdr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories - minus drive/files - (using RegEx if -idr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files - minus drive/directories - (using RegEx if -xfr) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files - minus drive/directories - (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."); 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 SizeHashFile = 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 (!SizeHashFile.ContainsKey(files[i].Length)) SizeHashFile.Add(files[i].Length, new Dictionary<string,List<FileInfo>>()); if (!SizeHashFile[files[i].Length].ContainsKey(SHA512string)) SizeHashFile[files[i].Length][SHA512string] = new List<FileInfo>() {}; SizeHashFile[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 SizeHashFile) { foreach (var HashGroup in SizeGroup.Value) { var SGK = (long)SizeGroup.Key; var HGVC = (long)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; deletedfiles++; } } } } } 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."); 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); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt") var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+1); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "\\temp") if (CheckNamesWorker(fullname, "-x", "-xr", true)) return false; if (CheckNamesWorker(filePart, "-xf", "-xfr", true)) return false; if (CheckNamesWorker(dirPart, "-xd", "-xdr", true)) return false; if (CheckNamesWorker(fullname, "-i", "-ir", false)) return false; if (CheckNamesWorker(filePart, "-if", "-ifr", false)) return false; if (CheckNamesWorker(dirPart, "-id", "-idr", false)) return false; return true; } private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType) { foreach (var filepath in optionspaths[pathskey]) { if (filestr.ToLower().StartsWith(filepath) == CheckType) return true; } foreach (var rgx in optionsregex[rgxkey]) { if (rgx.IsMatch(filestr) == CheckType) return true; } return 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/Invoke-Generic.ps1
Invoke-Generic.ps1
function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On','Type')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias('Returns')] [Type]$ReturnType , [Parameter(Position=3, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs ) process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } [Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() } [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } $Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($returnType).Invoke( $on, $Arguments ) } }
PowerShellCorpus/PoshCode/style acording video res.ps1
style acording video res.ps1
@@--------------------------------------------------------------------------------------------------------------------------- @@ this code is copied from http://www.ti4fun.com/myouikar/JavaScript/rotina.aspx?r=JJiKNeLQlIA[[ti&l=STN[ti]5tehuTA[[ti @@--------------------------------------------------------------------------------------------------------------------------- <script> document.write('<div id="div_panel" style="width:100%; height:'+ (screen.height > 768 ? '380px' : (screen.height > 600 ? '280px' : '275px')) +'; overflow:auto;">'); </script> @@-------------------------------------------------- @@ See more codes in http://www.ti4fun.com/myouikar @@--------------------------------------------------
PowerShellCorpus/PoshCode/Get-CrawlHealth (MOSS).ps1
Get-CrawlHealth (MOSS).ps1
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null @@#NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired @@# to something that more suits your reality. $crawlFreshnessDayThreshhold = 2 $crawlDurationHourThreshhold = 4 $successRatioThreshhold = 0.9 function Calculate-CrawlDuration( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) { return "Green - no current crawl" } $timespan = [datetime]::Now - $contentSource.CrawlStarted $timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days" + "($($timespan.TotalHours.ToString('0.0')) hours)" if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) { return "Green - $timespanFormatted" } elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-CrawlFreshness( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { $timespan = [datetime]::Now - $contentSource.CrawlCompleted $timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago" if ($timespan.Days -le 0) { return "Green - $timespanFormatted" } elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-IndexHealth( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource, $successCount, $warningCount, $errorCount) { $formatted = "($($successCount)/$($warningCount)/$($errorCount))" if ($errorCount -eq 1) { return "Red - exactly 1 error, usually indicates permissions/config error - $formatted" } $successRatio = ([double]$successCount)/([double]($warningCount + $errorCount)) $successRatioMidpointToPerfection = (1.0 - ((1.0 - $successRatioThreshhold)/2.0)) if ($successRatio -ge $successRatioMidpointToPerfection) { return "Green - $formatted" } elseif ($successRatio -ge $successRatioThreshhold) { return "Yellow - $formatted" } else { return "Red - $formatted" } } function Get-CrawlHealth { $serverContext = [Microsoft.Office.Server.ServerContext]::Default $searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext) $content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext $history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext $contentSources = $content.ContentSources | foreach { $_ } $contentSources | foreach { #unroll DataTable object into more useful DataRow object $crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ } add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value ( Calculate-CrawlDuration $_) add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value ( Calculate-CrawlFreshness $_) add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value ( Calculate-IndexHealth -contentSource $_ -successCount $crawlHistory.SuccessCount -warningCount ( $crawlHistory.WarningCount) -errorCount $crawlHistory.ErrorCount) } $contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth | fl } @@#USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials @@# (specifically, with access to the SSP - usually the SharePoint farm account) @@# -Tweak the threshholds (they may be too ambitious for your environment) @@# -Paste this text into an open PowerShell window and type (without the # mark) @@# Get-CrawlHealth
PowerShellCorpus/PoshCode/Get_Set Signature (CTP2)_3.ps1
Get_Set Signature (CTP2)_3.ps1
#Requires -version 2.0 ## Authenticode.psm1 #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## 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.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 MUST set the location to your default signing certificate, by either modifiying this script, ## or by creating a language resource file! The second is easier: For english, create a subdirectory ## next to this file called 'en' (for English) and in that folder, create a 'Authenticode.psd1' file ## EG: Set-Content .\\en\\Authenticode.psd1 $CertificatePath ## Basically, the file should contain the path to your code-signing certificate, preferably from the ## CERT:\\ PsProvider, but alternately, from a PFX file... ## EG: ## "Cert:\\CurrentUser\\My\\F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5" ## OR: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## See: http://huddledmasses.org/misusing-powershell-localizable-data/ #################################################################################################### CMDLET Get-UserCertificate -snapin Huddled.Authenticode { trap { Write-Host "The authenticode script module requires a configuration file to function fully!" Write-Host Write-Host "You must put the path to your default signing certificate in the configuration"` "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 "MkDir $(Join-Path $PsScriptRoot $(Get-Culture)) |" Write-Host " Join-Path -Path {`$_} 'Authenticode.psd1' |" Write-Host " New-Item -Path {`$_} -Type File -Value '`"ThePathToYourCertificate`"'" 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." return } Import-LocalizedData -bindingVariable CertificatePath -EA "STOP" $ResolvedPath = $Null $ResolvedPath = Resolve-Path $CertificatePath -ErrorAction "SilentlyContinue" if(!$ResolvedPath) { $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $CertificatePath -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath) { $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $CertificatePath -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } return $Certificate } $DefaultCertificate = Get-UserCertificate $CertificateThumbprint = $DefaultCertificate.Thumbprint CMDLET Test-Signature -snapin Huddled.Authenticode { PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] # We can't actually require the type, or we won't be able to check the fake ones # [System.Management.Automation.Signature] $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $CertificateThumbprint) ) ) } CMDLET Set-AuthenticodeSignature -snapin Huddled.Authenticode { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path , ## TODO: you should CHANGE THIS to a method which gets *your* default certificate [Parameter(Position=2, Mandatory=$false)] $Certificate = $DefaultCertificate ) PROCESS { if( ".psm1" -eq [IO.Path]::GetExtension($Path) ) { # function setpsm1sig($Path) { $ps1Path = "$Path.ps1" Rename-Item $Path (Split-Path $ps1Path -Leaf) $sig = Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $ps1Path | Select * Rename-Item $ps1Path (Split-Path $Path -Leaf) $sig.PSObject.TypeNames.Insert( 0, "System.Management.Automation.Signature" ) $sig.Path = $Path $sig } else { Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $Path } } } CMDLET Get-AuthenticodeSignature -snapin Huddled.Authenticode { PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path ) PROCESS { if( ".psm1" -eq [IO.Path]::GetExtension($Path) ) { # function getpsm1sig($Path) { $ps1Path = "$Path.ps1" Rename-Item $Path (Split-Path $ps1Path -Leaf) $sig = Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $ps1Path | select * Rename-Item $ps1Path (Split-Path $Path -Leaf) $sig.PSObject.TypeNames.Insert( 0, "System.Management.Automation.Signature" ) $sig.Path = $Path $sig } else { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path } } } CMDLET Select-Signed -snapin Huddled.Authenticode { 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] $Path , [Parameter()] [switch]$MineOnly , [Parameter()] [switch]$NotMineOnly , [Parameter()] [switch]$BrokenOnly , [Parameter()] [switch]$TrustedOnly , [Parameter()] [switch]$ValidOnly , [Parameter()] [switch]$InvalidOnly , [Parameter()] [switch]$UnsignedOnly ) if(!(Test-Path -PathType Leaf $Path)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$Path'" # } } else { $sig = Get-AuthenticodeSignature $Path # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $Path" return } # Trusted only returns ONLY things which are Valid if($TrustedOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $Path" return } # AllValid returns only things that are SIGNED and not HashMismatch if($ValidOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $Path" return } # NOTValid returns only things that are SIGNED and not HashMismatch if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $Path" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $Path" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $CertificateThumbprint))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $CertificateThumbprint" Write-Debug " $Path" return } # NotMine returns only things that were signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $CertificateThumbprint))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $CertificateThumbprint" Write-Debug " $Path" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { # Write-Debug ("You asked for Broken ({0}) or Trusted ({1}) or Valid ({2}) or Invalid ({3}) or Unsigned ({4}) and the cert is: ({5})" -f [int]$BrokenOnly, [int]$TrustedOnly, [int]$ValidOnly, [int]$InvalidOnly, [int]$UnsignedOnly, $sig.SignerCertificate) Write-Debug "$($sig.Status) - Not Signed: $Path" return } get-childItem $sig.Path } } Export-ModuleMember Set-AuthenticodeSignature,Get-AuthenticodeSignature,Test-Signature,Select-Signed,Get-UserCertificate # SIG # Begin signature block # MIIK0AYJKoZIhvcNAQcCoIIKwTCCCr0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUHoNib4Y35ha7fCzaYIyjS3sJ # HWGgggbEMIIGwDCCBKigAwIBAgIJAKpDRVMtv0LqMA0GCSqGSIb3DQEBBQUAMIHG # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEaMBgGA1UEChMRSHVkZGxlZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRp # ZmljYXRlIEF1dGhvcml0eTErMCkGA1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmlj # YXRlIEF1dGhvcml0eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNz # ZXMub3JnMB4XDTA4MDcwMjAzNTA1OVoXDTA5MDcwMjAzNTA1OVowgcAxCzAJBgNV # BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazESMBAGA1UEBxMJUm9jaGVzdGVyMRow # GAYDVQQKExFIdWRkbGVkTWFzc2VzLm9yZzEuMCwGA1UECxMlaHR0cDovL0h1ZGRs # ZWRNYXNzZXMub3JnL0NvZGVDZXJ0LmNydDEVMBMGA1UEAxMMSm9lbCBCZW5uZXR0 # MScwJQYJKoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwggIiMA0G # CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXuceXJZYARJbSTU4hoh91goVp2POx # 6Mz/QZ6D5jcT/JNhdW2GwYQ9YUxNj8jkhXg2Ixbgb1djRGMFC/ekgRkgLxyiuhRh # NrVE1IdV4hT4as3idqnvWOi0S3z2R2EGdebqwm2mrRmq9+DbY+FGxuNwLboWZx8Z # roGlLLHRPzt9pabQq/Nu/FIFO+4JzZ8S5ZnEaKTm4dpD0g6j653OWYVvNXJbS/W4 # Dis5aRkHT1q1Gp02dYHh3NTKrpv1nus9BTDlJRwmU/FgGLNQIvnRwqVoBh+I7tVq # NIRnI1RpDTGyFEohbH8mRlwq3z4ijtb6j9boUJEqd8hQshzUMcALoTIR1tN/5APX # u2j4OqGFESM/OG0i2hLKbnP81u581aZT1BfVfQxvDuWrFiurMxllVGY1NvKkXwc8 # aOZktqMQWbWAs2bxZqERbOILXOmkL/mvPdy+e5yQveriHAhrDONu7a79ylreMHBR # XrmYJTK2G/aHvB5vrXjMPw0TBeph0sM2BN2eVzenAAMsIiGlXPXvtKrpKRiBdx5f # 9SV5dyUG2tR8ANDuc2AMB8FKICuMUd8Sx96p4FOBQhXhvF/RZcWZIW5o+A4sHvYE # /s4oiX7LxGrQK2abNiCVs9BDLI/EcSs/TP+ZskBqu7Qb+AVeevoY3T7skihuyC/l # h7EwqjfNpVQ9UwIDAQABo4G0MIGxMB0GA1UdDgQWBBTgB9XYJV/kJAvnkWmKDHsh # 7Cn3PzAfBgNVHSMEGDAWgBQ+5x4ah0JG0o4iUj0TebNd4MCVxTAJBgNVHRMEAjAA # MBEGCWCGSAGG+EIBAQQEAwIEEDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzALBgNV # HQ8EBAMCBsAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRp # ZmljYXRlMA0GCSqGSIb3DQEBBQUAA4ICAQAw8B6+s48CZZo5h5tUeKV7OWNXKRG7 # xkyavMkXpEi58BSLutmE3O7smc3uvu3TdCXENNUlGrcq/KQ8y2eEI8QkHgT99VgX # r+v5xu2KnJXiOOIxi65EZybRFFFaGJNodTcrK8L/tY6QLF02ilOlEgfcc1sV/Sj/ # r60JS1iXIMth7nYZVjtWeYXOrsd+I+XwJuoVNJlELNdApOU4ZVNrPEuV+QRNMimj # lqIOv2tn9TDdNGUqaOCI0w+a1XQvapEPWETfQK+o9pvYINTswGDjNeb7Xz8ar2JB # 9IVs2xtxDohHB75kyRrlY1hkoY5j12ZhWOlm0L9Ks6XvmMtXJIjj0/m9Z+3s+9p6 # U7IYjz5NnzmDvtNUn2y9zxB/rUx/JqoUO3BWRKiLX0lvGRWJlzFr9978kH2SXxAD # rsKfzB7YZzMh9hZkGNlJf4T+HTB/OXG1jyfkyqQvhNB/tDAaq+ejDtKNBF4hMS7K # Z0B4vagIxFwMuTiei4UaOjrGzeCfT9w1Bmj6uLJme5ydQVM0V7z3Z6jR3LVq4c4s # Y1dfPmYlw62cbyV9Kb/H2hYw5K0OMX60LfLQZOzIPzAeRJ87NufwZnC1afxsSCmU # bvSx4kCMgRZMXw+d1SHRhh7z+06YTQjnUMmtTGt7DtUkU6I8LKEWF/mAzF7sq/7P # AyhPsbu91X5FuzGCA3YwggNyAgEBMIHUMIHGMQswCQYDVQQGEwJVUzERMA8GA1UE # CBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hlc3RlcjEaMBgGA1UEChMRSHVkZGxl # ZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTErMCkG # A1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmljYXRlIEF1dGhvcml0eTEnMCUGCSqG # SIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAqkNFUy2/QuowCQYF # Kw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkD # MQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJ # KoZIhvcNAQkEMRYEFIav5gxrUCeM18gHLn9rvM7Y9bSfMA0GCSqGSIb3DQEBAQUA # BIICAClTS+mIW7vAIsYB+MvbqD6oR5BW1TRXq5CAfPLK+XveUmYczvs4Ujx7TBAp # twJm4rR/nz9cEi+yI12R5YbYmVcfa2gxreXkp3BKWOvhYvfPggh07VssBc7Ik4q+ # ppqdD8tbh1lln8atkGaTfNm3h50es5KADSkMSErXlM+eMNAttnDElKzYszDlLkn4 # VTUrvqorx5kLpk7soOb7NdkqG4FnIBjGgpsCGcfkBZNzdIjJnnaXje5DF6MwLLKv # kBBXkmLXa4c+NpzDW9BhVa4VvfVPNpEMuOoJ9LxIXp4hWOcD4oAYGYbuqNpTzhsc # nrgebPHh1RmMbyShYCHIilMeLKJUgJqS7yCp+qAlxfKmtVKUJOMxJXZahDwLVImq # a89OiBDjsDtE2sKdlfVu+rFOa/itWa0NvMX6Qn5+jo/D//3EddYTPIUQnPjYcdo2 # RveOsun6apOo749M7WSTSCzvkwR86TpQU9sYyrhCMdOPdhDrqRgGwXpjUhzjG4Wl # Xk18XlpuqAMA7nQlcZ2SSIu7hgEXRR3zP/rXWvjcxan42qai3pFt9JBshieWveE2 # VveewNAv4ltAjE+80DXGf81q92uBB9ym3g9vbRRJY42J/4MG5Z9lL0SbDY54LiJh # BA/Z0IU5PGgpt5PEpejJqx4o/URH7bZTI5x16NWXhvQDJJyb # SIG # End signature block
PowerShellCorpus/PoshCode/LibrarySqlBackup.ps1
LibrarySqlBackup.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Excerpt from SQL Server Powershell Extensions (sqlpsx) ### http://sqlpsx.codeplex.com ### Defines backup and restore functions ### </Description> ### <Usage> ### . ./LibrarySqlBackup.ps1 ### $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") 'Z002\\SQL2K8' ### invoke-sqlbackup 'Z002\\SqlExpress' 'pubs' $($server.BackupDirectory + "\\pubs.bak") ### invoke-sqlrestore 'Z002\\SqlExpress' 'pubs' $($server.BackupDirectory + "\\pubs.bak") -force ### </Usage> ### </Script> # --------------------------------------------------------------------------- $smoAssembly = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") if (!($smoVersion)) { Set-Variable -name SmoVersion -value $smoAssembly.GetName().Version.Major -Scope Global -Option Constant -Description "SQLPSX variable" } [void][reflection.assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') ####################### function Invoke-SqlBackup { param($sqlserver=$(throw 'sqlserver required.'),$dbname=$(throw 'dbname required.'),$filepath=$(throw 'filepath required.') ,$action='Database', $description='',$name='',[switch]$force,[switch]$incremental,[switch]$copyOnly) #action can be Database or Log $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $sqlserver Write-Verbose "Invoke-SqlBackup $($server.Name) $dbname" $backup = new-object ("Microsoft.SqlServer.Management.Smo.Backup") $backupDevice = new-object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") $filepath, 'File' $backup.Action = $action $backup.BackupSetDescription = $description $backup.BackupSetName = $name if (!$server.Databases.Contains("$dbname")) {throw 'Database $dbname does not exist on $($server.Name).'} $backup.Database = $dbname $backup.Devices.Add($backupDevice) $backup.Initialize = $($force.IsPresent) $backup.Incremental = $($incremental.IsPresent) if ($copyOnly) { if ($server.Information.Version.Major -ge 9 -and $smoVersion -ge 10) { $backup.CopyOnly = $true } else { throw 'CopyOnly is supported in SQL Server 2005(9.0) or higher with SMO version 10.0 or higher.' } } trap { $ex = $_.Exception Write-Output $ex.message $ex = $ex.InnerException while ($ex.InnerException) { Write-Output $ex.InnerException.message $ex = $ex.InnerException }; continue } $backup.SqlBackup($server) if ($?) { Write-Host "$action backup of $dbname to $filepath complete." } else { Write-Host "$action backup of $dbname to $filepath failed." } } #Invoke-SqlBackup ####################### function Invoke-SqlRestore { param($sqlserver=$(throw 'sqlserver required.'),$dbname=$(throw 'dbname required.'),$filepath=$(throw 'filepath required.'), $action='Database',$stopat,$relocatefiles,[switch]$force,[switch]$norecovery,[switch]$keepreplication) #action can be Database or Log $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $sqlserver Write-Verbose "Invoke-SqlRestore $($server.Name) $dbname" $restore = new-object ("Microsoft.SqlServer.Management.Smo.Restore") $restoreDevice = new-object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") $filepath, 'File' $restore.Action = $action $restore.Database = $dbname $restore.Devices.Add($restoreDevice) $restore.ReplaceDatabase = $($force.IsPresent) $restore.NoRecovery = $($norecovery.IsPresent) $restore.KeepReplication = $($keepreplication.IsPresent) if ($stopat) { $restore.ToPointInTime = $stopAt } if ($relocatefiles) { if ($relocateFiles.GetType().Name -ne 'Hashtable') { throw 'Invoke-SqlRestore:Param relocateFile must be a hashtable' } $relocateFileAR = New-Object Collections.ArrayList foreach ($i in $relocatefiles.GetEnumerator()) { $logicalName = $($i.Key); $physicalName = $($i.Value); $relocateFile = new-object ("Microsoft.SqlServer.Management.Smo.RelocateFile") $logicalName, $physicalName [void]$relocateFileAR.Add($relocateFile) } $restore.RelocateFiles = $relocateFileAR } trap { $ex = $_.Exception Write-Output $ex.message $ex = $ex.InnerException while ($ex.InnerException) { Write-Output $ex.InnerException.message $ex = $ex.InnerException }; continue } $restore.SqlRestore($server) if ($?) { Write-Host "$action restore of $dbname from $filepath complete." } else { Write-Host "$action restore of $dbname from $filepath failed." } } #Invoke-SqlRestore #######################
PowerShellCorpus/PoshCode/Vim25-less Crazy Magic.ps1
Vim25-less Crazy Magic.ps1
cls $ws = New-WebServiceProxy -Uri "http://192.168.1.1/sdk/vimService?wsdl" ; $ws.Url = "http://192.168.1.1/sdk/vimService"; $ws.UserAgent = "VMware VI Client/4.0.0"; $ws.CookieContainer = New-Object system.net.CookieContainer; # set up some default MoRefs (see SDK docs) # if anyone knows how to work around these auto-gen types, then please let me know $mor_ret = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy192_168_1_1_sdk_vimService_wsdl.ManagedObjectReference; $mor_si = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy192_168_1_1_sdk_vimService_wsdl.ManagedObjectReference; $mor_si.type = "ServiceInstance"; $mor_si.Value = "ServiceInstance"; $mor_sm = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy192_168_1_1_sdk_vimService_wsdl.ManagedObjectReference; $mor_sm.type = "SessionManager"; $mor_sm.Value = "ha-sessionmgr"; $mor_hs = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy192_168_1_1_sdk_vimService_wsdl.ManagedObjectReference; $mor_hs.type = "HostSystem"; $mor_hs.Value = "ha-host"; $us = $ws.Login($mor_sm,"root","root", "en"); write-Host $ws.CurrentTime($mor_si); #$mor_ret = $ws.RebootHost_Task($mor_hs, $true); $ws.Logout($mor_sm);
PowerShellCorpus/PoshCode/Invoke-Sql_1.ps1
Invoke-Sql_1.ps1
<# .SYNOPSIS Runs a T-SQL Query and optional outputs results to a delimited file. .DESCRIPTION Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file. .EXAMPLE PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'" This example connects to Z003\\sqlprod2.Orders and executes a stored procedure which does not return a result set .EXAMPLE PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\\Scripts\\accounts.txt" -Delimiter "," This example connects to Z003\\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file .NOTES Version History v1.0 - Chad Miller - 12/14/2010 - Initial release IMPORTANT!!! The EventLog source which is set to the application needs to be registered with the Event log: New-EventLog -LogName Application -Source $Application #> param( #ServerInstance is Mandatory! [Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance, #Database is Mandatory! [Parameter(Position=1, Mandatory=$false)] [string]$Database, #Query is Mandatory! [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1", [Parameter(Position=4, Mandatory=$false)] [string]$FilePath, [Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|", #If UserName isn't supplied a trusted connection will be used [Parameter(Position=5, Mandatory=$false)] [string]$UserName, [Parameter(Position=6, Mandatory=$false)] [string]$Password, [Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15 ) #This must be run as administrator on Windows 2008 and higher! New-EventLog -LogName Application -Source $Application -EA SilentlyContinue $Error.Clear() ####################### function Invoke-SqlCmd2 { param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$UserName, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout ) try { if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn=new-object System.Data.SqlClient.SQLConnection $conn.ConnectionString=$ConnectionString $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) Write-Output ($ds.Tables[0]) } finally { $conn.Dispose() } } #Invoke-SqlCmd2 ####################### # MAIN # ####################### if ($PSBoundParameters.Count -eq 0) { get-help $myInvocation.MyCommand.Path -full break } try { $msg = $null $msg += "Application/Job Name: $Application`n" $msg += "Query: $Query`n" $msg += "ServerInstance: $ServerInstance`n" $msg += "Database: $Database`n" $msg += "FilePath: $FilePath`n" Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg" $dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout if ($FilePath) { if ($dt) { $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation } else #Query Returned No Output! {Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" } } Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg" } catch { $Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" ) Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception" throw }
PowerShellCorpus/PoshCode/Get-GroupMembership.ps1
Get-GroupMembership.ps1
## Get-DistinguishedName -- look up a DN from a user's (login) name function Get-DistinguishedName { Param($UserName) $ads = New-Object System.DirectoryServices.DirectorySearcher(([ADSI]'')) $ads.filter = "(&(objectClass=Person)(samAccountName=us321339))" $s = $ads.FindOne() return $s.GetDirectoryEntry().DistinguishedName } ## Get-GroupMembership -- Get AD group membership recursively function Get-GroupMembership { Param($DNName,[int]$RecurseLimit=-1) $groups = ([adsi]"LDAP://$DNName").MemberOf if ($groups -and $RecurseLimit) { Foreach ($gr in $groups) { $groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) | ? {$groups -notcontains $_}) } } return $groups } ## Usage: ################################################################################# ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) ## # To turn recursion off: ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -recurse 0
PowerShellCorpus/PoshCode/df.ps1
df.ps1
function df ( $Path ) { if ( !$Path ) { $Path = (Get-Location -PSProvider FileSystem).ProviderPath } $Drive = (Get-Item $Path).Root -replace "\\\\" $Output = Get-WmiObject -Query "select freespace from win32_logicaldisk where deviceid = `'$drive`'" Write-Output "$($Output.FreeSpace / 1mb) MB" }
PowerShellCorpus/PoshCode/chkhash_26.ps1
chkhash_26.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length $spaces = "" if ($global:lastlen -gt $writestr.length) { $spaces = " " * ($global:lastlen-$writestr.length) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:oldctop=[console]::cursortop if ([console]::cursorleft -ne 0) {$global:oldctop+=1} write-host "$spaces" -nonewline $global:lastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=0 } function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other { # and before printing something else if ($global:oldctop -ne $null) { [console]::cursortop=$global:oldctop [console]::cursorleft=0 } $global:oldctop=$null $global:lastlen=$null } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false "ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, " "in order to detect corrupt or hacked files." "" ".\\chkhash.ps1 -h for usage." "" for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]" " [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml" " or create it and store hashes there if not present]" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" " [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude " " c:\\users\\eve\\hashes directory and subdirs]" " PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u" " [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to" " existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]" " PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml" " [Load hashes.xml and check hashes of all files contained within.]" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { while (($i+1) -lt $args2.count) { $i++ if ($args2[$i] -like "-*") {break} $exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories. } continue } $args3+=@($args2[$i]) # Add files/dirs } if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files, minus directories and minus files in excluded paths if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} WriteFileNameEnd $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es)." $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {WriteFileName "Needs to be added: `"$($f.fullname)`"";WriteFileNameEnd;continue} # if not updating, then continue WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..." $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; WriteFileName "Updated `"$($f.fullname)`""; WriteFileNameEnd;continue} WriteFileName "Bad SHA-512 found: `"$($f.fullname)`""; WriteFileNameEnd } WriteFileNameEnd # restore cursor position after last write string if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}