full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Sweet Child O' Mine.ps1
|
Sweet Child O' Mine.ps1
|
#First Stanza
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(659.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(659.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
#Second Stanza
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(587.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(659.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(659.3,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(784,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1318.5,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1318.5,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1568,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1480,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1318.5,200)
[System.Console]::Beep(880,200)
[System.Console]::Beep(1174.7,200)
[System.Console]::Beep(880,200)
#Verse
[System.Console]::Beep(1174.7,1000)
|
PowerShellCorpus/PoshCode/Get MOSS User Profile.ps1
|
Get MOSS User Profile.ps1
|
function Get-UserProfile($accountName)
{
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
$upm =[Microsoft.Office.Server.UserProfiles.UserProfileManager](
[Microsoft.Office.Server.ServerContext]::Default)
$upm.GetUserProfile($accountName)
}
function Get-UserProfileData($profile)
{
$propsToDisplay = $upm.Properties | ? { $_.IsSystem -eq $false -and $_.IsSection -eq $false }
$o = new-object PSObject
$propsToDisplay | foreach {
add-member -inp $o -membertype NoteProperty -name $_.Name -value $profile[$_.Name]
}
$o
}
@@#
@@#
@@#USAGE 1: (update one profile)
@@# $up = Get-UserProfile "spadmin"
@@# $up["YourCustomField"].Value = "new value"
@@# $up.Commit()
@@#
@@#USAGE 2: (export profile data to CSV)
@@#
@@# $upm = [Microsoft.Office.Server.UserProfiles.UserProfileManager](
@@# [Microsoft.Office.Server.ServerContext]::Default)
@@# $unrolledProfilesCollection = $upm | foreach { $_ }
@@# $unrolledProfilesCollection | foreach { Get-UserProfileData $_ } | export-csv -NoTypeInformation "C:\\temp\\profiles.txt"
@@
@@
|
PowerShellCorpus/PoshCode/DEMO_ Trap Ctrl+C.ps1
|
DEMO_ Trap Ctrl+C.ps1
|
function Trap-CtrlC {
## Stops Ctrl+C from exiting this function
[console]::TreatControlCAsInput = $true
## And you have to check every keystroke to see if it's a Ctrl+C
## As far as I can tell, for CtrlC the VirtualKeyCode will be 67 and
## The ControlKeyState will include either "LeftCtrlPressed" or "RightCtrlPressed"
## Either of which will -match "CtrlPressed"
## But the simplest thing to do is just compare Character = [char]3
if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
{
throw (new-object ExecutionEngineException "Ctrl+C Pressed")
}
}
function Test-CtrlCIntercept {
Trap-CtrlC # Call Trap-CtrlC right away to turn on TreatControlCAsInput
## Do your work ...
while($true) {
$i = ($i+1)%16
Trap-CtrlC ## Constantly check ...
write-host (Get-Date) -fore ([ConsoleColor]$i) -NoNewline
foreach($sleep in 1..4) {
Trap-CtrlC ## Constantly check ...
sleep -milli 500; ## Do a few things ...
Write-Host "." -fore ([ConsoleColor]$i) -NoNewline
}
Write-Host
}
trap [ExecutionEngineException] {
Write-Host "Exiting now, don't try to stop me...." -Background DarkRed
continue # Be careful to do the right thing here (or just don't do anything)
}
}
## Another way to do the same thing without an external function ....
## Don't use this way unless your loop is really tight ...
## If you use this and hit CTRL+C right after a timestamp is printed,
## you'll notice the 2 second delay (compared with above)
function Test-CtrlCIntercept {
## Stops Ctrl+C from exiting this function
[console]::TreatControlCAsInput = $true
## Do your work here ...
while($true) {
$i = ($i+1)%16
write-host (Get-Date) -fore ([ConsoleColor]$i)
sleep 2;
## You have to be constantly checking for KeyAvailable
## And you have to check every keystroke to see if it's a Ctrl+C
## As far as I can tell, for CtrlC the VirtualKeyCode will be 67 and
## The ControlKeyState will include either "LeftCtrlPressed" or "RightCtrlPressed"
## Either of which will -match "CtrlPressed"
## But the simplest thing to do is just compare Character = [char]3
if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
{
Write-Host "Exiting now, don't try to stop me...." -Background DarkRed
break;
}
}
}
|
PowerShellCorpus/PoshCode/Test-Port_5.ps1
|
Test-Port_5.ps1
|
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
# Test-Port.ps1
# Does a TCP connection on specified port (135 by default)
$ErrorActionPreference = "SilentlyContinue"
# Create TCP Client
$tcpclient = new-Object system.Net.Sockets.TcpClient
# Tell TCP Client to connect to machine on Port
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
# Check to see if the connection is done
if(!$wait)
{
# Close the connection and report timeout
$tcpclient.Close()
if($verbose){Write-Host "Connection Timeout"}
Return $false
}
else
{
# Close the connection and report the error if there is one
$error.Clear()
$tcpclient.EndConnect($iar) | out-Null
if(!$?){if($verbose){write-host $error[0]};$failed = $true}
$tcpclient.Close()
}
# Return $true if connection Establish else $False
if($failed){return $false}else{return $true}
|
PowerShellCorpus/PoshCode/chkhash_31.ps1
|
chkhash_31.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
}
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate.
# e.g. PS>.\\writefilename.ps1 c:\\
# call WriteFileName [string]
# after done writing series of overwriting messages, call WriteFileNameEnd
function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling
{ # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done
# before printing anything else, so that you are not printing into a long file name with extra characters from it visible.
if ($Host.Name -match 'ise')
{ write-host $writestr; return }
if ($global:wfnlastlen -eq $null) {$global:wfnlastlen=0}
$ctop=[console]::cursortop
$cleft=[console]::cursorleft
$oldwritestrlen=$writestr.length
$rem=$null
$writelines = [math]::divrem($writestr.length+$cleft, [console]::bufferwidth, [ref]$rem)
#if ($rem -ne 0) {$writelines+=1}
$cwe = ($writelines-(([console]::bufferheight-1)-$ctop)) # calculate where text has scroll back to.
if ($cwe -gt 0) {$ctop-=($cwe)}
write-host "$writestr" -nonewline
$global:wfnoldctop=[console]::cursortop
$global:wfnoldcleft=[console]::cursorleft
if ($global:wfnlastlen -gt $writestr.length)
{
write-host (" " * ($global:wfnlastlen-$writestr.length)) -nonewline # this only overwrites previously written text if needed, so no need to compute buffer movement on this
}
$global:wfnlastlen = $oldwritestrlen
[console]::cursortop=$ctop
[console]::cursorleft=$cleft
}
function WriteFileNameEnd ( $switch=$true) # call this function when you are done overwriting messages on top of each other
{ # and before printing something else. Default switch=$true, which prints a newline, $false restores cursor position,
# to end of last WriteFileName printed message.
if ($Host.Name -match 'ise')
{ return }
if ($global:wfnoldctop -ne $null -and $global:wfnoldcleft -ne $null)
{
[console]::cursortop=$global:wfnoldctop
[console]::cursorleft=$wfnoldcleft
if ($global:wfnoldcleft -ne 0 -and $switch)
{
write-host ""
}
}
$global:wfnoldctop=$null
$global:wfnlastlen=$null
$global:wfnoldcleft=$null
}
# 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
$n = $null
"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 ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
if ($files.count -eq 0) {"No files found. Exiting."; exit}
$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) -or ($files.count -eq 0)) {"No files in Database or no files specified. 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 | %{get-item -ea 0 -literalpath $_.fullname}
}
"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)`" ..."
$fc++ # File checked increment.
if (($upd -eq $false) -and ($f.length -ne $xfiles[$n].length))
{
$errs++
WriteFileName "Size mixmatch: `"$($f.fullname)`""; WriteFileNameEnd
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
# Check SHA512 and size for mixmatch.
if ($xfiles[$n].length -eq $f.length)
{
if ($xfiles[$n].SHA512 -eq $f.SHA512)
{
$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 "SHA-512 and/or size mixmatch 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 Database: $hashespath"
"$nu file hash(es) added to Database."
"$errs file hash(es) updated in Database."
exit
}
"$errs SHA-512 or size mixmatch(es) found."
"$fm file(s) SHA512 and size matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Import-Delimited 2.4.ps1
|
Import-Delimited 2.4.ps1
|
################################################################################
## Convert-Delimiter - A function to convert between different delimiters.
## E.g.: commas to tabs, tabs to spaces, spaces to commas, etc.
################################################################################
## Written primarily as a way of enabling the use of Import-CSV when
## the source file was a columnar text file with data like services.txt:
## ip service port
## 13.13.13.1 http 8000
## 13.13.13.2 https 8001
## 13.13.13.1 irc 6665-6669
##
## Sample Use:
## Get-Content services.txt | Convert-Delimiter " +" "," | Set-Content services.csv
## would convert the file above into something that could passed to:
## Import-Csv services.csv
##
## Get-Content Delimited.csv | Convert-Delimiter "," "`t" | Set-Content Delimited.tab
## would convert a simple comma-separated-values file to a tab-delimited file
################################################################################
## Version History
## Version 1.0
## First working version
## Version 2.0
## Fixed the quoting so it adds quotes in case they're neeeded
## Version 2.1
## Remove quotes which aren't needed
## Version 2.2
## Trim spaces off the ends, they confuse things
## Version 2.3
## Allow empty columns: as in: there,are,six,"comma, delimited",,columns
## Version 2.4
## Allow QUOTED empty columns: as in: there,are,"",seven,"comma, delimited",,columns
## Also, if not -QuoteEmpty, then fix empty columns so they aren't quoted
Function Convert-Delimiter([regex]$from,[string]$to,[switch]$quoteEmpty)
{
begin
{
## The Magic Delimiter Ţ (something nobody ever uses in text)
$z = [char](222)
}
process
{
$_ = $_.Trim()
## We want to clean out the empty strings:
$_ = $_ -replace "(^|$from)`"`"($from|`$)","`$1`$2"
## replace the original delimiter with the new one, wrapping EVERY block in Ţ
## if there's quotes around some text with a delimiter, assume it doesn't count
## if there are two quotes "" stuck together inside quotes, assume they're an 'escaped' quote
$_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z$to"
## clean up the end where there might be duplicates
$_ = $_ -replace "$z(?:$to|$z)?`$","$z"
## normalize quotes so that they're all double "" quotes
$_ = $_ -replace "`"`"","`"" -replace "`"","`"`""
## remove the Ţ wrappers if there are no quotes inside them
$_ = $_ -replace "$z((?:[^$z`"](?!$to))+)$z($to|`$)","`$1`$2"
## (un)quote the empty fields:
if(!$quoteEmpty) {
$_ = $_ -replace "$to$z$z$to","$to$to"
}
## replace the Ţ with quotes, and explicitly emit the result
$_ = $_ -replace "$z","`"" -replace "$z","`""
$_
}
}
################################################################################
## Import-Delimited - A replacement function for Import-Csv that can handle other
## delimiters, and can import text (and collect it together) from the pipeline!!
## Dependends on the Convert-Delimiter function.
################################################################################
## NOTICE that this means you can use this to import multitple CSV files as one:
## Sample Use:
## ls ..\\*.txt | export-csv textfiles.csv
## ls *.doc | export-csv docs.csv
## ls C:\\Windows\\System32\\*.hlp | export-csv helpfiles.csv
##
## $files = ls *.csv | Import-Delimited
## OR
## Import-Delimited " +" services1.txt
## OR
## gc *.txt | Import-Delimited " +"
################################################################################
## Version History
## Version 1.0
## First working version
## Version 2.0
## Filter #TYPE lines
## Remove dependency on Convert-Delimiter if the files are already CSV
## Change to use my Template-Pipeline format (removing the nested Import-String function)
## Version 2.1
## Fix a stupid bug ...
## Add filtering for lines starting with "--", hopefully that's not a problem for other people...
## Added Write-DEBUG output for filtered lines...
Function Import-Delimited([regex]$delimiter=",", [string]$PsPath="")
{
BEGIN {
if ($PsPath.Length -gt 0) {
write-output ($PsPath | &($MyInvocation.InvocationName) $delimiter);
} else {
$script:tmp = [IO.Path]::GetTempFileName()
write-debug "Using tempfile $($script:tmp)"
}
}
PROCESS {
if($_ -and $_.Length -gt 0 ) {
if(Test-Path $_) {
if($delimiter -eq ",") {
Get-Content $_ | Where-Object {if($_.StartsWith("#TYPE") -or $_.StartsWith("--")){ write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp
} else {
Get-Content $_ | Convert-Delimiter $delimiter "," | Where-Object { if( $_.StartsWith("--") ) { write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp
}
}
else {
if($delimiter -eq ",") {
$_ | Where-Object {-not $_.StartsWith("#TYPE")} | Add-Content $script:tmp
} else {
$_ | Convert-Delimiter $delimiter "," | Add-Content $script:tmp
}
}
}
}
END {
# Need to guard against running this twice when you pass PsPath
if ($PsPath.Length -eq 0) {
Import-Csv $script:tmp
}
}
}
|
PowerShellCorpus/PoshCode/bb6a122a-f80d-4233-b795-beee3a70c3c0.ps1
|
bb6a122a-f80d-4233-b795-beee3a70c3c0.ps1
|
####################################################################################################
## Script Name: N++CR FuncGuard Module
## Created On: 12/19/2009
## Author: Thell Fowler
## File: FuncGuard.psm1
## Usage:
## Version: 0.0.1
## Purpose: Provides cmdlets for working with function guards in the N++CR source files:
## Add-FuncGuard - Create header and source entries for function guard.
## Get-FuncGuard - list available func_guards categories.
## Find-FuncGuard - list file and line instances of
## Update-FuncGuard - update category template headers.
## Enable-FuncGuard
## Disable-FuncGuard
## Remove-FuncGuard - Delete all entries for function guard.
##
## Requirements: PowerShell Version 2
## Last Updated: 12/19/2009
## History:
## 0.0.1 12/19/2009 - Initial rendition.
##
####################################################################################################
#requires -version 2.0
Set-StrictMode -Version 2
# The export function is obtained from example 7 in Export-FunctionMember
function export {
param (
[parameter(mandatory=$true)] [validateset("function","variable")] $type,
[parameter(mandatory=$true)] $name,
[parameter(mandatory=$true)] $value
)
if ( $args -ne "PSUnit" ) {
if ($type -eq "function")
{
Set-item "function:script:$name" $value
Export-ModuleMember $name
}
else
{
Set-Variable -scope Script $name $value
Export-ModuleMember -variable $name
}
}
}
export function Add-FuncGuard {
<#
.SYNOPSIS
Modifies the target C++ source code for a new function guard.
.DESCRIPTION
Function guards are a N++CR debug tool created by Jocelyn Legault for debug
function tracing. Add-FuncGuard generates the required source code lines to
for function guard definition, enable/disable control, and importing.
.EXAMPLE
PS C:\\NPPCR_ROOT>Add-FuncGuard -prefix "NPPCR" -path "$NPPCR_ROOT\\PowerEditor\\src\\MISC\\Debug\\" `
>> -name "WinMain" `
>> -description "Trace functions in WinMain.cpp, should not be used in other files."
Results in the following code being added:
... to FuncGuards_skel.h and FuncGuards.h (if it exists):
// func_guard(guard_WinMain);
// Description: Trace functions in WinMain.cpp, should not be used in other files.
// #define NPPCR_GUARD_WINMAIN
... to FuncGuards.cpp:
#ifdef NPPCR_GUARD_WINMAIN
func_guard_enable_cat(guard_WinMain);
#else
func_guard_disable_cat(guard_WinMain);
#endif
... to FuncGuardsImport.h
func_guard_import_cat(guard_WinMain);
.PARAMETER Prefix
An all upper case string prefixing the preprocessor MACRO value.
.PARAMETER Path
Path to th function guard source files directory.
.PARAMETER Name
CamelCase_UnderscoreSpaced name of the function guard category.
.PARAMETER Description
Category notes inserted as comments to FuncGuards_skel.h && FuncGuards.h
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[string]
$Prefix = $(Throw 'Preprocessor MACRO prefix is required.')
,
[Parameter(Position=1, Mandatory=$true)]
[string]
$Path = $(Throw 'Path to required function guard source files is required.')
,
[Parameter(Position=2, Mandatory=$true)]
[string]
$Name = $(Throw 'CamelCase_UnderscoreSpaced function guard name is required.')
,
[Parameter(Position=3, Mandatory=$false)]
[string]
$Description
)
BEGIN {
# Parameter Validation
try {
Test-PrefixParameter -Prefix $Prefix
Test-PathParameter -Path $Path
Test-NameParameter -Name $Name
Get-SourceFiles -sourceType "all" -Path $Path
}
catch {
Format-ErrorRecord $_ | Write-Debug
throw $_
}
}
PROCESS {
# Check for pre-existence of $Name in function guard files.
# Insert function guard statements into source files.
}
END {
# Report was done.
# Clean-up
return $true
}
}
function Test-PrefixParameter {
param([string]$Prefix)
}
function Test-PathParameter {
param([string]$Path)
if (! (Test-Path -Path $Path -PathType Container) ) {
throw (New-Object IO.DirectoryNotFoundException $Path);
}
}
function Test-NameParameter {
param([string]$Name)
$retVal=$false
if (! ( $Name -cmatch "(\\p{Lu}{1}\\p{Ll}+)+($|_((\\p{Lu}{1}\\p{Ll}+)|\\d)+|\\d+)+" ) ) {
throw (New-Object System.FormatException "Invalid function guard name format.")
}
return $true
}
function Get-SourceFiles {
param([string]$sourceType,[string]$Path)
$SourceFiles = @{}
if ( ( $sourceType -eq "all" ) -or ( $sourceType -eq "required" ) ) {
$SourceFiles = (Get-RequiredFiles $Path)
}
return $SourceFiles
}
function Get-RequiredFiles {
param([string]$Path)
$RequiredSourceFiles = @{}
$TestFiles = @{
"SkeletonHeader" = (Join-Path -Path $Path -ChildPath "FuncGuards_skel.h");
"GuardSource" = (Join-Path -Path $Path -ChildPath "FuncGuards.cpp");
"GuardImport" = (Join-Path -Path $Path -ChildPath "FuncGuardsImport.h")
}
$TestFiles.keys | foreach {
if (Test-Path -Path $TestFiles.$_ -PathType leaf) {
$RequiredSourceFiles.add("$_", (Get-Item $TestFiles.$_ ))
} else {
throw (New-Object IO.FileNotFoundException $TestFiles.$_)
}
}
$TestFiles = $null
return $RequiredSourceFiles
}
|
PowerShellCorpus/PoshCode/demo-attributes.ps1
|
demo-attributes.ps1
|
function demo-attributes
{
[System.Configuration.SettingsDescription({
@{something = 1;
this = 'that';
array = (1,2,3);
sub = @{ sub1 = 1 ; sub2 =2 }
}})]
[CmdletBinding(DefaultParameterSetName="noname")]
param (
[Parameter(Position=1,mandatory = $true)]
[string]$something
)
1..10
}
$settingstext = ((dir function:\\demo-attributes).scriptblock.attributes |Where-Object { $_.typeid -like '*settingsdescription*' }).description
$settingsscriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("DATA {" + $settingstext + "}")
&$settingsscriptblock
|
PowerShellCorpus/PoshCode/Get-WebFile 3.0.ps1
|
Get-WebFile 3.0.ps1
|
## Get-WebFile.ps1 (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
##############################################################################################################
#function wget {
param(
$url = "http://www.squirrelmail.org/countdl.php?fileurl=http%3A%2F%2Fprdownloads.sourceforge.net%2Fsquirrelmail%2Fsquirrelmail-1.4.13.tar.bz2",
$fileName
)
$req = [System.Net.HttpWebRequest]::Create($url);
$res = $req.GetResponse();
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName))
{
# if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not )))
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
if($res.StatusCode -eq 200) {
$reader = new-object System.IO.StreamReader $res.GetResponseStream()
$writer = new-object System.IO.StreamWriter $fileName
# TODO: stick this in a loop and give progress reports
$writer.Write($reader.ReadToEnd())
$reader.Close();
$writer.Close();
}
$res.Close();
ls $fileName
#}
|
PowerShellCorpus/PoshCode/Xml Module 3.1.ps1
|
Xml Module 3.1.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-Xml and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-Xml in 3.0 which I should not have released
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
if(!$xlr8r::Get["Stack"]) {
$xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
function Format-XML {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Indent
# The indent level (defaults to 2 spaces)
Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[xml]$xml
,
[Parameter(Mandatory=$false)]
$indent=2
)
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}
Set-Alias fxml Format-Xml
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter XPath
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
#.Parameter RemoveNamespace
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Hashtable]$Namespace
,
[Switch]$RemoveNamespace
)
BEGIN {
function Select-Node {
PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager)
BEGIN {
foreach($node in $xml) {
if($NamespaceManager -is [Hashtable]) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Namespace.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
}
foreach($path in $xpath) {
$node.SelectNodes($path, $NamespaceManager)
} } } }
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
$node = Remove-XmlNamespace $node
}
Select-Node $node $XPath $NSM
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
}
Set-Alias slxml Select-Xml
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias cvxml Convert-Xml
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
Convert-Node -Xml $Xml $StyleSheet
}
}
"Xml" {
$Xml | Convert-Node $StyleSheet
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias rmns Remove-XmlNamespace
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
# $xml = New-XDocument rss -dc $dc -version "2.0" {
# xe channel {
# xe title {"Test RSS Feed"}
# xe link {"http`://HuddledMasses.org"}
# xe description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# xe ($dc + "language") {"en"}
# xe ($dc + "creator") {"Jaykul@HuddledMasses.org"}
# xe ($dc + "rights") {"Copyright 2009, CC-BY"}
# xe ($dc + "date") {(Get-Date -f u) -replace " ","T"}
# xe item {
# xe title {"The First Item"}
# xe link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe description {"Ema Lazarus' Poem"}
# xe pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# $xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# $xml.ToString()
#
#
# OUTPUT: (NOTE: I added the space in the http: to paste it on PoshCode -- those aren't in the output)
#
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss xmlns:dc="http ://purl.org/dc/elements/1.1" version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <dc:language>en</dc:language>
# <dc:creator>Jaykul@HuddledMasses.org</dc:creator>
# <dc:rights>Copyright 2009, CC-BY</dc:rights>
# <dc:date>2009-07-26T00:50:08Z</dc:date>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#.Example
# This time with a default namespace
## IMPORTANT! ## NOTE that I use the "xe" shortcut which is redefined when you specify a namespace
## ## for the root element, so that all child elements (by default) inherit that.
## ## You can still control the prefixes by passing the namespace as a parameter
## ## e.g.: -atom $atom
## The `: in the http`: is still only there for PoshCode, you can just use http: ...
#
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# New-Xml ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org"}
# xe updated {(Get-Date -f u) -replace " ","T"}
# xe author {
# xe name {"Joel Bennett"}
# xe uri {"http`://HuddledMasses.org"}
# }
# xe id {"http`://huddledmasses.org/" }
#
# xe entry {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# xe id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# xe updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# xe summary {"Ema Lazarus' Poem"}
# xe link -rel license -href "http://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# xe ($dc + "rights") {"Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)"}
# xe category -scheme "http://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
#
# OUTPUT: (NOTE: I added the spaces again to the http: to paste it on PoshCode)
#
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceStack = New-Object 'Stack[XNamespace]'
if(![string]::IsNullOrEmpty( $root.NamespaceName )) {
$script:NameSpaceStack.Push( $root.Namespace )
} elseif( $script:NameSpaceStack.Count -gt 0 ) {
$script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() )
} else {
$script:NameSpaceStack.Push( $null )
}
}
PROCESS {
#New-Object XDocument (New-Object XDeclaration "1.0", "UTF-8", "yes"),(
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")) $value
} else {
New-XAttribute $attrib.TrimStart("-") $value
}
}
))
}
END {
#if(![string]::IsNullOrEmpty( $root.NamespaceName )) {
$null = $script:NameSpaceStack.Pop()
#}
}
}
Set-Alias xml New-XDocument
Set-Alias New-Xml New-XDocument
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute
Set-Alias New-XmlAttribute New-XAttribute
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
$tag = $($script:NameSpaceStack.Peek()) + $tag
if( $script:NameSpaceStack.Count -gt 0 ) {
$script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() )
} else {
$script:NameSpaceStack.Push( $null )
}
} else {
$script:NameSpaceStack.Push( $tag.Namespace )
}
}
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
)
}
END {
#if(![string]::IsNullOrEmpty( $tag.NamespaceName )) {
$null = $script:NameSpaceStack.Pop()
#}
}
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml
|
PowerShellCorpus/PoshCode/Copy-Item extended.ps1
|
Copy-Item extended.ps1
|
function Copy-ToCreateFolder
{
param(
[string]$src,
[string]$dest,
$exclude,
[switch]$Recurse
)
# The promlem with Copy-Item -Rec -Exclude is that -exclude effects only top-level files
# Copy-Item $src $dest -Exclude $exclude -EA silentlycontinue -Recurse:$recurse
# http://stackoverflow.com/questions/731752/exclude-list-in-powershell-copy-item-does-not-appear-to-be-working
if (Test-Path($src))
{
# nonstandard: I create destination directories on the fly
[void](New-Item $dest -itemtype directory -EA silentlycontinue )
Get-ChildItem -Path $src -Force -exclude $exclude | % {
if ($_.psIsContainer)
{
if ($Recurse) # non standard: I don't want to copy empty directories
{
$sub = $_
$p = Split-path $sub
$currentfolder = Split-Path $sub -leaf
#Get-ChildItem $_ -rec -name -exclude $exclude -Force | % { "{0} {1}" -f $p, "$currentfolder\\$_" }
[void](New-item $dest\\$currentfolder -type directory -ea silentlycontinue)
Get-ChildItem $_ -Recurse:$Recurse -name -exclude $exclude -Force | % { Copy-item $sub\\$_ $dest\\$currentfolder\\$_ }
}
}
else
{
#"{0} {1}" -f (split-path $_.fullname), (split-path $_.fullname -leaf)
Copy-Item $_ $dest
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-EasterEastern.ps1
|
Get-EasterEastern.ps1
|
function Get-EasterEastern {
Param(
[Parameter(Mandatory=$true)]
[int] $Year
)
$a = $Year % 4
$b = $Year % 7
$c = $Year % 19
$d = ((19 * $c) + 15) % 30
$e1 = -$d #here because powershell is picking up - (subtraction operator) as incorrect toekn
$e = ((2 * $a) + (4 * $b) + $e1 + 34) % 7
$month = [Math]::Floor(($d + $e + 114) / 31)
$day = (($d + $e + 114) % 31) + 1
$cal = New-Object -TypeName System.Globalization.JulianCalendar
New-Object -TypeName System.DateTime -ArgumentList $Year,$month,$day,$cal
<#
.SYNOPSIS
Calculates the Julian Easter date in the Julian calendar for a given year.
.DESCRIPTION
Calculates the Julian Easter date in the Julian calendar for a given year. This is not the Gregorian Easter now used by Western churches. Algorithm sourced from http://en.wikipedia.org/wiki/Computus, Meeus Julian algorithm.
.PARAMETER Year
The year to calculate easter for.
.EXAMPLE
PS C:\\> Get-EasterEastern 2017
.INPUTS
System.Int32
.OUTPUTS
System.DateTime
#>
}
|
PowerShellCorpus/PoshCode/PowerShellServer Cmdlet _2.ps1
|
PowerShellServer Cmdlet _2.ps1
|
\n#Global Hashtable to Control all Powershell Server Runspace\nSet-Variable -name '__PSRUNSPACES__' -scope 'global' -value @{} -force\n\nfunction global:New-PowerShellServerRunspace\n{\n param(\n $Credential,\n $ErrorAction='Stop',\n [switch]$Force,\n $Password,\n $Port=22,\n $Server='127.0.0.1',\n $SSHAccept,\n $Timeout=30,\n $user\n )\n $ErrorActionPreference = $ErrorAction\n trap{\n Throw "Function New-PowerShellServerRunspace threw error $($error[0])"\n }\n if(($Credential -eq $null) -and (($User -eq $null) -and ($Password -eq $null))){\n Throw "You Must Provide Authenication `n PSCredential or User and Password"\n } \n if( ($global:__PSRUNSPACES__.Keys -contains "$Server") -and ($global:__PSRunspaces__["$Server"].RunspaceStateInfo -eq 'OPENED' ) )\n {\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n else\n {\n if($Force){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n elseif($SSHAccept){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n else{\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n $global:__PSRUNSPACES__["$Server"] = $script:rs\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n}\n\nfunction global:Remove-PowerShellServerRunspace\n{\n param(\n $SSHRunspace\n )\n if($SSHRunspace)\n {\n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $SSHRunspace\n if( $global:__PSRUNSPACES__.Keys -contains $SSHRunspace.SSHServer )\n {\n $global:__PSRUNSPACES__.Remove($SSHRunspace.SSHServer)\n }\n }\n elseif( $global:__FPRUNSPACES__.Count -gt 0 )\n {\n $global:__FPRUNSPACES__ | Foreach-Object { \n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $_\n }\n $global:__PSRUNSPACES__.Clear()\n }\n}
|
PowerShellCorpus/PoshCode/Remove-SMVISnapshots.ps1
|
Remove-SMVISnapshots.ps1
|
<#
.Synopsis
Cleanup after SMVI
.PARAMETER Max
Maximum number of concurrent snapshot delete tasks. Default: 5
.PARAMETER Recurse
Recursively process snapshots untill they are all gone.
.Example
.\\Remove-SMVISnapshots.ps1 -Max 10
removes the 10 newest smvi leftovers, and returns the prompt
.Example
.\\Remove-SMVISnapshots.ps1 -Max 3 -Recurse
will chew through all SMVI snapshots three at a time.
.notes
#Requires -verson 2
Author: Glenn Sizemore
#>
[CmdletBinding(SupportsShouldProcess=$True,SupportsTransactions=$False,ConfirmImpact="low",DefaultParameterSetName="")]
Param(
[parameter()]
[int]
$Max=2,
[parameter()]
[switch]
$Recurse,
[parameter()]
[switch]
$RunAsync
)
begin{
Function Get-Snapinfo {
<#
.Synopsis
Get the snapshot info out of a Virtual Machine Managed Entity. Most useful for
reporting!
.PARAMETER VM
VirtualMachine object to scan to extract snapshots from
.PARAMETER VirtualMachineSnapshotTree
used to recursively crawl a VM for snapshots... just use -VM
.PARAMETER Filter
Specify the name of the snapshots you want to retrieve, will perform a regex match.
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo -Filter "^SMVI"
.notes
#Requires -verson 2
Author: Glenn Sizemore
get-admin.com/blog/?p=879
#>
[cmdletBinding(SupportsShouldProcess=$false,DefaultParameterSetName="VM")]
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="VM")]
[VMware.Vim.VirtualMachine[]]
$VM,
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="Snaptree")]
[VMware.Vim.VirtualMachineSnapshotTree[]]
$VirtualMachineSnapshotTree,
[parameter(ParameterSetName="VM")]
[parameter(ParameterSetName="Snaptree")]
[string]
$Filter
)
Process {
switch ($PScmdlet.ParameterSetName)
{
"Snaptree"
{
Foreach ($Snapshot in $VirtualMachineSnapshotTree) {
Foreach ($ChildSnap in $Snapshot.ChildSnapshotList) {
if ($ChildSnap) {
Get-Snapinfo -VirtualMachineSnapshotTree $ChildSnap -Filter $Filter
}
}
If ($Snapshot.Name -match $Filter ) {
write-output $Snapshot | Select Name, CreateTime, Vm, Snapshot
}
}
}
"VM"
{
Foreach ($v in $VM) {
Get-Snapinfo -VirtualMachineSnapshotTree $v.Snapshot.RootSnapshotList -Filter $Filter
}
}
}
}
}
$Snapshots = Get-View -ViewType virtualmachine `
-Property snapshot `
-Filter @{"Snapshot"="VMware.Vim.VirtualMachineSnapshotInfo"} `
-verbose:$False |
Get-Snapinfo -Filter "^smvi_" |
Sort-Object @{Expression="VM";Descending=$false},@{Expression="CreateTime";Descending=$true}
$Start = Get-date
}
Process
{
while ($snapshots.count -gt 0)
{
$VirtualMachineSnapshots = $Snapshots |
Group-Object -Property VM |
Foreach-Object {
# Select one snapshot for each VM we do this to ensure we
# don't try to delete more than one snapshot per VM, Per pass
$_.Group | Select-Object -first 1
} | Select-Object -first $max
$tasks = @()
# Remove snapshots
Foreach ($VirtualMachineSnapshot in $VirtualMachineSnapshots ) {
If ($pscmdlet.ShouldProcess($VirtualMachineSnapshot.VM,"removing snapshot $($VirtualMachineSnapshot.Name)")) {
$snap = Get-View $VirtualMachineSnapshot.snapshot -verbose:$False
# RemoveSnapshot_Task will return the task moref
$taskMoRef = $snap.RemoveSnapshot_Task($false)
# Convert that moref into a Task object
$Tasks += Get-VIObjectByVIView -MORef $taskMoRef -verbose:$False
}
}
if ($RunAsync) {
#return the taskimpl, and then break out
Foreach ($t in $Tasks) {
write-output $t
}
break
}
sleep 2
#Pause for snap delets
Wait-Task -Task $tasks -Verbose:$false
# if not recurse break out!
if (!$recurse -or $PSCmdlet.MyInvocation.BoundParameters.whatif.IsPresent){
$snapshots = $null
}
Else {
$Snapshots = Get-View -ViewType virtualmachine `
-Property snapshot `
-Filter @{"Snapshot"="VMware.Vim.VirtualMachineSnapshotInfo"} `
-verbose:$False |
Get-Snapinfo -Filter "^smvi_" |
Sort-Object @{Expression="VM";Descending=$false},@{Expression="CreateTime";Descending=$true}
}
}
}
End {write-output (New-TimeSpan -start $start)}
|
PowerShellCorpus/PoshCode/Logoff all users.ps1
|
Logoff all users.ps1
|
function RemoveSpace([string]$text) {
$private:array = $text.Split(" ", `
[StringSplitOptions]::RemoveEmptyEntries)
[string]::Join(" ", $array) }
$quser = quser
foreach ($sessionString in $quser) {
$sessionString = RemoveSpace($sessionString)
$session = $sessionString.split()
if ($session[0].Equals(">nistuke")) {
continue }
if ($session[0].Equals("USERNAME")) {
continue }
# Use [1] because if the user is disconnected there will be no session ID.
$result = logoff $session[1] }
|
PowerShellCorpus/PoshCode/New-WebServiceProxy_1.ps1
|
New-WebServiceProxy_1.ps1
|
#
# New-WebServiceProxy.ps1 (v3.0 Sep 23, 2009)
#
# Oisin Grehan <oising@gmail.com> (x0n)
#
# Usage:
# $proxy = .\\New-WebServiceProxy.ps1 [-Url] http://site/service.asmx [-Anonymous] [[-SoapProtocol] <Soap | Soap12>] [-Namespace <namespace>]
#
# to see available webmethods:
# $proxy | gm
#
# $url = "http://services.msdn.microsoft.com/contentservices/contentservice.asmx?wsdl"
param($url = $(throw "need `$url"), [switch]$Anonymous, [string]$protocol = "Soap", [string]$Namespace="")
[void][system.Reflection.Assembly]::LoadWithPartialName("system.web.services")
trap {
"Error:`n`n $error";
break;
}
#$request = [System.Net.WebRequest]::Create($url);
$dcp = new-object system.web.services.discovery.discoveryclientprotocol
if (! $Anonymous) {
Write-Progress "Network Credentials" "Awaiting input..."
$dcp.Credentials = (Get-Credential).GetNetworkCredential()
}
Write-Progress "Discovery" "Searching..."
$dcp.AllowAutoRedirect = $true
[void]$dcp.DiscoverAny($url)
$dcp.ResolveAll()
# get service name
foreach ($entry in $dcp.Documents.GetEnumerator()) { # needed for Dictionary
if ($entry.Value -is [System.Web.Services.Description.ServiceDescription]) {
$script:serviceName = $entry.Value.Services[0].Name
Write-Verbose "Service: $serviceName"
}
}
Write-Progress "WS-I Basic Profile 1.1" "Validating..."
$ns = new-Object System.CodeDom.CodeNamespace $Namespace
$wref = new-object System.Web.Services.Description.WebReference $dcp.Documents, $ns
$wrefs = new-object system.web.services.description.webreferencecollection
[void]$wrefs.Add($wref)
$ccUnit = new-object System.CodeDom.CodeCompileUnit
[void]$ccUnit.Namespaces.Add($ns)
$violations = new-object system.web.Services.Description.BasicProfileViolationCollection
$wsi11 = [system.web.services.WsiProfiles]::BasicProfile1_1
if ([system.web.Services.Description.WebServicesInteroperability]::CheckConformance($wsi11, $wref, $violations)) {
Write-Progress "Proxy Generation" "Compiling..."
$webRefOpts = new-object System.Web.Services.Description.WebReferenceOptions
$webRefOpts.CodeGenerationOptions = "GenerateNewAsync","GenerateProperties" #,"GenerateOldAsync"
#StringCollection strings = ServiceDescriptionImporter.GenerateWebReferences(
# webReferences, codeProvider, codeCompileUnit, parameters.GetWebReferenceOptions());
$csprovider = new-object Microsoft.CSharp.CSharpCodeProvider
$warnings = [System.Web.Services.Description.ServiceDescriptionImporter]::GenerateWebReferences(
$wrefs, $csprovider, $ccunit, $webRefOpts)
if ($warnings.Count -eq 0) {
$param = new-object system.CodeDom.Compiler.CompilerParameters
[void]$param.ReferencedAssemblies.Add("System.Xml.dll")
[void]$param.ReferencedAssemblies.Add("System.Web.Services.dll")
$param.GenerateInMemory = $true;
#$param.TempFiles = (new-object System.CodeDom.Compiler.TempFileCollection "c:\\temp", $true)
$param.GenerateExecutable = $false;
#$param.OutputAssembly = "$($ns.Name)_$($sdname).dll"
$param.TreatWarningsAsErrors = $false;
$param.WarningLevel = 4;
# do it
$compileResults = $csprovider.CompileAssemblyFromDom($param, $ccUnit);
if ($compileResults.Errors.Count -gt 0) {
Write-Progress "Proxy Generation" "Failed."
foreach ($output in $compileResults.Output) { write-host $output }
foreach ($err in $compileResults.Errors) { write-warning $err }
} else {
$assembly = $compileResults.CompiledAssembly
if ($assembly) {
$serviceType = $assembly.GetType($serviceName)
$assembly.GetTypes() | % { Write-Verbose $_.FullName }
} else {
Write-Warning "Failed: `$assembly is null"
return
}
# return proxy instance
$proxy = new-object $serviceType.FullName
if (! $Anonymous) {
$proxy.Credentials = $dcp.Credentials
}
$proxy # dump instance to pipeline
}
} else {
Write-Progress "Proxy Generation" "Failed."
Write-Warning $warnings
}
#Write-Progress -Completed
}
|
PowerShellCorpus/PoshCode/Execute-SQLCommand_1.ps1
|
Execute-SQLCommand_1.ps1
|
function Execute-SQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$Database, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=ml;Initial Catalog=$Database;Data Source=$Server"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
|
PowerShellCorpus/PoshCode/VM Performance Report_3.ps1
|
VM Performance Report_3.ps1
|
<#
.SYNOPSIS
The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address.
.DESCRIPTION
The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3491) or run interactively.
.NOTES
File Name : Get-VMPeformanceReport.ps1
Author : Samuel Mulhearn
Version History:
Version 1.0
28 Jun 2012.
Release
.LINK
http://poshcode.org/3493
.EXAMPLE
Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt>
#>
#Change These Values
$VC = "vm-trb-vc02.th.local" #VirtualCenter
$SMTPServer = "10.247.50.25" #SMTP Server
$SendersAddress = "noreply@tribalgroup.com" #The report comes from this address
$SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3491
$CompanyLogo = "http://placehold.it/150x50"
function Out-LogFile {
#Log File Function http://poshcode.org/3232
[CmdletBinding(DefaultParameterSetName='Message')]
param(
[Parameter(ParameterSetName='Message',
Position=0,
ValueFromPipeline=$true)]
[object[]]$Message,
[Parameter(ParameterSetName='Message')]
[string]$LogFile = $global:DefaultLogPath,
[Parameter(ParameterSetName='Message')]
[int]$BlankLine = 0,
[switch]$WriteHost = $global:WriteHostPreference,
[string]$Severity = "I",
[Parameter(ParameterSetName='Message')]
[switch]$DontFormat,
[Parameter(ParameterSetName='Message')]
[string]$DateFormat = "dd-MM-yyyy HH:mm:ss",
#[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)]
[string]$Title,
[System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor,
[System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor,
[ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')]
[string]$Encoding = 'Unicode',
[switch]$Force
)
begin {
Write-Verbose "Log File: $LogFile"
if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break}
if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break}
if ( $Title ) {
$text = $Title
$Title = $null
Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
}
}
process {
if ( $Message ) {
$text = $Message
foreach ( $text in $Message ) {
if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" }
if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor}
$text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
}
}
if ( $BlankLine -gt 0 ){
for ($i = 0; $i -lt $BlankLine; $i++ ) {
"" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor }
}
}
}
end {
}
}
#end of logfile function
#New Line Variable
$nl = [Environment]::NewLine
#INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential)
#NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3491), and retrive as below
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3491)
$VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3491
$VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key)
$VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password)
#Get Datafile, this wil contain VM's to report on, and an email address to send the report to
#Datafile format: first line is email address, subsequent lines are VM's, one per line)
if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error!
{ Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)"
#$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file
}
else
{ $Datafile = $args[0] }
#From Datafile, get a log file, and a
$LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log"
$Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm"
$global:WriteHostPreference = $true
$global:DefaultLogPath = $LogFile
Out-LogFile -Message "Starting script with $datafile"
#Load PowerCLI
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{ Add-PsSnapin VMware.VimAutomation.Core }
If (!(Get-PSSnapin -Name VMware.VimAutomation.Core))
{Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E"
Exit(1)
}
#Static HTML
$HTMLPreString=@"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css">
<style type="text/css">
body {
padding: 20px;
}
h2 {
color: #3A87AD;
}
.mytable {
width: 776px;
margin: 12px;
}
.alert-info {
color: #3A87AD;
background-color: #D9EDF7;
border-color: #BCE8F1;
padding: 8px 8px 8px 14px;
margin-top: 12px;
margin-left: 12px;
margin-right: 12px;
margin-bottom: 12px;
border: 1px solid;
border-radius: 4px;
}
.chart_wrap {
width: 800px;
border-style:solid;
border-width:1px;
border-color: #DDDDDD;
margin: 0px 0px 10px 0px;
}
.chart {
text-align: center;
width: 800px;
height: 400px;
}
</style>
<title>
Virtual Machine Performance statistics
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
"@
$HTMLPreString += "$nl"
$HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl"
$HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl"
$HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl"
$HTMLPostString=@"
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script>
</body>
</html>
"@
#Functions for dynamic HTML
Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title)
{
#https://developers.google.com/chart/interactive/docs/examples#custom_table_example
$mystring = "<script type=`"text/javascript`">$nl"
$mystring += "function drawVisualization$UID() {$nl"
$mystring += "// Create and populate the data table. $nl"
$mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl"
$mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl"
$VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"}
$mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl"
$ColumnCount = 0
$RowCount = 0
$Statistics | % {
$ColumnCount = 0
$formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null)
$JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0)
$formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm")
$formatteddate = "new Date($formatteddate)"
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl"
$_.Group |
% {
$ColumnCount = 0
foreach ($VM in $VMs)
{
$ColumnCount += 1
If ($_.Entity.Name -eq $VM )
{ if ($Summation -eq $true)
{ $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181
$strPercent = [system.math]::round($strPercent,2)
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl"
}
else
{ $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" }
}
}
}
$RowCount += 1
}
$mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl"
$VisParam = "`
{ `
legend: {position: 'in',alignment:`"center`"}, `
lineWidth:`"2`", `
curveType: `"none`",`
chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},`
focusTarget:`"category`", `
hAxis: {slantedText:`"true`", format:`"E, d MMM`"},`
vAxis: {textPosition:`"out`"},`
width: 800, `
height: 400, `
title:`"$Title`"}"
$mystring += "draw(" + "$UID" + "data, $VisParam);$nl"
$mystring +="}$nl"
$mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl"
return $mystring
}
function Get-DivHTML ($UID, $Notes)
{
$tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl"
$tempHTML += " <div class=`"chart_wrap`">$nl"
$tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl"
$tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl"
$tempHTML += " </div>$nl"
$tempHTML += "</div>$nl"
return $tempHTML
}
#Main Code
#Process datafile, get VM's to report on, and an email address to send the report to
$DataTable = @(Get-Content $Datafile)
$email = $DataTable[0]
$VMs = @($DataTable[1..($DataTable.Count)])
#Connect to VC
Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null
if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails.
{ Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost
Exit (1)
}
else
{Out-LogFile -Message "Connected to vCenter ($VC)"}
#Validate VM's exist
$VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue)
$VMs | % {
$tmpvm = $_
$Exists = $false
$VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}}
If ($Exists){
Out-LogFile -Message "$_ found in vCenter inventory"
}
Else {
Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W"
$VMs = $VMs |? {$_ -ne $tmpvm}
}
}
#To add new Stat
#1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics)
#2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#3. Invent a new UID - MyUID ?
#4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title")
#5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li>
#6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart")
#Start and Finish times
$todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1)
$metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average"
$start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart
$finish = $todayMidnight
$startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm")
$finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm")
Out-LogFile -Message "Getting stats from vCenter"
#Variable for all stats combined
$Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average
Out-LogFile -Message "Got stats from vCenter"
Out-LogFile -Message "Sorting and filtering stats"
#Split stats out by each indivial metric into individual variable
$CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#Creates HTML inside of <head> for javascript for the charts
Out-LogFile -Message "Creating HTML"
$HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)")
$HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)")
$HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)")
$HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)")
$HTMLOut += "</head>$nl"
$HTMLOut += $HTMLBodyBegin + $nl
#Navigation Tabs...
#Edit below to add a tab, when adding a new metric
$HTMLOut += @"
<div id="content">
<ul class="nav nav-tabs">
<li class="active"><a href="#Info" data-toggle="tab">Information</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#CPU" data-toggle="tab">CPU Usage</a></li>
<li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#Memory" data-toggle="tab">Memory Usage</a></li>
<li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li>
</ul>
<li>
<li><a href="#Disk" data-toggle="tab">Disk</a></li>
<li><a href="#Net" data-toggle="tab">Network</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane fade in active" id="Info">
<div class="chart_wrap">
<div class="alert alert-info">
<strong>Information: </strong>
"@
#Info for fist tab
$HTMLOut += "Each datapoint represents resource consumption since the last datapoint `
and its value is either an average, maximum, or summation of all usage in that interval. `
Any values that are zero may actually be zero, or may indicate statistics were not `
collected over that period (for example, if a virtual machine was powered off). $nl `
The statistics displayed are from $startstring to $finishstring</div>$nl"
#Table that contains VM resource config & limits.
$HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl"
$VCVMs | % {
$tmpname =$_.Name
$tmpNumCpu = $_.NumCpu
$TmpMemoryMB = $_.MemoryMB
$tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None")
$tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None")
$HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl"
}
$HTMLOut += "</tbody></table>$nl"
$HTMLOut +=@"
</div>
</div>
"@
#Div elements that contain each chart
$HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval")
$HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory")
$HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps")
$HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval")
$HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal")
$HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0")
$HTMLOut += @"
</div>
</div>
</div>
"@
$datenow = Get-Date -Format "F"
$HTMLOut += "<h6>Report generated at $datenow<h6>$nl"
$HTMLOut += $HTMLPostString
#Finished HTML
Out-LogFile -Message "Finished building HTML, writing to $Outfile"
$HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8"
#Build Email
$body =@"
<P>Performance statistics for the Virtual Machines listed below are attached</p>
"@
$body += "<p>Statistics are from $startstring to $finishstring<p>"
$VMs | % {$body+= "<li>$_</li>" }
Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer"
#Send email
Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer
Disconnect-VIServer -Confirm:$false
Out-LogFile -Message "Disconnected from vCenter"
Out-LogFile -Message "Finished"
|
PowerShellCorpus/PoshCode/Set-ConsoleProperties.ps.ps1
|
Set-ConsoleProperties.ps.ps1
|
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nSet-StrictMode -Version Latest\n\nPush-Location\nSet-Location HKCU:\\Console\nNew-Item '.\\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'\nSet-Location '.\\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'\n\nNew-ItemProperty . ColorTable00 -type DWORD -value 0x00562401\nNew-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee\nNew-ItemProperty . FaceName -type STRING -value "Lucida Console"\nNew-ItemProperty . FontFamily -type DWORD -value 0x00000036\nNew-ItemProperty . FontSize -type DWORD -value 0x000c0000\nNew-ItemProperty . FontWeight -type DWORD -value 0x00000190\nNew-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000\nNew-ItemProperty . QuickEdit -type DWORD -value 0x00000001\nNew-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078\nNew-ItemProperty . WindowSize -type DWORD -value 0x00320078\nPop-Location
|
PowerShellCorpus/PoshCode/Hex2Dec_5.ps1
|
Hex2Dec_5.ps1
|
<!DOCTYPE html>
<html>
<head>
<title>He2Dec</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
var num = {
hex2dec : function(n) {
return Number(n) ? Number(n) : 'Wrong data type';
},
dec2hex : function(n) {
return Number(n) ? '0x' + Number(n).toString(16).toUpperCase() : 'Wrong data type';
},
parseData : function(n) {
if (n.slice(0, 2) == '0x') return this.hex2dec(n);
else if (n.slice(0, 1) == 'x') return this.hex2dec('0' + n);
else return this.dec2hex(n);
}
};
function onClick() {
document.getElementById('out').value =
num.parseData(document.getElementById('in').value);
}
</script>
<style type="text/css">
body { font-family: tahoma, sans-serif; }
h1, h5 { color: #000080; margin-bottom: 0; }
h3 { color: #9933cc; margin-top: 0; padding-top: 0; }
h1 { font-size: 370%; }
h5 { font-size: 65%; }
p { font-size: 80%; }
</style>
</head>
<body>
<center>
<h1>Hex2Dec</h1>
<h3>Converts hex to decimal and vice versa</h3>
<p>Note that you should strongly input hex numbers with '0x' or 'x' prefixes.</p>
<p>Input: <input type="textbox" id="in" /></p>
<p>Output: <input type="textbox" id="out" /></p>
<input type="button" value="Convert" onclick="onClick();" />
<br />
<h5>Copyright (C) 2010-2013 greg zakharov gregzakh@gmail.com</h5>
</center>
</body>
</html>
|
PowerShellCorpus/PoshCode/ConvertTo-Hex_4.ps1
|
ConvertTo-Hex_4.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/Get-WebFile 3.7.2.ps1
|
Get-WebFile 3.7.2.ps1
|
## Get-WebFile (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## 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
)
$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
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/Check latest BIOS Rev_1.ps1
|
Check latest BIOS Rev_1.ps1
|
$BiosRev = Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName -Credential $Credentials
# Shortened URL for the Dell Support page, fileid=441102, appears to be the identifier for BIOS downloads
# I tested this on a few different models of Dell workstations.
$DellBIOSPage = "http://support.dell.com/support/downloads/download.aspx?c=us&cs=RC956904&l=en&s=hied&releaseid=R294848&SystemID=PLX_960&servicetag=$($BiosRev.SerialNumber)&fileid=441102"
# This HTML code immediately preceed's the actual service tag, you can see it when you 'view source' on the page
$DellPageVersionString = "<span id=`"Version`" class=`"para`">"
If ($BiosRev.Manufacturer -match "Dell")
{
$DellPage = (New-Object -TypeName net.webclient).DownloadString($DellBIOSPage)
# Assuming that Dell BIOS rev's remain 3 characters, I find where my string starts and add the length to it
# and the substring returns the BIOS rev.
$DellCurrentBios = $DellPage.Substring($DellPage.IndexOf($DellPageVersionString)+$DellPageVersionString.Length,3)
}
If (($BiosRev.SMBIOSBIOSVersion -eq $DellCurrentBios) -eq $false)
{
# Download the latest installer if the Rev's don't match
$BIOSDownloadURL = $DellPage.Substring($DellPage.IndexOf("http://ftp"),(($DellPage.Substring($DellPage.IndexOf("'http://ftp"),100)).indexof(".EXE'"))+3)
$BIOSFile = $BIOSDownloadURL.Substring(($BIOSDownloadURL.Length)-12,12)
If ((Test-Path "C:\\Dell\\") -eq $false)
{
New-Item -Path "C:\\" -Name "Dell" -ItemType Directory
}
If ((Test-Path "C:\\Dell\\$($ComputerName)") -eq $false)
{
New-Item -Path "C:\\Dell" -Name $ComputerName -ItemType Directory
}
(New-Object -TypeName net.webclient).DownloadFile($BIOSDownloadURL,"C:\\Dell\\$($ComputerName)\\$($BIOSFile)")
Write-Host "Latest BIOS for $($ComputerName) downloaded to C:\\Dell\\$($ComputerName)\\$($BIOSFile)"
}
|
PowerShellCorpus/PoshCode/Get-MSCSRestartAction.ps1
|
Get-MSCSRestartAction.ps1
|
param($cluster)
gwmi -ComputerName $cluster -Namespace "root\\mscluster" -Class MSCluster_Resource | Select @{n='Cluster';e={$cluster}},Name, RestartAction
|
PowerShellCorpus/PoshCode/Sync-Time_2.ps1
|
Sync-Time_2.ps1
|
function sync-time(
[string] $server = "clock.psu.edu",
[int] $port = 37)
{
$servertime = get-time -server $server -port $port -set
#leave off -set to just check the remote time
write-host "Server time:" $servertime
write-host "Local time :" $(date)
}
|
PowerShellCorpus/PoshCode/Get-WebSite_6.ps1
|
Get-WebSite_6.ps1
|
function Get-WebSite {
<#
.SYNOPSIS
Retrieves information about a website.
.DESCRIPTION
Retrieves information about a website.
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER TimeOut
Timeout to connect to site, in milliseconds
.PARAMETER Credential
Provide alternate credentials
.NOTES
Name: Get-WebSite
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebSite -url "http://www.bing.com"
Description
------------
Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[Int]$Timeout,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebRequest object using the given url
Write-Verbose "Creating the web request object"
$webRequest = [net.WebRequest]::Create($url)
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Set timeout
If ($PSBoundParameters.ContainsKey('TimeOut')) {
#Setting the timeout on web request
Write-Verbose "Setting the timeout on web request"
$webRequest.Timeout = $timeout
}
#Determine if using Default Credentials
If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($PSBoundParameters.ContainsKey('Credentials')) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
#Set TimeStamp prior to attempting connection
$then = get-date
}
Process {
Try {
#Make connection to gather response from site
$response = $webRequest.GetResponse()
#If successful, get the date for comparison
$now = get-date
#Generate report
Write-Verbose "Generating report from website connection and response"
$report = @{
URL = $url
StatusCode = $response.Statuscode -as [int]
StatusDescription = $response.StatusDescription
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
Catch {
#Get timestamp of failed attempt
$now = get-date
#Put the current error into a variable for later use
$errorstring = "$($error[0])"
#Generate report
$report = @{
URL = $url
StatusCode = ([regex]::Match($errorstring,"\\b\\d{3}\\b")).value
StatusDescription = (($errorstring.split('\\)')[2]).split('.\\')[0]).Trim()
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
}
End {
#Display Report
New-Object PSObject -property $report
}
}
|
PowerShellCorpus/PoshCode/Get-FileEncoding_2.ps1
|
Get-FileEncoding_2.ps1
|
##############################################################################\n##\n## Get-FileEncoding\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\nGets the encoding of a file\n\n.EXAMPLE\n\nGet-FileEncoding.ps1 .\\UnicodeScript.ps1\n\nBodyName : unicodeFFFE\nEncodingName : Unicode (Big-Endian)\nHeaderName : unicodeFFFE\nWebName : unicodeFFFE\nWindowsCodePage : 1200\nIsBrowserDisplay : False\nIsBrowserSave : False\nIsMailNewsDisplay : False\nIsMailNewsSave : False\nIsSingleByte : False\nEncoderFallback : System.Text.EncoderReplacementFallback\nDecoderFallback : System.Text.DecoderReplacementFallback\nIsReadOnly : True\nCodePage : 1201\n\n#>\n\nparam(\n ## The path of the file to get the encoding of.\n $Path\n)\n\nSet-StrictMode -Version Latest\n\n## The hashtable used to store our mapping of encoding bytes to their\n## name. For example, "255-254 = Unicode"\n$encodings = @{}\n\n## Find all of the encodings understood by the .NET Framework. For each,\n## determine the bytes at the start of the file (the preamble) that the .NET\n## Framework uses to identify that encoding.\n$encodingMembers = [System.Text.Encoding] |\n Get-Member -Static -MemberType Property\n\n$encodingMembers | Foreach-Object {\n $encodingBytes = [System.Text.Encoding]::($_.Name).GetPreamble() -join '-'\n $encodings[$encodingBytes] = $_.Name\n}\n\n## Find out the lengths of all of the preambles.\n$encodingLengths = $encodings.Keys | Where-Object { $_ } |\n Foreach-Object { ($_ -split "-").Count }\n\n## Assume the encoding is UTF7 by default\n$result = "UTF7"\n\n## Go through each of the possible preamble lengths, read that many\n## bytes from the file, and then see if it matches one of the encodings\n## we know about.\nforeach($encodingLength in $encodingLengths | Sort -Descending)\n{\n $bytes = (Get-Content -encoding byte -readcount $encodingLength $path)[0]\n $encoding = $encodings[$bytes -join '-']\n\n ## If we found an encoding that had the same preamble bytes,\n ## save that output and break.\n if($encoding)\n {\n $result = $encoding\n break\n }\n}\n\n## Finally, output the encoding.\n[System.Text.Encoding]::$result
|
PowerShellCorpus/PoshCode/Set-IPAddress_8.ps1
|
Set-IPAddress_8.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/Get-GrowthRate_3.ps1
|
Get-GrowthRate_3.ps1
|
function Get-GrowthRate {
param( $Start, $End, $Period )
$rate = [math]::Abs( [math]::Pow( ( $End / $Start ),( 1 / ( $Period - 1 ) ) ) - 1 )
"{0:P}" -f $rate
}
|
PowerShellCorpus/PoshCode/PowerShell Talk Mass VMs.ps1
|
PowerShell Talk Mass VMs.ps1
|
#The PowerShell Talk
#Virtualization Congress 2009
#
#Provision from CSV (csv-provision.ps1)
#Grab from the cli the path to the csv file
Param ( $path_to_csv )
#Get credentials & Connect
Get-Credential | connect-viserver -server "Your vCenter Here"
#Import the CSV, and build our VMs
$csv = Import-Csv -Path $path_to_csv
$csv | foreach-object {
New-VM -Name $_.ServerName -NumCPU $_.CPU -Resourcepool $acct -NetworkName "Replace This" -MemoryMB $_.RAM -DiskMB $_.DISK -GuestId $_.OS -Datastore "supernova-staging" -vmhost "178331-kickstart2.iad1.rvi.local" -CD -RunAsync
}
|
PowerShellCorpus/PoshCode/Convert-BounceToX500.ps1
|
Convert-BounceToX500.ps1
|
# $Id: Convert-BounceToX500.ps1 608 2010-10-31 02:12:44Z jon $
# $Revision: 608 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address
#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true)][string]$bounceAddress
)
Add-Type -AssemblyName System.Web|Out-Null
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
|
PowerShellCorpus/PoshCode/Add-ADPhoto.ps1
|
Add-ADPhoto.ps1
|
#Add-ADPhoto Powershell v1 compatibile script for updating
#user thumbnailphoto attribute. Resizes input photo to recommended
#dimensions and size. Only updates for the currently logged in user.
#This is a script for user self service.
#Author: Nathan Linley
#Site: http://myitpath.blogspot.com
$infile = $args[0]
$aspect = $args[1]
function usage {
write-host "Usage: Add-ADPhoto filename [aspect]"
write-host " Provide the name of an image file in your current directory."
write-host " If you wish to preserve the aspect ratio of the image, type"
write-host " 1 after your file name. Images are resized to the recommended"
write-host " 96x96, converted to JPG and set to 70% quality to limit size."
exit
}
$imagefile = (pwd).path + "\\" + $infile
$imagefileout = (pwd).path + "\\adout.jpg"
##############################################################################
#Check to see if the argument for filename was provided, and that it exists###
##############################################################################
if ([string]::isnullorempty($infile) -or -not (test-path $imagefile)) {
&usage
}
###############################
#Remove any old converted file#
###############################
if (test-path $imagefileout) {
del -path $imagefileout -ErrorAction "silentlycontinue"
}
$Image = New-Object -ComObject Wia.ImageFile
$ImageProcessor = New-Object -ComObject Wia.ImageProcess
##########################################################
#Try loading the file, if its not an image this will fail#
##########################################################
$Image.LoadFile($ImageFile)
if (-not $?) { &usage }
#############################################################
#Create filters, set aspect ratio setting, change dimensions#
#to max 96pixels, convert to JPG and set quality #
#############################################################
$Scale = $ImageProcessor.FilterInfos.Item("Scale").FilterId
$ImageProcessor.Filters.Add($Scale)
$Qual = $ImageProcessor.FilterInfos.Item("Convert").FilterID
$ImageProcessor.Filters.Add($qual)
if ([string]::isnullorempty($aspect) -or [string]$aspect -ne "1") {
$ImageProcessor.Filters.Item(1).Properties.Item("PreserveAspectRatio") = $false
} else {
$ImageProcessor.Filters.Item(1).Properties.Item("PreserveAspectRatio") = $true
}
$ImageProcessor.Filters.Item(1).Properties.Item("MaximumHeight") = 96
$ImageProcessor.Filters.Item(1).Properties.Item("MaximumWidth") = 96
$ImageProcessor.Filters.Item(2).Properties.Item("FormatID") = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
####################################################################
#Drop image quality until it meets the size recommendation of 10kb #
####################################################################
$quality = 80
do {
Remove-Item -path $imagefileout -ErrorAction "silentlycontinue"
$ImageProcessor.Filters.Item(2).Properties.Item("Quality") = $quality
$Image = $ImageProcessor.Apply($Image)
$Image.SaveFile($ImageFileOut)
[byte[]]$imagedata = get-content $imagefileout -encoding byte
$quality -= 10
} while ($imagedata.length -gt 10kb)
#####################################################################
#Find domain, and Account distinguished name. Open user object, add#
#thumbnailphoto data and save.
#####################################################################
$de = new-object directoryservices.directoryentry("LDAP://" + $env:logonserver.substring(2))
$ds = new-object directoryservices.directorysearcher($de)
$ds.filter = "(&(objectclass=user)(samaccountname=" + $env:username + "))"
$myaccount = $ds.findone()
$de = new-object directoryservices.directoryentry($myaccount.path)
$de.properties["Thumbnailphoto"].clear()
$de.properties["Thumbnailphoto"].add($imagedata) |out-null
$de.setinfo()
Write-Host "Photo has been uploaded"
|
PowerShellCorpus/PoshCode/Wacth TechED Sessions.ps1
|
Wacth TechED Sessions.ps1
|
ipmo WPK
Function Get-TechEDSession {
$url = "https://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/RSS/"
$wc = New-Object net.webclient
#$wc.Proxy.Credentials = Get-Credential
$feed = ([xml]($wc.downloadstring($url))).rss.channel.item
$feed | ForEach {
New-Object PSObject -Property @{
Title = $_.title
Url = $_.Enclosure.url
Category = @($_.Category)
}
}
}
$sessions = Get-TechEDSession
New-Window -Title "TechED - NA 2011 Session viewer" -WindowStartupLocation CenterScreen -Width 1200 -Height 600 -On_Loaded {
$lstBox = $window | Get-ChildControl lstBox
$lstBox.ItemsSource = $sessions
} {
New-Grid -Rows 32, 1* -Columns 300, 900* {
New-ComboBox -Name cmbBox -MaxHeight 400 -MaxWidth 300 -ItemsSource @($sessions | Select -ExpandProperty Category -Unique) -On_SelectionChanged {
$lstBox = $window | Get-ChildControl lstBox
$lstBox.ItemsSource = @($sessions | ? { $_.Category -Contains $this.SelectedValue})
}
New-ListBox -Name lstBox -Row 1 -Column 0 -DisplayMemberPath Title -On_SelectionChanged {
$wplayer = $window | Get-ChildControl player
$wplayer.Source = $this.SelectedItem.Url
}
New-MediaElement -Name player -Column 1 -RowSpan 2
}
} -Show
|
PowerShellCorpus/PoshCode/CIM SMI-S Query Library_1.ps1
|
CIM SMI-S Query Library_1.ps1
|
function Invoke-CIM_EnumerateInstances {
<#
.SYNOPSIS
Enumerate Instances of a class on a CIMOM via CIM-XML interface
.DESCRIPTION
Primary use case of this function is to gather inventory and performance information from IT
infrastructure assets. The inventory information feeds into capacity planning, troubleshooting,
managing product life cycle, budgeting, vendor price negotiations and technology strategy in
large enterprise environments. The output from this function would typically go into a datawarehouse
front ended with a business intelligence platform such as COGNOS, QlikView, Business Objects, etc.
The function queries any CIM server, called CIMOM, that supports the CIM-XML interface. It
creates an XML message to encapsulate the CIM query, converts the message to byte stream and
then sends it using HTTP POST method. The response byte stream is converted back to XML message
and name value pairs are parsed out. SMI-S is an instance of CIM, and is thus also fully supported.
Tested against SAN devices such as EMC Symmetrix VMAX Fibre Channel Storage Array and Cisco MDS
Fibre Channel switch. It can be used to query VMWARE vSphere vCenter, IBM XIV, NetApp Filer, EMC
VNX Storage Array, HP Insight Manager, Dell OpenManage, HDS: USP, USPV, VSP, AMS, etc.
.NOTES
Author: Parul Jain (paruljain@hotmail.com)
Version: 0.2, Jan, 2013
Requires: PowerShell v2 or better
.EXAMPLE
This works with EMC Symmetrix
Invoke-CIM_EnumerateInstances -Class Symm_StorageSystem -CIMServer seserver -user admin -Pass '#1Password' -ns 'root/emc'
.PARAMETER class
Mandatory. Information within CIM is classified into classes. The device documentation (or SNIA
documntation in case of SMI-S) should list all the classes supported by the CIMOM. CIM_ComputerSystem
class is available universally and is a good place to start testing.
.PARAMETER CIMServer
Mandatory. IP address or DNS name of the device or CIMOM server if CIMOM runs outside the device
.PARAMETER user
Mandatory. User ID authorized to perform queries. Most hardware vendors have a factory default
.PARAMETER pass
Mandatory. Password for the user. Again most hardware vendors have a factory default for servicing the equipment
.PARAMETER port
Optional. The TCP port number that the CIMOM is listening to. Default is used if not specified.
.PARAMETER ssl
Optional switch. When used function will use HTTPS instead of default HTTP
.PARAMETER ns
Optional. CIM namespace to use. Default is root/cimv2. EMC uses root/emc
.PARAMETER dbg
Optional switch. Returns CIM-XML response message instead of parsed name-value pairs for
troubleshooting parsing if needed
#>
[CmdletBinding()]
Param (
[parameter(Mandatory=$true, ValueFromPipeline=$true)][String]$Class,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$User,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$Pass,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$CIMServer,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Port,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$ssl,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$ns = 'root/cimv2',
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$dbg
)
# CIM-XML message template
$messageText = @'
<?xml version="1.0" encoding="utf-8" ?>
<CIM CIMVERSION="2.0" DTDVERSION="2.0">
<MESSAGE ID="1000" PROTOCOLVERSION="1.0">
<SIMPLEREQ>
<IMETHODCALL NAME="EnumerateInstances">
<LOCALNAMESPACEPATH>
</LOCALNAMESPACEPATH>
<IPARAMVALUE NAME="ClassName">
<CLASSNAME NAME="CIM_ComputerSystem" />
</IPARAMVALUE>
<IPARAMVALUE NAME="DeepInheritance">
<VALUE>FALSE</VALUE>
</IPARAMVALUE>
<IPARAMVALUE NAME="LocalOnly">
<VALUE>TRUE</VALUE>
</IPARAMVALUE>
<IPARAMVALUE NAME="IncludeClassOrigin">
<VALUE>FALSE</VALUE>
</IPARAMVALUE>
<IPARAMVALUE NAME="IncludeQualifiers">
<VALUE>FALSE</VALUE>
</IPARAMVALUE>
</IMETHODCALL>
</SIMPLEREQ>
</MESSAGE>
</CIM>
'@
# Parse the XML text into XMLDocument
$message = [xml]($messageText)
# Set class name
($message.CIM.MESSAGE.SIMPLEREQ.IMETHODCALL.IPARAMVALUE | where { $_.Name -eq 'ClassName' }).Classname.Name = $Class
# Set the namespace
$nsNode = $message.SelectSingleNode('/CIM/MESSAGE/SIMPLEREQ/IMETHODCALL/LOCALNAMESPACEPATH')
foreach ($item in $ns.split('/')) {
$nsNode.InnerXml += '<NAMESPACE NAME="' + $item + '" />'
}
# Do not validate server certificate when using HTTPS
# Amazing how easy it is to create a delegated function in PowerShell!
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
# Process other parameters and switches
if ($ssl) { $protocol = 'https://' } else { $protocol = 'http://' }
if (!$port) { if ($ssl) { $port = '5989' } else { $port = '5988' } }
$url = $protocol + $CIMServer + ":" + $port + '/cimom'
# Instantiate .Net WebClient class
$req = New-Object Net.WebClient
# Add headers required by CIMOM
$req.Headers.Add('Content-Type', 'application/xml;charset="UTF-8"')
$req.Headers.Add('CIMOperation', 'MethodCall')
$req.Headers.Add('CIMMethod', 'EnumerateInstances')
$req.Headers.Add('CIMObject', $ns)
$req.Headers.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([text.encoding]::UTF8.GetBytes($user + ':' + $pass)))
# Send the message to CIMOM server and build $result object based on response XML
$result = [xml]($req.UploadString($url, $message.OuterXml))
# Return the raw XML message and exit if debug option is used
if ($dbg) { return $result }
# Parse attributes from response and build object $object from it
foreach ($instance in @($result.CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.IRETURNVALUE.'Value.NamedInstance')) {
$object = New-Object PSObject
foreach ($prop in @($instance.instance.property)) {
if ($prop.value -ne $null -and $prop.value -ne '') {
$object | Add-Member -MemberType NoteProperty -Name $prop.Name -Value $prop.Value
}
}
$object # Return multiple objects (array)
}
}
function Invoke-CIM_GetInstance {
[CmdletBinding()]
Param (
[parameter(Mandatory=$true, ValueFromPipeline=$true)][String]$Class,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$User,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$Pass,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$CIMServer,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Port,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$ssl,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$ns = 'root/cimv2',
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$dbg,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$key
)
# CIM-XML message template
$messageText = @'
<?xml version="1.0" encoding="utf-8" ?>
<CIM CIMVERSION="2.0" DTDVERSION="2.0">
<MESSAGE ID="1000" PROTOCOLVERSION="1.0">
<SIMPLEREQ>
<IMETHODCALL NAME="GetInstance">
<LOCALNAMESPACEPATH>
</LOCALNAMESPACEPATH>
<IPARAMVALUE NAME="InstanceName">
<INSTANCENAME CLASSNAME="Symm_StorageSystem">
<KEYBINDING NAME="CreationClassName">
<KEYVALUE VALUETYPE="string">Symm_StorageSystem</KEYVALUE>
</KEYBINDING>
<KEYBINDING NAME="Name">
<KEYVALUE VALUETYPE="string">SYMMETRIX+000192601380</KEYVALUE>
</KEYBINDING>
</INSTANCENAME>
</IPARAMVALUE>
<IPARAMVALUE NAME="LocalOnly">
<VALUE>FALSE</VALUE>
</IPARAMVALUE>
</IMETHODCALL>
</SIMPLEREQ>
</MESSAGE>
</CIM>
'@
# Parse the XML text into XMLDocument
$message = [xml]($messageText)
# Set class name
($message.CIM.MESSAGE.SIMPLEREQ.IMETHODCALL.IPARAMVALUE | where { $_.Name -eq 'InstanceName' }).InstanceName.ClassName = $Class
(($message.CIM.MESSAGE.SIMPLEREQ.IMETHODCALL.IPARAMVALUE |
where { $_.Name -eq 'InstanceName' }).instancename.keybinding | where { $_.Name -eq 'CreationClassName' }).KeyValue.InnerText = $Class
(($message.CIM.MESSAGE.SIMPLEREQ.IMETHODCALL.IPARAMVALUE |
where { $_.Name -eq 'InstanceName' }).instancename.keybinding | where { $_.Name -eq 'Name' }).KeyValue.InnerText = $Key
# Set the namespace
$nsNode = $message.SelectSingleNode('/CIM/MESSAGE/SIMPLEREQ/IMETHODCALL/LOCALNAMESPACEPATH')
foreach ($item in $ns.split('/')) {
$nsNode.InnerXml += '<NAMESPACE NAME="' + $item + '" />'
}
# Do not validate server certificate when using HTTPS
# Amazing how easy it is to create a delegated function in PowerShell!
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
# Process other parameters and switches
if ($ssl) { $protocol = 'https://' } else { $protocol = 'http://' }
if (!$port) { if ($ssl) { $port = '5989' } else { $port = '5988' } }
$url = $protocol + $CIMServer + ":" + $port + '/cimom'
# Instantiate .Net WebClient class
$req = New-Object Net.WebClient
# Add headers required by CIMOM
$req.Headers.Add('Content-Type', 'application/xml;charset="UTF-8"')
$req.Headers.Add('CIMOperation', 'MethodCall')
$req.Headers.Add('CIMMethod', 'GetInstance')
$req.Headers.Add('CIMObject', $ns)
$req.Headers.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([text.encoding]::UTF8.GetBytes($user + ':' + $pass)))
# Send the message to CIMOM server and build $result object based on response XML
$result = [xml]($req.UploadString($url, $message.OuterXml))
# Return the raw XML message and exit if debug option is used
if ($dbg) { return $result }
# Parse attributes from response and build object $object from it
$object = New-Object PSObject
foreach ($prop in @($result.CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.IRETURNVALUE.INSTANCE.PROPERTY)) {
if ($prop.value -ne $null -and $prop.value -ne '') {
$object | Add-Member -MemberType NoteProperty -Name $prop.Name -Value $prop.Value
}
}
$object # Return multiple objects (array)
}
function Get-EMCStoragePools ($SMIserver) {
Invoke-CIM_EnumerateInstances -Class EMC_ConcreteStoragePool -CIMserver $SMIserver -user admin -Pass '#1Password' -ns 'root/emc'
}
function Get-SNIADiskDriveView ($SMIServer) {
Invoke-CIM_EnumerateInstances -Class SNIA_DiskDriveView -CIMserver $SMIserver -user admin -Pass '#1Password' -ns 'root/emc'
}
function Get-SymmStorageSystem ([string]$SMIServer, [string]$sid) {
if (!$sid) {
Invoke-CIM_EnumerateInstances -Class Symm_StorageSystem -CIMserver $SMIserver -user admin -Pass '#1Password' -ns 'root/emc'
} else {
Invoke-CIM_GetInstance -Class Symm_StorageSystem -ns 'root/emc' -user admin -pass '#1Password' -CIMServer $SMIserver -key 'SYMMETRIX+' + $sid
}
}
function Get-SymmStorageVolume ($SMIServer) {
# Caution - returns a LOT OF DATA!
Invoke-CIM_EnumerateInstances -Class Symm_StorageVolume -CIMServer $SMIServer -User admin -Pass '#1Password' -ns 'root/emc'
}
|
PowerShellCorpus/PoshCode/Get default AppPath.ps1
|
Get default AppPath.ps1
|
Function Get-ApplicationPath {
Param ([string[]]$extension)
Write-Verbose "Saving current location"
Push-Location
$extension | % {
try {
Set-Location "HKLM:\\Software\\Classes\\$($_)" -ErrorAction Stop
$default = (Get-ItemProperty -Path $pwd.Path -Name '(Default)').'(Default)'
try {
Set-Location "HKLM:\\Software\\Classes\\$($default)\\shell\\open\\command" -errorAction Stop
(Get-ItemProperty -Path $pwd.Path -Name '(Default)').'(Default)' -match '([^"^\\s]+)\\s*|"([^"]+)"\\s*' | Out-Null
$path = $matches[0].ToString()
New-Object PSObject -Property @{
"Extension" = $_
"AppPath" = $path
}
}
catch {
Write-Error $_
}
}
catch {
Write-Error $_
}
}
Pop-Location
}
|
PowerShellCorpus/PoshCode/WPK_TunnelGradient.ps1
|
WPK_TunnelGradient.ps1
|
[CmdletBinding()]
param (
[string]$InsideColor = 'White',
[string]$OutsideColor = 'Transparent',
[int]$BorderThickness = 5
)
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName WindowsBase
# script requires STA... let us check it.
if ([Threading.Thread]::CurrentThread.GetApartmentState() -eq 'MTA') {
Write-Warning @'
This script is using controls, that require STA mode. You can:
* Try to run 'PowerShell -STA' and launch the script again
* Run it from PowerShell ISE where STA is default mode.
See you than! ;)
'@
exit
}
Function New-TunnelGradientBrush {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, HelpMessage = 'Color that will fill interior of the brush')]
[System.Windows.Media.Color]$InsideColor,
[Parameter(Mandatory = $true, HelpMessage = 'Color that will be used for border of the brush')]
[System.Windows.Media.Color]$OutsideColor,
[Parameter(Mandatory = $true, HelpMessage = 'Size of border as part of width, acceptable values: 0 - 0.49')]
[ValidateRange(0,49)]
[int]$BorderThickness
)
Set-StrictMode -Version Latest
# Prepare few points that will be necessary later in the process...
$Left = New-Object Windows.Point 0, 0.5
$Right = New-Object Windows.Point 1, 0.5
$Top = New-Object Windows.Point 0.5, 0
$Bottom = New-Object Windows.Point 0.5, 1
$LeftTop = New-Object Windows.Point 0, 0
$LeftBottom = New-Object Windows.Point 0, 1
$RightTop = New-Object Windows.Point 1, 0
$RightBottom = New-Object Windows.Point 1, 1
# Now some values that relate to $BorderTickness selected.
[double]$StartOffset = $BorderThickness / 100
[double]$EndOffset = - ($BorderThickness / 100) + 1
$NarrowSize = 100 - 2 * $BorderThickness
$CornerSize = $BorderThickness
# Build brushes that will be used to create our final brush (VisualBrush)
$GradientStops = New-Object Windows.Media.GradientStopCollection
@{ 0 = $OutsideColor
$StartOffset = $InsideColor
$EndOffset = $InsideColor
1 = $OutsideColor
}.GetEnumerator() | Foreach { $GradientStops.Add($(New-Object Windows.Media.GradientStop $_.Value, $_.Name)) }
$GradientStopsRadial = New-Object Windows.Media.GradientStopCollection
@{ 1 = $OutsideColor
0 = $InsideColor
}.GetEnumerator() | Foreach { $GradientStopsRadial.Add($(New-Object Windows.Media.GradientStop $_.Value, $_.Name)) }
$BrushLeftRight = New-Object Windows.Media.LinearGradientBrush -Property @{
StartPoint = $Left
EndPoint = $Right
GradientStops = $GradientStops
}
$BrushTopBottom = New-Object Windows.Media.LinearGradientBrush -Property @{
StartPoint = $Top
EndPoint = $Bottom
GradientStops = $GradientStops
}
$CommonProperty = @{
RadiusX = 1
RadiusY = 1
GradientStops = $GradientStopsRadial
}
$BrushLeftTop = New-Object Windows.Media.RadialGradientBrush -Property (@{
Center = $RightBottom
GradientOrigin = $RightBottom
} + $CommonProperty)
$BrushLeftBottom = New-Object Windows.Media.RadialGradientBrush -Property (@{
Center = $RightTop
GradientOrigin = $RightTop
} + $CommonProperty)
$BrushRightTop = New-Object Windows.Media.RadialGradientBrush -Property (@{
Center = $LeftBottom
GradientOrigin = $LeftBottom
} + $CommonProperty)
$BrushRightBottom = New-Object Windows.Media.RadialGradientBrush -Property (@{
Center = $LeftTop
GradientOrigin = $LeftTop
} + $CommonProperty)
# Create Visual Brush Elements (StackPanels).
$Horizontal = New-Object Windows.Controls.StackPanel -Property @{
Background = $BrushLeftRight
Width = 100
Height = $NarrowSize
}
$Vertical = New-Object Windows.Controls.StackPanel -Property @{
Background = $BrushTopBottom
Width = $NarrowSize
Height = 100
}
$Corners = @{
Width = $CornerSize
Height = $CornerSize
}
$TopLeft = New-Object Windows.Controls.StackPanel -Property (@{
Background = $BrushLeftTop
VerticalAlignment = 'Top'
HorizontalAlignment = 'Left'
} + $Corners)
$BottomLeft = New-Object Windows.Controls.StackPanel -Property (@{
Background = $BrushLeftBottom
VerticalAlignment = 'Bottom'
HorizontalAlignment = 'Left'
} + $Corners)
$TopRight = New-Object Windows.Controls.StackPanel -Property (@{
Background = $BrushRightTop
VerticalAlignment = 'Top'
HorizontalAlignment = 'Right'
} + $Corners)
$BottomRight = New-Object Windows.Controls.StackPanel -Property (@{
Background = $BrushRightBottom
VerticalAlignment = 'Bottom'
HorizontalAlignment = 'Right'
} + $Corners)
# Grid that will hold all panels and will be Visual for VisualBrush
$Grid = New-Object Windows.Controls.Grid
foreach ($Control in $Vertical, $Horizontal, $BottomLeft, $BottomRight, $TopLeft, $TopRight) {
$Grid.Children.Add($Control) | Out-Null
}
# Send visualBrush to pipe... at last! :)
New-Object System.Windows.Media.VisualBrush $Grid
}
# Sample...
try {
$Brush = New-TunnelGradientBrush -InsideColor $InsideColor -OutsideColor $OutsideColor -BorderThickness $BorderThickness
} catch {
Write-Host "Try some valid values. -Verbose for more."
Write-Verbose $_
exit
}
$Window = New-Object Windows.Window -Property @{
BackGround = $Brush
Width = 200
Height = 200
WindowStyle = 'None'
AllowsTransparency = $True
}
$Window.Add_MouseLeftButtonDown({ $this.DragMove() })
$Window.Add_MouseRightButtonDown({ $this.Close() })
$Window.ShowDialog() | Out-Null
|
PowerShellCorpus/PoshCode/Get-ChildItemColor.ps1
|
Get-ChildItemColor.ps1
|
function Get-ChildItemColor {
<#
.Synopsis
Returns childitems with colors by type.
.Description
This function wraps Get-ChildItem and tries to output the results
color-coded by type:
Compressed - Yellow
Directories - Dark Cyan
Executables - Green
Text Files - Cyan
Others - Default
See Also: Get-ChildItem
.ReturnValue
All objects returned by Get-ChildItem are passed down the pipeline
unmodified.
.Notes
NAME: Get-ChildItemColor
AUTHOR: Tojo2000 <tojo2000@tojo2000.com>
#>
$fore = $Host.UI.RawUI.ForegroundColor
Invoke-Expression ("Get-ChildItem $args") |
%{
if ($_.GetType().Name -eq 'DirectoryInfo') {
$Host.UI.RawUI.ForegroundColor = 'DarkCyan'
echo $_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($_.Name -match '\\.(zip|tar|gz|rar)$') {
$Host.UI.RawUI.ForegroundColor = 'Yellow'
echo $_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($_.Name -match '\\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg)$') {
$Host.UI.RawUI.ForegroundColor = 'Green'
echo $_
$Host.UI.RawUI.ForegroundColor = $fore
} elseif ($_.Name -match '\\.(txt|cfg|conf|ini|csv)$') {
$Host.UI.RawUI.ForegroundColor = 'Cyan'
echo $_
$Host.UI.RawUI.ForegroundColor = $fore
} else {
echo $_
}
}
}
|
PowerShellCorpus/PoshCode/Autoload (beta 2).ps1
|
Autoload (beta 2).ps1
|
#Requires -Version 2.0
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1)
## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile)
## 4) Dot-source this file, or include it as part of your profile
## 5) Add one line to your profile (or on the commandline):
<#
autoload Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
$script:AutoloadHash = @{}
function Autoloaded {
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
if(!$CommandName) { throw "Unable to determine command" }
Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
if($Script:AutoloadHash[$CommandName]) {
$Module = Get-Module $Script:AutoloadHash[$CommandName]
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
# $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $CommandName -Type ExternalScript
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
ForEach($token in $tokens) {
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $CommandName ) {
$script = $script.Insert( $prev.Start, "global:" )
if($Module){
$script = iex "{ $Script }"
}
}
$prev = $token
}
if($Module) {
Write-Verbose "What the $($Module)"
&$Module $Script | Out-Null
$command = Get-Command $CommandName -Type Function
Write-Verbose "Loaded Module Function: $($command |Out-String)"
} else {
Invoke-Expression $script | out-null
$command = Get-Command $CommandName -Type Function
Write-Verbose "Loaded Local Function: $($command |Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($CommandName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function and removed the alias... $($command | Out-string)"
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}#DynamicParam
begin {
Write-Verbose "Autoloaded Begin: $($MyInvocation.InvocationName)"
$command = $ExecutionContext.InvokeCommand.GetCommand( $MyInvocation.InvocationName, [System.Management.Automation.CommandTypes]::Function )
$scriptCmd = {& $command @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($true)
}
process
{
Write-Verbose "Autoloaded Process: $($MyInvocation.InvocationName) ($_)"
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Autoloaded End: $($MyInvocation.InvocationName)"
}
}#AutoLoaded
function autoload {
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
,
[Parameter(Mandatory=$false)]
[String]$Module
)
begin {
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
process {
foreach($function in $Name) {
Write-Verbose "Set-Alias $function Autoloaded -Scope $Scope"
Set-Alias $function Autoloaded -Scope $Scope
$Script:AutoloadHash[$function] = $Module
}
}
}
|
PowerShellCorpus/PoshCode/Set Resource Limits.ps1
|
Set Resource Limits.ps1
|
Param([Parameter(Mandatory=$true)] [string]$VMGuest)
$vm = get-vm $VMGuest
$cpuCap = $vm.NumCPU*1000
$cpuRes = $cpuCap/2
$memCap = $vm.MemoryMB
$memRes = $memCap/4
$spec = new-object VMware.Vim.VirtualMachineConfigSpec;
$spec.memoryAllocation = New-Object VMware.Vim.ResourceAllocationInfo;
$spec.memoryAllocation.Shares = New-Object VMware.Vim.SharesInfo;
$spec.memoryAllocation.Limit = -1;
$spec.memoryAllocation.Reservation = $memRes;
$spec.cpuAllocation = New-Object VMware.Vim.ResourceAllocationInfo;
$spec.cpuAllocation.Limit = $cpuCap;
$spec.cpuAllocation.Reservation = $cpuRes;
($vm | get-view).ReconfigVM_Task($spec)
|
PowerShellCorpus/PoshCode/SyntaxHighlighter Brush_1.ps1
|
SyntaxHighlighter Brush_1.ps1
|
//
/**
* PowerShell 2.0 Brush for highlighter 2.0
*
* SyntaxHighlighter http://alexgorbatchev.com/wiki/SyntaxHighlighter
*
* @version
* 2.1.0 (April 07 2009)
*
* @copyright
* Copyright (C) 2008-2009 Joel Bennett http://HuddledMasses.org/
*
* @license
* This file is for SyntaxHighlighter.
*
* SyntaxHighlighter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* SyntaxHighlighter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SyntaxHighlighter. If not, see <http://www.gnu.org/licenses/>.
*/
SyntaxHighlighter.brushes.Powershell = function()
{
var keywords ='while validateset validaterange validatepattern validatelength validatecount ' +
'until trap switch return ref process param parameter in if global: '+
'function foreach for finally filter end elseif else dynamicparam do default ' +
'continue cmdletbinding break begin alias \\\\? % #script #private #local #global '+
'mandatory parametersetname position valuefrompipeline ' +
'valuefrompipelinebypropertyname valuefromremainingarguments helpmessage ';
var operators ='and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' +
'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' +
'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' +
'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' +
'lt match ne not notcontains notlike notmatch or regex replace wildcard';
var verbs = 'write where wait use update unregister undo trace test tee take suspend ' +
'stop start split sort skip show set send select scroll resume restore ' +
'restart resolve resize reset rename remove register receive read push ' +
'pop ping out new move measure limit join invoke import group get format ' +
'foreach export expand exit enter enable disconnect disable debug cxnew ' +
'copy convertto convertfrom convert connect complete compare clear ' +
'checkpoint aggregate add';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
{ regex: new RegExp('@"\\\\n[\\\\s\\\\S]*?\\\\n"@', 'gm'), css: 'string' }, // double quoted here-strings
{ regex: new RegExp("@'\\\\n[\\\\s\\\\S]*?\\\\n'@", 'gm'), css: 'string' }, // single quoted here-strings
{ regex: new RegExp('"(?:\\\\$\\\\([^\\\\)]*\\\\)|[^"]|`"|"")*[^`]"','g'), css: 'string' }, // double quoted strings
{ regex: new RegExp("'(?:[^']|'')*'", 'g'), css: 'string' }, // single quoted strings
{ regex: new RegExp('[\\\\$|@|@@](?:(?:global|script|private|env):)?[A-Z0-9_]+', 'gi'), css: 'variable' }, // $variables
{ regex: new RegExp('(?:'+verbs.replace(/ /g, '\\\\b|\\\\b')+')-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'functions' }, // functions and cmdlets
{ regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' }, // keywords
{ regex: new RegExp('-'+this.getKeywords(operators), 'gmi'), css: 'value bold' }, // operators
{ regex: new RegExp('\\\\s+-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'color1' }, // parameters
{ regex: new RegExp('\\\\[[A-Z_\\\\[][A-Z0-9_. `,\\\\[\\\\]]*\\\\]', 'gi'), css: 'constants' } // .Net [Type]s
];
}
SyntaxHighlighter.brushes.Powershell.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Powershell.aliases = ['monad', 'msh', 'powershell', 'PowerShell', 'posh'];
|
PowerShellCorpus/PoshCode/Add Voice to Powershell.ps1
|
Add Voice to Powershell.ps1
|
###
# Description: Add Voice to Powershell
# Version: 1.1 (11 Nov 2008)
# Mike Hays / www.mike-hays.net / blog.mike-hays.net
# Virtualization, Powershell, and more...
###
# This is the actual speaking part. I cheat by adding spaces
# (This makes the word sound right).
$spokenText = "Super ca li fragilistic expi alidocious"
# Create an object that represents the COM SAPI.SpVoice
$voice = New-Object -com SAPI.SpVoice
# Get the list of available voices
$voiceList = $voice.GetVoices()
# This script prefers using LH Michelle as a stand-in for Mary Poppins,
# but I can't be sure that she exists on all computers, so I check for that.
# She comes with some installations of Microsoft Word 2003.
$voiceDescList = @()
for ($i=0; $i -lt $voiceList.Count; $i++)
{
$voiceDescList += $voiceList.Item($i).GetDescription()
}
if ($voiceDescList -contains "LH Michelle")
{
$voiceMember = "Name=LH Michelle"
}
else
{
# This is the default voice if LH Michelle doesn't exist.
# This will probably be Microsoft Sam
$voiceMember = "Name=" + $voiceDescList[0]
}
$voiceToUse = $voice.GetVoices($voiceMember)
# This sets the voice property on the COM object
$voice.Voice = $voiceToUse.Item(0)
# This actually does the speaking.
[void] $voice.Speak($spokenText)
# She's no Julie Andrews, but she'll say what you want.
# END
|
PowerShellCorpus/PoshCode/Hack ESXi_3.ps1
|
Hack ESXi_3.ps1
|
$screen = " You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
"
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/The PowerShell Talk Xen2.ps1
|
The PowerShell Talk Xen2.ps1
|
#The PowerShell Talk
#Demo 2 - VM Easy Bake Oven
#XenServer
#Connect to XenServer
Get-Credential | connect-Xenserver -Url http://XenServer_URL/sdk
#Create the new VM
Create-XenServer:VM -NameLabel "Dave" -VCPUsAtStartup 1 -MemoryDynamicMax 536870912 -MemoryStaticMax 536870912 -MemoryDynamicMin 536870912 -MemoryStaticMin 536870912 -MemoryTarget 536870912
#Get some info on said VM
Get-XenServer:VM -name "Dave" | fl * | more
#Change the Memory
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryDynamicMax -DynamicMax 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryDynamicMin -DynamicMin 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryStaticmin -StaticMin 268435456
Get-XenServer:vm -name "Dave" | Set-XenServer:VM.MemoryStaticMax -Value 268435456
#Delete the VM
Get-XenServer:vm -name "Dave" | Destroy-XenServer:VM
|
PowerShellCorpus/PoshCode/Farm Backup.ps1
|
Farm Backup.ps1
|
##################################
#This errors out in ISE, so use cmd window.
#The script below fixes the error just below.
#Cannot access the local farm. Verify that the local farm is
#properly configured, currently available, and that you have
#the appropriate permissions to access the database before
#trying again.
#Enable-PSRemoting -Force
#Enable-WSManCredSSP -Role Server -Force
##################################
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
try
{
# specify here your backup folder
$backupRoot = "\\\\SERVER\\SPFarmBackUP\\"
$logPath = Join-Path $backupRoot "_logs"
$tmpPath = Join-Path $backupRoot "_tmp"
# removes all the old backup files on the target folder (valid values: 0 = do not remove; 1 = remove files
$clearUpOldFiles = 0
# specifies the days for the backups that should be persisted
$removeFilesOlderThanDays = -1
# specifies the backupfolder based on the current weekday (Monday... etc.)
$todaysBackupFolder = Join-Path $backupRoot ((Get-Date).DayOfWeek.toString())
# generate all necessary folders if they are missing
if (-not (Test-Path $logPath)) {
New-Item $logPath -type directory
}
if (-not (Test-Path $tmpPath)) {
New-Item $tmpPath -type directory
}
if (-not (Test-Path $todaysBackupFolder)) {
New-Item $todaysBackupFolder -type directory
}
# creates a log file
Start-Transcript -Path (Join-Path $logPath ((Get-Date).ToString('MMddyyyy_hhmmss') + ".log"))
$TXTFile = Join-Path $logPath ((Get-Date).ToString('MMddyyyy_hhmmss') + ".log")
# loop over all web applications (specify filter criteria here if you want to filter them out)
foreach ($webApplication in Get-SPWebApplication) {
Write-Host
Write-Host
Write-Host "Processing $webApplication"
Write-Host "*******************************"
foreach ($site in $webApplication.Sites) {
# we have to replace some characters from the url name
$name = $site.Url.Replace("http://", "").Replace("https://", "").Replace("/", "_").Replace(".", "_");
# replace all special characters from url with underscores
[System.Text.RegularExpressions.Regex]::Replace($name,"[^1-9a-zA-Z_]","_");
# define the backup name
$backupPath = Join-Path $tmpPath ($name + (Get-Date).ToString('MMddyyyy_hhmmss') + ".bak")
Write-Host "Backing up $site to $backupPath"
Write-Host
# backup the site
Backup-SPSite -Identity $site.Url -Path $backupPath
}
Write-Host "*******************************"
Write-Host "*******************************"
}
Write-Host
Write-Host
# remove the old backup files in the todays folder if specified
if ($clearUpOldFiles -eq 1) {
Write-Host "Cleaning up the folder $todaysBackupFolder"
Remove-Item ($todaysBackupFolder + "\\*")
}
# move all backup files from the tmp folder to the target folder
Write-Host "Moving backups from $tmpPath to $todaysBackupFolder"
Move-Item -Path ($tmpPath + "\\*") -Destination $todaysBackupFolder
# you can specify an additial parameter that removes filders older than the days you specified
if ($removeFilesOlderThanDays -gt 0) {
Write-Host "Checking removal policy on $todaysBackupFolder"
$toRemove = (Get-Date).AddDays(-$removeFilesOlderThanDays)
$filesToRemove = Get-ChildItem $todaysBackupFolder | Where {$_.LastWriteTime -le “$toRemove”}
foreach ($fileToRemove in $filesToRemove) {
Write-Host "Removing the file $fileToRemove because it is older than $removeFilesOlderThanDays days"
Remove-Item (Join-Path $todaysBackupFolder $fileToRemove) | out-null
}
}
Stop-Transcript
$today = (Get-Date -Format MM-dd-yyyy)
# Edit the From Address as per your environment.
$emailFrom = "admin@domain.com"
# Edit the mail address to which the Notification should be sent.
$emailTo = "admin@domain.com"
# Subject for the notification email. The + “$today” part will add the date in the subject.
$subject = "Site collections on Farm Backup Report for this day "+"$today"
# Body or the notification email. The + “$today” part will add the date in the subject.
$body = "The SharePoint backup of all Site collections in the farm has been run and was successful this day "+"$today"
# IP address of your SMTP server. Make sure relay Is enabled for the SharePoint server on your SMTP server
$smtpServer = "smtp.domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
Send-MailMessage -SmtpServer $smtpServer -From $emailFrom -To $emailTo -Subject $subject -Body $body -Attachment $TXTFile
}
catch
{
[System.Exception]
$ErrorMessage = $_.Exception.Message
# Configure the below parameters as per the above.
$emailFrom = "admin@domain.com"
$emailTo = "admin@domain.com"
$subject = "Site collections on Farm Backup Report for this day "+"$today"
$body = "The SharePoint backup of all Site collections in the farm has been run and the Job failed today, the "+"$today because... $ErrorMessage."
$smtpServer = "smtp.domain.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
Send-MailMessage -SmtpServer $smtpServer -From $emailFrom -To $emailTo -Subject $subject -Body $body
}
|
PowerShellCorpus/PoshCode/Get-Dependency.ps1
|
Get-Dependency.ps1
|
$BuiltInAliases = @{}
$BuiltInCmdlets = @{}
$BuiltInFunctions = @{}
$BuiltInVariables = @{}
##############################################################################
#.SYNOPSIS
# Gets a list of tokenized strings from the specified PowerShell code sample
# which can be used for dependency analysis or other unique purposes.
#
#.DESCRIPTION
# This command will use the currently active PowerShell ISE editor tab if the
# current shell is PowerShell ISE and a block of code was not provided to
# the command.
#
#.PARAMETER Type
# If specified, returns only PSTokens of the specified type(s).
#
#.PARAMETER Token
# If specified, returns only PSTokens that contain the specified text.
#
#.PARAMETER Text
# The block of text to tokenize. If this parameter is not specified, and the
# current shell is PowerShell ISE, the current editor tab's text will be used
# otherwise, no output is returned.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Lines
# If specified, returns only the tokens that are on one of the line numbers
# specified. This is useful for doing a two-pass check as in the first example
# which aims to list function declarations which consist of two related tokens,
# the keyword containing the word "function" and the command argument containing
# the function name. It is assumed they will both be on the same line.
#
#.EXAMPLE
# $FunctionLines = Get-PSToken -Type Keyword -Token function | %{ $_.StartLine }
# $FunctionNames = Get-PSToken -Type CommandArgument | ?{ $FunctionLines -contains $_.StartLine }
#
#.LINK
# Get-Dependency
#
#.RETURNVALUE
# A collection of PSTokens parsed from the source code.
##############################################################################
function Get-PSToken {
[CmdletBinding(DefaultParameterSetName='Selection')]
param(
[Parameter(Position=1)]
[String[]]$Type,
[Parameter(Position=2)]
[String[]]$Token,
[Parameter(ParameterSetName='Path', Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$Path,
[Alias("PSPath")]
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$LiteralPath,
[Parameter()]
[Int32[]]$Lines
)
process {
if ($PSCmdlet.ParameterSetName -eq 'Selection') {
if (-not $PSISE) { throw 'The Selection parameter set is not valid outside of the PowerShell ISE.' }
if (-not $PSISE.CurrentOpenedFile) { throw 'There is no file currently opened.' }
if (-not $PSISE.CurrentOpenedFile.IsSaved) { throw 'Please save the currently active document first.' }
if ($PSISE.CurrentOpenedFile.IsUntitled) { throw 'Please save the currently active document first.' }
$ResolvedPaths = @(Resolve-Path -LiteralPath $PSISE.CurrentOpenedFile.FullPath)
}
elseif ($PSCmdlet.ParameterSetName -match '^(Literal)?Path$') {
switch ($PSCmdlet.ParameterSetName) {
Path { $ResolvedPaths = @(Resolve-Path -Path $Path) }
LiteralPath { $ResolvePathArgs = @(Resolve-Path -LiteralPath $LiteralPath) }
}
}
# Delegate path expansion to Resolve-Path
foreach ($ResolvedPath in $ResolvedPaths) {
$ScriptContent = Get-Content $ResolvedPath
# Call the PSParser to tokenize!
$ParserErrors = [System.Management.Automation.PSParseError[]]@()
$ParserTokens = [System.Management.Automation.PSParser]::Tokenize($ScriptContent, [Ref]$ParserErrors)
# If there were any errors, write them out as warnings
for ($i=0; $i -lt $ParserErrors.Length; $i++) {
$ParserError = $ParserErrors[$i]
if (-not $ParserError.Token) { Write-Warning $ParserError.Message }
else { Write-Warning "($($ParserError.Token.StartLine), $($ParserError.Token.StartColumn)) $($ParserError.Message)" }
}
if (-not $ParserTokens.Count) { return }
# Filter the output
if ($Type.Length) { $ParserTokens = @($ParserTokens | ?{ $Type -contains $_.Type }) } # Filter By Type
if ($Token.Length) { $ParserTokens = @($ParserTokens | ?{ $Token -contains $_.Content }) } # Filter By Content
if ($Lines.Length) { $ParserTokens = @($ParserTokens | ?{ $Lines -contains $_.StartLine }) } # Filter By Line
if (-not $ParserTokens.Count) { return }
# Return the tokens, adding a Path property to each one
# that points back to the script or editor file
# note that text blocks will have a null path
$ParserTokens | Add-Member -PassThru NoteProperty Script (Split-Path -Leaf $ResolvedPath)
}
} # process
}
##############################################################################
#.SYNOPSIS
# Calculates the dependencies of a script file, block of PowerShell code, or
# an open PowerShell ISE document.
#
#.DESCRIPTION
# Before deploying a script or module, it is important to ensure that any
# external dependencies are resolved otherwise code that runs fine on your
# machine will bomb on someone else's. This function will scan a single
# level of dependencies from the specified script and by default returns
# any dependency that is 1) not a part of the built-in PowerShell command
# and variable configuration and 2) not defined in the script being analyzed.
# You can override this behavior and include these dependencies with the
# Force parameter.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Text
# The block of text to tokenize. If this parameter is not specified, and the
# current shell is PowerShell ISE, the current editor tab's text will be used
# otherwise, no output is returned.
#
#.PARAMETER Unresolved
# When specified, only unresolved dependencies are returned.
#
#.PARAMETER Force
# When specified, all dependencies are included, even if they are known to
# be defined locally or in the default PowerShell configuration.
#
#.EXAMPLE
# Get-Dependency | Out-GridView
#
#.LINK
# Get-PSToken
#
#.RETURNVALUE
# An array of PSObjects containing information about the external dependencies.
##############################################################################
function Get-Dependency {
[CmdletBinding(DefaultParameterSetName='Selection')]
param(
[Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$Path,
[Alias("PSPath")]
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$LiteralPath,
[Parameter()]
[Switch]$Unresolved,
[Parameter()]
[Switch]$Force
)
begin {
$Dependencies = New-Object System.Collections.ArrayList
$LocalFunctions = @{}
$ImportedAliases = @{}
$ImportedCmdlets = @{}
$ImportedFunctions = @{}
##############################################################################
#.SYNOPSIS
# Strips off the scope modifier of an identifier so its name can be checked.
##############################################################################
filter Normalize-Identifier([String]$Name) {
if ($_ -is [System.Management.Automation.PSToken]) { $Name = $_.Content }
if ($_ -is [String]) { $Name = $_ }
$Name -replace '^$?(Script|Global|Local):',''
}
##############################################################################
#.SYNOPSIS
# Wraps calls to Get-PSToken, making sure to use the appropriate parameter set.
##############################################################################
function Get-PSTokenProxy([String[]]$Type,[String[]]$Token,[Int32[]]$Lines) {
$GetPSTokenArgs = @{}
if ($Type.Length) { $GetPSTokenArgs['Type'] = $Type }
if ($Token.Length) { $GetPSTokenArgs['Token'] = $Token }
if ($Lines.Length) { $GetPSTokenArgs['Lines'] = $Lines }
$ResolvedPaths | Get-PSToken @GetPSTokenArgs
}
##############################################################################
#.SYNOPSIS
# Rebuilds the cache of built-in command, alias, function, and variable names
# that are present in an unconfigured PowerShell session so that they can
# be skipped from dependency checking.
##############################################################################
function Discover-BuiltInCommands {
if ($BuiltInCmdlets.Count -eq 0) {
$BuiltInAliases.Clear()
$BuiltInCmdlets.Clear()
$BuiltInFunctions.Clear()
$BuiltInVariables.Clear()
$Posh = [PowerShell]::Create()
try {
[Void]$Posh.AddScript('Get-Command -CommandType Cmdlet,Function,Alias')
foreach($CommandInfo in $Posh.Invoke()) {
switch($CommandInfo.CommandType) {
Alias { $BuiltInAliases[$CommandInfo.Name] = $true }
Cmdlet { $BuiltInCmdlets[$CommandInfo.Name] = $true }
Function { $BuiltInFunctions[$CommandInfo.Name] = $true }
}
}
[Void]$Posh.AddScript('Get-Variable')
foreach($VariableInfo in $Posh.Invoke()) {
$BuiltInVariables[$VariableInfo.Name] = $true
}
# Note: PSISE won't appear as a built-in variable this way
# I decided I actually prefer it that way. I want to know if
# I accidentially couple a script to the ISE
$BuiltInVariables['this'] = $true
}
finally {
$Posh.Dispose()
}
} # if count 0
}
##############################################################################
#.SYNOPSIS
# Scans the source code for Import-Module statements and gathers up the
# module export information into hashtables.
##############################################################################
function Discover-ModuleImports {
$ImportedAliases.Clear()
$ImportedCmdlets.Clear()
$ImportedFunctions.Clear()
$TokenLines = @(Get-PSTokenProxy Command Import-Module | %{$_.StartLine})
if (-not $TokenLines.Length) { return } # nothing to do
$TokenNames = @(Get-PSTokenProxy CommandArgument -Lines $TokenLines | Normalize-Identifier)
if (-not $TokenNames.Length) { return } # nothing to do
# Find out which referenced modules are not imported
$MissingModules = @()
foreach ($TokenName in $TokenNames) {
if (-not (Get-Module $TokenName)) {
$MissingModules += $TokenName
}
}
if ($MissingModules.Length) {
$MenuItem1 = New-Object System.Management.Automation.Host.ChoiceDescription "&No - Do Not Import Modules"
$MenuItem2 = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes - Import These Modules"
[System.Management.Automation.Host.ChoiceDescription[]]$MenuItems = @($MenuItem1,$MenuItem2)
$MenuCaption = "Imported Modules Not Loaded"
$MenuMessage = "One or more modules imported by the script are not currently loaded.`r`n" +
"This can lead to unresolved external references and missing`r`n" +
"information in the dependency report.`r`n" +
"`r`n" +
"You can attempt to temporarily import the following modules into the`r`n" +
"session by selection the option below.`r`n" +
"`r`n"
foreach ($MissingModule in $MissingModules) {
$MenuMessage += " Import-Module $MissingModule`r`n"
}
# Show the menu
# If the user picks choice Y then import the modules
# Because you can't import modules into the global scope from a lower scope,
# the imported module will not be visible from outside of the current scope.
$Response = $Host.UI.PromptForChoice($MenuCaption, $MenuMessage, $MenuItems, 0)
if ($Response = 1) {
foreach ($MissingModule in $MissingModules) {
# Using Invoke-Expression so this Import-Module command
# doesn't cause a screw-up when checking dependencies of
# Dependency.psm1. Gay huh...
Invoke-Expression ".{Import-Module $MissingModule -ErrorAction Continue}"
}
}
}
$ImportedModules = @(Get-Module $TokenNames -ListAvailable) + @(Get-Module $TokenNames)
foreach ($ImportedModule in $ImportedModules) {
$ImportedModule.ExportedAliases.Values | %{ $ImportedAliases[$_.Name] = $_ }
$ImportedModule.ExportedCmdlets.Values | %{ $ImportedCmdlets[$_.Name] = $_ }
$ImportedModule.ExportedFunctions.Values | %{ $ImportedFunctions[$_.Name] = $_ }
}
}
##############################################################################
#.SYNOPSIS
# Scans the source code for function and filter keywords that define local
# functions that should not be treated as external dependencies.
##############################################################################
function Discover-LocalFunctions {
$LocalFunctions.Clear()
# Gather information about defined functions
$TokenLines = @(Get-PSTokenProxy Keyword function,filter | %{$_.StartLine})
if (-not $TokenLines.Length) { return } # nothing to do
$TokenNames = @(Get-PSTokenProxy CommandArgument -Lines $TokenLines | Normalize-Identifier)
if (-not $TokenNames.Length) { return } # nothing to do
# No CommandInfo for these so we'll just store a bool
foreach ($TokenName in $TokenNames) {
$LocalFunctions[$TokenName] = $true
}
}
##############################################################################
#.SYNOPSIS
# Removes references to built-in Cmdlets, functions, variables, etc from
# the input stream.
##############################################################################
filter Exclude-BuiltInReferences {
if ($Force) { return $_ }
$Token = $_
$TokenName = Normalize-Identifier $Token.Content
# Is it built in?
# If so, skip it.
if ($Token.Type -eq 'Command') {
if ($BuiltInAliases[$TokenName]) { return }
if ($BuiltInCmdlets[$TokenName]) { return }
if ($BuiltInFunctions[$TokenName]) { return }
}
elseif ($Token.Type -eq 'Variable') {
if ($BuiltInVariables[$TokenName]) { return }
}
$Token
}
##############################################################################
#.SYNOPSIS
# Removes references to locally defined functions from the input stream.
##############################################################################
filter Exclude-LocalReferences {
if ($Force) { return $_ }
$Token = $_
$TokenName = Normalize-Identifier $Token.Content
# Is it built in?
# If so, skip it.
if ($Token.Type -eq 'Command') {
if ($LocalFunctions[$TokenName]) { return }
}
$Token
}
##############################################################################
#.SYNOPSIS
# Gets a single command with the specified name, taking into account that the
# command name may need to have conflicting wildcard characters escaped and
# avoiding the error when a command does not exist.
##############################################################################
function Get-SafeCommand([String]$Name) {
$SafeName = [System.Management.Automation.WildcardPattern]::Escape($Name)
$CommandInfo = Get-Command -Name $SafeName -ErrorAction SilentlyContinue | Select -First 1
if (-not $CommandInfo) { $CommandInfo = $ImportedAliases[$Name] }
if (-not $CommandInfo) { $CommandInfo = $ImportedFunctions[$Name] }
if (-not $CommandInfo) { $CommandInfo = $ImportedCmdlets[$Name] }
$CommandInfo
}
##############################################################################
#.SYNOPSIS
# Gets a single variable with the specified name, taking into account that the
# variable name may need to have conflicting wildcard characters escaped and
# avoiding the error when a variable does not exist.
##############################################################################
function Get-SafeVariable([String]$Name) {
$SafeName = [System.Management.Automation.WildcardPattern]::Escape($Name)
$VariableInfo = Get-Variable -Name $SafeName -Scope Global -ErrorAction SilentlyContinue | Select -First 1
$VariableInfo
}
##############################################################################
#.SYNOPSIS
# Selects the first instance of each distinct combination of token type and
# content (function/variable name etc) and includes the line number of the
# first occurrence.
#
#.DESCRIPTION
# This is a basically just a ugly way of doing:
# SELECT Type,Content,Min(StartLine) FROM ... GROUP BY Type,Content
# Which PowerShell cannot easily represent as far as I know
##############################################################################
function Select-UniqueTokens {
$Input |
Group-Object Type,Content |
Select-Object @(
@{N='Type'; E={ $_.Group[0].Type } },
@{N='Content'; E={ $_.Group[0].Content } },
@{N='Script'; E={ $_.Group[0].Script } }
@{N='StartLine'; E={ $_.Group[0].StartLine } }
)
}
##############################################################################
#.SYNOPSIS
# Creates a new PSObject for holding information about the external dependency
##############################################################################
function New-Dependency($Token) {
# Create a PSObject to hold the values
# we will output from this function
New-Object PSObject |
Add-Member -PassThru NoteProperty Script ($Token.Script) |
Add-Member -PassThru NoteProperty Module ($null) |
Add-Member -PassThru NoteProperty Type ($Token.Type) |
Add-Member -PassThru NoteProperty Name (Normalize-Identifier $Token.Content) |
Add-Member -PassThru NoteProperty Target ($null) |
Add-Member -PassThru NoteProperty Resolved ($false) |
Add-Member -PassThru NoteProperty File ($null)
}
} # begin
process {
if ($PSCmdlet.ParameterSetName -eq 'Selection') {
if (-not $PSISE) { throw 'The Selection parameter set is not valid outside of the PowerShell ISE.' }
if (-not $PSISE.CurrentOpenedFile) { throw 'There is no file currently opened.' }
if (-not $PSISE.CurrentOpenedFile.IsSaved) { throw 'Please save the currently active document first.' }
if ($PSISE.CurrentOpenedFile.IsUntitled) { throw 'Please save the currently active document first.' }
$ResolvedPaths = @(Resolve-Path -LiteralPath $PSISE.CurrentOpenedFile.FullPath)
}
elseif ($PSCmdlet.ParameterSetName -match '^(Literal)?Path$') {
switch ($PSCmdlet.ParameterSetName) {
Path { $ResolvedPaths = @(Resolve-Path -Path $Path) }
LiteralPath { $ResolvedPaths = @(Resolve-Path -LiteralPath $LiteralPath) }
}
}
# Discover imported modules and function definitions
Discover-BuiltInCommands
Discover-ModuleImports
Discover-LocalFunctions
# Parse the source code
# Gives back command and variable references
$Tokens = @(
Get-PSTokenProxy Command,Variable |
Exclude-BuiltInReferences |
Exclude-LocalReferences |
Select-UniqueTokens
)
foreach ($Token in $Tokens) {
$Dependency = New-Dependency $Token
# HANDLE VARIABLE REFERENCES
if ($Token.Type -eq 'Variable') {
if ($VariableInfo = Get-SafeVariable $Dependency.Name) {
$Dependency.Module = $VariableInfo.ModuleName
$Dependency.Resolved = $true
}
else {
# Skip this dependency
# Could not find this variable in global state
# So we can only assume that the variable is
# localized somewhere and cannot really be
# resolved as an external dependency
# TODO: maybe look for a setter or arg name
# to determine if it's really external or not
continue
}
} # Token Type = Variable
# HANDLE COMMAND REFERENCES
if ($Token.Type -eq 'Command') {
if ($CommandInfo = Get-SafeCommand $Dependency.Name) {
$Dependency.Type= $CommandInfo.CommandType
$Dependency.Resolved = $true
# Is it an alias?
# If so, we want to resolve the target
if ($CommandInfo.CommandType -eq 'Alias') {
# Is the alias resolved?
if ($CommandInfo.ResolvedCommandName) {
# Is alias the same name as the target?
# If so, this is generally a disambiguating alias and can be ignored.
if ($CommandInfo.Name -eq $CommandInfo.ResolvedCommandName) {
if ($BuiltInAliases[$CommandInfo.ResolvedCommandName]) { continue }
if ($BuiltInCmdlets[$CommandInfo.ResolvedCommandName]) { continue }
if ($BuiltInFunctions[$CommandInfo.ResolvedCommandName]) { continue }
}
$Dependency.Target = $CommandInfo.ResolvedCommandName
$CommandInfo = $CommandInfo.ResolvedCommand
}
else {
# The alias points to an unresolved command
$Dependency.Resolved = $false
}
} # Command Type = Alias
# Command Source Info
# Note that in the case of resolved aliases, CommandInfo is now
# pointing to the resolved command and modules/paths/etc will reflect that
if ($CommandInfo.ModuleName) { $Dependency.Module = $CommandInfo.ModuleName }
if ($CommandInfo.ScriptBlock.File) { $Dependency.File = $CommandInfo.ScriptBlock.File }
if ($CommandInfo.Path) { $Dependency.File = $CommandInfo.Path }
if ($CommandInfo.DLL) { $Dependency.File = $CommandInfo.DLL }
} # Is Command Is Resolved
} # Token Type = Command
if ($Unresolved -and $Dependency.Resolved) { continue }
[Void]$Dependencies.Add($Dependency)
} # foreach Token
} # process
end {
# returns all output at the end
$Dependencies | Sort Script,Module,Type,Name
} # end
}
|
PowerShellCorpus/PoshCode/FTP upload_6.ps1
|
FTP upload_6.ps1
|
@charset "utf-8";
/*
Credit:http://www.templatemo.com
*/
body {
margin: 0px;
padding: 0px;
color: #c2bead;
font-family: Tahoma, Geneva, sans-serif;
font-size: 12px;
line-height: 1.5em;
background-color: #2f2e28;
background-image: url(images/templatemo_body.jpg);
background-repeat: repeat-y;
background-position: left;
}
a, a:link, a:visited { color: #34baf9; text-decoration: none; }
a:hover { color: #CCFF00; text-decoration: underline; }
p { margin: 0 0 10px 0; padding: 0; }
img { border: none; }
h1, h2, h3, h4, h5, h6 { color: #e2c934; }
h1 { font-size: 24px; font-weight: normal; margin: 0 0 30px 0; padding: 5px 0; }
h2 { font-size: 20px; font-weight: normal; margin: 0 0 30px 0; font-weight: normal; }
h3 { font-size: 16px; margin: 0 0 15px 0; padding: 0; padding: 0; font-weight: normal; }
h4 { font-size: 14px; margin: 0 0 15px 0; padding: 0; }
.cleaner { clear: both; width: 100%; height: 0px; font-size: 0px; }
.cleaner_h10 { clear: both; width:100%; height: 10px; }
.cleaner_h20 { clear: both; width:100%; height: 20px; }
.cleaner_h30 { clear: both; width:100%; height: 30px; }
.cleaner_h40 { clear: both; width:100%; height: 40px; }
.cleaner_h50 { clear: both; width:100%; height: 50px; }
.cleaner_h60 { clear: both; width:100%; height: 60px; }
.float_l { float: left; }
.float_r { float: right; }
.image_wrapper { display: inline-block; border: 1px solid #000; background: #333; padding: 4px; margin-bottom: 10px; }
.image_fl { float: left; margin: 3px 15px 0 0; }
.image_fr { float: right; margin: 3px 0 0 15px; }
blockquote { font-style: italic; margin: 0 0 0 10px;}
cite { font-weight: bold; color:#333; }
cite span { color: #666; }
em { color: #f9a834; }
.tmo_list { margin: 20px 0 20px 20px; padding: 0; list-style: none; }
.tmo_list li { background: transparent url(images/templatemo_list.png) no-repeat; margin:0 0 20px; padding: 0 0 0 20px; line-height: 1em; }
.tmo_list li a { color: #fff; }
.tmo_list li a:hover { color: #ff4301; }
.btn_more a {
display: inline-block;
font-weight: bold;
color: #dcd9cb;
}
.btn_more a span {
font-size: 16px;
}
.btn_more a:hover {
color: #CCFF00;
text-decoration: none;
}
.service_list { margin: 40px 0 0 30px; padding: 0; list-style: none; }
.service_list li { margin: 0; padding: 0; }
.service_list li a { display: block; height: 25px; margin-bottom: 20px; padding-left: 35px; }
.service_list li .service_one { background: url(images/onebit_08.png) center left no-repeat; }
.service_list li .service_two { background: url(images/onebit_11.png) center left no-repeat; }
.service_list li .service_three { background: url(images/onebit_17.png) center left no-repeat; }
.service_list li .service_four { background: url(images/onebit_21.png) center left no-repeat; }
.service_list li .service_five { background: url(images/onebit_12.png) center left no-repeat; }
#contact_form { padding: 0; }
#contact_form form { margin: 0px; padding: 0px; }
#contact_form form .input_field { width: 440px; padding: 8px; background: #333028; border: 1px solid #886; color: #FFF; }
#contact_form form label { display: block; width: 100px; margin-right: 10px; font-size: 14px; margin-bottom: 3px; }
#contact_form form textarea {
width: 440px;
height: 120px;
padding: 8px;
background: #333028;
font-family: Arial, Helvetica, sans-serif;
border: 1px solid #886;
color: #FFF;
}
#contact_form form .submit_btn {
color: #886;
background: #333028;
border: 1px solid #886;
padding: 10px 20px;
margin-right: 140px;
font-size: 15px;
}
#gallery_container {
clear: both;
margin-top: 30px;
padding-right: 40px;
width: 480px;
height: 320px;
overflow: auto;
}
#gallery_container .gallery_box {
clear: both;
display: block;
padding: 0;
margin: 0 0 40px 0;
}
.gallery_box img {
float: left;
width: 120px;
height: 100px;
padding: 4px;
background: #fff;
border: 1px solid #ccc;
margin: 3px 30px 0 0;
}
#templatemo_footer {
clear: both;
width: 600px;
padding: 20px 0;
text-align: center;
}/* CSS Document */
|
PowerShellCorpus/PoshCode/Shift Operators(Correct)_1.ps1
|
Shift Operators(Correct)_1.ps1
|
#requires -version 2.0
Add-Type @"
public class Shift {
public static int Right(int x, int count) { return x >> count; }
public static uint Right(uint x, int count) { return x >> count; }
public static long Right(long x, int count) { return x >> count; }
public static ulong Right(ulong x, int count) { return x >> count; }
public static int Left(int x, int count) { return x << count; }
public static uint Left(uint x, int count) { return x << count; }
public static long Left(long x, int count) { return x << count; }
public static ulong Left(ulong x, int count) { return x << count; }
}
"@
#.Example
# Shift-Left 16 1 ## returns 32
#.Example
# 8,16 |Shift-Left ## returns 16,32
function Shift-Left {
PARAM( $x=1, $y )
BEGIN {
if($y) {
[Shift]::Left( $x, $y )
}
}
PROCESS {
if($_){
[Shift]::Left($_, $x)
}
}
}
#.Example
# Shift-Right 8 1 ## returns 4
#.Example
# 2,4,8 |Shift-Right 2 ## returns 0,1,2
function Shift-Right {
PARAM( $x=1, $y )
BEGIN {
if($y) {
[Shift]::Right( $x, $y )
}
}
PROCESS {
if($_){
[Shift]::Right($_, $x)
}
}
}
|
PowerShellCorpus/PoshCode/Migrate-ADMTUser.ps1
|
Migrate-ADMTUser.ps1
|
###########################################################################"
#
# NAME: Migrate-ADMTUser.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: A function to migrate a single user in the Active Directory Migration Tool, based on the sample script Invoke-ADMTUserMigration.ps1: http://poshcode.org/2046
#
# Instead of hardcoding the variables for the migration, you could add additional parameters to the function to define these.
#
# NOTE: Since ADMT is a 32-bit application, this script must be run from Windows PowerShell (x86).
# It also requires elevated privileges.
#
# For more details, see the following blog-post:
# http://blog.powershell.no/2010/08/04/automate-active-directory-migration-tool-using-windows-powershell
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 04.08.2010 - Initial release
#
###########################################################################"
function Migrate-ADMTUser {
<#
.SYNOPSIS
Migrate a single user object using ADMT
.DESCRIPTION
Migrates the specified source domain user object to the target domain.
One mandatory parameter: samaccountname
.PARAMETER samaccountname
The samaccountname of the source domain user object to migrate
.EXAMPLE
Migrate-ADMTUser -samaccountname JDoe
.NOTES
AUTHOR: Jan Egil Ring
BLOG: http://blog.powershell.no
LASTEDIT: 04.08.2010
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true)]
[string]$samaccountname
)
### BEGIN ADMT Scripting Constants ###
# PasswordOption constants
$admtComplexPassword = "&H0001"
$admtCopyPassword = "&H0002"
$admtDoNotUpdatePasswordsForExisting = "&H0010"
# ConflictOptions constants
$admtIgnoreConflicting = "&H0000"
$admtMergeConflicting = "&H0001"
$admtRemoveExistingUserRights = "&H0010"
$admtRemoveExistingMembers = "&H0020"
$admtMoveMergedAccounts = "&H0040"
# DisableOption constants
$admtLeaveSource = "&H0000"
$admtDisableSource = "&H0001"
$admtTargetSameAsSource = "&H0000"
$admtDisableTarget = "&H0010"
$admtEnableTarget = "&H0020"
# SourceExpiration constant
$admtNoExpiration = "-1"
# Translation Option
$admtTranslateReplace = "0"
$admtTranslateAdd = "1"
$admtTranslateRemove = "2"
# Report Type
$admtReportMigratedAccounts = "0"
$admtReportMigratedComputers = "1"
$admtReportExpiredComputers = "2"
$admtReportAccountReferences = "3"
$admtReportNameConflicts = "4"
# Option constants
$admtNone = "0"
$admtData = "1"
$admtFile = "2"
$admtDomain = "3"
$admtRecurse = "&H0100"
$admtFlattenHierarchy = "&H0000"
$admtMaintainHierarchy = "&H0200"
# Event related constants
# Progress type
$admtProgressObjectMigration = "0"
$admtProgressAgentDispatch = "1"
$admtProgressAgentOperation = "2"
$admtProgressMailboxMigration = "3"
# Event type
$admtEventNone = "0"
$admtEventObjectInputPreprocessed = "1"
$admtEventTaskStart = "2"
$admtEventTaskFinish = "3"
$admtEventObjectProcessed = "4"
$admtEventGroupMembershipProcessed = "5"
$admtEventAgentStatusUpdate ="6"
$admtEventAgentNotStarted = "7"
$admtEventAgentFailedToStart = "8"
$admtEventAgentWaitingForReboot = "9"
$admtEventAgentRunning = "10"
$admtEventAgentCancelled = "11"
$admtEventAgentPassed = "12"
$admtEventAgentFailed = "13"
$admtEventAgentWaitingForRetry = "14"
$admtEventAgentSuccessful = "15"
$admtEventAgentCompletedWithWarnings = "16"
$admtEventAgentCompletedWithErrors = "17"
$admtEventTaskLogSaved = "18"
$admtAgentPreCheckPhase = "&H100"
$admtAgentAgentOperationPhase = "&H200"
$admtAgentPostCheckPhase = "&H300"
$admtAgentStatusMask = "&HFF"
$admtAgentPhaseMask = "&H300"
# Status type
$admtStatusSuccess = "0"
$admtStatusWarnings = "1"
$admtStatusErrors = "2"
### END ADMT Scripting Constants ###
#Creates an instance of an ADMT migration object using the COM-object provided with ADMT
$Migration = New-Object -ComObject "ADMT.Migration"
$Migration.IntraForest = $false
$Migration.SourceDomain = "contoso-old.local"
$Migration.SourceDomainController = "dc01.contoso-old.local"
$Migration.SourceOU = "Europe/Norway/Oslo"
$Migration.TargetDomain = "contoso-new.local"
$Migration.TargetDomainController = "dc02.contoso-new.local"
$Migration.TargetOU = "Europe/Norway/Oslo"
$Migration.PasswordOption = $admtComplexPassword
$Migration.PasswordServer = "dc01.contoso-old.local"
$Migration.PasswordFile = "C:\\WINDOWS\\ADMT\\Logs\\Passwords.txt"
$Migration.ConflictOptions = $admtIgnoreConflicting
$Migration.UserPropertiesToExclude = ""
$Migration.InetOrgPersonPropertiesToExclude = ""
$Migration.GroupPropertiesToExclude = ""
$Migration.ComputerPropertiesToExclude = ""
$Migration.SystemPropertiesToExclude = ""
$Migration.PerformPreCheckOnly = $false
$Migration.AdmtEventLevel = $admtStatusWarnings
$Migration.CommandLine = $false
#Creates an user migration object
$UserMigration = $Migration.CreateUserMigration()
$UserMigration.DisableOption = $admtTargetSameAsSource
$UserMigration.SourceExpiration = $admtNoExpiration
$UserMigration.MigrateSIDs = $true
$UserMigration.TranslateRoamingProfile = $false
$UserMigration.UpdateUserRights = $false
$UserMigration.MigrateGroups = $false
$UserMigration.UpdatePreviouslyMigratedObjects = $false
$UserMigration.FixGroupMembership = $true
$UserMigration.MigrateServiceAccounts = $false
#Initiates user migration. Logs are written to C:\\Windows\\ADMT\\Logs by default.
$UserMigration.Migrate($admtData,$samaccountname,$null)
#Creates a password migration object
$PasswordMigration = $Migration.CreatePasswordMigration()
#Initiates password migration. Logs are written to C:\\Windows\\ADMT\\Logs by default.
$PasswordMigration.Migrate($admtData,$samaccountname,$null)
}
|
PowerShellCorpus/PoshCode/Get-HtmlHelp_2.ps1
|
Get-HtmlHelp_2.ps1
|
Hello,
I may have contacted you in the past, but wanted to reach out again to inquire about the possibility of advertising on your blog in the form of sponsored guest posts.
Either I can have content written or you can write content that is relevant to your audience and helps to promote our client's service. We then pay for that post and the opportunity to have exposure to your readers.
Thank you,
-Brandon Murphy
brandon@submitdigital.com
www.SubmitDigital.com
http://huddledmasses.org
|
PowerShellCorpus/PoshCode/Add -__ Get-Help -Full.ps1
|
Add -__ Get-Help -Full.ps1
|
$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
# Only for interactive commands (and that doesn't include "prompt")
# I should exclude out-default so we don't handle it on every pipeline, but ...
if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) {
## Create a new script block that checks for the "-??" argument
## And if -?? exists, calls Get-Help -Full instead
## Otherwise calls the expected command
$CommandLookupEventArgs.CommandScriptBlock = {
if($Args.Length -eq 1 -and $Args[0] -eq "-??") {
Get-Help $CommandName -Full
} else {
& $CommandName @args
}
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
|
PowerShellCorpus/PoshCode/Convert-FspToUsername.ps1
|
Convert-FspToUsername.ps1
|
Function Convert-FspToUsername
{
<#
.SYNOPSIS
Convert a FSP to a sAMAccountName
.DESCRIPTION
This function converts FSP's to sAMAccountName's.
.PARAMETER UserSID
This is the SID of the FSP in the form of S-1-5-20. These can be found
in the ForeignSecurityPrincipals container of your domain.
.EXAMPLE
Convert-FspToUsername -UserSID "S-1-5-11","S-1-5-17","S-1-5-20"
sAMAccountName Sid
-------------- ---
NT AUTHORITY\\Authenticated Users S-1-5-11
NT AUTHORITY\\IUSR S-1-5-17
NT AUTHORITY\\NETWORK SERVICE S-1-5-20
Description
===========
This example shows passing in multipe sids to the function
.EXAMPLE
Get-ADObjects -ADSPath "LDAP://CN=ForeignSecurityPrincipals,DC=company,DC=com" -SearchFilter "(objectClass=foreignSecurityPrincipal)" |
foreach {$_.Properties.name} |Convert-FspToUsername
sAMAccountName Sid
-------------- ---
NT AUTHORITY\\Authenticated Users S-1-5-11
NT AUTHORITY\\IUSR S-1-5-17
NT AUTHORITY\\NETWORK SERVICE S-1-5-20
Description
===========
This example takes the output of the Get-ADObjects function, and pipes it through foreach to get to the name
property, and the resulting output is piped through Convert-FspToUsername.
.NOTES
This function currently expects a SID in the same format as you see being displayed
as the name property of each object in the ForeignSecurityPrincipals container in your
domain.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Convert-FspToUsername
#>
Param
(
[Parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true)]
$UserSID
)
Begin
{
}
Process
{
foreach ($Sid in $UserSID)
{
try
{
$SAM = (New-Object System.Security.Principal.SecurityIdentifier($Sid)).Translate([System.Security.Principal.NTAccount])
$Result = New-Object -TypeName PSObject -Property @{
Sid = $Sid
sAMAccountName = $SAM.Value
}
Return $Result
}
catch
{
$Result = New-Object -TypeName PSObject -Property @{
Sid = $Sid
sAMAccountName = $Error[0].Exception.InnerException.Message.ToString().Trim()
}
Return $Result
}
}
}
End
{
}
}
|
PowerShellCorpus/PoshCode/HttpRest 1.0.2.ps1
|
HttpRest 1.0.2.ps1
|
## Http Rest
####################################################################################################
## The first implementation of the HttpRest module, as a bunch of script functions
## Based on the REST api from MindTouch's Dream SDK
##
## INSTALL:
## You need log4net.dll mindtouch.core.dll mindtouch.dream.dll and SgmlReaderDll.dll from the SDK
## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
## Unpack it, and you can find these dlls in the "dist" folder.
## Make sure to put them in the folder with the module.
##
## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream
####################################################################################################
## Version History
## 1.0 First Release
## 1.0.1 Added Get-WebPageContent
## 1.0.2 Fix for Invoke-Http not passing credentials correctly
####################################################################################################
## Usage:
## function Get-Google {
## Invoke-Http GET http`://www.google.com/search @{q=$args} |
## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
## }
## #########################################################################
## function Get-WebFile($url,$cred) {
## Invoke-Http GET $url -auth $cred | Receive-Http File
## }
## #########################################################################
## function Send-Paste {
## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
## PROCESS {
## if($_){[IO.FileInfo]$file=$_}
##
## if($file.Exists) {
## $ofs="`n"
## $result = Invoke-Http POST $PastebinURI @{
## format="posh" # PowerShell
## expiry="d" # (d)ay or (m)onth or (f)orever
## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1])
## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
## paste="Send"
## } -Type FORM_URLENCODED -Wait
## $xml = $result.AsDocument().ToXml()
## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
## } else { throw "File Not Found" }
## }}
##
####################################################################################################
if(!$PSScriptRoot){
Write-Debug $($MyInvocation.MyCommand | out-string)
$PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
}
# Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
# Write-Debug "Invocation: $($MyInvocation.MyCommand)"
# Write-Debug "Invocation: $($MyInvocation)"
Write-Debug "PSScriptRoot: '$PSScriptRoot'"
# This Module depends on MindTouch.Dream
$null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" )
# MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
# This Module also depends on utility functions from System.Web
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
## Some utility functions are defined at the bottom
[uri]$global:url = ""
[System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
function Get-DreamMessage($Content,$Type) {
if(!$Content) {
return [MindTouch.Dream.DreamMessage]::Ok()
}
if( $Content -is [System.Xml.XmlDocument]) {
return [MindTouch.Dream.DreamMessage]::Ok( $Content )
}
if(Test-Path $Content -EA "SilentlyContinue") {
return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
}
if($Type -is [String]) {
$Type = [MindTouch.Dream.MimeType]::$Type
}
if($Type -is [MindTouch.Dream.DreamMessage]) {
return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
} else {
return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
}
}
function Get-DreamPlug {
PARAM ( $Url, [hashtable]$With )
if($Url -is [array]) {
if($Url[0] -is [hashtable]) {
$plug = [MindTouch.Dream.Plug]::New($global:url)
foreach($param in $url.GetEnumerator()) {
if($param.Value) {
$plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
} else {
$plug = $plug.At($param.Key)
}
}
}
else
{
[URI]$uri = Join-Url $global:url $url
$plug = [MindTouch.Dream.Plug]::New($uri)
}
}
elseif($url -is [string])
{
[URI]$uri = $url
if(!$uri.IsAbsoluteUri) {
$uri = Join-Url $global:url $url
}
$plug = [MindTouch.Dream.Plug]::New($uri)
}
else {
$plug = [MindTouch.Dream.Plug]::New($global:url)
}
if($with) {
foreach($param in $with.GetEnumerator()) {
if($param.Value) {
$plug = $plug.With($param.Key,$param.Value)
}
}
}
return $plug
}
#CMDLET Receive-Http {
Function Receive-Http {
PARAM(
# [Parameter(Position=1, Mandatory=$false)]
# [ValidateSet("Xml", "File", "Text","Bytes")]
# [Alias("As")]
$Output = "Xml"
,
# [Parameter(Position=2, Mandatory=$false)]
[string]$Path
,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
# [Alias("IO")]
# [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
$InputObject
#,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
# [MindTouch.Dream.DreamMessage]
# $response
)
BEGIN {
if($InputObject) {
Write-Output $inputObject | Receive-Http $Output $Path
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
$response = $null
if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
$response = $_.Wait()
} elseif($_ -is [MindTouch.Dream.DreamMessage]) {
$response = $_
} elseif($_) {
throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
}
if($response) {
Write-Debug $($response | Out-String)
if(!$response.IsSuccessful) {
Write-Error $($response | Out-String)
Write-Verbose $response.AsText()
throw "ERROR: '$($response.Status)' Response Status."
} else {
switch($Output) {
"File" {
## Joel's magic filename guesser ...
if(!$Path) {
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
$Path = $fileName.trim("\\/""'")
if(!$Path) {
$fileName = $response.ResponseUri.Segments[-1]
$Path = $fileName.trim("\\/")
if(!([IO.FileInfo]$Path).Extension) {
$Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
}
}
}
$File = Get-FileName $Path
[StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
Get-ChildItem $File
}
"XDoc" {
if($Path) {
$response.AsDocument()[$Path]
} else {
$response.AsDocument()#.ToXml()
}
}
"Xml" {
if($Path) {
$response.AsDocument().ToXml().SelectNodes($Path)
} else {
$response.AsDocument().ToXml()
}
}
"Text" {
if($Path) {
$response.AsDocument()[$Path] | % { $_.AsText }
} else {
$response.AsText()
}
}
"Bytes" {
$response.AsBytes()
}
}
}
}
}
}
## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
## Nobody actually uses HEAD or OPTIONS, right?
## And nobody's even heard of TRACE or CONNECT ;)
# CMDLET Invoke-Http {
Function Invoke-Http {
PARAM(
# [Parameter(Position=0, Mandatory=$false)]
# [ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
[string]$Verb = "Get"
,
# [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]
# [string]
$Path
,
# [Parameter(Position=2, Mandatory=$false)]
[hashtable]$with
,
# [Parameter(Position=3, Mandatory=$false)]
$Content
,
$Type # Of Content
,
$authenticate
,
[switch]$waitForResponse
)
BEGIN {
$Verbs = "Post", "Get", "Put", "Delete", "Head", "Options"
if($Verbs -notcontains $Verb) {
Write-Warning "The specified verb '$Verb' is NOT one of the common verbs: $Verbs"
}
if($Path) {
if($Content) {
Write-Output ($Path | Invoke-Http $Verb -With $With -Content $Content -Type $Type -Authenticate $authenticate -waitForResponse:$WaitForResponse)
} else {
Write-Output ($Path | Invoke-Http $Verb -With $With -Type $Type-Authenticate $authenticate -waitForResponse:$WaitForResponse)
}
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
if($_) {
$Path = $_
$plug = Get-DreamPlug $Path $With
Write-Verbose "Content Type: $Type"
Write-Verbose "Content: $Content"
## Special Handling for FORM_URLENCODED
if($Type -like "Form*" -and !$Content) {
$dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
$Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
} else {
$dream = Get-DreamMessage $Content $Type
}
if(!$plug -or !$dream) {
throw "Can't come up with a request!"
}
Write-Verbose $( $dream | Out-String )
if($authenticate){
Write-Verbose "AUTHENTICATE AS $($authenticate.UserName)"
if($authenticate -is [System.Management.Automation.PSCredential]) {
Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
$plug = $plug.WithCredentials($authenticate.GetNetworkCredential())
} elseif($authenticate -is [System.Net.NetworkCredential]) {
Write-Verbose "AUTHENTICATING AS $($authenticate.UserName)"
$plug = $plug.WithCredentials($authenticate)
} else {
$null = Get-HttpCredential
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 | Out-String)
$result = $plug.InvokeAsync( $Verb.ToUpper(), $dream )
Write-Debug $($result | Out-String)
# if($DebugPreference -eq "Continue") {
# Write-Debug $($result.Wait() | Out-String)
# }
if($waitForResponse) {
$result = $result.Wait()
}
write-output $result
trap [MindTouch.Dream.DreamResponseException] {
Write-Error @"
TRAPPED DreamResponseException
$($_.Exception.Response | Out-String)
$($_.Exception.Response.Headers | Out-String)
"@
break;
}
}
}
}
function Get-WebPageContent {
#[CmdletBinding()]
param(
# [Parameter(Position=0,Mandatory=$true)]
[string]$url
,
# [Parameter(Position=1,Mandatory=$false)]
[string]$xpath=""
,
# [Parameter(Mandatory=$false)]
[hashtable]$with=@{}
,
# [Parameter(Position=2,Mandatory=$false)]
[switch]$AsXml
)
BEGIN { $out = "Text"; if($AsXml) { $out="Xml" } }
PROCESS {
invoke-http get $url $with | receive-http $out $xpath
}
}
new-alias gwpc Get-WebPageContent -EA "SilentlyContinue"
new-alias http Invoke-Http -EA "SilentlyContinue"
new-alias rcv Receive-Http -EA "SilentlyContinue"
# function Get-Http { return Invoke-Http "GET" @args }
# function New-Http { return Invoke-Http "PUT" @args }
# function Update-Http { return Invoke-Http "POST" @args }
# function Remove-Http { return Invoke-Http "DELETE" @args }
# new-alias Set-Http Update-Http
# new-alias Put-Http New-Http
# new-alias Post-Http Update-Http
# new-alias Delete-Http Remove-Http
function Set-HttpDefaultUrl {
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
$global:url = $baseUri
}
function Set-HttpCredential {
param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $($global:url.Host)) )
if($Credential -is [System.Management.Automation.PSCredential]) {
$global:HttpRestCredential = $Credential
} elseif($Credential -is [System.Net.NetworkCredential]) {
$global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
}
}
function Get-HttpCredential([switch]$Secure) {
if(!$global:url) { Set-HttpDefaultUrl }
if(!$global:HttpRestCredential) { Set-HttpCredential }
if(!$Secure) {
return $global:HttpRestCredential.GetNetworkCredential();
} else {
return $global:HttpRestCredential
}
}
# function Authenticate-Http {
# PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
# $plug = [MindTouch.Dream.Plug]::New( $global:url )
# $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
# }
function Encode-Twice {
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
function Join-Url ( [uri]$baseUri=$global:url ) {
$ofs="/";$BaseUrl = ""
if($BaseUri -and $baseUri.AbsoluteUri) {
$BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
}
return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
}
function ConvertTo-SecureString {
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
## Unit-Test Get-FileName ## Should return TRUE
## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and
## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe"
function Get-FileName {
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
## if the $Path has a file name, and it's folder exists:
if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
$path
## if the $Path is just a folder (and it exists)
} elseif($Path -and (Test-Path $path -Type Container)) {
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
## If there's no valid $Path, and the $FileName has a folder...
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
$fileName
} else {
Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
}
}
function Get-UtcTime {
Param($Format="yyyyMMddhhmmss")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
## Get-CredentialBetter
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-CredentialBetter{
PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
$ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds"
## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
$cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
## Compare to $True, because by default it's $null ...
$cp = $cp.ConsolePrompting -eq $True
if($Console -and !$cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $True
} elseif(!$Console -and $Console.IsPresent -and $cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $False
}
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
$Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
Set-ItemProperty $ShellIdKey ConsolePrompting $cp
}
|
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_1.ps1
|
TabExpansion for V2CTP_1.ps1
|
## Tab-Completion
#################
## For V2CTP3.
## This won't work on V1 and V2CTP and V2CTP2.
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames and Type accelerators expansion
## [Dec<tab>
## [system.Man<tab>.auto<tab>.p<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.win<tab>.for<tab>.bu<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
## #Type accelerators expansion with no charactors
## [<tab>
## New-Object -typename <tab>
## New-Object <tab>
### Generate ProgIDs list...
if ( Test-Path $PSHOME\\ProgIDs.txt )
{
$_reader = New-Object IO.StreamReader $PSHOME\\ProgIDs.txt
$_ProgID = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_reader.Close()
Remove-Variable _reader
}
else
{
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
[Object[]] $_ProgID = $null
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID += $_i.GetValue("")
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose
}
### Generate TypeNames list...
if ( Test-Path $PSHOME\\TypeNames.txt )
{
$_reader = New-Object IO.StreamReader $PSHOME\\TypeNames.txt
$_TypeNames = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_reader.Close()
Remove-Variable _reader
}
else
{
[Object[]] $_TypeNames = $null
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames += $_type.FullName
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose
}
if ( Test-Path $PSHOME\\TypeNames_System.txt )
{
$_reader = New-Object IO.StreamReader $PSHOME\\TypeNames_System.txt
$_TypeNames_System = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_reader.Close()
Remove-Variable _reader
}
else
{
$_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.'
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose
}
### Generate WMIClasses list...
if ( Test-Path $PSHOME\\WMIClasses.txt )
{
$_reader = New-Object IO.StreamReader $PSHOME\\WMIClasses.txt
$_WMIClasses = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_reader.Close()
Remove-Variable _reader
}
else
{
[Object[]] $_WMIClasses = $null
foreach ( $_class in gwmi -List )
{
$_WMIClasses += $_class.Name
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose
}
$global:_snapin = $null
$global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort
function Write-ClassNames ( $data, $i, $prefix='', $sep='.' )
{
$preItem = ""
foreach ( $class in $data -like $_opt )
{
$Item = $class.Split($sep)
if ( $preItem -ne $Item[$i] )
{
if ( $i+1 -eq $Item.Count )
{
if ( $prefix -eq "[" )
{
$suffix = "]"
}
elseif ( $sep -eq "_" )
{
$suffix = ""
}
else
{
$suffix = " "
}
}
else
{
$suffix = ""
}
$prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix
$preItem = $Item[$i]
}
}
}
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru |
Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru |
Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru |
Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru |
Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru |
Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru |
Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru |
Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru |
Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru |
Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru |
Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru |
Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru |
Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru |
Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru |
Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru |
Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru |
Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru |
Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru
}
if ( $global:_mix -eq $null )
{
$f = gi $PSHOME\\powershell.exe
$t = [type]
$s = ""
$global:_mix = `
Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru |
Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru |
Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru |
Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru |
Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru |
Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru |
Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru |
Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru |
Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru |
Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru |
Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru |
Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru |
Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru |
Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru |
Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru |
Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru |
Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru |
Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru |
Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru |
Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru |
Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru |
Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru |
Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru |
Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru |
Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru |
Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru |
Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru |
Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru |
Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru |
Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru |
Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru |
Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru |
Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru |
Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru |
Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru |
Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru |
Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru |
Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru |
Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru |
Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru |
Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru |
Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru |
Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru |
Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru |
Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru |
Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru |
Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru |
Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru |
Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru |
Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru |
Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru |
Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru |
Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru |
Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru |
Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru |
Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru |
Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru |
Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru |
Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru |
Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru |
Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru |
Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru |
Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru |
Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru |
Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru |
Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru |
Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru |
Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru |
Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru |
Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru |
Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru |
Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru |
Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru |
Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru |
Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru |
Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru
}
if ( "Add-Member" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Compare-Object" -eq $_cmdlet )
{
$global:_dummy = (Compare-Object 1 2)[0]
}
if ( "ConvertFrom-SecureString" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "ConvertTo-SecureString" -eq $_cmdlet )
{
$global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force
}
if ( "ForEach-Object" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Acl" -eq $_cmdlet )
{
$global:_dummy = Get-Acl
}
if ( "Get-Alias" -eq $_cmdlet )
{
$global:_dummy = (Get-Alias)[0]
}
if ( "Get-AuthenticodeSignature" -eq $_cmdlet )
{
$global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe
}
if ( "Get-ChildItem" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-Command" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-Content" -eq $_cmdlet )
{
$global:_dummy = (type $PSHOME\\profile.ps1)[0]
}
if ( "Get-Credential" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Culture" -eq $_cmdlet )
{
$global:_dummy = Get-Culture
}
if ( "Get-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( "Get-Event" -eq $_cmdlet )
{
$global:_dummy = (Get-Event)[0]
}
if ( "Get-EventLog" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-ExecutionPolicy" -eq $_cmdlet )
{
$global:_dummy = Get-ExecutionPolicy
}
if ( "Get-Help" -eq $_cmdlet )
{
$global:_dummy = Get-Help Add-Content
}
if ( "Get-History" -eq $_cmdlet )
{
$global:_dummy = Get-History -Count 1
}
if ( "Get-Host" -eq $_cmdlet )
{
$global:_dummy = Get-Host
}
if ( "Get-Item" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-ItemProperty" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Location" -eq $_cmdlet )
{
$global:_dummy = Get-Location
}
if ( "Get-Member" -eq $_cmdlet )
{
$global:_dummy = (1|Get-Member)[0]
}
if ( "Get-Module" -eq $_cmdlet )
{
$global:_dummy = (Get-Module)[0]
}
if ( "Get-PfxCertificate" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Process" -eq $_cmdlet )
{
$global:_dummy = ps powershell
}
if ( "Get-PSBreakpoint" -eq $_cmdlet )
{
$global:_dummy =
Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru
}
if ( "Get-PSCallStack" -eq $_cmdlet )
{
$global:_dummy = Get-PSCallStack
}
if ( "Get-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Function
}
if ( "Get-PSProvider" -eq $_cmdlet )
{
$global:_dummy = Get-PSProvider FileSystem
}
if ( "Get-PSSnapin" -eq $_cmdlet )
{
$global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core
}
if ( "Get-Service" -eq $_cmdlet )
{
$global:_dummy = (Get-Service)[0]
}
if ( "Get-TraceSource" -eq $_cmdlet )
{
$global:_dummy = Get-TraceSource AddMember
}
if ( "Get-UICulture" -eq $_cmdlet )
{
$global:_dummy = Get-UICulture
}
if ( "Get-Variable" -eq $_cmdlet )
{
$global:_dummy = Get-Variable _
}
if ( "Get-WmiObject" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Group-Object" -eq $_cmdlet )
{
$global:_dummy = 1 | group
}
if ( "Measure-Command" -eq $_cmdlet )
{
$global:_dummy = Measure-Command {}
}
if ( "Measure-Object" -eq $_cmdlet )
{
$global:_dummy = Measure-Object
}
if ( "New-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Alias
}
if ( "New-TimeSpan" -eq $_cmdlet )
{
$global:_dummy = New-TimeSpan
}
if ( "Resolve-Path" -eq $_cmdlet )
{
$global:_dummy = $PWD
}
if ( "Select-String" -eq $_cmdlet )
{
$global:_dummy = " " | Select-String " "
}
if ( "Set-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( $property -ne $null)
{
foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) )
{
$global:_dummy = @($global:_dummy.$name)[0]
}
}
}
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$params = @{view = 'extended','adapted','base'}
}
else
{
$params = @{static=$true}
}
if ( $_val -is [Hashtable] )
{
[Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
}
if ( $_keys -ne $null )
{
$_members = (Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat})
} else {
$_members = (Get-Member @params -InputObject $_val $_pat)
}
foreach ($_m in $_members | Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
$host.UI.RawUI.WindowTitle = "Windows PowerShell V2 (CTP2)" + $lastword
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[8] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[((\\w+\\.?)*)$' {
$_opt = $matches[1] + '*'
if ( $_opt -eq "*" )
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
}
else
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '['
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '['
}
break;
}
# Handle file/directory name which contains $env: variable
# e.g. $env:windir\\<tab>
'^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' {
$path = iex ('"' + $Matches[0] + '"')
if ( $Matches[2].Length -gt 1 )
{
$parent = Split-Path $path -Parent
$leaf = (Split-Path $path -Leaf) + '*'
}
else
{
$parent = $path
$leaf = '*'
}
if ( Test-Path $parent )
{
$i = $Matches[0].LastIndexOfAny("/\\")
$_base = $Matches[0].Substring(0,$i+1)
[IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') }
}
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_command = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_command -match '\\{([^\\{\\}]*)$')
{
$_command = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_command -match '\\(([^()]*)$')
{
$_command = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_command = $_command.Trim().Split()[0]
# now get the info object for it...
$_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command)[0]
# loop resolving aliases...
while ($_command.CommandType -eq 'alias')
{
$_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command.Definition)[0]
}
if ( $_command -ne $null )
{
# expand the parameter sets and emit the matching elements
foreach ($_n in $_command.Parameters.Keys | sort)
{
if ($_n -like $_pat) { '-' + $_n }
}
}
else
{
"-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt",
"-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge",
"-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike",
"-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains",
"-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat"
}
break;
}
# try to find a matching command...
default {
$lastex = [regex]::Split($line, '[|;]')[-1]
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' )
{
if ( $Matches[6] -ne $nul )
{
$brackets = "[]"
}
'['+ $global:_enum + $brackets + ']'
break;
}
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' )
{
$_pat = $Matches[7] + '*'
$_type = @(iex $Matches[1])[0].GetType()
if ( $_type.IsEnum )
{
$global:_enum = $_type.FullName
[Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"'
break;
}
}
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$')
{
'['+ $global:_enum + ']'
}
elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' )
{
$_method = $Matches[1]
if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" )
{
$continuous = $true
$_opt = $Matches[5] + '*'
$_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1'
$position = $Matches[1].Split(",").Length
}
else
{
$continuous = $false
$_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*"
$position = $Matches[3].Split(",").Length
}
if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null )
{
$tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }')
}
foreach ( $def in $_mdefs )
{
[void] ($def -match '\\((.*)\\)')
foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] )
{
if ($param -eq $null -or $param -eq "")
{
continue;
}
$type = $param.split()[0]
if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" )
{
continue;
}
$fullname = @($_typenames -like "*$type*")
foreach ( $name in $fullname )
{
if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$global:_enum = $name
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"'
$output | sort
}
}
}
}
if ( $output -ne $null )
{
break;
}
}
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeAccelerators
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | gm -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0]
if ( $_cmdlet.Name -eq "powershell.exe" )
{
"-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive",
"-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort
break;
}
if ( $_cmdlet.Name -eq "fsutil.exe" )
{
"behavior query", "behavior set", "dirty query", "dirty set",
"file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew",
"fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics",
"hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create",
"quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query",
"reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange",
"usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort
break;
}
if ( $_cmdlet.Name -eq "net.exe" )
{
"ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ",
"HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ",
"SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort
break;
}
if ( $_cmdlet.Name -eq "ipconfig.exe" )
{
"/?", "/all", "/renew", "/release", "/flushdns", "/displaydns",
"/registerdns", "/showclassid", "/setclassid"
break;
}
}
if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' )
{
#$_opt = $Matches[1] + '*'
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2]
$_opt = $Matches[1].Split(" ,")[-1] + '*'
$_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length)
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeAccelerators -like $_opt
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1)
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1)
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_'
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
#$_opt = ($Matches[3] -replace '(^.*\\s*,?\\s*)\\w*$','$1') + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name `
-and "groupBy" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or
"ErrorVariable" -like $_param -or "OutVariable" -like $_param)
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort
break;
}
if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param )
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name `
-and "Encoding" -like $_param)
{
"Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -like $_cmdlet.Name )
{
if ( "ComObject" -like $_param )
{
$_ProgID -like $_opt | % { $_ -replace '\\s','` ' }
break;
}
if ( "TypeName" -like $_param )
{
if ( $_opt -eq "*" )
{
$_TypeAccelerators -like $_opt
}
else
{
$_TypeAccelerators -like $_opt
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1)
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1)
}
break;
}
}
if ( "New-Item" -eq $_cmdlet.Name )
{
if ( "ItemType" -like $_param )
{
"directory", "file" -like $_opt
break;
}
}
if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name `
-and "PSProvider" -like $_param )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param)
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
}
if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias",
"New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" `
-contains $_cmdlet.Name -and "Scope" -like $_param )
{
"Global", "Local", "Script" -like $_opt
break;
}
if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_'
break;
}
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name -and "Property" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Select-Object" -eq $_cmdlet.Name )
{
if ( "ExcludeProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "ExpandProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
# parse the script...
$_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null)
if ($_tokens)
{
$_lastToken = $_tokens[$_tokens.count - 1]
if ($_lastToken.Type -eq 'Command')
{
$_cmd = $_lastToken.Content
# don't look for paths...
if ($_cmd.IndexOfAny('/\\') -eq -1)
{
# handle parsing errors - the last token string should be the last
# string in the line...
if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd)
{
$_pat = $_cmd + '*'
$_base = $lastword.substring(0, $lastword.length-$_cmd.length)
"begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (",
"end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ",
"param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" `
-like $_pat | % {'{0}{1}' -f $_base,$_ }
$ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) |
Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ }
}
}
}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-MountPointData.ps1
|
Get-MountPointData.ps1
|
# Convert from one device ID format to another.
function Get-DeviceIDFromMP {
param([Parameter(Mandatory=$true)][string] $VolumeString,
[Parameter(Mandatory=$true)][string] $Directory)
if ($VolumeString -imatch '^\\s*Win32_Volume\\.DeviceID="([^"]+)"\\s*$') {
# Return it in the wanted format.
$Matches[1] -replace '\\\\{2}', '\\'
}
else {
# Return a presumably unique hashtable key if there's no match.
"Unknown device ID for " + $Directory
}
}
function Get-MountPointData {
param([Parameter(Mandatory=$true)][string[]] $ComputerName,
#[switch] $DoNotExcludeDefaults,
[switch] $IncludeRootDrives
)
foreach ($Computer in $ComputerName) {
try {
# Collect mount point device IDs and populate a hashtable with IDs as keys
$MountPointData = @{}
Get-WmiObject Win32_MountPoint -ComputerName $Computer |
Where { if ($IncludeRootDrives) { $true } else { $_.Directory -NotMatch '^\\s*Win32_Directory\\.Name="[a-z]:\\\\{2}"\\s*$' } } | ForEach-Object {
$MountPointData.(Get-DeviceIDFromMP $_.Volume $_.Directory) = $_.Directory
}
$Volumes = Get-WmiObject Win32_Volume -ComputerName $Computer | Where {
if ($IncludeRootDrives) { $true } else { -not $_.DriveLetter }
} |
Select-Object Label, Caption, Capacity, FreeSpace, FileSystem, DeviceID, @{n='Computer';e={$Computer}}
}
catch {
Write-Host -Fore Red "Terminating WMI error for ${Computer} (skipping): $($Error[0])"
continue
}
if (-not $Volumes) {
Write-Host -Fore Red "No mount points found on $Computer. Skipping..."
continue
}
$Volumes | ForEach-Object {
if ($MountPointData.ContainsKey($_.DeviceID)) {
if ($_.Capacity) { $PercentFree = $_.FreeSpace*100/$_.Capacity }
else { $PercentFree = 0 }
$_ | Select-Object Computer, Label, Caption, FileSystem, @{n='Size (GB)';e={$_.Capacity/1GB}},
@{n='Free space';e={($_.FreeSpace/1GB).ToString('N')}}, @{n='Percent free';e={$PercentFree}}
}
} | Sort-Object -Property 'Percent free', @{Descending=$true;e={$_.'Size (GB)'}}, Label, Caption |
Select-Object Computer, Label, Caption, FileSystem, @{n='Size (GB)';e={$_.'Size (GB)'.ToString('N')}},
'Free space', @{n='Percent free';e={$_.'Percent free'.ToString('N')}}
}
}
|
PowerShellCorpus/PoshCode/Create-Printers_3.ps1
|
Create-Printers_3.ps1
|
###########################################################################"
#
# NAME: Create-Printers.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
# BLOG: http://blog.powershell.no
#
# COMMENT: Simple script to bulk-create printers on a print-server. Printers are imported from a csv-file.
# Running the script from Windows Server 2003 returns an access denied error, possibly due to the impersonation-model in Windows Server 2003.
# Created and tested from Windows Server 2008 against a remote Windows Server 2003 print-server.
# Should work from Windows Vista, Windows 7, Windows Server 2008 and Windows Server 2008 R2 against remote print-servers (2000/2003/2008/2008 R2)
#
# 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 07.11.2009 - Initial release
#
###########################################################################"
function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_Printer").createInstance()
$print.drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID = $args[6]
$print.Put()
}
function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_TCPIPPrinterPort").createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=1
$port.HostAddress= $args[2]
$port.Put()
}
$printers = Import-Csv c:\\printers.csv
foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}
|
PowerShellCorpus/PoshCode/Updated CloneVM from CSV.ps1
|
Updated CloneVM from CSV.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- Clean up unnecessary output during script run.
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
#>
<#
# ** Verify server names are unique **
$VMTargets = Import-CSV $servercsv
$VCs = "vcenter101.ma.tmpw.net","vcenter102.ma.tmpw.net","vcenter201.be.tmpw.net"
$VCs | % {
Connect-VIServer $_ | Out-Null
$AllVMs = Get-VM | Sort
$i = 0;
while ($VMTargets[$i]) {
$j = 0
while ($AllVMs[$j]) {
If ($VMTargets[$i].Name -eq $AllVMs[$j].Name) {
Write-Host "Requested VM name" $VMTargets[$i].Name "is in use. `n"
$DupeNames = $true
} # end If
$j++
} # end while
$i++
} # end while
} #end %
If ($dupenames = $false) {
#>
$serverlist = Import-CSV $servercsv
$serverlist | Format-Table -Autosize
# ** Clone new VM
$serverlist | % {
Connect-VIServer $_.VC #| Out-Null
sleep 5
New-VM -Confirm:$False `
-Name ($_.Name).ToLower() `
-Template $_.Template `
-DiskStorageFormat Thin `
-ResourcePool (Get-ResourcePool -location $_.Cluster | Where { $_ -match $_.ResourcePool } | get-random) `
-Description $_.Description `
-VMHost (Get-VMHost -location $_.Cluster | Sort $_.CPuUsageMhz -Descending | Select -First 1) `
-Datastore (C:\\ops\\posh\\vmware\\Get-DatastoreMostFree.ps1 $_.Cluster).Name
Set-VM -Confirm:$false `
-VM $_.Name `
-NumCpu $_.NumCpu `
-MemoryMB ([int]$_.RAMSizeGB * 1024)
New-HardDisk -vm $_.Name -CapacityKB ([int]$_.D_DriveSizeGB * 1024 * 1024) -ThinProvisioned -Confirm:$false
Get-NetworkAdapter -VM $_.Name | Set-NetworkAdapter -NetworkName $_.VLAN -Confirm:$false
Set-CustomField -Entity $_.Name -Name "Clearquest #" -Value $_.CQTicket
Set-CustomField -Entity $_.Name -Name Environment -value $_.Environment
Set-CustomField -Entity $_.Name -Name Owner -value $_.Owner
Get-FloppyDrive -VM $_.Name | Remove-FloppyDrive -Confirm:$false
Get-UsbDevice -VM $_.Name | Remove-UsbDevice -Confirm:$false
} # end %
# } #end If
# Input file format
<#
VC,Cluster,Name,Description,Template,ResourcePool,NumCPU,RAMSizeGB,D_DriveSizeGB,VLAN,CQTicket,Environment,Owner
vcenterxxx.fqdn.com,Bed-QADevIntv35,QA-DBHYPESS201,Hyperion QA DB,w2k8_std_x64_r2_tmpl,Normal,1,3,50,VLAN350,DEV00451152,QA-Hyperion,Hyperion
#>
|
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object_5.ps1
|
h20 -Hashtables 2 object_5.ps1
|
#hashtable to object function.
#used to be able to make custom objects with math inside the pipeline
#e.g. 1..10 | h20 { @{karl = $_;dude = $_+1} }
#gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} }
function h20([scriptblock]$sb )
{
begin {}
process{ if ($sb -ne $null)
{
$ht = &$sb;
if ($ht -is [hashtable])
{
New-Object PSObject -Property $ht}
}
if ($ht -is [object[]])
{
$ht | % { New-Object PSObject -Property $_ }
}
}
end{}
}
|
PowerShellCorpus/PoshCode/Start-RDP_1.ps1
|
Start-RDP_1.ps1
|
########################################################################################################################
# NAME
# Start-RDP
#
# SYNOPSIS
# Opens a remote desktop connection to another computer.
#
# SYNTAX
# Start-RDP [[-Server] <string>] [[-Width] <int>] [[-Height] <int>]
# Start-RDP -Path <string> [[-Width] <int>] [[-Height] <int>]
#
# DETAILED DESCRIPTION
# The Start-RDP cmdlet opens a new Remote Desktop connection using the Microsoft Terminal Services Client.
# Connection settings can be specified by argument or read from a standard RDP file.
#
# PARAMETERS
# -Server <string>
# Specifies the name of the server to connect to. May also include an IP address, domain, and/or port.
#
# Required? false
# Position? 1
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Width <int>
# Specifies the desired width of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 2
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Height <int>
# Specifies the desired height of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 3
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Path <string>
# Specifies the path to an RDP file to connect with (resolution settings can be overridden using the
# -Width and -Height parameters.
#
# Required? false
# Position? 4
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Console <SwitchParameter>
# Connect to a Windows Server 2003 console session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Admin <SwitchParameter>
# Connect to a Windows Server 2008 administrator session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Fullscreen <SwitchParameter>
# Open connection in full screen mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Public <SwitchParameter>
# Run Remote Desktop in public mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Span <SwitchParameter>
# Span the Remote Desktop connection across multiple monitors. Each monitor must have the same height
# and be arranged vertically.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# INPUT TYPE
# String,System.IO.FileInfo
#
# RETURN TYPE
#
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>Start-RDP
#
#
# This command opens the Terminal Services Client connection dialog to specify a connection.
#
#
# -------------------------- EXAMPLE 2 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Width 1024 -Height 768
#
#
# This command opens a new Remote Desktop connection to the server named "myserver" in a window with 1024x768 resolution.
#
#
# -------------------------- EXAMPLE 3 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Fullscreen
#
#
# This command opens a new full screen Remote Desktop connection to the server named "myserver".
#
#
# -------------------------- EXAMPLE 4 --------------------------
#
# C:\\PS>Start-RDP -Path C:\\myserver.rdp
#
#
# This command opens a new Remote Desktop connection using the specified RDP file.
#
#
#Function global:Start-RDP {
param(
[string]$Server = "",
[int]$Width = "",
[int]$Height = "",
[string]$Path = "",
[switch]$Console,
[switch]$Admin,
[switch]$Fullscreen,
[switch]$Public,
[switch]$Span
)
begin {
$arguments = ""
$dimensions = ""
$processed = $false
if ($admin) {
$arguments += "/admin "
} elseif ($console) {
$arguments += "/console "
}
if ($fullscreen) {
$arguments += "/f "
}
if ($public) {
$arguments += "/public "
}
if ($span) {
$arguments += "/span "
}
if ($width -and $height) {
$dimensions = "/w:$width /h:$height"
}
}
process {
Function script:executePath([string]$path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
}
Function script:executeArguments([string]$Server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
}
if ($_) {
if ($_ -is [string]) {
if ($_ -imatch '\\.rdp$') {
if (Test-Path $_) {
executePath $_
$processed = $true
} else {
throw "Path does not exist."
}
} else {
executeArguments $_
$processed = $true
}
} elseif ($_ -is [System.IO.FileInfo]) {
if (Test-Path $_.FullName) {
executePath $_.FullName
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.Path) {
if (Test-Path $_.Path) {
executePath $_.Path
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.DnsName) {
executeArguments $_.DnsName
$processed = $true
} elseif ($_.Server) {
executeArguments $_.Server
$processed = $true
} elseif ($_.ServerName) {
executeArguments $_.ServerName
$processed = $true
} elseif ($_.Name) {
executeArguments $_.Name
$processed = $true
}
}
}
end {
if ($path) {
if (Test-Path $path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
} else {
throw "Path does not exist."
}
} elseif ($server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
} elseif (-not $processed) {
Invoke-Expression "mstsc.exe $dimensions $arguments"
}
}
#}
|
PowerShellCorpus/PoshCode/Set-TopMost.ps1
|
Set-TopMost.ps1
|
#Requires -Version 2.0
$signature = @"
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static IntPtr FindWindow(string windowName){
return FindWindow(null,windowName);
}
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
public static void MakeTopMost (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
public static void MakeNormal (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_NOTOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
"@
$app = Add-Type -MemberDefinition $signature -Name Win32Window -Namespace ScriptFanatic.WinAPI -ReferencedAssemblies System.Windows.Forms -Using System.Windows.Forms -PassThru
function Set-TopMost
{
param(
[Parameter(
Position=0,ValueFromPipelineByPropertyName=$true
)][Alias('MainWindowHandle')]$hWnd=0,
[Parameter()][switch]$Disable
)
if($hWnd -ne 0)
{
if($Disable)
{
Write-Verbose "Set process handle :$hWnd to NORMAL state"
$null = $app::MakeNormal($hWnd)
return
}
Write-Verbose "Set process handle :$hWnd to TOPMOST state"
$null = $app::MakeTopMost($hWnd)
}
else
{
Write-Verbose "$hWnd is 0"
}
}
function Get-WindowByTitle($WindowTitle="*")
{
Write-Verbose "WindowTitle is: $WindowTitle"
if($WindowTitle -eq "*")
{
Write-Verbose "WindowTitle is *, print all windows title"
Get-Process | Where-Object {$_.MainWindowTitle} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
else
{
Write-Verbose "WindowTitle is $WindowTitle"
Get-Process | Where-Object {$_.MainWindowTitle -like "*$WindowTitle*"} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
}
Exaples:
# set powershell console on top of other windows
gps powershell | Set-TopMost
# unset
gps powershell | Set-TopMost -disable
# set an application on top of other windows by its windows title (wildcard is supported)
Get-WindowByTitle *pad* | Set-TopMost
# unset
Get-WindowByTitle textpad | Set-TopMost -Disable
|
PowerShellCorpus/PoshCode/Set-DNSServersToOpenDNS.ps1
|
Set-DNSServersToOpenDNS.ps1
|
Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'" | ForEach-Object {
$_.SetDNSServerSearchOrder(@("208.67.222.222","208.67.220.220"));
}
|
PowerShellCorpus/PoshCode/Update-GAC.ps1
|
Update-GAC.ps1
|
# author: jeffrey snover
# url: http://blogs.msdn.com/powershell/archive/2008/09/02/speeding-up-powershell-startup-updating-update-gac-ps1.aspx
Set-Alias ngen (Join-Path ([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) ngen.exe)
[AppDomain]::CurrentDomain.GetAssemblies() |
sort {Split-path $_.location -leaf} |
%{
$Name = (Split-Path $_.location -leaf)
if ([System.Runtime.InteropServices.RuntimeEnvironment]::FromGlobalAccessCache($_))
{
Write-Host "Already GACed: $Name"
}else
{
Write-Host -ForegroundColor Yellow "NGENing : $Name"
ngen $_.location | %{"`t$_"}
}
}
|
PowerShellCorpus/PoshCode/Demo-v3-Gui.ps1
|
Demo-v3-Gui.ps1
|
#requires -version 3
[Windows.Window]@{
OpacityMask = [Windows.Media.DrawingBrush]@{
Drawing = [Windows.Media.GeometryDrawing]@{
Brush = 'Black'
Geometry = [Windows.Media.EllipseGeometry]@{
radiusX = 123
radiusY = 321
}
}
}
Background = [Windows.Media.LinearGradientBrush]@{
Opacity = 0.5
StartPoint = '0,0.5'
Endpoint = '1,0.5'
GradientStops = & {
$Stopki = New-Object Windows.Media.GradientStopCollection
$Colors = 'Blue', 'Green'
foreach ($i in 0..1) {
$Stopki.Add(
[Windows.Media.GradientStop]@{
Color = $Colors[$i]
Offset = $i
}
)
}
, $Stopki
}
}
Width = 800
Height = 400
WindowStyle = 'None'
AllowsTransparency = $true
Effect = [Windows.Media.Effects.DropShadowEffect]@{
BlurRadius = 10
}
Content = & {
$Stos = [Windows.Controls.StackPanel]@{
VerticalAlignment = 'Center'
HorizontalAlignment = 'Center'
}
$Stos.AddChild(
[Windows.Controls.Label]@{
Content = 'PowerShell Rocks!'
FontSize = 80
FontFamily = 'Consolas'
Foreground = 'White'
Effect = [Windows.Media.Effects.DropShadowEffect]@{
BlurRadius = 5
}
}
)
, $Stos
}
} | foreach {
$_.Add_MouseLeftButtonDown({
$this.DragMove()
})
$_.Add_MouseRightButtonDown({
$this.Close()
})
$_.ShowDialog()
}
|
PowerShellCorpus/PoshCode/Add Voice to Powershell_2.ps1
|
Add Voice to Powershell_2.ps1
|
###
# Description: Add Voice to Powershell
# Version: 1.1 (11 Nov 2008)
# Mike Hays / www.mike-hays.net / blog.mike-hays.net
# Virtualization, Powershell, and more...
###
# This is the actual speaking part. I cheat by adding spaces
# (This makes the word sound right).
$spokenText = "Super ca li fragilistic expi alidocious"
# Create an object that represents the COM SAPI.SpVoice
$voice = New-Object -com SAPI.SpVoice
# Get the list of available voices
$voiceList = $voice.GetVoices()
# This script prefers using LH Michelle as a stand-in for Mary Poppins,
# but I can't be sure that she exists on all computers, so I check for that.
# She comes with some installations of Microsoft Word 2003.
$voiceDescList = @()
for ($i=0; $i -lt $voiceList.Count; $i++)
{
$voiceDescList += $voiceList.Item($i).GetDescription()
}
if ($voiceDescList -contains "LH Michelle")
{
$voiceMember = "Name=LH Michelle"
}
else
{
# This is the default voice if LH Michelle doesn't exist.
# This will probably be Microsoft Sam
$voiceMember = "Name=" + $voiceDescList[0]
}
$voiceToUse = $voice.GetVoices($voiceMember)
# This sets the voice property on the COM object
$voice.Voice = $voiceToUse.Item(0)
# This actually does the speaking.
[void] $voice.Speak($spokenText)
# She's no Julie Andrews, but she'll say what you want.
# END
|
PowerShellCorpus/PoshCode/Execute-SQLCommand_2.ps1
|
Execute-SQLCommand_2.ps1
|
function Execute-SQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$Database, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=user;Initial Catalog=$Database;Data Source=$Server"
$Command.CommandType = 1 # 1 is the 'Text' command type
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
|
PowerShellCorpus/PoshCode/Highlight-Syntax 1.0.ps1
|
Highlight-Syntax 1.0.ps1
|
# Highlight-Syntax.ps1
# version 1.0
# by Jeff Hillman
#
# this script uses regular expressions to highlight PowerShell
# syntax with HTML.
param( [string] $code, [switch] $LineNumbers )
if ( Test-Path $code -ErrorAction SilentlyContinue )
{
$code = Get-Content $code | Out-String
}
$backgroundColor = "#DDDDDD"
$foregroundColor = "#000000"
$stringColor = "#800000"
$commentColor = "#008000"
$operatorColor = "#C86400"
$numberColor = "#800000"
$keywordColor = "#C86400"
$typeColor = "#404040"
$variableColor = "#000080"
$cmdletColor = "#C86400"
$lineNumberColor = "#404040"
filter Html-Encode( [switch] $Regex )
{
# some regular expressions operate on strings that have already
# been through this filter, so the patterns need to be updated
# to look for the encoded characters instead of the literal ones.
# we do it with this filter instead of directly in the regular
# expression so the expressions can be a bit more readable (ha!)
$_ = $_ -replace "&", "&"
if ( $Regex )
{
$_ = $_ -replace "(?<!\\(\\?)<", "<"
$_ = $_ -replace "(?<!\\(\\?)>", ">"
}
else
{
$_ = $_ -replace "\\t", " "
$_ = $_ -replace " ", " "
$_ = $_ -replace "<", "<"
$_ = $_ -replace ">", ">"
}
$_
}
# regular expressions
$operatorRegex = @"
((?x:
(?# assignment operators)
=|\\+=|-=|\\*=|/=|%=|
(?# arithmatic operators)
(?<!\\de)
(\\+|-|\\*|/|%)(?![a-z])|
(?# unary operators)
\\+\\+|\\-\\-|
(?# logical operators)
(-and|-or|-not)\\b|!|
(?# bitwise operators)
(-band|-bor)\\b|
(?# redirection and pipeline operators)
2>>|>>|2>&1|1>&2|2>|>|<|\\||
(?# comparison operators)
(
-[ci]? (?# case and case-insensitive variants)
(eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains)\\b
)|
(?# type operators)
(-is|-isnot|-as)\\b|
(?# range and miscellaneous operators)
\\.\\.|(?<!\\d)\\.(?!\\d)|&|::|:|,|``|
(?# string formatting operator)
-f\\b
))
"@ | Html-Encode -Regex
$numberRegex = @"
((?x:
(
(?# hexadecimal numbers)
(\\b0x[0-9a-f]+)|
(?# regular numbers)
(?<!&)
((\\b[0-9]+(\\.(?!\\.))?[0-9]*)|((?<!\\.)\\.[0-9]+))
(?!(>>|>&[12]|>))
(?# scientific notation)
(e(\\+|-)?[0-9]+)?
)
(
(?# type specifiers)
(l|ul|u|f|ll|ull)?
(?# size shorthand)
(b|kb|mb|gb)?
\\b
)?
))
"@ | Html-Encode -Regex
$keyWordRegex = @"
((?x:
\\b(
(?# don't match anything that looks like a variable or a parameter)
(?<![-$])
(
(?# condition keywords)
if|else|elseif|(?<!\\[)switch(?!\\])|
(?# loop keywords)
for|(?<!\\|</span> )foreach(?!-object)|in|do|while|until|default|break|continue|
(?# scope keywords)
global|script|local|private|
(?# block keywords)
begin|process|end|
(?# other keywords)
function|filter|param|throw|trap|return
)
)\\b
))
"@
$typeRegex = @"
((?x:
\\[
(
(?# primitive types and arrays of those types)
((int|long|string|char|bool|byte|double|decimal|float|single)(\\[\\])?)|
(?# other types)
regex|array|xml|scriptblock|switch|hashtable|type|ref|psobject|wmi|wmisearcher|wmiclass
)
\\]
))
"@
$cmdletNames = Get-Command -Type Cmdlet | Foreach-Object { $_.Name }
function Highlight-Other( [string] $code )
{
$highlightedCode = $code | Html-Encode
# operators
$highlightedCode = $highlightedCode -replace
$operatorRegex, "<span style='color: $operatorColor'>`$1</span>"
# numbers
$highlightedCode = $highlightedCode -replace
$numberRegex, "<span style='color: $numberColor'>`$1</span>"
# keywords
$highlightedCode = $highlightedCode -replace
$keyWordRegex, "<span style='color: $keywordColor'>`$1</span>"
# types
$highlightedCode = $highlightedCode -replace
$typeRegex, "<span style='color: $typeColor'>`$1</span>"
# Cmdlets
$cmdletNames | Foreach-Object {
$highlightedCode = $highlightedCode -replace
"\\b($_)\\b", "<span style='color: $cmdletColor'>`$1</span>"
}
$highlightedCode
}
$RegexOptions = [System.Text.RegularExpressions.RegexOptions]
$highlightedCode = ""
# we treat variables, strings, and comments differently because we don't
# want anything inside them to be highlighted. we combine the regular
# expressions so they are mutually exclusive
$variableRegex = '(\\$(\\w+|{[^}`]*(`.[^}`]*)*}))'
$stringRegex = @"
(?x:
(?# here strings)
@[`"'](.|\\n)*?^[`"']@|
(?# double-quoted strings)
`"[^`"``]*(``.[^`"``]*)*`"|
(?# single-quoted strings)
'[^'``]*(``.[^'``]*)*'
)
"@
$commentRegex = "#[^\\r\\n]*"
[regex]::Matches( $code,
"(?<before>(.|\\n)*?)" +
"((?<variable>$variableRegex)|" +
"(?<string>$stringRegex)|" +
"(?<comment>$commentRegex))",
$RegexOptions::MultiLine ) | Foreach-Object {
# highlight everything before the variable, string, or comment
$highlightedCode += Highlight-Other $_.Groups[ "before" ].Value
if ( $_.Groups[ "variable" ].Value )
{
$highlightedCode +=
"<span style='color: $variableColor'>" +
( $_.Groups[ 'variable' ].Value | Html-Encode ) +
"</span>"
}
elseif ( $_.Groups[ "string" ].Value )
{
$string = $_.Groups[ 'string' ].Value | Html-Encode
$string = "<span style='color: $stringColor'>$string</span>"
# we have to highlight each piece of multi-line strings
if ( $string -match "\\r\\n" )
{
# highlight any line continuation characters as operators
$string = $string -replace
"(``)(?=\\r\\n)", "<span style='color: $operatorColor'>``</span>"
$string = $string -replace
"\\r\\n", "</span>`r`n<span style='color: $stringColor'>"
}
$highlightedCode += $string
}
else
{
$highlightedCode +=
"<span style='color: $commentColor'>" +
$( $_.Groups[ 'comment' ].Value | Html-Encode ) +
"</span>"
}
# we need to keep track of the last position of a variable, string,
# or comment, so we can highlight everything after it
$lastMatch = $_
}
if ( $lastMatch )
{
# highlight everything after the last variable, string, or comment
$highlightedCode += Highlight-Other $code.SubString( $lastMatch.Index + $lastMatch.Length )
}
else
{
$highlightedCode = Highlight-Other $code
}
# add line breaks
$highlightedCode =
[regex]::Replace( $highlightedCode, '(?=\\r\\n)', '<br />', $RegexOptions::MultiLine )
# put the highlighted code in the pipeline
"<div style='width: 100%; " +
"/*height: 100%;*/ " +
"overflow: auto; " +
"font-family: Consolas, `"Courier New`", Courier, mono; " +
"font-size: 12px; " +
"background-color: $backgroundColor; " +
"color: $foregroundColor; " +
"padding: 2px 2px 2px 2px; white-space: nowrap'>"
if ( $LineNumbers )
{
$digitCount =
( [regex]::Matches( $highlightedCode, "^", $RegexOptions::MultiLine ) ).Count.ToString().Length
$highlightedCode = [regex]::Replace( $highlightedCode, "^",
"<li style='color: $lineNumberColor; padding-left: 5px'><span style='color: $foregroundColor'>",
$RegexOptions::MultiLine )
$highlightedCode = [regex]::Replace( $highlightedCode, "<br />", "</span><br />",
$RegexOptions::MultiLine )
"<ol start='1' style='border-left: " +
"solid 1px $lineNumberColor; " +
"margin-left: $( ( $digitCount * 10 ) + 15 )px; " +
"padding: 0px;'>"
}
$highlightedCode
if ( $LineNumbers )
{
"</ol>"
}
"</div>"
|
PowerShellCorpus/PoshCode/Build-TFSProjects_2.ps1
|
Build-TFSProjects_2.ps1
|
#-------------------------------------------------------------------------
# Script that will:
# 1. Create a workspace. Workspacce Name: _Root
# 2. Get the latest code from repository
#-------------------------------------------------------------------------
Param(
[switch]
$CSRWEB,
[switch]
$CSRWS,
[switch]
$CSRServices,
[string]
$LogPath,
[String]
$Outdir = "C:\\Application\\CSR"
)
Begin
{
$MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild"
$WEBPROJECTOUTPUTDIR="$OUTDIR\\CSRWeb"
$script:Log=@()
#-------------------------------------------------------------------------
Function SetTFS
{
$SCRIPT:tfsServer = "172.29.4.179"
$script:userName = [system.environment]::UserName;
$script:computerName = [system.environment]::machinename
$script:workspaceName = $computerName + "_" + $userName +"_WS" #Use 'WS' as an acronym for "WorkSpace"
$script:CSRDIR = "C:\\Brassring2\\Application\\";
$script:WEBPROJECTOUTPUTDIR="$Outdir\\CSRWeb"
$script:WEBPROJECTOUTPUTDIR1="$Outdir\\CSRWS"
$script:WEBPROJECTOUTPUTDIR2="$Outdir\\CSRServices"
$script:REFPATH="referenceToAllAssembiesUsedInTheProjectSeperatedbySemiColon"
$script:MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild"
$script:failed = $false
# Set up the TF Alias
# Find where VS is installed.
$key = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\VisualStudio\\9.0
$dir = [string] (Get-ItemProperty $key.InstallDir)
$script:tf = "$dir\\tf.exe"
} # End SetTFS
#-------------------------------------------------------------------------
Function CreateWorkspace
{
Begin
{
Write-Debug "Starting CreateWorkspace"
Function DeleteWorkspace
{
# Delete the workspace if it exists.
Write-Verbose "Deleting workspace (if exists): $workspaceName"
$log += "Deleting workspace (if exists): $workspaceName"
&$TF workspace /delete $workspaceName /noprompt | out-null
Write-Verbose "Done deleting workspace."
$log += "Done deleting workspace."
} #END DeleteWorkspace
}
Process
{
DeleteWorkspace
# Create the folder
if (! (Test-Path $CSRDIR))
{
Write-Verbose "Creating folder: $CSRDIR"
$log += "Creating folder: $CSRDIR"
new-item -itemtype directory -path $CSRDIR -force | out-null
Write-Verbose "Completed Creating folder: $CSRDIR"
$log += "Completed Creating folder: $CSRDIR"
}
# Move to folder
cd $CSRDIR
# Create the workspace
Write-Verbose "Creating workspace: $workspaceName"
$log += "Creating workspace: $workspaceName"
&$TF workspace /new /computer:$computerName /server:$TFsServer /noprompt $workspaceName
Write-Verbose "Done Creating workspace: $workspaceName"
$log += "Done Creating workspace: $workspaceName"
# Get the latest
Write-Verbose "Getting the latest code from: $TFsServer. This could take awhile..."
$log += "Getting the latest code from: $TFsServer. This could take awhile..."
&$TF get $/CSR/CSR /recursive
Write-Verbose "Done getting latest."
$log += "Done getting latest."
Write-Verbose "Tree initialization is complete."
$log += "Tree initialization is complete."
}
End
{
Write-Debug "CreateWorkspace Complete"
}
} #END CreateWorkspace
#-------------------------------------------------------------------------
# Get Next Label
#
# Labels are BL{major}.{minor}
# major = 1 - ???
# minor = 001 - 999
#-------------------------------------------------------------------------
Function GetNextLabel()
{
Begin
{
Write-Debug "Starting GetNextLabel"
}
Process
{
$major = 1
$minor = 1
$list = (&$TF labels /format:brief |? { $_ -notmatch "-.+" -and $_ -notmatch "Label.+Owner.+Date"})
if ($list -ne $null) {
# Split label into major minor
$major,[int]$minor= (($list | Select-Object -last 1).split()).split(".")
# Increment minor label
$minor++
# Remove BL from string, and cast to int
[int]$major = $major.substring(2)
# If minor gt 999 increment major and reset minor
if ($minor -gt 999) {
$major++
$minor = 1
}
}
# return label
$label = "BL{0}.{1:000}" -f $major, $minor
write-output $label
}
End
{
Write-Debug "GetNextLabel Completed"
}
}
#-------------------------------------------------------------------------
Function MSBuild($outputdir, $webproject, $project, $ref)
{
Begin
{
Write-Debug "Starting MSBuild"
Write-Debug "outputdir: $outputdir webproject: $webproject project: $project ref: $ref"
}
Process
{
# I think this can be cleaned up with where-object, but it's too important to play with
$failed = $false
&$MSBUILD /p:Configuration=Release /p:OutDir=$Outputdir /p:WebProjectOutputDir=$webproject $project |% {
if ($_ -match "Build FAILED") { $failed = $true } ; $_
}
if ($failed) { throw (new-object NullReferenceException) }
$failed = $false
&$MSBUILD /p:Configuration=Release /t:ResolveReferences /p:OutDir=$Outputdir\\bin\\ /p:ReferencePath=$ref $project |% {
if ($_ -match "Build FAILED") { $failed = $true } ; $_
}
if ($failed) { throw (new-object NullReferenceException) }
}
End
{
Write-Debug "MSBuild Completed"
}
}
#-------------------------------------------------------------------------
# Create the Label
#-------------------------------------------------------------------------
Function ApplyLabel()
{
Write-verbose "Create the Label"
$log += "Create the Label"
$label = GetNextLabel
&$TF label $label $/CSR/CSR /recursive
&$TF get /version:L$($label)
Write-verbose "Applied label $label"
$log += "Applied label $label"
return $Label
} # END ApplyLabel
} # End Begin
Process
{
trap [Exception]
{
write-verbose "Build Failed"
$log += "Build Failed"
exit 1;
}
. SetTFS
. CreateWorkspace
. ApplyLabel
IF (!$CSRWS -AND !$CSRWEB -AND !$CSRServices)
{
Write-Debug "No Options Found Setting ALL"
$CSRWS = $TRUE
$CSRWEB = $TRUE
$CSRServices = $TRUE
}
Switch ("")
{
{$CSRWEB}
{
Write-Verbose "Building CSRWEB"
$log += "Building CSRWEB"
. MsBuild "$Outdir\\CSRWeb\\" $WEBPROJECTOUTPUTDIR "$CSRDIR\\CSR\\CSR\\CSRWeb\\CSRWeb\\CSRWeb.csproj" $REFPATH
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRWeb\\*.config -recurse
rm $Outdir\\CSRWeb\\*.pdb -recurse
rm $Outdir\\CSRWeb\\*.dll -recurse
rm $Outdir\\CSRWeb\\*.xml -recurse
rm $Outdir\\CSRWeb\\bin\\*.pdb -recurse
rm $Outdir\\CSRWeb\\bin\\*.config -recurse
rm $Outdir\\CSRWeb\\bin\\*.xml -recurse
Write-verbose "Build CSRWEB Successful"
$log += "Build CSRWEB Successful"
}
{$CSRWS}
{
Write-verbose "Building CSRWS"
$log +="Building CSRWS"
. MsBuild "$Outdir\\CSRWS\\" $WEBPROJECTOUTPUTDIR1 "$CSRDIR\\CSR\\CSR\\CSRWS\\CSRWS\\CSRWS.csproj" $REFPATH
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRWS\\*.config -recurse
rm $Outdir\\CSRWS\\*.pdb -recurse
rm $Outdir\\CSRWS\\*.dll -recurse
rm $Outdir\\CSRWS\\*.xml -recurse
rm $Outdir\\CSRWS\\bin\\*.pdb -recurse
rm $Outdir\\CSRWS\\bin\\*.config -recurse
rm $Outdir\\CSRWS\\bin\\*.xml -recurse
Write-verbose "Build CSRWS Successful"
$log += "Build CSRWS Successful"
}
{$CSRServices}
{
Write-verbose "Building CSR Services"
$Log += "Building CSR Services"
. MsBuild "$Outdir\\CSRSERVICES\\" $WEBPROJECTOUTPUTDIR2 "$CSRDIR\\CSR\\CSR\\CSRSERVICES\\CSRSERVICES\\CSRSERVICES.csproj" $REFPATH
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# copy-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRSERVICES\\*.config -recurse
rm $Outdir\\CSRSERVICES\\*.pdb -recurse
rm $Outdir\\CSRSERVICES\\*.dll -recurse
rm $Outdir\\CSRSERVICES\\*.xml -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.pdb -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.config -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.xml -recurse
Write-verbose "Build CSR Services Successful"
$Log += "Build CSR Services Successful"
}
} # End Switch
} #End Process
End
{
IF ($LogPath)
{
$log | Out-file -FilePath $LogPath -Encoding ascii -Append
}
} #END End
|
PowerShellCorpus/PoshCode/validate an IP address_3.ps1
|
validate an IP address_3.ps1
|
# validate given IP address as an IPAdress (given string input)
PARAM($IP=$(read-host "Enter any IP Address"))
## YOU could do this, but ...
# $IP -match "(\\d{1,3}).(\\d{1,3}).(\\d{1,3}).(\\d{1,3})" -and -not ([int[]]$matches[1..4] -gt 255)
## you shouldn't parse things yourself when it's in the framework. You might make a mistake ;-)
trap { return $false }
[IPAddress]$IP # Just cast it to an IPAddress ... if it's valid, it will work.
return $true
|
PowerShellCorpus/PoshCode/Repair-ScriptQuotes.ps1
|
Repair-ScriptQuotes.ps1
|
function Repair-ScriptQuotes {
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$path
)
if ( !( Test-Path $path ) ) {
Write-Warning "'$path' does not exist."
Continue
}
(( Get-Content $path) |
ForEach-Object {
# replace double quotes
[Net.WebUtility]::HtmlDecode($_)
} |
ForEach-Object {
# replace double quotes
$_ -replace "(\\u201c|\\u201d|\\u201e)",[char]34
} |
ForEach-Object {
# replace single quotes
$_ -replace "(\\u2018|\\u2019|\\u201a)",[char]39
} |
ForEach-Object {
# replace dash
$_ -replace "(\\u2013)",[char]45
} |
ForEach-Object {
# replace tab with four spaces
$_ -replace "`t",(" " * 4)
}) |
Set-Content $path
Write-Host "Done"
}
|
PowerShellCorpus/PoshCode/Powershell Only Outlook.ps1
|
Powershell Only Outlook.ps1
|
#connect to outlook
$GetOutlook = New-Object -com "Outlook.Application";
$olName = $GetOutlook.GetNamespace("MAPI")
$olxEmailFolder = $olName.GetDefaultFolder(‘olFolderInbox’)
$olxEmailFolder.Name
$olxEmailItem = $olxemailFolder.items
#show unread emails in inbox
$olxEmailItem | ?{$_.Unread -eq $True} | select SentOn, SenderName, Subject, Body | Format-Table -auto
#go through each subfolder and get name
$SubFolders = $olxEmailFolder.Folders
ForEach($Folder in $SubFolders)
{
$Folder.Name
$SubfolderItem = $Folder.Items
$EmailCount = 1
#create status bar for each subfolder
ForEach($Email in $SubfolderItem)
{
Do
{
Write-Progress -Activity "Checking folder" -status $Folder.Name -
PercentComplete ($EmailCount/$Folder.Items.Count*100)
$EmailCount++
}
#show unread emails from subfolders
While($EmailCount -le $Folders.Item.Count)
$Email | ?{$_.Unread -eq $True} | select SentOn, SenderName, Subject, Body | Format-Table -
Auto
}
}
#connect to tasks
$olxTasksFolder = $olName.GetDefaultFolder(‘olFolderTasks’)
$olxTaskItems = $olxTasksFolder.items
$TaskCount = 1
#create task array
$TaskList = @()
ForEach($TaskItem in $olxTaskItems)
{
#create status bar for tasks
Do
{
Write-Progress -Activity "Checking" -status "Tasks" -PercentComplete ($Taskcount/
$olxTasksFolder.Items.count*100)
$TaskCount++
}
#add each incomplete tash to array
While($TaskCount -le $olxTaskFolder.Items.Count)
If($TaskItem.Complete -eq $False)
{
$TaskList+=New-Object -TypeName PSObject -Property @{
Subject=$TaskItem.Subject
DateCreated=$TaskItem.CreationTime
Percent=$TaskItem.PercentComplete
Due=$TaskItem.DueDate
}}
}
#show task array to screen
$TaskList | Sort DueDate -descending | Format-Table -Auto
|
PowerShellCorpus/PoshCode/New-VMHostShellAccount.ps1
|
New-VMHostShellAccount.ps1
|
# original by c_shanklin @ http://communities.vmware.com/message/1013362#1013362
function New-VMHostShellAccount {
param (
$Name,
$Password = $null,
$Description = $null,
$PosixId = $null
)
$SvcInstance = Get-View serviceinstance
$AcctMgr = Get-View $SvcInstance.Content.AccountManager
$AcctSpec = new-object VMware.Vim.HostPosixAccountSpec
$AcctSpec.id = $Name
$AcctSpec.password = $Password
$AcctSpec.description = $Description
$AcctSpec.shellAccess = $true # Enable shell access
$AcctSpec.posixId = $PosixId
$AcctMgr.CreateUser($AcctSpec) # Create user
# Write new user to output stream just as New-VMHostAccount would
Get-VMHostAccount | Where-Object { $_.Id -eq $Name }
}
|
PowerShellCorpus/PoshCode/Chassis Type.ps1
|
Chassis Type.ps1
|
$SystemEnclosure = Get-WMIObject -Class Win32_SystemEnclosure; $Type = $SystemEnclosure.ChassisTypes; CLS ; Write-Host -BackgroundColor White -ForegroundColor Blue "Chassis Type:"
if ($Type -eq 1)
{Write-Host "$Type - Other"}
elseif ($Type -eq 2)
{Write-Host "$Type - Virtual Machine"}
elseif ($Type -eq 3)
{Write-Host "$Type - Desktop"}
elseif ($Type -eq 4)
{Write-Host "$Type - Low Profile Desktop"}
elseif ($Type -eq 5)
{Write-Host "$Type - Pizza Box"}
elseif ($Type -eq 6)
{Write-Host "$Type - Mini Tower"}
elseif ($Type -eq 7)
{Write-Host "$Type - Tower"}
elseif ($Type -eq 8)
{Write-Host "$Type - Portable"}
elseif ($Type -eq 9)
{Write-Host "$Type - Laptop"}
elseif ($Type -eq 10)
{Write-Host "$Type - Notebook"}
elseif ($Type -eq 11)
{Write-Host "$Type - Handheld"}
elseif ($Type -eq 12)
{Write-Host "$Type - Docking Station"}
elseif ($Type -eq 13)
{Write-Host "$Type - All-in-One"}
elseif ($Type -eq 14)
{Write-Host "$Type - Sub-Notebook"}
elseif ($Type -eq 15)
{Write-Host "$Type - Space Saving"}
elseif ($Type -eq 16)
{Write-Host "$Type - Lunch Box"}
elseif ($Type -eq 17)
{Write-Host "$Type - Main System Chassis"}
elseif ($Type -eq 18)
{Write-Host "$Type - Expansion Chassis"}
elseif ($Type -eq 19)
{Write-Host "$Type - Sub-Chassis"}
elseif ($Type -eq 20)
{Write-Host "$Type - Bus Expansion Chassis"}
elseif ($Type -eq 21)
{Write-Host "$Type - Peripheral Chassis"}
elseif ($Type -eq 22)
{Write-Host "$Type - Storage Chassis"}
elseif ($Type -eq 23)
{Write-Host "$Type - Rack Mount Chassis"}
elseif ($Type -eq 24)
{Write-Host "$Type - Sealed-Case PC"}
else
{Write-Host "$Type - Unknown"}
|
PowerShellCorpus/PoshCode/Invoke-LongRunningOperat.ps1
|
Invoke-LongRunningOperat.ps1
|
##############################################################################\n##\n## Invoke-LongRunningOperation\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the functionality of the Write-Progress cmdlet\n\n#>\n\nSet-StrictMode -Version Latest\n\n$activity = "A long running operation"\n$status = "Initializing"\n\n## Initialize the long-running operation\nfor($counter = 0; $counter -lt 100; $counter++)\n{\n $currentOperation = "Initializing item $counter"\n Write-Progress $activity $status -PercentComplete $counter `\n -CurrentOperation $currentOperation\n Start-Sleep -m 20\n}\n\n$status = "Running"\n\n## Initialize the long-running operation\nfor($counter = 0; $counter -lt 100; $counter++)\n{\n $currentOperation = "Running task $counter"\n Write-Progress $activity $status -PercentComplete $counter `\n -CurrentOperation $currentOperation\n Start-Sleep -m 20\n}
|
PowerShellCorpus/PoshCode/Script permissions.ps1
|
Script permissions.ps1
|
<#
.SYNOPSIS
Applies permissions and roles to vSphere vApps
.DESCRIPTION
Applies permissions and roles to vSphere vApps
-VIServer (Optional, defaults to Development) {FQDN of VCentre Server}
-AppName (Required) {VApp Label}
-ADGroup (Optional) {Domain\\Group_Object}
-Role (Optional) {vSphere Role, ReadOnly, Owner-Managed, Supplier-Managed}
.EXAMPLE
Grants the Owner-Managed vSphere role to MYDOM\\MYGroup on the "Test VApp".
Create-Permissions -AppName "Test VApp" -ADGroup "MYDOM\\MYGroup" -Role "Owner-Managed"
#>
#Author: Ant B 2012
Param(
@@[String]$VIServer = "<Default VC>",
[parameter(Mandatory=$true)][String]$AppName,
[parameter(Mandatory=$true)][string]$ADGroup,
[parameter(Mandatory=$true)][string]$Role
)
#Check for the VMware Snapin, load if it isn't already there.
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin VMware.VimAutomation.Core
}
#Connect to VCentre
Connect-VIServer $VIServer
$authmgr = Get-View AuthorizationManager
$perm = New-Object Vmware.VIM.Permission
$perm.principal = $ADGroup
$perm.group = $true
$perm.propagate = $true
$perm.roleid = ($authmgr.Rolelist | where{$_.Name -eq $Role}).Roleid
$target = get-vapp | select name, Id | where{$_.Name -eq $AppName}
$authmgr.SetEntityPermissions($target.Id, $perm)
|
PowerShellCorpus/PoshCode/Invoke-Standby.ps1
|
Invoke-Standby.ps1
|
#Autor: Mateusz Świetlicki
#Site: mateusz.swietlicki.net
#Create: 2010-10-04
function Invoke-Shutdown
{
&"$env:SystemRoot\\System32\\shutdown.exe" -s
}
function Invoke-Reboot
{
&"$env:SystemRoot\\System32\\shutdown.exe" -r
}
function Invoke-Logoff
{
&"$env:SystemRoot\\System32\\shutdown.exe" -l
}
Set-Alias lg Invoke-Logoff
function Invoke-Standby
{
&"$env:SystemRoot\\System32\\rundll32.exe" powrprof.dll,SetSuspendState Standby
}
Set-Alias csleep Invoke-Standby
function Invoke-Hibernate
{
&"$env:SystemRoot\\System32\\rundll32.exe" powrprof.dll,SetSuspendState Hibernate
}
|
PowerShellCorpus/PoshCode/New-WebServiceProxy_2.ps1
|
New-WebServiceProxy_2.ps1
|
#
# New-WebServiceProxy.ps1 (v3.0 Sep 23, 2009)
#
# Oisin Grehan <oising@gmail.com> (x0n)
#
# Usage:
# $proxy = .\\New-WebServiceProxy.ps1 [-Url] http://site/service.asmx [-Anonymous] [[-SoapProtocol] <Soap | Soap12>] [-Namespace <namespace>]
#
# to see available webmethods:
# $proxy | gm
#
# $url = "http://services.msdn.microsoft.com/contentservices/contentservice.asmx?wsdl"
param($url = $(throw "need `$url"), [switch]$Anonymous, [string]$protocol = "Soap", [string]$Namespace="")
[void][system.Reflection.Assembly]::LoadWithPartialName("system.web.services")
trap {
"Error:`n`n $error";
break;
}
#$request = [System.Net.WebRequest]::Create($url);
$dcp = new-object system.web.services.discovery.discoveryclientprotocol
if (! $Anonymous) {
Write-Progress "Network Credentials" "Awaiting input..."
$dcp.Credentials = (Get-Credential).GetNetworkCredential()
}
Write-Progress "Discovery" "Searching..."
$dcp.AllowAutoRedirect = $true
[void]$dcp.DiscoverAny($url)
$dcp.ResolveAll()
# get service name
foreach ($entry in $dcp.Documents.GetEnumerator()) { # needed for Dictionary
if ($entry.Value -is [System.Web.Services.Description.ServiceDescription]) {
$script:serviceName = $entry.Value.Services[0].Name
Write-Verbose "Service: $serviceName"
}
}
Write-Progress "WS-I Basic Profile 1.1" "Validating..."
$ns = new-Object System.CodeDom.CodeNamespace $Namespace
$wref = new-object System.Web.Services.Description.WebReference $dcp.Documents, $ns
$wrefs = new-object system.web.services.description.webreferencecollection
[void]$wrefs.Add($wref)
$ccUnit = new-object System.CodeDom.CodeCompileUnit
[void]$ccUnit.Namespaces.Add($ns)
$violations = new-object system.web.Services.Description.BasicProfileViolationCollection
$wsi11 = [system.web.services.WsiProfiles]::BasicProfile1_1
if ([system.web.Services.Description.WebServicesInteroperability]::CheckConformance($wsi11, $wref, $violations)) {
Write-Progress "Proxy Generation" "Compiling..."
$webRefOpts = new-object System.Web.Services.Description.WebReferenceOptions
$webRefOpts.CodeGenerationOptions = "GenerateNewAsync","GenerateProperties" #,"GenerateOldAsync"
#StringCollection strings = ServiceDescriptionImporter.GenerateWebReferences(
# webReferences, codeProvider, codeCompileUnit, parameters.GetWebReferenceOptions());
$csprovider = new-object Microsoft.CSharp.CSharpCodeProvider
$warnings = [System.Web.Services.Description.ServiceDescriptionImporter]::GenerateWebReferences(
$wrefs, $csprovider, $ccunit, $webRefOpts)
if ($warnings.Count -eq 0) {
$param = new-object system.CodeDom.Compiler.CompilerParameters
[void]$param.ReferencedAssemblies.Add("System.Xml.dll")
[void]$param.ReferencedAssemblies.Add("System.Web.Services.dll")
$param.GenerateInMemory = $true;
#$param.TempFiles = (new-object System.CodeDom.Compiler.TempFileCollection "c:\\temp", $true)
$param.GenerateExecutable = $false;
#$param.OutputAssembly = "$($ns.Name)_$($sdname).dll"
$param.TreatWarningsAsErrors = $false;
$param.WarningLevel = 4;
# do it
$compileResults = $csprovider.CompileAssemblyFromDom($param, $ccUnit);
if ($compileResults.Errors.Count -gt 0) {
Write-Progress "Proxy Generation" "Failed."
foreach ($output in $compileResults.Output) { write-host $output }
foreach ($err in $compileResults.Errors) { write-warning $err }
} else {
$assembly = $compileResults.CompiledAssembly
if ($assembly) {
if ($namespace) {
$serviceType = $assembly.GetType($namespace + "." + $serviceName)
} else {
$serviceType = $assembly.GetType($serviceName)
}
$assembly.GetTypes() | % { Write-Verbose $_.FullName }
} else {
Write-Warning "Failed: `$assembly is null"
return
}
# return proxy instance
$proxy = new-object $serviceType.FullName
if (! $Anonymous) {
$proxy.Credentials = $dcp.Credentials
}
$proxy # dump instance to pipeline
}
} else {
Write-Progress "Proxy Generation" "Failed."
Write-Warning $warnings
}
#Write-Progress -Completed
}
|
PowerShellCorpus/PoshCode/TheGameOfLife_1.ps1
|
TheGameOfLife_1.ps1
|
#TheGameOfLife.ps1
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$SCRIPT:hostProperties = @{};
$SCRIPT:hostState = $null;
$SCRIPT:BoardWidth = 50;
$SCRIPT:BoardHeight = 50;
Function Initialize-Host
{
Param(
[Parameter(Mandatory=$false)]
$wndTitle = "Game of Life...",
[Parameter(Mandatory=$false)]
[Int]$wndWidth=50,
[Parameter(Mandatory=$false)]
[Int]$wndHeight=50
)
$wndSize = $Host.UI.RawUI.WindowSize;
$wndSize.Width = $wndWidth;
$wndSize.Height = $wndHeight;
$wndBuffSize = $wndSize;
#Set Console
$Host.UI.RawUI.WindowTitle = $wndTitle;
$Host.UI.RawUI.WindowSize = $wndSize;
$Host.UI.RawUI.BufferSize = $wndBuffSize;
$Host.UI.RawUI.CursorSize = 0;
$Host.UI.RawUI.ForegroundColor = "Green";
$Host.UI.RawUI.BackgroundColor = "Black";
#get a clear the screen.
Clear-Host;
}
Function Push-Host
{
#Get the full buffer
$hostRect = "System.Management.Automation.Host.Rectangle"
$bufferObject = New-Object $hostRect 0, 0, $(($Host.UI.RawUI.BufferSize).Width), $(($Host.UI.RawUI.BufferSize).Height)
$SCRIPT:hostProperties= @{
"Title" = $Host.UI.RawUI.WindowTitle
"WindowSize" = $Host.UI.RawUI.WindowSize
"WindowPosition" = $Host.UI.RawUI.WindowPosition
"BufferSize" = $Host.UI.RawUI.BufferSize
"Buffer" = $Host.UI.RawUI.GetBufferContents($bufferObject)
"Background" = $Host.UI.RawUI.BackgroundColor
"Foreground" = $Host.UI.RawUI.ForegroundColor
"CursorSize" = $Host.UI.RawUI.CursorSize
"CursorPosition" = $Host.UI.RawUI.CursorPosition
}
$SCRIPT:hostState = New-Object -TypeName PSCustomObject -Property $SCRIPT:hostProperties
}
Function Pop-Host
{
#Restore buffer contents
$Host.UI.RawUI.BufferSize = $SCRIPT:hostState.BufferSize;
$initPosition = $Host.UI.RawUI.WindowPosition;
$initPosition.x = 0;
$initPosition.y = 0;
$Host.UI.RawUI.SetBufferContents($initPosition, $SCRIPT:hostState.Buffer)
#Start with the window
$Host.UI.RawUI.WindowTitle = $SCRIPT:hostState.Title;
$Host.UI.RawUI.WindowPosition = $SCRIPT:hostState.WindowPosition;
$Host.UI.RawUI.WindowSize = $SCRIPT:hostState.WindowSize;
#Set cursor
$Host.UI.RawUI.CursorSize = $SCRIPT:hostState.CursorSize;
$Host.UI.RawUI.CursorPosition = $SCRIPT:hostState.CursorPosition;
#set colors
$Host.UI.RawUI.ForegroundColor = $SCRIPT:hostState.Foreground;
$Host.UI.RawUI.BackgroundColor = $SCRIPT:hostState.Background;
}
Function Get-CursorPosition
{
$dY = ([System.Windows.Forms.Cursor]::Position.Y ) #read the Y coordinates
$dX = ([System.Windows.Forms.Cursor]::Position.X ) #read the X coordinates
return @($dX, $dY)
}
Function Draw-Pixel
{
param(
[Parameter(Mandatory=$true)]
[Int]$X,
[Parameter(Mandatory=$true)]
[Int]$Y,
[Parameter(Mandatory=$false)]
[String]$ForeColor = 'White',
[Parameter(Mandatory=$false)]
[String]$BackColor = 'Black',
[Parameter(Mandatory=$false)]
[String]$pixel = [Char]9608
)
$pos = $Host.UI.RawUI.WindowPosition
$pos.x = $x
$pos.y = $y
$row = $Host.UI.RawUI.NewBufferCellArray($pixel, $ForeColor, $BackColor)
$Host.UI.RawUI.SetBufferContents($pos,$row)
}
#Initialize a full board of dead cells.
Function Initialize-GameMatrix
{
param(
[Int32]$M,
[Int32]$N
)
$gameMatrix = New-Object "Int32[,]" $M, $N
for($i=0; $i -lt $M; $i++)
{
for($j=0; $j -lt $N; $j++)
{
$gameMatrix[$i, $j] = 0;
}
}
return ,$gameMatrix
}
#show the game board in 1's and 0's
Function Show-Matrix
{
param(
[Int[,]]$matrix
)
[Int]$m = $matrix.GetLength(0);
[Int]$n = $matrix.GetLength(1);
for($i=0; $i -lt $m; $i++)
{
for($j=0; $j -lt $n; $j++)
{
Write-Host("{0}" -f $matrix[$i,$j]) -NoNewLine;
}
Write-Host ""
}
}
#Currently Taking 10.5 Secs to generate next generation.
#consumes around 20-25% cpu.
#need to find a better way to do this.
Function Get-NextGeneration
{
param(
[Int[,]]$GameMatrix
)
BEGIN
{
$tmpGameMatrix = $GameMatrix;
#The game board for game of life is infinite. So, we simulate this by wrapping the
#width and height.
Function Get-WrappedWidth
{
param(
[Int]$x,
[Int]$xEdge
)
$x += $xEdge;
if($x -lt 0){
$x += $SCRIPT:BoardWidth;
}elseif($x -ge $SCRIPT:BoardWidth){
$x -= $SCRIPT:BoardWidth;
}
return $x;
}
Function Get-WrappedHeight
{
param(
[Int]$y,
[Int]$yEdge
)
$y += $yEdge;
if($y -lt 0){
$y += $SCRIPT:BoardHeight;
}elseif($y -ge $SCRIPT:BoardHeight){
$y -= $SCRIPT:BoardHeight
}
return $y;
}
Function Get-Neighbours
{
param(
[Int[,]]$ArrayMatrix,
[Int]$coordX,
[Int]$coordY
)
[Int]$nx = 0;
[Int]$ny = 0;
[Int]$count = 0;
for($nx = -1; $nx -le 1; $nx++)
{
for($ny = -1; $ny -le 1; $ny++)
{
if($nx -or $ny)
{
if($ArrayMatrix[$(Get-WrappedWidth $coordX $nx), $(Get-WrappedHeight $coordY $ny)])
{
$count += 1;
}
}
}
}
return $count;
}
}
PROCESS
{
for($x = 0; $x -lt $SCRIPT:BoardWidth; $x++)
{
for($y = 0; $y -lt $SCRIPT:BoardHeight; $y++)
{
$neighbors = Get-Neighbours $tmpGameMatrix $x $y
switch($neighbors)
{
{($neighbors -lt 2) -or ($neighbors -gt 3)}{$tmpGameMatrix[$x, $y] = 0;}
{($neighbors -eq 3)}{$tmpGameMatrix[$x, $y] = 1;}
}
}
}
}
END
{
$GameMatrix = $tmpGameMatrix;
#should we even do this? : return ,$GameMatrix
return ,$GameMatrix;
}
}
Function Draw-Board
{
param(
[Int[,]]$Board
)
for($bx = 0; $bx -lt $SCRIPT:BoardWidth; $bx++)
{
for($by = 0; $by -lt $SCRIPT:BoardHeight; $by++)
{
if($Board[$bx, $by])
{
Draw-Pixel -X $bx -Y $by -ForeColor "Green" -BackColor "Yellow"
}else{
Draw-Pixel -X $bx -Y $by -ForeColor "Black" -BackColor "Black"
}
}
}
}
#Setting a little bit of complex pattern on the board.
Function Set-SampleOnBoard
{
param(
[Int[,]]$ArrayMatrix
)
$ArrayMatrix[6,1] = 1
$ArrayMatrix[7,1] = 1
$ArrayMatrix[6,2] = 1
$ArrayMatrix[7,2] = 1
$ArrayMatrix[6,11] = 1
$ArrayMatrix[7,11] = 1
$ArrayMatrix[8,11] = 1
$ArrayMatrix[9,12] = 1
$ArrayMatrix[10,13] = 1
$ArrayMatrix[10,14] = 1
$ArrayMatrix[9,16] = 1
$ArrayMatrix[8,17] = 1
$ArrayMatrix[7,17] = 1
$ArrayMatrix[6,17] = 1
$ArrayMatrix[5,16] = 1
$ArrayMatrix[4,14] = 1
$ArrayMatrix[4,13] = 1
$ArrayMatrix[5,12] = 1
$ArrayMatrix[7,15] = 1
$ArrayMatrix[7,18] = 1
$ArrayMatrix[4,21] = 1
$ArrayMatrix[5,21] = 1
$ArrayMatrix[6,21] = 1
$ArrayMatrix[4,22] = 1
$ArrayMatrix[5,22] = 1
$ArrayMatrix[6,22] = 1
$ArrayMatrix[7,23] = 1
$ArrayMatrix[3,23] = 1
$ArrayMatrix[3,25] = 1
$ArrayMatrix[2,25] = 1
$ArrayMatrix[7,25] = 1
$ArrayMatrix[8,25] = 1
$ArrayMatrix[3,35] = 1
$ArrayMatrix[3,36] = 1
$ArrayMatrix[4,35] = 1
$ArrayMatrix[4,36] = 1
return ,$ArrayMatrix;
}
Function Main
{
Push-Host;
Initialize-Host;
$gameBoard = Initialize-GameMatrix 50 50;
#Sample filler
$gameBoard = Set-SampleOnBoard $gameBoard
Draw-Board $gameBoard
do{
$newBoard = Get-NextGeneration $gameBoard;
#Clear-Host;
Draw-Board $newBoard;
}until($Host.UI.RawUI.KeyAvailable)
Pop-Host;
}
. Main
|
PowerShellCorpus/PoshCode/vProfiles_1.ps1
|
vProfiles_1.ps1
|
#
# vProfiles V1
# By Alan Renouf
# http://virtu-al.net
#
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.3.0
# Generated On: 27/06/2009 9:17 PM
# Generated By: Alan
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$vProfiles = New-Object System.Windows.Forms.Form
$label3 = New-Object System.Windows.Forms.Label
$label2 = New-Object System.Windows.Forms.Label
$Disconnect = New-Object System.Windows.Forms.Button
$Connect = New-Object System.Windows.Forms.Button
$OutputWin = New-Object System.Windows.Forms.TextBox
$CopyNetwork = New-Object System.Windows.Forms.Button
$NewHost = New-Object System.Windows.Forms.ListBox
$BaseHost = New-Object System.Windows.Forms.ListBox
$label1 = New-Object System.Windows.Forms.Label
$VCSRV = New-Object System.Windows.Forms.TextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$Disconnect_OnClick=
{
Disconnect-VIServer $ConVISRV -Confirm:$false
$Disconnect.Enabled = $false
$CopyNetwork.Enabled = $false
$OutputWin.Text += "`r`nDisconnect Successful"
$vProfiles.Refresh()
}
$handler_NewHost_SelectedIndexChanged=
{
#TODO: Place custom script here
}
$handler_button3_Click=
{
$OutputWin.Text += "`r`nConnecting to $($Basehost.SelectedItem)"
$vProfiles.Refresh()
$CBASEHost = Get-VMHost -Name ($Basehost.SelectedItem)
$OutputWin.Text += "`r`nConnecting to $($Newhost.SelectedItem)"
$vProfiles.Refresh()
$CNEWHost = Get-VMHost -Name ($NewHost.SelectedItem)
$OutputWin.Text += "`r`nRetrieving Virtual Switches"
$vProfiles.Refresh()
$CBASEHost | Get-VirtualSwitch | Foreach {
If (($CNEWHost | Get-VirtualSwitch -Name $_.Name -ErrorAction SilentlyContinue) -eq $null){
$vSwitch = $_
$OutputWin.Text += "`r`nCreating Virtual Switch $($_.Name)"
$vProfiles.Refresh()
$NewSwitch = $CNEWHost | New-VirtualSwitch -Name $_.Name -NumPorts $_.NumPorts -Mtu $_.Mtu
}
$_ | Get-VirtualPortGroup | Foreach {
If (($CNEWHost | Get-VirtualPortGroup -Name $_.Name -ErrorAction SilentlyContinue) -eq $null){
$OutputWin.Text += "`r`n..Creating Portgroup $($_.Name) on $($vSwitch.Name)"
$vProfiles.Refresh()
$NewPortGroup = $CNEWHost | Get-VirtualSwitch -Name $vSwitch | New-VirtualPortGroup -Name $_.Name -VLanId $_.VLanID
}
}
}
$OutputWin.Text += "`r`n-- Configuration Completed --"
$vProfiles.Refresh()
}
$handler_label1_Click=
{
#TODO: Place custom script here
}
$handler_listBox1_SelectedIndexChanged=
{
#TODO: Place custom script here
}
$handler_button1_Click=
{
If ($VCSRV.Text -eq "") {$OutputWin.Text = "Please Specify a VC Server above"}
Else
{
$OutputWin.Text = "Connecting to $($VCSRV.Text)"
$vProfiles.Refresh()
$ConVISRV = Connect-VIServer $VCSRV.Text
If ($ConVISRV.IsConnected -eq $true) {
$OutputWin.Text += "`r`nConnection Successful"
$vProfiles.Refresh()
$Disconnect.Enabled = $true
$CopyNetwork.Enabled = $true
Foreach ($EsxHost in (Get-VMHost))
{
$BaseHost.Items.Add("$($EsxHost.Name)")|Out-Null
$NewHost.Items.Add("$($EsxHost.Name)")|Out-Null
}
}
Else {
$OutputWin.Text += "`r`nConnection Un-Successful - Please try again."
$vProfiles.Refresh()
}
}
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$vProfiles.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 563
$System_Drawing_Size.Height = 503
$vProfiles.MaximumSize = $System_Drawing_Size
$vProfiles.AutoSize = $True
$vProfiles.Text = 'vProfiles'
$vProfiles.ShowInTaskbar = $False
$vProfiles.MaximizeBox = $False
$vProfiles.Name = 'vProfiles'
$vProfiles.SizeGripStyle = 2
$vProfiles.ShowIcon = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 563
$System_Drawing_Size.Height = 503
$vProfiles.MinimumSize = $System_Drawing_Size
$vProfiles.StartPosition = 1
$vProfiles.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 547
$System_Drawing_Size.Height = 465
$vProfiles.ClientSize = $System_Drawing_Size
$label3.TabIndex = 11
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 13
$label3.Size = $System_Drawing_Size
$label3.Text = 'Destination:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 271
$System_Drawing_Point.Y = 43
$label3.Location = $System_Drawing_Point
$label3.DataBindings.DefaultDataSourceUpdateMode = 0
$label3.Name = 'label3'
$label3.add_Click($handler_label3_Click)
$vProfiles.Controls.Add($label3)
$label2.TabIndex = 10
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 13
$label2.Size = $System_Drawing_Size
$label2.Text = 'Source:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 43
$label2.Location = $System_Drawing_Point
$label2.DataBindings.DefaultDataSourceUpdateMode = 0
$label2.Name = 'label2'
$vProfiles.Controls.Add($label2)
$Disconnect.TabIndex = 9
$Disconnect.Name = 'Disconnect'
$Disconnect.Enabled = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$Disconnect.Size = $System_Drawing_Size
$Disconnect.UseVisualStyleBackColor = $True
$Disconnect.Text = 'Disconnect'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 442
$System_Drawing_Point.Y = 10
$Disconnect.Location = $System_Drawing_Point
$Disconnect.DataBindings.DefaultDataSourceUpdateMode = 0
$Disconnect.add_Click($Disconnect_OnClick)
$vProfiles.Controls.Add($Disconnect)
$Connect.TabIndex = 8
$Connect.Name = 'Connect'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$Connect.Size = $System_Drawing_Size
$Connect.UseVisualStyleBackColor = $True
$Connect.Text = 'Connect'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 360
$System_Drawing_Point.Y = 10
$Connect.Location = $System_Drawing_Point
$Connect.DataBindings.DefaultDataSourceUpdateMode = 0
$Connect.add_Click($handler_button1_Click)
$vProfiles.Controls.Add($Connect)
$OutputWin.Multiline = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 491
$System_Drawing_Size.Height = 264
$OutputWin.Size = $System_Drawing_Size
$OutputWin.DataBindings.DefaultDataSourceUpdateMode = 0
$OutputWin.AcceptsReturn = $True
$OutputWin.ScrollBars = 2
$OutputWin.Name = 'OutputWin'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 189
$OutputWin.Location = $System_Drawing_Point
$OutputWin.Enabled = $False
$OutputWin.TabIndex = 7
$vProfiles.Controls.Add($OutputWin)
$CopyNetwork.TabIndex = 6
$CopyNetwork.Name = 'CopyNetwork'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 179
$System_Drawing_Size.Height = 23
$CopyNetwork.Size = $System_Drawing_Size
$CopyNetwork.UseVisualStyleBackColor = $True
$CopyNetwork.Enabled = $false
$CopyNetwork.Text = 'Copy vSwitches and PortGroups'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 175
$System_Drawing_Point.Y = 160
$CopyNetwork.Location = $System_Drawing_Point
$CopyNetwork.DataBindings.DefaultDataSourceUpdateMode = 0
$CopyNetwork.add_Click($handler_button3_Click)
$vProfiles.Controls.Add($CopyNetwork)
$NewHost.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 244
$System_Drawing_Size.Height = 95
$NewHost.Size = $System_Drawing_Size
$NewHost.DataBindings.DefaultDataSourceUpdateMode = 0
$NewHost.ScrollAlwaysVisible = $True
$NewHost.Name = 'NewHost'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 271
$System_Drawing_Point.Y = 59
$NewHost.Location = $System_Drawing_Point
$NewHost.TabIndex = 5
$NewHost.add_SelectedIndexChanged($handler_NewHost_SelectedIndexChanged)
$vProfiles.Controls.Add($NewHost)
$BaseHost.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 241
$System_Drawing_Size.Height = 95
$BaseHost.Size = $System_Drawing_Size
$BaseHost.DataBindings.DefaultDataSourceUpdateMode = 0
$BaseHost.ScrollAlwaysVisible = $True
$BaseHost.Name = 'BaseHost'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 59
$BaseHost.Location = $System_Drawing_Point
$BaseHost.TabIndex = 4
$BaseHost.add_SelectedIndexChanged($handler_listBox1_SelectedIndexChanged)
$vProfiles.Controls.Add($BaseHost)
$label1.TabIndex = 1
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 86
$System_Drawing_Size.Height = 23
$label1.Size = $System_Drawing_Size
$label1.Text = 'Virtual Center:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 34
$System_Drawing_Point.Y = 15
$label1.Location = $System_Drawing_Point
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$label1.Name = 'label1'
$label1.add_Click($handler_label1_Click)
$vProfiles.Controls.Add($label1)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 228
$System_Drawing_Size.Height = 20
$VCSRV.Size = $System_Drawing_Size
$VCSRV.DataBindings.DefaultDataSourceUpdateMode = 0
$VCSRV.Name = 'VCSRV'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 126
$System_Drawing_Point.Y = 12
$VCSRV.Location = $System_Drawing_Point
$VCSRV.TabIndex = 0
$vProfiles.Controls.Add($VCSRV)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $vProfiles.WindowState
#Init the OnLoad event to correct the initial state of the form
$vProfiles.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$vProfiles.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/ISE-Comments.ps1
|
ISE-Comments.ps1
|
#requires -version 2.0
## ISE-Comments module v 1.0
## DEVELOPED FOR CTP3
## See comments for each function for changes ...
##############################################################################################################
## Provides Comment cmdlets for working with ISE
## ConvertTo-BlockComment - Comments out selected text with <# before and #> after
## ConvertTo-BlockUncomment - Removes <# before and #> after selected text
## ConvertTo-Comment - Comments out selected text with a leeding # on every line
## ConvertTo-Uncomment - Removes leeding # on every line of selected text
##############################################################################################################
## ConvertTo-BlockComment
##############################################################################################################
## Comments out selected text with <# before and #> after
## This code was originaly designed by Jeffrey Snover and was taken from the Windows PowerShell Blog.
## The original function was named ConvertTo-Comment but as it comments out a block I renamed it.
##############################################################################################################
function ConvertTo-BlockComment
{
$editor = $psISE.CurrentOpenedFile.Editor
$CommentedText = "<#`n" + $editor.SelectedText + "#>"
# INSERTING overwrites the SELECTED text
$editor.InsertText($CommentedText)
}
## ConvertTo-BlockUncomment
##############################################################################################################
## Removes <# before and #> after selected text
##############################################################################################################
function ConvertTo-BlockUncomment
{
$editor = $psISE.CurrentOpenedFile.Editor
$CommentedText = $editor.SelectedText -replace ("^<#`n", "")
$CommentedText = $CommentedText -replace ("#>$", "")
# INSERTING overwrites the SELECTED text
$editor.InsertText($CommentedText)
}
## ConvertTo-Comment
##############################################################################################################
## Comments out selected text with a leeding # on every line
##############################################################################################################
function ConvertTo-Comment
{
$editor = $psISE.CurrentOpenedFile.Editor
$CommentedText = $editor.SelectedText.Split("`n")
# INSERTING overwrites the SELECTED text
$editor.InsertText( "#" + ( [String]::Join("`n#", $CommentedText)))
}
## ConvertTo-Uncomment
##############################################################################################################
## Comments out selected text with <# before and #> after
##############################################################################################################
function ConvertTo-Uncomment
{
$editor = $psISE.CurrentOpenedFile.Editor
$CommentedText = $editor.SelectedText.Split("`n") -replace ( "^#", "" )
# INSERTING overwrites the SELECTED text
$editor.InsertText( [String]::Join("`n", $CommentedText))
}
##############################################################################################################
## Inserts a submenu Comments to ISE's Custum Menu
## Inserts command Block Comment Selected to submenu Comments
## Inserts command Block Uncomment Selected to submenu Comments
## Inserts command Comment Selected to submenu Comments
## Inserts command Uncomment Selected to submenu Comments
##############################################################################################################
if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "Comments" } ) )
{
$commentsMenu = $psISE.CustomMenu.Submenus.Add("_Comments", $null, $null)
$null = $commentsMenu.Submenus.Add("Block Comment Selected", {ConvertTo-BlockComment}, "Ctrl+SHIFT+B")
$null = $commentsMenu.Submenus.Add("Block Uncomment Selected", {ConvertTo-BlockUncomment}, "Ctrl+Alt+B")
$null = $commentsMenu.Submenus.Add("Comment Selected", {ConvertTo-Comment}, "Ctrl+SHIFT+C")
$null = $commentsMenu.Submenus.Add("Uncomment Selected", {ConvertTo-Uncomment}, "Ctrl+Alt+C")
}
|
PowerShellCorpus/PoshCode/Highlight-Syntax _1.0.ps1
|
Highlight-Syntax _1.0.ps1
|
# Highlight-Syntax.ps1
# version 1.0
# by Jeff Hillman
#
# this script uses regular expressions to highlight PowerShell
# syntax with HTML.
param( [string] $code, [switch] $LineNumbers )
if ( Test-Path $code -ErrorAction SilentlyContinue )
{
$code = Get-Content $code | Out-String
}
$backgroundColor = "#DDDDDD"
$foregroundColor = "#000000"
$stringColor = "#800000"
$commentColor = "#008000"
$operatorColor = "#C86400"
$numberColor = "#800000"
$keywordColor = "#C86400"
$typeColor = "#404040"
$variableColor = "#000080"
$cmdletColor = "#C86400"
$lineNumberColor = "#404040"
filter Html-Encode( [switch] $Regex )
{
# some regular expressions operate on strings that have already
# been through this filter, so the patterns need to be updated
# to look for the encoded characters instead of the literal ones.
# we do it with this filter instead of directly in the regular
# expression so the expressions can be a bit more readable (ha!)
$_ = $_ -replace "&", "&"
if ( $Regex )
{
$_ = $_ -replace "(?<!\\(\\?)<", "<"
$_ = $_ -replace "(?<!\\(\\?)>", ">"
}
else
{
$_ = $_ -replace "\\t", " "
$_ = $_ -replace " ", " "
$_ = $_ -replace "<", "<"
$_ = $_ -replace ">", ">"
}
$_
}
# regular expressions
$operatorRegex = @"
((?x:
(?# assignment operators)
=|\\+=|-=|\\*=|/=|%=|
(?# arithmatic operators)
(?<!\\de)
(\\+|-|\\*|/|%)(?![a-z])|
(?# unary operators)
\\+\\+|\\-\\-|
(?# logical operators)
(-and|-or|-not)\\b|!|
(?# bitwise operators)
(-band|-bor)\\b|
(?# redirection and pipeline operators)
2>>|>>|2>&1|1>&2|2>|>|<|\\||
(?# comparison operators)
(
-[ci]? (?# case and case-insensitive variants)
(eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains)\\b
)|
(?# type operators)
(-is|-isnot|-as)\\b|
(?# range and miscellaneous operators)
\\.\\.|(?<!\\d)\\.(?!\\d)|&|::|:|,|``|
(?# string formatting operator)
-f\\b
))
"@ | Html-Encode -Regex
$numberRegex = @"
((?x:
(
(?# hexadecimal numbers)
(\\b0x[0-9a-f]+)|
(?# regular numbers)
(?<!&)
((\\b[0-9]+(\\.(?!\\.))?[0-9]*)|((?<!\\.)\\.[0-9]+))
(?!(>>|>&[12]|>))
(?# scientific notation)
(e(\\+|-)?[0-9]+)?
)
(
(?# type specifiers)
(l|ul|u|f|ll|ull)?
(?# size shorthand)
(b|kb|mb|gb)?
\\b
)?
))
"@ | Html-Encode -Regex
$keyWordRegex = @"
((?x:
\\b(
(?# don't match anything that looks like a variable or a parameter)
(?<![-$])
(
(?# condition keywords)
if|else|elseif|(?<!\\[)switch(?!\\])|
(?# loop keywords)
for|(?<!\\|</span> )foreach(?!-object)|in|do|while|until|default|break|continue|
(?# scope keywords)
global|script|local|private|
(?# block keywords)
begin|process|end|
(?# other keywords)
function|filter|param|throw|trap|return
)
)\\b
))
"@
$typeRegex = @"
((?x:
\\[
(
(?# primitive types and arrays of those types)
((int|long|string|char|bool|byte|double|decimal|float|single)(\\[\\])?)|
(?# other types)
regex|array|xml|scriptblock|switch|hashtable|type|ref|psobject|wmi|wmisearcher|wmiclass
)
\\]
))
"@
$cmdletNames = Get-Command -Type Cmdlet | Foreach-Object { $_.Name }
function Highlight-Other( [string] $code )
{
$highlightedCode = $code | Html-Encode
# operators
$highlightedCode = $highlightedCode -replace
$operatorRegex, "<span style='color: $operatorColor'>`$1</span>"
# numbers
$highlightedCode = $highlightedCode -replace
$numberRegex, "<span style='color: $numberColor'>`$1</span>"
# keywords
$highlightedCode = $highlightedCode -replace
$keyWordRegex, "<span style='color: $keywordColor'>`$1</span>"
# types
$highlightedCode = $highlightedCode -replace
$typeRegex, "<span style='color: $typeColor'>`$1</span>"
# Cmdlets
$cmdletNames | Foreach-Object {
$highlightedCode = $highlightedCode -replace
"\\b($_)\\b", "<span style='color: $cmdletColor'>`$1</span>"
}
$highlightedCode
}
$RegexOptions = [System.Text.RegularExpressions.RegexOptions]
$highlightedCode = ""
# we treat variables, strings, and comments differently because we don't
# want anything inside them to be highlighted. we combine the regular
# expressions so they are mutually exclusive
$variableRegex = '(\\$(\\w+|{[^}`]*(`.[^}`]*)*}))'
$stringRegex = @"
(?x:
(?# here strings)
@[`"'](.|\\n)*?^[`"']@|
(?# double-quoted strings)
`"[^`"``]*(``.[^`"``]*)*`"|
(?# single-quoted strings)
'[^'``]*(``.[^'``]*)*'
)
"@
$commentRegex = "#[^\\r\\n]*"
[regex]::Matches( $code,
"(?<before>(.|\\n)*?)" +
"((?<variable>$variableRegex)|" +
"(?<string>$stringRegex)|" +
"(?<comment>$commentRegex))",
$RegexOptions::MultiLine ) | Foreach-Object {
# highlight everything before the variable, string, or comment
$highlightedCode += Highlight-Other $_.Groups[ "before" ].Value
if ( $_.Groups[ "variable" ].Value )
{
$highlightedCode +=
"<span style='color: $variableColor'>" +
( $_.Groups[ 'variable' ].Value | Html-Encode ) +
"</span>"
}
elseif ( $_.Groups[ "string" ].Value )
{
$string = $_.Groups[ 'string' ].Value | Html-Encode
$string = "<span style='color: $stringColor'>$string</span>"
# we have to highlight each piece of multi-line strings
if ( $string -match "\\r\\n" )
{
# highlight any line continuation characters as operators
$string = $string -replace
"(``)(?=\\r\\n)", "<span style='color: $operatorColor'>``</span>"
$string = $string -replace
"\\r\\n", "</span>`r`n<span style='color: $stringColor'>"
}
$highlightedCode += $string
}
else
{
$highlightedCode +=
"<span style='color: $commentColor'>" +
$( $_.Groups[ 'comment' ].Value | Html-Encode ) +
"</span>"
}
# we need to keep track of the last position of a variable, string,
# or comment, so we can highlight everything after it
$lastMatch = $_
}
if ( $lastMatch )
{
# highlight everything after the last variable, string, or comment
$highlightedCode += Highlight-Other $code.SubString( $lastMatch.Index + $lastMatch.Length )
}
else
{
$highlightedCode = Highlight-Other $code
}
# add line breaks
$highlightedCode =
[regex]::Replace( $highlightedCode, '(?=\\r\\n)', '<br />', $RegexOptions::MultiLine )
# put the highlighted code in the pipeline
"<div style='width: 100%; " +
"/*height: 100%;*/ " +
"overflow: auto; " +
"font-family: Consolas, `"Courier New`", Courier, mono; " +
"font-size: 12px; " +
"background-color: $backgroundColor; " +
"color: $foregroundColor; " +
"padding: 2px 2px 2px 2px; white-space: nowrap'>"
if ( $LineNumbers )
{
$digitCount =
( [regex]::Matches( $highlightedCode, "^", $RegexOptions::MultiLine ) ).Count.ToString().Length
$highlightedCode = [regex]::Replace( $highlightedCode, "^",
"<li style='color: $lineNumberColor; padding-left: 5px'><span style='color: $foregroundColor'>",
$RegexOptions::MultiLine )
$highlightedCode = [regex]::Replace( $highlightedCode, "<br />", "</span><br />",
$RegexOptions::MultiLine )
"<ol start='1' style='border-left: " +
"solid 1px $lineNumberColor; " +
"margin-left: $( ( $digitCount * 10 ) + 15 )px; " +
"padding: 0px;'>"
}
$highlightedCode
if ( $LineNumbers )
{
"</ol>"
}
"</div>"
|
PowerShellCorpus/PoshCode/PowerShell Template_5.ps1
|
PowerShell Template_5.ps1
|
Function new-script
{
$strName = $env:username
$date = get-date -format d
$name = Read-Host "Filename"
$email = Read-Host "eMail Address"
$file = New-Item -type file "c:\\Scripts\\$name.ps1" -force
add-content $file "#=========================================================================="
add-content $file "#"
add-content $file "# NAME: $name.ps1"
add-content $file "#"
add-content $file "# AUTHOR: $strName"
add-content $file "# EMAIL: $email"
add-content $file "#"
add-content $file "# COMMENT: "
add-content $file "#"
add-content $file "# You have a royalty-free right to use, modify, reproduce, and"
add-content $file "# distribute this script file in any way you find useful, provided that"
add-content $file "# you agree that the creator, owner above has no warranty, obligations,"
add-content $file "# or liability for such use."
add-content $file "#"
add-content $file "# VERSION HISTORY:"
add-content $file "# 1.0 $date - Initial release"
add-content $file "#"
add-content $file "#=========================================================================="
ii $file
}
|
PowerShellCorpus/PoshCode/style acording video res_1.ps1
|
style acording video res_1.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/Convert-ToCHexString_3.ps1
|
Convert-ToCHexString_3.ps1
|
function Convert-ToCHexString {
param([String] $input
$ans = ''
[System.Text.Encoding]::ASCII.GetBytes($str) | % { $ans += "0x{0:X2}, " -f $_ }
return $ans.Trim(',',' ')
}
|
PowerShellCorpus/PoshCode/ESX Lun Latencies_1.ps1
|
ESX Lun Latencies_1.ps1
|
function Get-VMHostLunLatency {
param([parameter(Mandatory=$true, ValueFromPipeline=$true)] $VMHost)
process {
$luns = Get-ScsiLun -VmHost $VMHost
$DiskStats = $VMHost |
Get-Stat -stat disk.totalreadlatency.average,disk.totalwritelatency.average -maxsamples 1 -realtime
foreach ($lun in $luns) {
$Stats = $DiskStats |
Where { $_.Instance -eq $Lun.CanonicalName }
if ($stats.length -ne $null) {
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name VMHost -Value $VMHost.Name
$obj | Add-Member -MemberType NoteProperty -Name Lun -Value $lun.CanonicalName
$obj | Add-Member -MemberType NoteProperty -Name ReadLatency -Value ($stats[0].Value)
$obj | Add-Member -MemberType NoteProperty -Name WriteLatency -Value ($stats[1].Value)
Write-Output $obj
}
}
}
}
|
PowerShellCorpus/PoshCode/Set-IPAddress_4.ps1
|
Set-IPAddress_4.ps1
|
# ahhh ... much better. Don't ask for prompts. It's not scriptable if you do.
function Set-IPAddress {
param( [string]$networkinterface,
[string]$ip,
[string]$mask,
[string]$gateway,
[string]$dns1,
[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/Get-FtpList.ps1
|
Get-FtpList.ps1
|
function Get-FtpList {
#.Synopsis
# Read a list of files (and directories) from FTP
#.Description
# An initial implementation of a string-parsing lister for FTP which converts lists to objects (in the one format that I've seen -- there are other formats)
#
# This implementation will use whatever proxy is set up in the "Internet Options" proxy settings (usually your web proxy, and basically never an FTP server with USER@HOST settings), which may affect the file list format.
#.Parameter Path
# The full path to the directory you want a listing from, in the form: ftp://servername/folder/
#.Parameter Credentials
# The login credentials for the ftp server, if needed
#.Example
# $List = Get-FtpList "ftp://joelbennett.net/" (Get-Credential)
# C:\\PS>$list | ft Name, Type, Length, LastWriteTime, FullName -auto
#
# Name Type Length LastWriteTime FullName
# ---- ---- ------ ------------- --------
# DeskOps Directory 5/24/2009 12:00:00 AM ftp://joelbennett.net/DeskOps/
# GeoShell Directory 5/24/2009 12:00:00 AM ftp://joelbennett.net/GeoShell/
# Jaykul.asc File 1626 5/24/2009 12:00:00 AM ftp://joelbennett.net/Jaykul.asc
# ShotGlass Directory 5/24/2009 12:00:00 AM ftp://joelbennett.net/ShotGlass/
# images Directory 2/6/2010 2:13:00 PM ftp://joelbennett.net/images/
# index.php File 407 5/9/2009 12:00:00 AM ftp://joelbennett.net/index.php
#
# Description
# -----------
# The first command gets a list of files, directories (and symlinks, if there are any) into $List
# The second command outputs that list in a useable table format, because the Huddled.FtpItemInfo type hasn't been set up in my Format ps1xml files so by default the output will be in list form.
#
#.Notes
# This will use a proxy, but only if it's set up correctly in "Internet Options" proxy settings.
#.Link
# The FTP WebRequest class
# * http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
#.Link
# The FTP Methods enumeration
# * http://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp.aspx
#
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Path
,
[Parameter(Mandatory=$false)]
[System.Net.ICredentials]$Credential
)
[System.Net.FtpWebRequest]$request = [System.Net.WebRequest]::Create($path)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails
if($credential) { $request.Credentials = $credential }
$response = $request.GetResponse()
if( $response.StatusCode -ne "CommandOK" ) {
throw "Response Status: $($response.StatusDescription)"
}
$global:ftpOutputCache = (Receive-Stream $response.GetResponseStream())
$list = $global:ftpOutputCache -replace "(?:.|\\n)*<PRE>\\s+((?:.*|\\n)+)\\s+</PRE>(?:.|\\n)*",'$1' -split "`n"
$( foreach($line in $list | ? { $_ }) {
[DateTime]$date, [string]$length, [string]$url, [string]$name, $null = $line -split ' + | <A HREF="|">|</A>'
New-Object PSObject -Property @{
LastWriteTime = $date
FullName = $path.trim().trim('/') + '/' + $url
Length = $(if($length -eq (($length -as [int]) -as [string])) { [int]$length } else { $null })
Type = $(if($length -eq (($length -as [int]) -as [string])) { "File" } else { $length })
Name = $name
}
} # Note: I put a (fake) "Huddled.FtpItemInfo" type name on. You can use that for format.ps1xml
) | Sort Type | %{ $_.PSTypeNames.Insert(0, "Huddled.FtpItemInfo"); $_ } | Write-Output
}
function Receive-Stream {
#.Synopsis
# Read a stream to the end and close it
#.Description
# Will read from a byte stream and output a string or a file
#.Param reader
# The stream to read from
#.Param fileName
# A file to write to. If this parameter is provided, the function will output to file
#.Param encoding
# The text encoding, if you want to override the default.
param( [System.IO.Stream]$reader, $fileName, $encoding = [System.Text.Encoding]::GetEncoding( $null ) )
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
} else {
[string]$output = ""
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length)
if($fileName) {
$writer.Write($buffer, 0, $count)
} else {
$output += $encoding.GetString($buffer, 0, $count)
}
} while ($count -gt 0)
$reader.Close()
if(!$fileName) { $output }
}
|
PowerShellCorpus/PoshCode/gpupdate on remote pc's.ps1
|
gpupdate on remote pc's.ps1
|
###############################################################################
#
# Get all servers from a OU and run GPUpdate /force on this machines.
#
# Version 1.0
#
# (C) 2009 - Arne Fokkema
# www.ict-freak.nl
#
# Install the Quest AD cmdlets first!!
#
###############################################################################
# Requires QAD cmdlets
if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" `
-ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Quest.ActiveRoles.ADManagement"
}
$url = "http://live.sysinternals.com/psexec.exe"
$target = "c:\\Tools\\psexec.exe"
$TempFile = "C:\\Machines.txt"
$Domain = Read-Host ("Enter the FQDN of the Domain")
$OU = Read-Host ("Enter the name of the OU")
# Check if psexec does exist
if (test-path $target)
{
write-host "psexec.exe is already installed"
}
else
{
write-host "psexec.exe doesn't exist"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $target);
write-host "psexec.exe is now installed"
}
$Servers = Get-QADComputer -SearchRoot $Domain/$OU | Select Name | out-file $TempFile -force
#Cleanup Textfile
(Get-Content $TempFile) | Foreach-Object {$_ -replace "Name ", ""} | Set-Content $TempFile
(Get-Content $TempFile) | Foreach-Object {$_ -replace "---- ", ""} | Set-Content $TempFile
(Get-Content $TempFile) | Foreach-Object {$_ -replace " ", ""} | Set-Content $TempFile
(Get-Content $TempFile) | where {$_ -ne ""} >$TempFile
$colComputers = Get-Content $TempFile
Foreach ($strComputer in $colComputers){c:\\Tools\\psexec.exe \\\\$strComputer gpupdate.exe /target:computer /force}
RM $TempFile
|
PowerShellCorpus/PoshCode/Dell Order Status_2.ps1
|
Dell Order Status_2.ps1
|
# Version: 0.1
# Author: Stefan Stranger
# Description: Retrieve Dell Order Status
# Start Page Order Status USA: https://support.dell.com/support/order/status.aspx?c=us&cs=19&l=en&s=dhs&~ck=pn
# Start Page Order Status EMEA(nl): http://support.euro.dell.com/support/index.aspx?c=nl&l=nl&s=gen&~ck=bt
# Example Dell Order Status URL: http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=[IR Number]&ea=[emailaddress]'
#param ([string]$url = $(read-host "Please enter Dell Order Status URL"))
$wc = New-Object System.Net.WebClient
$url = 'http://support.euro.dell.com/support/order/emea/OrderStatus.aspx?c=nl&l=nl&s=gen&ir=NL0131-8510-29070&ea=stefan.stranger@getronics.com'
$RawResult = $wc.DownloadString($url)
# $RawResult = gc orderstatus.txt
# Search for the Estimated Delivery Date in the url that starts with the word "lever" (Levering is the Dutch word for Delivery" and
# and ends with </B></TD></TR>
# You should probable need to change the string "Lever" in "Deliv" or something
$r = New-Object regex('Lever.*?(\\d+-\\d+-\\d{4})</B></TD></TR>','SingleLine' )
# String block with the Estimated Delivery Date
$m = $r.Matches($RawResult)
# Extract Delivery Date from string block
$date = ($m |% {$_.groups[1].value })
# Search for Current Order Status ("In preproduction" is Dutch for "In preproduction"
$r = New-Object regex('target="popup:640x480">(.*?)</a>' )
$m = $r.Matches($RawResult)
$status = ($m |% {$_.groups[1].value })
$Orderstatus = 1 | select @{name='Status';expression={$status[0]}},@{name='Estimated Delivery Date';expression={$date}}
$Orderstatus | ft -a
#[string]$output = $orderstatus
$startdate = "16-09-2007"
$startdate
$currentdate = (get-date).ToString('MM-dd-yyyy')
$currentdate
$date
|
PowerShellCorpus/PoshCode/Get-Parameter_13.ps1
|
Get-Parameter_13.ps1
|
#Requires -version 2.0
##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)]
$Name
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$ShowCommon
,
[switch]$Full
,
[switch]$Passthru
)
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
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
$Name
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$ShowCommon
,
[switch]$Full
,
[switch]$Passthru
)
if($Passthru) {
$PSBoundParameters.Remove("Passthru")
Get-ParameterRaw @PSBoundParameters
} elseif(!$Full) {
Get-ParameterRaw @PSBoundParameters | Format-Table Name, Type, ParameterSet, Mandatory -GroupBy @{n="Command";e={"{0}`n Set: {1}" -f $_.Command,$_.ParameterSet}}
} else {
Get-ParameterRaw @PSBoundParameters | Format-Table Name, Aliases, Type, Mandatory, Pipeline, PipelineByName, Position -GroupBy @{n="Command";e={"{0}`n Set: {1}" -f $_.Command,$_.ParameterSet}}
}
}
## This is Hal's original script (modified a lot)
Function global:Get-ParameterRaw {
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
$Name
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$ShowCommon
,
[switch]$Full
)
BEGIN {
$PropertySet = @( "Name",
"Aliases",
@{n="Type";e={$_.ParameterType.Name}},
@{n="ParameterSet";e={$paramset.Name}},
@{n="Command";e={"{0}/{1}" -f $(if($command.ModuleName){$command.ModuleName}else{$Command.CommandType.ToString()+":"}),$command.Name}}
@{n="Mandatory";e={$_.IsMandatory}},
@{n="Pipeline";e={$_.ValueFromPipeline}},
@{n="PipelineByName";e={$_.ValueFromPipelineByPropertyName}},
"Position"
)
if(!$Full) {
$PropertySet = $PropertySet[0,2,3,4,5]
}
}
PROCESS{
if($ModuleName) { $Name = "$ModuleName\\$Name" }
foreach($command in Get-Command $Name -ErrorAction silentlycontinue) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) { continue }
foreach ($paramset in $command.ParameterSets){
foreach ($param in $paramset.Parameters) {
if(!$ShowCommon -and ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue }
$parameter = $param | Select-Object $PropertySet
if($parameter.ParameterSet -eq "__AllParameterSets") { $parameter.ParameterSet = "Default" }
if($Full -and $parameter.Position -lt 0) {$parameter.Position = $null}
Write-Output $parameter
}
}
}
}
}
# 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/Get-Delegate_1.ps1
|
Get-Delegate_1.ps1
|
#requires -version 3
function Get-Delegate {
<#
.SYNOPSIS
Create an action[] or func[] delegate for a psmethod reference.
.DESCRIPTION
Create an action[] or func[] delegate for a psmethod reference.
.PARAMETER Method
A PSMethod reference to create a delegate for. This parameter accepts pipeline input.
.PARAMETER ParameterType
An array of types to use for method overload resolution. If there are no overloaded methods
then this array will be ignored but a warning will be omitted if the desired parameters were
not compatible.
.PARAMETER DelegateType
The delegate to create for the corresponding method. Example: [string]::format | get-delegate -delegatetype func[int,string]
.INPUTS System.Management.Automation.PSMethod, System.Type[]
.EXAMPLE
$delegate = [string]::format | Get-Delegate string,string
Gets a delegate for a matching overload with string,string parameters.
It will actually return func<object,string> which is the correct
signature for invoking string.format with string,string.
.EXAMPLE
$delegate = [console]::beep | Get-Delegate @()
Gets a delegate for a matching overload with no parameters.
.EXAMPLE
$delegate = [console]::beep | get-delegate int,int
Gets a delegate for a matching overload with @(int,int) parameters.
.EXAMPLE
$delegate = [string]::format | Get-Delegate -Delegate 'func[string,object,string]'
Gets a delegate for an explicit func[].
.EXAMPLE
$delegate = [console]::writeline | Get-Delegate -Delegate 'action[int]'
Gets a delegate for an explicit action[].
.EXAMPLE
$delegate = [string]::isnullorempty | get-delegate
For a method with no overloads, we will choose the default method and create a corresponding action/action[] or func[].
#>
[CmdletBinding(DefaultParameterSetName="FromParameterType")]
[outputtype('System.Action','System.Action[]','System.Func[]')]
param(
[parameter(mandatory=$true, valuefrompipeline=$true)]
[system.management.automation.psmethod]$Method,
[parameter(position=0, valuefromremainingarguments=$true, parametersetname="FromParameterType")]
[validatenotnull()]
[allowemptycollection()]
[Alias("types")]
[type[]]$ParameterType = @(),
[parameter(mandatory=$true, parametersetname="FromDelegate")]
[validatenotnull()]
[validatescript({ ([delegate].isassignablefrom($_)) })]
[type]$DelegateType
)
$base = $method.GetType().GetField("baseObject","nonpublic,instance").GetValue($method)
if ($base -is [type]) {
[type]$baseType = $base
[reflection.bindingflags]$flags = "Public,Static"
} else {
[type]$baseType = $base.GetType()
[reflection.bindingflags]$flags = "Public,Instance"
}
if ($pscmdlet.ParameterSetName -eq "FromDelegate") {
write-verbose "Inferring from delegate."
if ($DelegateType -eq [action]) {
# void action
$ParameterType = [type[]]@()
} elseif ($DelegateType.IsGenericType) {
# get type name
$name = $DelegateType.Name
# is it [action[]] ?
if ($name.StartsWith("Action``")) {
$ParameterType = @($DelegateType.GetGenericArguments())
} elseif ($name.StartsWith("Func``")) {
# it's a [func[]]
$ParameterType = @($DelegateType.GetGenericArguments())
$ParameterType = $ParameterType[0..$($ParameterType.length - 2)] # trim last element (TReturn)
} else {
throw "Unsupported delegate type: Use Action<> or Func<>."
}
}
}
[reflection.methodinfo]$methodInfo = $null
if ($Method.OverloadDefinitions.Count -gt 1) {
# find best match overload
write-verbose "$($method.name) has multiple overloads; finding best match."
$finder = [type].getmethod("GetMethodImpl", [reflection.bindingflags]"NonPublic,Instance")
write-verbose "base is $($base.gettype())"
$methodInfo = $finder.invoke(
$baseType,
@(
$method.Name,
$flags,
$null,
$null,
[type[]]$ParameterType,
$null
)
) # end invoke
} else {
# method not overloaded
Write-Verbose "$($method.name) is not overloaded."
if ($base -is [type]) {
$methodInfo = $base.getmethod($method.name, $flags)
} else {
$methodInfo = $base.gettype().GetMethod($method.name, $flags)
}
# if parametertype is $null, fill it out; if it's not $null,
# override it to correct it if needed, and warn user.
if ($pscmdlet.ParameterSetName -eq "FromParameterType") {
if ($ParameterType -and ((compare-object $parametertype $methodinfo.GetParameters().parametertype))) {
write-warning "Method not overloaded: Ignoring provided parameter type(s)."
}
$ParameterType = $methodInfo.GetParameters().parametertype
write-verbose ("Set default parameters to: {0}" -f ($ParameterType -join ","))
}
}
if (-not $methodInfo) {
write-warning "Could not find matching signature for $($method.Name) with $($parametertype.count) parameter(s)."
} else {
write-verbose "MethodInfo: $methodInfo"
# it's important here to use the actual MethodInfo's parameter types,
# not the desired types ($parametertype) because they may not match,
# e.g. asked for method(int) but match is method(object).
if ($pscmdlet.ParameterSetName -eq "FromParameterType") {
if ($methodInfo.GetParameters().count -gt 0) {
$ParameterType = $methodInfo.GetParameters().ParameterType
}
# need to create corresponding [action[]] or [func[]]
if ($methodInfo.ReturnType -eq [void]) {
if ($ParameterType.Length -eq 0) {
$DelegateType = [action]
} else {
# action<...>
# replace desired with matching overload parameter types
#$ParameterType = $methodInfo.GetParameters().ParameterType
$DelegateType = ("action[{0}]" -f ($ParameterType -join ",")) -as [type]
}
} else {
# func<...>
# replace desired with matching overload parameter types
#$ParameterType = $methodInfo.GetParameters().ParameterType
$DelegateType = ("func[{0}]" -f (($ParameterType + $methodInfo.ReturnType) -join ",")) -as [type]
}
}
Write-Verbose $DelegateType
if ($flags -band [reflection.bindingflags]::Instance) {
$methodInfo.createdelegate($DelegateType, $base)
} else {
$methodInfo.createdelegate($DelegateType)
}
}
}
#
# tests
#
function Assert-True {
param(
[parameter(position=0, mandatory=$true)]
[validatenotnull()]
[scriptblock]$Script,
[parameter(position=1)]
[validatenotnullorempty()]
[string]$Name = "Assert-True"
)
$eap = $ErrorActionPreference
Write-Host -NoNewline "Assert-True [ $Name ] "
try {
$erroractionpreference = "stop"
if ((& $script) -eq $true) {
write-host -ForegroundColor Green "[PASS]"
return
}
$reason = "Assert failed."
}
catch {
$reason = "Error: $_"
}
finally {
$ErrorActionPreference = $eap
}
write-host -ForegroundColor Red "[FAIL] " -NoNewline
write-host "Reason: '$reason'"
}
#
# static methods
#
assert-true {
$delegate = [string]::format | Get-Delegate -Delegate 'func[string,object,string]'
$delegate.invoke("hello, {0}", "world") -eq "hello, world"
} -name "[string]::format | get-delegate -delegate 'func[string,object,string]'"
assert-true {
$delegate = [console]::writeline | Get-Delegate -Delegate 'action[int]'
$delegate -is [action[int]]
} -name "[console]::writeline | get-delegate -delegate 'action[int]'"
assert-true {
$delegate = [string]::format | Get-Delegate string,string
$delegate.invoke("hello, {0}", "world") -eq "hello, world"
} -name "[string]::format | get-delegate string,string"
assert-true {
$delegate = [console]::beep | Get-Delegate @()
$delegate -is [action]
} -name "[console]::beep | get-delegate @()"
assert-true {
$delegate = [console]::beep | Get-Delegate -DelegateType action
$delegate -is [action]
} -name "[console]::beep | Get-Delegate -DelegateType action"
assert-true {
$delegate = [string]::IsNullOrEmpty | get-delegate
$delegate -is [func[string,bool]]
} -name "[string]::IsNullOrEmpty | get-delegate # single overload"
assert-true {
$delegate = [string]::IsNullOrEmpty | get-delegate string
$delegate -is [func[string,bool]]
} -name "[string]::IsNullOrEmpty | get-delegate string # single overload"
#
# instance methods
#
assert-true {
$sb = new-object text.stringbuilder
$delegate = $sb.Append | get-delegate string
$delegate -is [System.Func[string,System.Text.StringBuilder]]
} -name "`$sb.Append | get-delegate string"
assert-true {
$sb = new-object text.stringbuilder
$delegate = $sb.AppendFormat | get-delegate string, int, int
$delegate -is [System.Func[string,object,object,System.Text.StringBuilder]]
} -name "`$sb.AppendFormat | get-delegate string, int, int"
|
PowerShellCorpus/PoshCode/Show-NodeXLMap.ps1
|
Show-NodeXLMap.ps1
|
# Author: Doug Finke http://www.dougfinke.com/blog/
# Originally Posted: 08/13/08 (Microsoft Research .NetMap and PowerShell)
# http://www.dougfinke.com/blog/?p=465
# Modified by Steven Murawski http://www.mindofroot.com
# Updated to use the new project name "NodeXL"
# Added support for coloring the labels
# By adding a color property to the input objects, the source and target vertices
# will show with that color. If the source vertex already exists, its color will
# not be changed.
# Date: 12/15/2008
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[Reflection.Assembly]::Loadfrom("$pwd\\Microsoft.NodeXL.Control.dll") | Out-Null
function Add-Edge($source, $target, $color)
{
[Microsoft.NodeXL.Core.IVertex]$sourceVertex=$null
$res=$netMapControl.Graph.Vertices.Find($source, [ref] $sourceVertex)
if ($sourceVertex -eq $null)
{
$sourceVertex = $netMapControl.Graph.Vertices.Add()
$sourceVertex.Name = $source
$sourceVertex.SetValue("~PVLDPrimaryLabel", $source)
if ($color -ne $null)
{
$sourceVertex.SetValue("~PVLDPrimaryLabelFillColor", [System.Drawing.Color]::$color )
}
}
[Microsoft.NodeXL.Core.IVertex]$targetVertex=$null
$res=$netMapControl.Graph.Vertices.Find($target, [ref] $targetVertex)
if ($targetVertex -eq $null)
{
$targetVertex = $netMapControl.Graph.Vertices.Add()
$targetVertex.Name = $target
$targetVertex.SetValue("~PVLDPrimaryLabel", $target)
if ($color -ne $null)
{
$targetVertex.SetValue("~PVLDPrimaryLabelFillColor", [System.Drawing.Color]::$color )
}
}
$edge=$netMapControl.Graph.Edges.Add($sourceVertex, $targetVertex, $true)
}
function Show-NodeXLMap($layoutType="circular") {
Begin {
$form = New-Object Windows.Forms.Form
$netMapControl = New-Object Microsoft.NodeXL.Visualization.NodeXLControl
$netMapControl.Dock = "Fill"
$netMapControl.VertexDrawer = new-object Microsoft.NodeXL.Visualization.PerVertexWithLabelDrawer
$netMapControl.EdgeDrawer = new-object Microsoft.NodeXL.Visualization.PerEdgeWithLabelDrawer
$netMapControl.BeginUpdate()
}
Process {
if($_) {
Add-Edge $_.Source $_.Target $_.Color
}
}
End {
switch -regex ($layoutType) {
"C" { $Layout = New-Object Microsoft.NodeXL.Visualization.CircleLayout }
"S" { $Layout = New-Object Microsoft.NodeXL.Visualization.SpiralLayout }
"H" { $Layout = New-Object Microsoft.NodeXL.Visualization.SinusoidHorizontalLayout }
"V" { $Layout = New-Object Microsoft.NodeXL.Visualization.SinusoidVerticalLayout }
"G" { $Layout = New-Object Microsoft.NodeXL.Visualization.GridLayout }
"F" { $Layout = New-Object Microsoft.NodeXL.Visualization.FruchtermanReingoldLayout }
"R" { $Layout = New-Object Microsoft.NodeXL.Visualization.RandomLayout }
"Y" { $Layout = New-Object Microsoft.NodeXL.Visualization.SugiyamaLayout }
}
$netMapControl.Layout=$layout
$netMapControl.EndUpdate()
$form.Controls.Add($NetMapControl)
$form.WindowState="Maximized"
#$form.Size = New-Object Drawing.Size @(1000, 600)
$form.ShowDialog() | out-null
}
}
|
PowerShellCorpus/PoshCode/Exchange Services.ps1
|
Exchange Services.ps1
|
#Requires input from the user
$Server = read-host "Enter Exchange Server Name"
#Finds only the services that contain "Exchange"
$Status = (Get-Service -ComputerName $server |Where-object {$_.Displayname -like "*Exchange*"})
#Displays which Exchange Services are stopped
foreach ($Name in $status) {
IF ($Name.status -eq "Stopped"){Write-Host $Name.displayname "was stopped" -foreground red}}
#Starts all stopped services
foreach ($Name in $status) {
IF ($Name.status -eq "Stopped"){Start-Service -InputObject $Name}}
#Displays all Exchange services and their Status
Get-Service -ComputerName $server |Where-object {$_.Displayname -like "*Exchange*"
}
|
PowerShellCorpus/PoshCode/Get-WMIVersions.ps1
|
Get-WMIVersions.ps1
|
param ( $Credential, $ComputerName )
# The official way to detect .NET versions is to look at their known location on the hard drive as per
# this article: http://msdn.microsoft.com/en-us/kb/kb00318785.aspx
# thanks to David M (http://twitter.com/makovec) for the WQL
$query = "select name from win32_directory where name like 'c:\\\\windows\\\\microsoft.net\\\\framework\\\\v%'"
$res = Get-WmiObject -query $query -Credential $Credential -ComputerName $ComputerName | ForEach-Object {
Split-Path $_.name -Leaf } | # returns directories
Where-Object { $_ -like 'v*' } | # only include those that start with v
ForEach-Object { [system.version]( $_ -replace "^v" ) } # remove "v" from the string and convert to version object
# Create hashtable with computername and version details
$prop = @{
ComputerName = $ComputerName
V1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 0 } ) { $true } }
V1_1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 1 } ) { $true } }
V2Present = &{ if ( $res | Where-Object { $_.Major -eq 2 -and $_.Minor -eq 0 } ) { $true } }
V3_5Present = &{ if ( $res | Where-Object { $_.Major -eq 3 -and $_.Minor -eq 5 } ) { $true } }
VersionDetails = $res
}
# Create and output PSobject using hashtable
New-Object PSObject -Property $prop
|
PowerShellCorpus/PoshCode/2nd Line Support.ps1
|
2nd Line Support.ps1
|
##Creates variable for filename
$date = (get-date).tostring("yyyy-MM-dd")
$filename = "H:\\dailychecks\\checks_$date.xls"
## Imports exchange modules
Import-Module "\\\\emailserver\\c$\\PS Modules\\vamail.videoarts.info.psm1"
## Start Internet Explorer to check that Video Arts website is up
Start-Process iexplore.exe
## Creates new excel object
$erroractionpreference = "SilentlyContinue"
$a = New-Object -comobject Excel.Application
$a.visible = $True
##creates workbook and three worksheets. Names three worksheets.
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$d = $b.Worksheets.Item(2)
$e = $b.Worksheets.Item(3)
$b.name = "$title"
$c.name = "Stopped Services"
$d.name = "Free Disk Space"
$e.name = "Server Connectivity"
##Populates cells with the titles
$c.Cells.Item(1,1) = "STOPPED SERVICES"
$c.Cells.Item(2,1) = "Machine Name"
$c.Cells.Item(2,2) = "Service Name"
$c.Cells.Item(2,3) = "State"
$d.Cells.Item(1,1) = "FREE DISK SPACE"
$d.Cells.Item(2,1) = "Machine Name"
$d.Cells.Item(2,2) = "Drive"
$d.Cells.Item(2,3) = "Total size (MB)"
$d.Cells.Item(2,4) = "Free Space (MB)"
$d.Cells.Item(2,5) = "Free Space (%)"
$e.Cells.Item(1,1) = "SERVER CONNECTIVITY"
$e.Cells.Item(2,1) = "Server Name"
$e.Cells.Item(2,2) = "Server Status"
##Changes colours and fonts for header sections populated above
$c = $c.UsedRange
$c.Interior.ColorIndex = 19
$c.Font.ColorIndex = 11
$c.Font.Bold = $True
$d = $d.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$e = $e.UsedRange
$e.Interior.ColorIndex = 19
$e.Font.ColorIndex = 11
$e.Font.Bold = $True
$e.EntireColumn.AutoFit()
##sets variables for the row in which data will start populating
$servRow = 3
$diskRow = 3
$pingRow = 3
###Create new variable to run connectivity check###
$colservers = Get-Content "C:\\dailychecks\\Servers.txt"
foreach ($strServer in $colservers)
##Populate computer names in first column
{
$e.Cells.Item($pingRow, 1) = $strServer.ToUpper()
## Create new object to ping computers, if they are succesful populate cells with green/success, if anything else then red/offline
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.send($strServer)
if ($Reply.status –eq “Success”)
{
$rightcolor = $e.Cells.Item($pingRow, 2)
$e.Cells.Item($pingRow, 2) = “Online”
$rightcolor.interior.colorindex = 10
}
else
{
$wrongcolor = $e.Cells.Item($pingRow, 2)
$e.Cells.Item($pingRow, 2) = "Offline"
$wrongcolor.interior.colorindex = 3
}
$Reply = ""
##Set looping variable so that one cell after another populates rather than the same cell getting overwritten
$pingRow = $pingRow + 1
##Autofit collumnn
$e.EntireColumn.AutoFit()
}
##gets each computer
$colComputers = get-content "C:\\dailychecks\\Servers.txt"
foreach ($strComputer in $colComputers)
{
##gets each service with startmode 'Auto' and state 'Stopped' for each computer
$stoppedservices = get-wmiobject Win32_service -computername $strComputer | where{$_.StartMode -eq "Auto" -and $_.State -eq "stopped"}
foreach ($objservice in $stoppedservices)
{
##Populates cells
$c.Cells.Item($servRow, 1) = $strComputer.ToUpper()
$c.Cells.Item($servRow, 2) = $objService.Name
$c.Cells.Item($servRow, 3) = $objService.State
$servRow = $servRow + 1
$c.EntireColumn.AutoFit()
}
##Gets disk information for each computer
$colDisks = get-wmiobject Win32_LogicalDisk -computername $strComputer -Filter "DriveType = 3"
foreach ($objdisk in $colDisks)
{
##Populates cells
$d.Cells.Item($diskRow, 1) = $strComputer.ToUpper()
$d.Cells.Item($diskRow, 2) = $objDisk.DeviceID
$d.Cells.Item($diskRow, 3) = "{0:N0}" -f ($objDisk.Size/1024/1024)
$d.Cells.Item($diskRow, 4) = "{0:N0}" -f ($objDisk.FreeSpace/1024/1024)
$d.Cells.Item($diskRow, 5) = "{0:P0}" -f ([double]$objDisk.FreeSpace/[double]$objDisk.Size)
$diskRow = $diskRow + 1
$d.EntireColumn.AutoFit()
}
}
##Saves file using Filename variable set at the top of the document
$b.SaveAs($filename, 1)
|
PowerShellCorpus/PoshCode/Get-StrictMode_1.psm1.ps1
|
Get-StrictMode_1.psm1.ps1
|
function Get-Version {
<#
.SYNOPSIS
V2.0 Incorporate Version() and ToString() Methods, 1 Jan 2012.
A very simple module to retrieve the Set-StrictMode setting of the user
session.
.DESCRIPTION
This procedure is necessary as there is, apparently, no equivalent Power-
Shell variable for this and it enables the setting to be returned to its
original state after possibly being changed within a script.
.EXAMPLE
Get-StrictMode
The various values returned will be Version 1, Version 2, or Off.
.EXAMPLE
$a = (Get-StrictMode).Version()
This will allow the environment to be restored just by entering the commmand
Invoke-Expression "Set-StrictMode $a"
#>
$version = '0'
try {
$version = '2'
$z = "2 * $nil" #V2 will catch this one.
$version = '1'
$z = 2 * $nil #V1 will catch this.
$version = 'Off'
}
catch {
}
New-Module -ArgumentList $version -AsCustomObject {
param ($version)
function Version() {
if ($version -eq 'Off') {
$output = '-Off'
}
else {
$output = "-Version $version"
}
"$output" #(Get-StrictMode).Version()
}
function ToString() {
$output = $version
if ($version -ne 'Off') {
$output = "Version $version"
}
"StrictMode: $output" #Get-StrictMode output string.
}
Export-ModuleMember -function Version,ToString
}
}
|
PowerShellCorpus/PoshCode/ISE NativeConsole Hooks.ps1
|
ISE NativeConsole Hooks.ps1
|
# Uses NativeConsole, which is available under a bunch of Open Source licenses
# http://poshconsole.codeplex.com/SourceControl/changeset/view/f9bb2b127402#Huddled/Interop/NativeConsole.cs
add-type -Path ~\\Projects\\PoshConsole\\Huddled\\Interop\\NativeConsole.cs
$NativeConsole = New-Object Huddled.Interop.NativeConsole
$ConsoleError = Register-ObjectEvent -InputObject $NativeConsole -EventName WriteError -Action {
Add-Content -Path $Pwd\\Error.log -Value $EventArgs.Text
Add-Content -Path $Pwd\\Output.log -Value $EventArgs.Text
Write-Error $EventArgs.Text
# Fake output, so I get to see it immediately
Write-Host $EventArgs.Text -ForegroundColor Red
}
$ConsoleOutput = Register-ObjectEvent -InputObject $NativeConsole -EventName WriteOutput -Action {
Add-Content -Path $Pwd\\Output.log -Value $EventArgs.Text
Write-Output $EventArgs.Text
# Fake output, so I get to see it immediately
Write-Host $EventArgs.Text
}
# Now just call any console app, because NativeConsole's going to handle the output
cmd /c "dir && dir brokenthing"
# To get the real output, receive-it
function receive-output {
Receive-Job $ConsoleOutput, $ConsoleError
}
|
PowerShellCorpus/PoshCode/Get-NetworkStatistics.ps1
|
Get-NetworkStatistics.ps1
|
function Get-NetworkStatistics
{
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding(DefaultParameterSetName='name')]
param(
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='port')]
[System.Int32]$Port='*',
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='name')]
[System.String]$ProcessName='*',
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='address')]
[System.String]$Address='*',
[Parameter()]
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[Parameter()]
[ValidateSet('*','Closed','CloseWait','Closing','DeleteTcb','Established','FinWait1','FinWait2','LastAck','Listen','SynReceived','SynSent','TimeWait','Unknown')]
[System.String]$State='*'
)
begin
{
$properties = 'Protocol','LocalAddress','LocalPort'
$properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
}
process
{
netstat -ano | Select-String -Pattern '\\s+(TCP|UDP)' | ForEach-Object {
$item = $_.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\\[::')
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\\]:')[-1]
}
else
{
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\\]:')[-1]
}
else
{
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
$procId = $item[-1]
$procName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
$pso = New-Object -TypeName PSObject -Property @{
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
if($PSCmdlet.ParameterSetName -eq 'port')
{
if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port)
{
if($pso.Protocol -like $Protocol -and $pso.State -like $State)
{
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'address')
{
if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address)
{
if($pso.Protocol -like $Protocol -and $pso.State -like $State)
{
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'name')
{
if($pso.ProcessName -like $ProcessName)
{
if($pso.Protocol -like $Protocol -and $pso.State -like $State)
{
$pso
}
}
}
}
}
}
<#
.SYNOPSIS
Displays the current TCP/IP connections.
.DESCRIPTION
Displays active TCP connections and includes the process ID (PID) and Name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
CloseWait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
DeleteTcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
FinWait1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
FinWait2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
LastAck - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
SynReceived - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
SynSent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
TimeWait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
.EXAMPLE
Get-NetworkStatistics
.EXAMPLE
Get-NetworkStatistics iexplore
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy
Blog : http://PowerShay.com
#>
}
help Get-NetworkStatistics
|
PowerShellCorpus/PoshCode/Reflection Module_3.ps1
|
Reflection Module_3.ps1
|
#requires -version 2.0
# ALSO REQUIRES Autoload for some functionality
# You should create a Reflection.psd1 with the contents: @{ RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="3.5.0.0" }
#History:
# 1.0 - First public release (March 19, 2010)
# 2.0 - Private Build
# - Included the Accelerator function inline
# - Added a few default aliases
# 3.0 - September 3, 2010
# - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!)
# - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312
# 3.5 - January 28, 2011
# - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature
# - Fixed alias exporting so aliases will show up now
# - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies
# 3.6 - January 28, 2011
# - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin
# 3.7 - February 1, 2001 - NOT RELEASED
# - Added [TransformAttribute] type
# 3.8 - May 4, 2011 - NOT RELEASED
# - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649)
# 3.9 - May 25, 2011 - NOT RELEASED
# - Added "Interface" parameter to Get-Type
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Collections.ObjectModel;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TransformAttribute : ArgumentTransformationAttribute {
private ScriptBlock _scriptblock;
private string _noOutputMessage = "Transform Script had no output.";
public override string ToString() {
return string.Format("[Transform(Script='{{{0}}}')]", Script);
}
public override Object Transform( EngineIntrinsics engine, Object inputData) {
try {
Collection<PSObject> output =
engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData );
if(output.Count > 1) {
Object[] transformed = new Object[output.Count];
for(int i =0; i < output.Count;i++) {
transformed[i] = output[i].BaseObject;
}
return transformed;
} else if(output.Count == 1) {
return output[0].BaseObject;
} else {
throw new ArgumentTransformationMetadataException(NoOutputMessage);
}
} catch (ArgumentTransformationMetadataException) {
throw;
} catch (Exception e) {
throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e);
}
}
public TransformAttribute() {
this.Script = ScriptBlock.Create("{`$args}");
}
public TransformAttribute( ScriptBlock Script ) {
this.Script = Script;
}
public ScriptBlock Script {
get { return _scriptblock; }
set { _scriptblock = value; }
}
public string NoOutputMessage {
get { return _noOutputMessage; }
set { _noOutputMessage = value; }
}
}
"@
function Get-Type {
<#
.Synopsis
Gets the types that are currenty loaded in .NET, or gets information about a specific type
.Description
Gets information about one or more loaded types, or gets the possible values for an enumerated type or value.
.Parameter Assembly
The Assemblies to search for types.
Can be an actual Assembly object or a regex to pass to Get-Assembly.
.Parameter TypeName
The type name(s) to search for (wildcard patterns allowed).
.Parameter BaseType
A Base type they should derive from (wildcard patterns allowed).
.Parameter Interface
An interface they should implement (wildcard patterns allowed).
.Parameter Enum
An enumeration to list all of enumeration values for
.Parameter Namespace
A namespace to restrict where we selsect types from (wildcard patterns allowed).
.Parameter Force
Causes Private types to be included
.Example
Get-Type
Gets all loaded types (takes a VERY long time to print out)
.Example
Get-Type -Assembly ([PSObject].Assembly)
Gets types from System.Management.Automation
.Example
[Threading.Thread]::CurrentThread.ApartmentState | Get-Type
Gets all of the possible values for the ApartmentState property
.Example
[Threading.ApartmentState] | Get-Type
Gets all of the possible values for an apartmentstate
#>
[CmdletBinding(DefaultParameterSetName="Assembly")]
param(
# The assembly to collect types from
[Parameter(ValueFromPipeline=$true)]
[PsObject[]]$Assembly
,
# The type names to return from
[Parameter(Mandatory=$false,Position=0)]
[String[]]$TypeName
,
# The type names to return from
[Parameter(Mandatory=$false)]
[String[]]$Namespace
,
# A Base Type they should derive from
[Parameter(Mandatory=$false)]
[String[]]$BaseType
,
# An Interface they should implement
[Parameter(Mandatory=$false)]
[String[]]$Interface
,
# The enumerated value to get all of the possibilties of
[Parameter(ParameterSetName="Enum")]
[PSObject]$Enum
,
[Parameter()][Alias("Private","ShowPrivate")]
[Switch]$Force
)
process {
if($psCmdlet.ParameterSetName -eq 'Enum') {
if($Enum -is [Enum]) {
[Enum]::GetValues($enum.GetType())
} elseif($Enum -is [Type] -and $Enum.IsEnum) {
[Enum]::GetValues($enum)
} else {
throw "Specified Enum is neither an enum value nor an enumerable type"
}
}
else {
if($Assembly -as [Reflection.Assembly[]]) {
## This is what we expected, move along
} elseif($Assembly -as [String[]]) {
$Assembly = Get-Assembly $Assembly
} elseif(!$Assembly) {
$Assembly = [AppDomain]::CurrentDomain.GetAssemblies()
}
:asm foreach ($asm in $assembly) {
Write-Verbose "Testing Types from Assembly: $($asm.Location)"
if ($asm) {
trap {
if( $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) {
$PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail")
continue asm
}
Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail"
Write-Debug $( $_.Exception.LoaderExceptions | Out-String )
continue asm
}
$asm.GetTypes() | Where {
( $Force -or $_.IsPublic ) -AND
( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND
( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND
( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND
( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 )
}
}
}
}
}
}
function Add-Assembly {
#.Synopsis
# Load assemblies
#.Description
# Load assemblies from a folder
#.Parameter Path
# Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#.Parameter Passthru
# Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output.
# Aliased to -Types
#.Parameter Recurse
# Gets the items in the specified locations and in all child items of the locations.
#
# Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("PSPath")]
[string[]]$Path = "."
,
[Alias("Types")]
[Switch]$Passthru
,
[Switch]$Recurse
)
process {
foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) {
Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic }
}
}
}
function Get-Assembly {
<#
.Synopsis
Get a list of assemblies available in the runspace
.Description
Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match
.Parameter Name
A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true, Position=0)]
[string[]]$Name = ''
)
process {
[appdomain]::CurrentDomain.GetAssemblies() | Where {
$Assembly = $_
if($Name){
$(
foreach($n in $Name){
if(Resolve-Path $n -ErrorAction 0) {
$n = [Regex]::Escape( (Resolve-Path $n).Path )
}
$Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n)
}
) -contains $True
} else { $true }
}
}
}
function Update-PSBoundParameters {
#.Synopsis
# Ensure a parameter value is set
#.Description
# Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it.
#.Parameter Name
# The name (key) of the parameter you want to set in PSBoundParameters
#.Parameter Default
# A Default value for the parameter, in case it's not already set
#.Parameter Min
# The Minimum allowed value for the parameter
#.Parameter Max
# The Maximum allowed value for the parameter
#.Parameter PSBoundParameters
# The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it)
Param(
[Parameter(Mandatory=$true, Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false, Position=1)]
$Default
,
[Parameter()]
$Min
,
[Parameter()]
$Max
,
[Parameter(Mandatory=$true, Position=99)]
$PSBoundParameters=$PSBoundParameters
)
end {
$outBuffer = $null
## If it's not set, and you passed a default, we set it to the default
if($Default) {
if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer))
{
$PSBoundParameters[$Name] = $Default
}
}
## If you passed a $max, and it's set greater than $max, we set it to $max
if($Max) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max)
{
$PSBoundParameters[$Name] = $Max
}
}
## If you passed a $min, and it's set less than $min, we set it to $min
if($Min) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min)
{
$PSBoundParameters[$Name] = $Min
}
}
$PSBoundParameters
}
}
function Get-Constructor {
<#
.Synopsis
Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type.
.Description
Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor.
.Parameter Type
The type to get the constructor for
.Parameter Force
Force inclusion of Private and Static constructors which are hidden by default.
.Parameter NoWarn
Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors.
.Example
Get-Constructor System.IO.FileInfo
Description
-----------
Gets all the information about the single constructor for a FileInfo object.
.Example
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax
Description
-----------
Displays the constructor syntax for all of the *Info objects in the System.IO namespace.
Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors.
.Example
$path = $pwd
$driveName = $pwd.Drive
$fileName = "$Profile"
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax }
Description
-----------
Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo.
Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("ParameterType")]
[Type]$Type
, [Switch]$Force
, [Switch]$NoWarn
)
process {
$type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *,
@{ name = "TypeName"; expression = { $_.ReflectedType.FullName } },
@{ name = "Definition";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "Syntax";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "SafeSyntax";
expression = {Get-MemberSignature $_}
}
if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" }
}
}
function Get-Method {
<#
.Synopsis
Returns MethodInfo for the (public) methods of the specified Type.
.Description
Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method.
.Parameter Type
The type to get methods on
.Parameter Name
The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns)
.Parameter Force
Force inclusion of Private methods and property accessors which are hidden by default.
#>
[CmdletBinding(DefaultParameterSetName="Type")]
param(
[Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Type]$Type
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)]
[String[]]$Name ="*"
, [Switch]$Definition
, [Switch]$Force
)
process {
foreach($method in
$type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } |
# Hide the Property accessor methods
Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } |
Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } )
{
$method |
Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru |
Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member AliasProperty Syntax Definition -Passthru |
#Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru
}
}
}
function Get-MemberSignature {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
[System.Reflection.MethodBase]$MethodBase,
[Switch]$Simple
)
process {
$parameters = $(
foreach($param in $MethodBase.GetParameters()) {
# Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan
Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)"
if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' }
if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' }
if($Simple) {
'{0} {1}' -f $param.ParameterType.ToString(), $param.Name
} else {
'{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.ToString().TrimEnd('&'), $param.Name
}
}
)
if($MethodBase.IsConstructor) {
"New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')"
} elseif($Simple) {
"$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))"
} elseif($MethodBase.IsStatic) {
"[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))"
} else {
"[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))"
}
}
}
function Read-Choice {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[hashtable[]]$Choices
,
[Parameter(Mandatory=$False)]
[string]$Caption = "Please choose!"
,
[Parameter(Mandatory=$False)]
[string]$Message = "Choose one of the following options:"
,
[Parameter(Mandatory=$False)]
[int[]]$Default = 0
,
[Switch]$MultipleChoice
,
[Switch]$Passthru
)
begin {
[System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() }
}
process {
$Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $(
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value
}
) )
if(!$MultipleChoice) { [int]$Default = $Default[0] }
[int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default)
if($Passthru) {
Write-Verbose "$Answer"
Write-Output $Descriptions[$Answer]
} else {
Write-Output $Answer
}
}
}
function Get-Argument {
param(
[Type]$Target
, [ref]$Method
, [Array]$Arguments
)
end {
trap {
write-error $_
break
}
$flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance"
[Type[]]$Types = @(
foreach($arg in $Arguments) {
if($arg -is [type]) {
$arg
}
else {
$arg.GetType()
}
}
)
try {
Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)"
$MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null)
$Arguments
if($MethodBase) {
$Method.Value = $MethodBase.Name
}
} catch { }
if(!$MethodBase) {
Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):"
$MethodBase = Get-Method $target $($Method.Value)
if(@($MethodBase).Count -gt 1) {
$i = 0
$i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:"
[System.Reflection.MethodBase]$MethodBase = $MethodBase[$i]
}
ForEach($parameter in $MethodBase.GetParameters()) {
$found = $false
For($a =0;$a -lt $Arguments.Count;$a++) {
if($argument[$a] -as $parameter.ParameterType) {
Write-Output $argument[$a]
if($a -gt 0 -and $a -lt $Arguments.Count) {
$Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a)
} elseif($a -eq 0) {
$Arguments = $Arguments | Select -Last ($Arguments.Count - 1)
} else { # a -eq count
$Arguments = $Arguments | Select -First ($Arguments.Count - 1)
}
$found = $true
break
}
}
if(!$Found) {
$userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)"
if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) {
Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType)
} else {
Write-Output ($userInput -as $parameter.ParameterType)
}
}
}
}
}
}
function Invoke-Member {
[CmdletBinding()]
param(
[parameter(position=10, valuefrompipeline=$true, mandatory=$true)]
[allowemptystring()]
$InputObject
,
[parameter(position=0, mandatory=$true)]
[validatenotnullorempty()]
$Member
,
[parameter(position=1, valuefromremainingarguments=$true)]
[allowemptycollection()]
$Arguments
,
[parameter()]
[switch]$Static
)
# begin {
# if(!(get-member SafeSyntax -input $Member -type Property)){
# if(get-member Name -inpup $Member -Type Property) {
# $Member = Get-Method $InputObject $Member.Name
# } else {
# $Member = Get-Method $InputObject $Member
# }
# }
# $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax )
# }
process {
# if ($InputObject)
# {
# if ($InputObject | Get-Member $Member -static:$static)
# {
if ($InputObject -is [type]) {
$target = $InputObject
} else {
$target = $InputObject.GetType()
}
if(Get-Member $Member -InputObject $InputObject -Type Properties) {
$_.$Member
}
elseif($Member -match "ctor|constructor") {
$Member = ".ctor"
[System.Reflection.BindingFlags]$flags = "CreateInstance"
$InputObject = $Null
}
else {
[System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod"
if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" }
}
[ref]$Member = $Member
[Object[]]$Parameters = Get-Argument $Target $Member $Arguments
[string]$Member = $Member.Value
Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ")
try {
Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))"
Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))"
$target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters)
} catch {
Write-Warning $_.Exception
if ($_.Exception.Innerexception -is [MissingMethodException]) {
write-warning "Method argument count (or type) mismatch."
}
}
# } else {
# write-warning "Method $Member not found."
# }
# }
}
}
function Invoke-Generic {
#.Synopsis
# Invoke Generic method definitions via reflection:
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('On')]
$InputObject
,
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
[Alias('Named')]
[string]$MethodName
,
[Parameter(Position=2)]
[Alias("Types")]
[Type[]]$ParameterTypes
,
[Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
[Object[]]$WithArgs
,
[Switch]$Static
)
begin {
if($Static) {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static"
} else {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance"
}
}
process {
$Type = $InputObject -as [Type]
if(!$Type) { $Type = $InputObject.GetType() }
if($WithArgs -and -not $ParameterTypes) {
$ParameterTypes = $withArgs | % { $_.GetType() }
} elseif(!$ParameterTypes) {
$ParameterTypes = [Type]::EmptyTypes
}
trap { continue }
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags)
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null)
}
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object {
$MI = $_
[bool]$Accept = $MI.Name -eq $MethodName
if($Accept){
Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)"
[Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name)
[Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value {
$GenericTypes -Contains $this.ParameterType
} -Passthru)
$Accept = $ParameterTypes.Count -eq $Parameters.Count
Write-Verbose " $Accept = $($Parameters.Count) Arguments"
if($Accept) {
for($i=0;$i -lt $Parameters.Count;$i++) {
$Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType))
Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)"
}
}
}
return $Accept
} | Sort { @($_.GetGenericArguments()).Count } | Select -First 1
}
Write-Verbose "Time to make generic methods."
Write-Verbose $MemberInfo
[Type[]]$GenericParameters = @()
[Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType)
for($i=0;$i -lt $ParameterTypes.Count;$i++){
Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])"
if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) {
$GenericParameters += $ParameterTypes[$i]
}
$ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru
}
$ParameterTypes | Where-Object { $_.IsGeneric }
Write-Verbose "$($GenericParameters -join ', ') generic parameters"
$MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters )
Write-Verbose $MemberInfo
if($WithArgs) {
[Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')"
$MemberInfo.Invoke( $InputObject, $Arguments )
} else {
$MemberInfo.Invoke( $InputObject )
}
} }
# get a reference to the Type
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
function Import-Namespace {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]$Namespace
,
[Switch]$Force
)
Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator
}
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
$xlr8r::Add( $a, $Type)
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
param(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type[]]$Type
)
process {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","FullName")]
[string[]]$Accelerator
)
process {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
###############################################################################
##### Imported from PowerBoots
$Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree'
$DependencyProperties = @{}
if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) {
#$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) )
$DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml
}
function Get-ReflectionModule { $executioncontext.sessionstate.module }
function Set-ObjectProperties {
[CmdletBinding()]
param( $Parameters, [ref]$DObject )
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() }
if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White }
foreach ($param in $Parameters) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" }
## INGORE DEPENDENCY PROPERTIES FOR NOW :)
if($param.Key -eq "DependencyProps") {
## HANDLE EVENTS ....
}
elseif ($param.Key.StartsWith("On_")) {
$EventName = $param.Key.SubString(3)
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" }
$sb = $param.Value -as [ScriptBlock]
if(!$sb) {
$sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock
}
$Dobject.Value."Add_$EventName".Invoke( $sb );
# $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) );
# $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) );
} ## HANDLE PROPERTIES ....
else {
try {
## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here.
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray
}
if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) {
$Values = @()
foreach($sb in $param.Value) {
$Values += & (Get-ReflectionModule) $sb
}
} else {
$Values = $param.Value
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green }
Set-Property $Dobject $Param.Key $Values
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta }
if($DebugPreference -ne "SilentlyContinue") {
if( $Dobject.Value.$($param.Key) -ne $null ) {
Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green
}
}
}
catch [Exception]
{
Write-Host "COUGHT AN EXCEPTION" -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
while($DependencyProps) {
$name, $value, $DependencyProps = $DependencyProps
$name = ([string]@($name)[0]).Trim("-")
if($name -and $value) {
Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value
}
}
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host }
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() }
}
function Set-Property {
PARAM([ref]$TheObject, $Name, $Values)
$DObject = $TheObject.Value
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta }
$PropertyType = $DObject.GetType().GetProperty($Name).PropertyType
if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green}
# [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject )
# [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) )
# In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
[Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject )
[Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) )
$Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null
$TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() )
}
elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) {
$Binding = @($Values)[0];
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan}
if(!$Binding.Source -and !$Binding.ElementName) {
$Binding.Source = $DObject.DataContext
}
if($DependencyProperties.ContainsKey($Name)) {
$field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType)
if($field) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue }
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue}
$DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null
} else {
throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )"
}
} else {
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan
}
try {
$DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null
# $DObject.Add_Loaded( {
# $this.SetBinding( ($this.GetType())::ItemsSourceProperty, (Binding -Source $this.DataContext) )
# } )
if($DebugPreference -ne "SilentlyContinue") {
Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow
}
} catch {
Write-Host "Nope, was not able to set it." -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
}
elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) {
if($Values -is [System.Collections.IEnumerable]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan }
$DObject.$($Name) = $Values
} else {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan }
$DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]"
$DObject.$($Name).Add($Values)
}
}
elseif($DObject.$($Name) -is [System.Collections.IList]) {
foreach ($value in @($Values)) {
try {
$null = $DObject.$($Name).Add($value)
}
catch
{
# Write-Host "CAUGHT array problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) )
} else {
Write-Error $_.Exception
throw
}
}
}
}
else {
## If they pass an array of 1 when we only want one, we just use the first value
if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White}
try {
$DObject.$($Name) = $Values[0]
}
catch [Exception]
{
# Write-Host "CAUGHT collection value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $Values[0]) )
}else {
throw
}
}
}
else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings
{
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan}
try {
$DObject.$($Name) = $Values
} catch [Exception]
{
# Write-Host "CAUGHT value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $values) )
}else {
throw
}
}
}
}
}
function Set-DependencyProperty {
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true)]
$Property
,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Element
,
[Parameter()]
[Switch]$Passthru
)
DYNAMICPARAM {
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
$Param1 = new-object System.Management.Automation.RuntimeDefinedParameter
$Param1.Name = "Value"
# $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) )
$Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) )
if( $Property ) {
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])))
{
$Param1.ParameterType = $Property.PropertyType
}
elseif($Property -is [string] -and $Property.Contains(".")) {
$Class,$Property = $Property.Split(".")
if($DependencyProperties.ContainsKey($Property)){
$type = $DependencyProperties.$Property.Keys -like "*$Class"
if($type) {
$Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType
}
}
} elseif($DependencyProperties.ContainsKey($Property)){
if($Element) {
if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) {
$Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType
}
} else {
$Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType
}
}
else
{
$Param1.ParameterType = [PSObject]
}
}
else
{
$Param1.ParameterType = [PSObject]
}
$paramDictionary.Add("Value", $Param1)
return $paramDictionary
}
PROCESS {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red
continue
}
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))
){
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red
continue
}
$Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType))
}
else {
if("$Property".Contains(".")) {
$Class,$Property = "$Property".Split(".")
}
if( $DependencyProperties.ContainsKey("$Property" ) ) {
$fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } )
if($fields.Count -eq 0 ) {
$fields = @($DependencyProperties.$Property.Keys -like "*$Class" )
}
if($fields.Count) {
$success = $false
foreach($field in $fields) {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red
continue
}
$Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType)))
if($?) { $success = $true; break }
}
if(!$success) {
throw "food"
}
} else {
Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red
}
}
else {
Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red
}
}
if( $Passthru ) { $Element }
}
}
Add-Type -Assembly WindowsBase
function Add-ConstructorFunction {
<#
.Synopsis
Add support for a new class by creating the dynamic constructor function(s).
.Description
Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias.
Exposes all of the properties and events of the type as perameters to the function.
NOTE: The Type MUST have a default parameterless constructor.
.Parameter Assembly
The Assembly you want to generate constructors for. All public types within it will be generated if possible.
.Parameter Type
The type you want to create a constructor function for. It must have a default parameterless constructor.
.Example
Add-ConstructorFunction System.Windows.Controls.Button
Creates a new function for the Button control.
.Example
[Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction
Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
.Example
Add-ConstructorFunction -Assembly PresentationFramework
Will create constructor functions for all the WPF components in the PresentationFramework assembly.
.Links
http://HuddledMasses.org/powerboots
.ReturnValue
The name(s) of the function(s) created -- so you can export them, if necessary.
.Notes
AUTHOR: Joel Bennett http://HuddledMasses.org
LASTEDIT: 2009-01-13 16:35:23
#>
[CmdletBinding(DefaultParameterSetName="FromType")]
PARAM(
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)]
[type[]]$type
,
[Alias("FullName")]
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)]
[string[]]$Assembly
,
[Parameter()]
[string]$Path = "$PSScriptRoot\\Types_Generated"
,
[switch]$Force
,
[switch]$ShortAliases
,
[Switch]$Quiet
)
BEGIN {
[Type[]]$Empty=@()
if(!(Test-Path $Path)) {
MkDir $Path
}
$ErrorList = @()
}
END {
#Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties ))
Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties
if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." }
$ErrorList | Write-Error
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "FromAssembly") {
[type[]]$type = @()
foreach($lib in $Assembly) {
$asm = $null
trap { continue }
if(Test-Path $lib) {
$asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") )
}
if(!$asm) {
## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5
$asm = [Reflection.Assembly]::LoadWithPartialName( $lib )
}
if($asm) {
$type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and
!$_.IsAbstract -and !$_.IsInterface -and
$_.GetConstructor( "Instance,Public", $Null, $Empty, @() )}
} else {
Write-Error "Can't find the assembly $lib, please check your spelling and try again"
}
}
}
foreach($T in $type) {
$TypeName = $T.FullName
$ScriptPath = Join-Path $Path "New-$TypeName.ps1"
Write-Verbose $TypeName
## Collect all dependency properties ....
$T.GetFields() |
Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } |
ForEach-Object {
[string]$Field = $_.DeclaringType::"$($_.Name)".Name
[string]$TypeName = $_.DeclaringType.FullName
if(!$DependencyProperties.ContainsKey( $Field )) {
$DependencyProperties.$Field = @{}
}
$DependencyProperties.$Field.$TypeName = @{
Name = [string]$_.Name
PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName
}
}
if(!( Test-Path $ScriptPath ) -OR $Force) {
$Pipelineable = @();
## Get (or generate) a set of parameters based on the the Type Name
$PropertyNames = New-Object System.Text.StringBuilder "@("
$Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n"
## Add all properties
$Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") |
Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) }
$Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique
foreach ($p in $Properties) {
$null = $PropertyNames.AppendFormat(",'{0}'",$p.Name)
switch( $p.MemberType ) {
Event {
$null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name)
$null = $Parameters.AppendFormat(@'
[Parameter()]
[PSObject]${{On_{0}}}
,
'@, $p.Name)
}
Property {
if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") {
$null = $Parameters.AppendFormat(@'
[Parameter(Position=1,ValueFromPipeline=$true)]
[Object[]]${{{0}}}
,
'@, $p.Name)
$Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru)
}
elseif($p.PropertyType -eq [System.Boolean])
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Switch]${{{0}}}
,
'@, $p.Name)
}
else
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Object[]]${{{0}}}
,
'@, $p.Name)
}
}
}
}
$null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)]
[string[]]$DependencyProps
)')
$null = $PropertyNames.Remove(2,1).Append(')')
$collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true)
$ofs = "`n";
$function = $(
"
if(!( '$TypeName' -as [Type] )) {
$(
if( $T.Assembly.GlobalAssemblyCache ) {
" `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) "
} else {
" `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) "
}
)
}
## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) {
## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`"
## # `$scriptParam = `$PSBoundParameters
## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`"
## }
Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!""
function New-$TypeName {
<#
.Synopsis
Create a new $($T.Name) object
.Description
Generates a new $TypeName object, and allows setting all of it's properties.
(From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version))
.Notes
GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org
GENERATED : $(Get-Date)
ASSEMBLY : $($T.Assembly.FullName)
FULLPATH : $($T.Assembly.Location)
#>
$Parameters
BEGIN {
`$DObject = New-Object $TypeName
`$All = $PropertyNames
}
PROCESS {
"
if(!$collectable) {
"
# The content of $TypeName is not a collection
# So if we're in a pipeline, make a new $($T.Name) each time
if(`$_) {
`$DObject = New-Object $TypeName
}
"
}
@'
foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) {
$PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure()
}
Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject)
'@
if(!$collectable) {
@'
Microsoft.PowerShell.Utility\\Write-Output $DObject
} #Process
'@
} else {
@'
} #Process
END {
Microsoft.PowerShell.Utility\\Write-Output $DObject
}
'@
}
@"
}
## New-$TypeName `@PSBoundParameters
"@
)
Set-Content -Path $ScriptPath -Value $Function
}
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName"
}
}#PROCESS
}
function Import-ConstructorFunctions {
#.Synopsis
# Autoload pre-generated constructor functions and generate aliases for them.
#.Description
# Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory.
#.Parameter Path
# The path to a folder with functions to preload
param(
[Parameter()]
[Alias("PSPath")]
[string[]]$Path = "$PSScriptRoot\\Types_Generated"
)
end {
$Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" })
Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")"
foreach($script in Get-ChildItem $Paths -ErrorAction 0) {
$TypeName = $script.Name -replace 'New-(.*).ps1','$1'
$ShortName = ($TypeName -split '\\.')[-1]
Write-Verbose "Importing constructor for type: $TypeName ($ShortName)"
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-Autoload -Name $Script.FullName -Alias "New-$TypeName"
# Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String)
Get-Command "New-$TypeName"
}
}
}
#.Parameter Snapin
# The full path to where the snapin .dll is
#.Parameter OutputPath
# Force the module manifest(s) to output in a different location than where the snapin .dll is
#.Parameter ModuleName
# Override the snapin name(s) for the module manifest
#.Parameter Author
# Overrides the Company Name from the manifest when generating the module's "Author" comment
#.Parameter Passthru
# Returns the ModuleManifest (same as -Passthru on New-ModuleManifest)
#.Example
# New-ModuleManifestFromSnapin ".\\Quest Software\\Management Shell for AD" -ModuleName QAD
#
# Description
# -----------
# Generates a new module manifest file: QAD.psd1 in the folder next to the Quest.ActiveRoles.ArsPowerShellSnapIn.dll
#.Example
# New-ModuleManifestFromSnapin "C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\\" -Output $pwd
#
# Description
# -----------
# Generates module manifest files for the SqlServer PSSnapins and stores them in the current folder
function New-ModuleManifestFromSnapin {
param(
[Parameter(Mandatory=$true, Position="0", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[String[]]$Snapin
,
[Parameter()]
$OutputPath
,
[Parameter()]
$ModuleName
,
[Parameter()]
[String]$Author
,
[Switch]$Passthru
)
# $SnapinPath = $(Get-ChildItem $SnapinPath -Filter *.dll)
$EAP = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
Add-Assembly $Snapin
$ErrorActionPreference = $EAP
$SnapinTypes = Get-Assembly $Snapin | Get-Type -BaseType System.Management.Automation.PSSnapIn, System.Management.Automation.CustomPSSnapIn -WarningAction SilentlyContinue
foreach($SnapinType in $SnapinTypes) {
$Installer = New-Object $SnapinType
if(!$PSBoundParameters.ContainsKey("OutputPath")) {
$OutputPath = (Split-Path $SnapinType.Assembly.Location)
}
if(!$PSBoundParameters.ContainsKey("ModuleName")) {
$ModuleName = $Installer.Vendor
}
if(!$PSBoundParameters.ContainsKey("Author")) {
$Author = $Installer.Name
}
$ManifestPath = (Join-Path $OutputPath "$ModuleName.psd1")
Write-Verbose "Creating Module Manifest: $ManifestPath"
$RequiredAssemblies = @( $SnapinType.Assembly.GetReferencedAssemblies() | Get-Assembly | Where-Object { (Split-Path $_.Location) -eq (Split-Path $SnapinType.Assembly.Location) } | Select-Object -Expand Location | Resolve-Path -ErrorAction Continue)
# New-ModuleManifest has a bad bug -- it makes paths relative to the current location (and it does it wrong).
Push-Location $OutputPath
if($Installer -is [System.Management.Automation.CustomPSSnapIn]) {
$Cmdlets = $Installer.Cmdlets | Select-Object -Expand Name
$Types = $Installer.Types | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
$Formats = $Installer.Formats | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
} else {
$Types = $Installer.Types | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
$Formats = $Installer.Formats | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
}
if(!$Cmdlets) { $Cmdlets = "*" }
if(!$Types) { $Types = @() }
if(!$Formats) { $Formats = @() }
New-ModuleManifest -Path $ManifestPath -Author $Author -Company $Installer.Vendor -Description $Installer.Description `
-ModuleToProcess $SnapinType.Assembly.Location -Types $Types -Formats $Formats -Cmdlets $Cmdlets `
-RequiredAssemblies $RequiredAssemblies -Passthru:$Passthru `
-NestedModules @() -Copyright $Installer.Vendor -FileList @()
Pop-Location
}
}
###############################################################################
Add-Accelerator list System.Collections.Generic.List``1
Add-Accelerator dictionary System.Collections.Generic.Dictionary``2
Set-Alias aasm Add-Assembly
Set-Alias gt Get-Type
Set-Alias gasm Get-Assembly
Set-Alias gctor Get-Constru
|
PowerShellCorpus/PoshCode/Out-DataTable_6.ps1
|
Out-DataTable_6.ps1
|
#######################
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Fixed Issue with Properties
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
$DT.Columns.Add($Col)
}
if ($property.IsArray)
{ $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }
else { $DR.Item($property.Name) = $property.value }
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output @(,($dt))
}
} #Out-DataTable
|
PowerShellCorpus/PoshCode/PerformanceTracking.psm1.ps1
|
PerformanceTracking.psm1.ps1
|
$Parser = [System.Management.Automation.PsParser]
$script:lastMemory = Get-Process -id $PID
$global:LastTweets = new-object System.Collections.Generic.List[PSObject]
$global:PerformanceHistory = @{}
if(!(Test-Path Variable:PrePerformanceTrackingPrompt -EA 0)){
$Global:PrePerformanceTrackingPrompt = ${Function:Prompt}
}
function Global:Prompt {
$currMemory = Get-Process -id $PID
$lastCommand = Get-History -Count 1
$global:PerformanceHistory[$lastCommand.Id] = Get-Performance $lastCommand @{
PrivateMemoryDiff = $currMemory.PrivateMemorySize64 - $lastMemory.PrivateMemorySize64
VirtualMemoryDiff = $currMemory.VirtualMemorySize64 - $lastMemory.VirtualMemorySize64
PrivateMemorySize64 = $currMemory.PrivateMemorySize64
VirtualMemorySize64 = $currMemory.VirtualMemorySize64
}
if($PerformanceHistory.Count -gt $MaximumHistoryCount) {
$null = $PerformanceHistory.Remove( ($lastCommand.Id - $MaximumHistoryCount) )
}
$lastMemory = $currMemory
return &$PrePerformanceTrackingPrompt @args
}
function Get-PerformanceHistory {
param( [int]$count=1, [int64[]]$id=@((Get-History -count 1| Select Id).Id), [switch]$Memory )
# if there's only one id, then the count counts, otherwise we just use the ids
# ... basically: { 1..$count | % { $id += $id[-1]-1 } }
if($id.Count -eq 1) { $id = ($id[0])..($id[0]-($count-1)) }
$global:PerformanceHistory[$id]
}
function Format-TimeSpan($ts) {
if($ts.Minutes) {
if($ts.Hours) {
if($ts.Days) {
return "{0:##}d {1:00}:{2:00}:{3:00}.{4:00000}" -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}:{2:00}.{3:00000}" -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}.{2:00000}" -f $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:#0}.{1:00000}s" -f $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
#requires -version 2.0
## Get-Performance.ps1
##############################################################################################################
## Returns time/performance information about history objects
## History:
## v2.5 - added "average" calculation if the first thing in your command line is a range: 1..x
## v2 - added measuring the scripts involved in the command, (uses Tokenizer)
## - adds a ton of parsing to make the output pretty
##############################################################################################################
function Get-Performance {
param(
[Microsoft.PowerShell.Commands.HistoryInfo[]]$History = $(Get-History -count 1),
[hashtable]$Property = @{}
)
ForEach($cmd in $History) {
$msr = $null
# default formatting values
$avg = 7; $len = 8; $count = 1
$tok = $Parser::Tokenize( $cmd.CommandLine, [ref]$null )
if( ($tok[0].Type -eq "Number") -and
($tok[0].Content -le 1) -and
($tok[2].Type -eq "Number") -and
($tok[1].Content -eq "..") )
{
$count = ([int]$tok[2].Content) - ([int]$tok[0].Content) + 1
}
$com = @( $tok | where {$_.Type -eq "Command"} |
foreach {
$Local:ErrorActionPreference = "SilentlyContinue"
get-command $_.Content
$Local:ErrorActionPreference = $Script:ErrorActionPreference
} |
where { $_.CommandType -eq "ExternalScript" } |
foreach { $_.Path } )
# If we actually got a script, measure it out
if($com.Count -gt 0){
$msr = Get-Content -path $com | Measure-Object -Line -Word -Char
} else {
$msr = Measure-Object -in $cmd.CommandLine -Line -Word -Char
}
New-Object PSObject -Property (@{
Id = $cmd.Id
StartTime = $cmd.StartExecutionTime
EndTime = $cmd.EndExecutionTime
Duration = Format-TimeSpan ($cmd.EndExecutionTime - $cmd.StartExecutionTime)
Average = Format-TimeSpan ([TimeSpan]::FromTicks( (($cmd.EndExecutionTime - $cmd.StartExecutionTime).Ticks / $count) ))
Lines = $msr.Lines
Words = $msr.Words
Chars = $msr.Characters
Type = $(if($com.Count -gt 0){"Script"}else{"Command"})
Commmand = $cmd.CommandLine
} + $Property)
} # |
}
Export-ModuleMember Get-PerformanceHistory
|
PowerShellCorpus/PoshCode/Manage ASP_1.NET Providers.ps1
|
Manage ASP_1.NET Providers.ps1
|
# Manage_ASP_NET_Providers.ps1
# by Chistian Glessner
# http://iLoveSharePoint.com
# have to be initaized. If you want to change the app config you have to restart PowerShell
param($appConfigPath=$(throw "-appConfigPath is mandatory"))
{
# App config path have to be set before loading System.Web.dll
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $path )
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") # posh 2.0: Add-Type -Assembly "System.Web"
}
function global:Get-MembershipProvider($providerName=$null)
{
if($providerName -eq $null)
{
return [System.Web.Security.Membership]::Provider
}
else
{
return [System.Web.Security.Membership]::Providers[$providerName]
}
}
function global:Get-RoleProvider($providerName=$null)
{
if($providerName -eq $null)
{
return [System.Web.Security.Roles]::Provider
}
else
{
return [System.Web.Security.Roles]::Providers[$providerName]
}
}
function global:Get-ProfileProvider($providerName=$null)
{
if($providerName -eq $null)
{
return [System.Web.Profile.ProfileManager]::Provider
}
else
{
return [System.Web.Profile.ProfileManager]::Providers[$providerName]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.