full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/group-byobject.ps1
|
group-byobject.ps1
|
#groups by a set of properties, but returns then rather than as a string, as seperate properties on an object with _count , and _group for the original
#ones returned from group object
#TODO: rewrite as an advanced function
function group-byobject ([object[]]$property,[switch]$includeGroup,[switch]$includeCount)
{
$results = $input | group-object $property
$results | % {
$hash = @{}
$obj = $_;
if ($includeCount) { $hash._count = $obj.count; }
if ($includeGroup) { $hash._group = $obj.group; }
$property | % { $hash.$_ = $obj.group[0].$_ }
new-object psobject -property $hash
}
}
set-alias groupby group-byobject
set-alias grby group-byobject
|
PowerShellCorpus/PoshCode/An example for you.ps1
|
An example for you.ps1
|
\n#Requires -version 1.0\n## New-PoshCode (formerly Send-Paste)\n##############################################################################################################\n## Uploads code to the PowerShell Script Repository and returns the url for you.\n##############################################################################################################\n## Usage:\n## get-content myscript.ps1 | New-PoshCode "An example for you" "This is just to show how to do it"\n## would send the script with the specified title and description\n## ls *.ps1 | New-PoshCode -Keep Forever\n## would flood the pastebin site with all your scripts, using filename as the title\n## and a generic description, and mark them for storing indefinitely\n## get-history -count 5 | % { $_.CommandLine } | New-PoshCode\n## would paste the last 5 commands in your history!\n##############################################################################################################\n## History:\n## v 3.0 - Renamed to New-PoshCode. \n## Removed the -Permanent switch, since this is now exclusive to the permanent repository\n##\n## v 2.1 - Changed some defaults\n## - Added "PermanentPosh" switch ( -P ) to switch the upload to the PowerShellCentral repository\n## v 2.0 - works with "pastebin" (including posh.jaykul.com/p/ and PowerShellCentral.com/scripts/)\n## v 1.0 - Worked with a special pastebin\n##############################################################################################################\n# Set-StrictMode -Version Latest\n$version = 1\n$PoshCodeRepository = Add-Member -in "http://PoshCode.org/" -type NoteProperty -Name "UserName" -Value "Anonymous" -Passthru\n\nfunction New-PoshCode {\nparam( \n $Title, \n $Description=$(Read-Host "Please enter a description for this script"), \n $KeepFor="f", \n $Language="posh", \n $Author = $($PoshCodeRepository.UserName), \n $url= $($PoshCodeRepository)\n)\n \nBEGIN {\n $null = [Reflection.Assembly]::LoadWithPartialName("System.Web")\n [string]$data = $null;\n [string]$meta = $null;\n \n if($language) {\n $meta = "format=" + [System.Web.HttpUtility]::UrlEncode($language)\n # $url = $url + "?" +$lang\n } else {\n $meta = "format=text"\n }\n \n do {\n switch -regex ($KeepFor) {\n "^d.*" { $meta += "&expiry=d" }\n "^m.*" { $meta += "&expiry=m" }\n "^f.*" { $meta += "&expiry=f" }\n default { \n $KeepFor = Read-Host "Invalid value for 'KeepFor' parameter. Please specify 'day', 'month', or 'forever'"\n }\n }\n } until ( $meta -like "*&expiry*" )\n \n if($Description) {\n $meta += "&descrip=" + [System.Web.HttpUtility]::UrlEncode($Description)\n } else {\n $meta += "&descrip="\n } \n $meta += "&poster=" + [System.Web.HttpUtility]::UrlEncode($Author)\n \n function Send-PoshCode ($meta, $title, $data, $url= $($PoshCodeRepository)) {\n $meta += "&paste=Send&posttitle=" + [System.Web.HttpUtility]::UrlEncode($Title)\n $data = $meta + "&code2=" + [System.Web.HttpUtility]::UrlEncode($data)\n \n $request = [System.Net.WebRequest]::Create($url)\n $request.ContentType = "application/x-www-form-urlencoded"\n $request.ContentLength = $data.Length\n $request.Method = "POST"\n \n $post = new-object IO.StreamWriter $request.GetRequestStream()\n $post.Write($data,0,$data.Length)\n $post.Flush()\n $post.Close()\n \n # $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8\n # write-output $reader.ReadToEnd()\n # $reader.Close()\n write-output $request.GetResponse().ResponseUri.AbsoluteUri\n $request.Abort() \n }\n}\nPROCESS {\n switch($_) {\n { $_ -is [System.IO.FileInfo] } {\n if(!$Title) {\n if ($_.Extension.Length -gt 0)\n { \n $Title = $_.Name.Remove($_.Name.Length - $_.Extension.Length) \n } else { \n $Title = $_.Name \n }\n }\n Write-Verbose $_.FullName\n Write-Output $(Send-PoshCode $meta $Title $([string]::join("`n",(Get-Content $_.FullName))))\n }\n { $_ -is [String] } {\n if(!$data -and !$Title){\n $Title = Read-Host "Give us a title for your post"\n }\n $data += "`n" + $_ \n }\n ## Todo, handle folders?\n default {\n Write-Error "Unable to process $_"\n }\n }\n}\nEND {\n if($data) { \n Write-Output $(Send-PoshCode $meta $Title $data)\n }\n}\n}\n \n## Get-PoshCode (download Repository script)\n##############################################################################################################\n## Downloads a specified script from a Pastbin.com based site, by Id\n## ### OR ###\n## Searches the powershellcentral.com/script site and returns lists of results\n## All search terms are automatically surrounded with wildcards\n## NOTE: powershellcentral.com currently uses MySql fulltext search syntax...\n##############################################################################################################\n## Usage:\n## Get-PoshCode 184\n## would download the original Get-PoshCode script to 184.ps1\n## Get-PoshCode 184 -Passthru\n## would output the contents of Get-PoshCode to the pipeline\n## Get-PoshCode 184 Get-PoshCode.ps1\n## would download Get-PoshCode to Get-PoshCode.ps1 in the current directory\n##############################################################################################################\n## History:\n## v 1.0 - Working against our special pastebin\n##############################################################################################################\nfunction Get-PoshCode {\n param(\n [string]$query = (throw "You must specify a query string, or the id of the paste to get"),\n [string]$SaveAs,\n [switch]$QueryIsID,\n [switch]$InBrowser,\n [switch]$Passthru,\n $url= $($PoshCodeRepository)\n )\n if($QueryIsID){$id = $query -as [int]}\n \n if(!$id) {\n ([xml](Get-WebFile "$($url)api$($version)/*$($query)*" -passthru)).rss.channel.item |\n Select @{n="Id";e={($_.link -replace $url,'') -as [int]}},\n @{n="Title";e={$_.title }},\n @{n="Author";e={$_.creator }},\n @{n="Date";e={$_.pubDate }},\n @{n="Link";e={$_.link }},\n @{n="Description";e={"$($_.description.get_InnerText())" }}\n } else {\n if(!$InBrowser) {\n if($SaveAs) {\n Get-WebFile "$($url)?dl=$id" -fileName $SaveAs\n } elseif($Passthru) {\n Get-WebFile "$($url)?dl=$id" -Passthru\n } else {\n Get-WebFile "$($url)?dl=$id"\n }\n } else {\n [Diagnostics.Process]::Start( "$($url)$id" )\n }\n }\n}\n \n\n## Get-WebFile (aka wget for PowerShell)\n##############################################################################################################\n## Downloads a file or page from the web\n## History:\n## v3.6 - Add -Passthru switch to output TEXT files \n## v3.5 - Add -Quiet switch to turn off the progress reports ...\n## v3.4 - Add progress report for files which don't report size\n## v3.3 - Add progress report for files which report their size\n## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:\n## it was messing up binary files, and making mistakes with extended characters in text\n## v3.1 - Unwrap the filename when it has quotes around it\n## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible\n## v2 - adds a ton of parsing to make the output pretty\n## added measuring the scripts involved in the command, (uses Tokenizer)\n##############################################################################################################\nfunction Get-WebFile {\n param( \n $url = (Read-Host "The URL to download"),\n $fileName = $null,\n [switch]$Passthru,\n [switch]$quiet\n )\n \n $req = [System.Net.HttpWebRequest]::Create($url);\n \n \n ################## Added by Dmitry Sotnikov ##############################################\n # The next 3 lines are required if your network has a proxy server\n $req.Credentials = [System.Net.CredentialCache]::DefaultCredentials\n if($req.Proxy -ne $null) {\n $req.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials\n }\n ################## Added by Dmitry Sotnikov ##############################################\n \n $res = $req.GetResponse();\n \n if($fileName -and !(Split-Path $fileName)) {\n $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName\n } \n elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName)))\n {\n [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value\n $fileName = $fileName.trim("\\/""'")\n $ofs = ""\n $fileName = [Regex]::Replace($fileName, "[$([Regex]::Escape(""$([System.IO.Path]::GetInvalidPathChars())$([IO.Path]::AltDirectorySeparatorChar)$([IO.Path]::DirectorySeparatorChar)""))]", "_")\n $ofs = " "\n\n if(!$fileName) {\n $fileName = $res.ResponseUri.Segments[-1]\n $fileName = $fileName.trim("\\/")\n if(!$fileName) { \n $fileName = Read-Host "Please provide a file name"\n }\n $fileName = $fileName.trim("\\/")\n\n if(!([IO.FileInfo]$fileName).Extension) {\n $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]\n }\n }\n $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName\n }\n if($Passthru) {\n $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet )\n [string]$output = ""\n }\n \n if($res.StatusCode -eq 200) {\n [int]$goal = $res.ContentLength\n $reader = $res.GetResponseStream()\n if($fileName) {\n $writer = new-object System.IO.FileStream $fileName, "Create"\n }\n [byte[]]$buffer = new-object byte[] 4096\n [int]$total = [int]$count = 0\n do\n {\n $count = $reader.Read($buffer, 0, $buffer.Length);\n if($fileName) {\n $writer.Write($buffer, 0, $count);\n } \n if($Passthru){\n $output += $encoding.GetString($buffer,0,$count)\n } elseif(!$quiet) {\n $total += $count\n if($goal -gt 0) {\n Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)\n } else {\n Write-Progress "Downloading $url" "Saving $total bytes..." -id 0\n }\n }\n } while ($count -gt 0)\n \n $reader.Close()\n if($fileName) {\n $writer.Flush()\n $writer.Close()\n }\n if($Passthru){\n $output\n }\n }\n $res.Close(); \n if($fileName) {\n if( ([IO.Path]::GetExtension($fileName) -eq ".ps1") -and \n ((get-content $fileName) -match "Export-ModuleMember") )\n { \n $oldFile = $fileName\n $fileName = [IO.Path]::ChangeExtension($fileName,".psm1")\n Move-Item $oldFile $fileName\n }\n ls $fileName\n }\n}\n# SIG # Begin signature block\n# MIIVBgYJKoZIhvcNAQcCoIIU9zCCFPMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB\n# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR\n# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUuARGZtezywbfvagd5AQuTquY\n# AYugghEMMIIDejCCAmKgAwIBAgIQOCXX+vhhr570kOcmtdZa1TANBgkqhkiG9w0B\n# AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp\n# BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMDcw\n# NjE1MDAwMDAwWhcNMTIwNjE0MjM1OTU5WjBcMQswCQYDVQQGEwJVUzEXMBUGA1UE\n# ChMOVmVyaVNpZ24sIEluYy4xNDAyBgNVBAMTK1ZlcmlTaWduIFRpbWUgU3RhbXBp\n# bmcgU2VydmljZXMgU2lnbmVyIC0gRzIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ\n# AoGBAMS18lIVvIiGYCkWSlsvS5Frh5HzNVRYNerRNl5iTVJRNHHCe2YdicjdKsRq\n# CvY32Zh0kfaSrrC1dpbxqUpjRUcuawuSTksrjO5YSovUB+QaLPiCqljZzULzLcB1\n# 3o2rx44dmmxMCJUe3tvvZ+FywknCnmA84eK+FqNjeGkUe60tAgMBAAGjgcQwgcEw\n# NAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC52ZXJpc2ln\n# bi5jb20wDAYDVR0TAQH/BAIwADAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js\n# LnZlcmlzaWduLmNvbS90c3MtY2EuY3JsMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI\n# MA4GA1UdDwEB/wQEAwIGwDAeBgNVHREEFzAVpBMwETEPMA0GA1UEAxMGVFNBMS0y\n# MA0GCSqGSIb3DQEBBQUAA4IBAQBQxUvIJIDf5A0kwt4asaECoaaCLQyDFYE3CoIO\n# LLBaF2G12AX+iNvxkZGzVhpApuuSvjg5sHU2dDqYT+Q3upmJypVCHbC5x6CNV+D6\n# 1WQEQjVOAdEzohfITaonx/LhhkwCOE2DeMb8U+Dr4AaH3aSWnl4MmOKlvr+ChcNg\n# 4d+tKNjHpUtk2scbW72sOQjVOCKhM4sviprrvAchP0RBCQe1ZRwkvEjTRIDroc/J\n# ArQUz1THFqOAXPl5Pl1yfYgXnixDospTzn099io6uE+UAKVtCoNd+V5T9BizVw9w\n# w/v1rZWgDhfexBaAYMkPK26GBPHr9Hgn0QXF7jRbXrlJMvIzMIIDxDCCAy2gAwIB\n# AgIQR78Zld+NUkZD99ttSA0xpDANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMC\n# WkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIGA1UEBxMLRHVyYmFudmlsbGUx\n# DzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhhd3RlIENlcnRpZmljYXRpb24x\n# HzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcgQ0EwHhcNMDMxMjA0MDAwMDAw\n# WhcNMTMxMjAzMjM1OTU5WjBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp\n# Z24sIEluYy4xKzApBgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2Vydmlj\n# ZXMgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpyrKkzM0grwp9\n# iayHdfC0TvHfwQ+/Z2G9o2Qc2rv5yjOrhDCJWH6M22vdNp4Pv9HsePJ3pn5vPL+T\n# rw26aPRslMq9Ui2rSD31ttVdXxsCn/ovax6k96OaphrIAuF/TFLjDmDsQBx+uQ3e\n# P8e034e9X3pqMS4DmYETqEcgzjFzDVctzXg0M5USmRK53mgvqubjwoqMKsOLIYdm\n# vYNYV291vzyqJoddyhAVPJ+E6lTBCm7E/sVK3bkHEZcifNs+J9EeeOyfMcnx5iIZ\n# 28SzR0OaGl+gHpDkXvXufPF9q2IBj/VNC97QIlaolc2uiHau7roN8+RN2aD7aKCu\n# FDuzh8G7AgMBAAGjgdswgdgwNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhho\n# dHRwOi8vb2NzcC52ZXJpc2lnbi5jb20wEgYDVR0TAQH/BAgwBgEB/wIBADBBBgNV\n# HR8EOjA4MDagNKAyhjBodHRwOi8vY3JsLnZlcmlzaWduLmNvbS9UaGF3dGVUaW1l\n# c3RhbXBpbmdDQS5jcmwwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDgYDVR0PAQH/BAQD\n# AgEGMCQGA1UdEQQdMBukGTAXMRUwEwYDVQQDEwxUU0EyMDQ4LTEtNTMwDQYJKoZI\n# hvcNAQEFBQADgYEASmv56ljCRBwxiXmZK5a/gqwB1hxMzbCKWG7fCCmjXsjKkxPn\n# BFIN70cnLwA4sOTJk06a1CJiFfc/NyFPcDGA8Ys4h7Po6JcA/s9Vlk4k0qknTnqu\n# t2FB8yrO58nZXt27K4U+tZ212eFX/760xX71zwye8Jf+K9M7UhsbOCf3P0owggS/\n# MIIEKKADAgECAhBBkaFaOXjfz0llZjgdTHXCMA0GCSqGSIb3DQEBBQUAMF8xCzAJ\n# BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE3MDUGA1UECxMuQ2xh\n# c3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0w\n# NDA3MTYwMDAwMDBaFw0xNDA3MTUyMzU5NTlaMIG0MQswCQYDVQQGEwJVUzEXMBUG\n# A1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5l\n# dHdvcmsxOzA5BgNVBAsTMlRlcm1zIG9mIHVzZSBhdCBodHRwczovL3d3dy52ZXJp\n# c2lnbi5jb20vcnBhIChjKTA0MS4wLAYDVQQDEyVWZXJpU2lnbiBDbGFzcyAzIENv\n# ZGUgU2lnbmluZyAyMDA0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\n# AQEAvrzuvH7vg+vgN0/7AxA4vgjSjH2d+pJ/GQzCa+5CUoze0xxIEyXqwWN6+VFl\n# 7tOqO/XwlJwr+/Jm1CTa9/Wfbhk5NrzQo3YIHiInJGw4kSfihEmuG4qh/SWCLBAw\n# 6HGrKOh3SlHx7M348FTUb8DjbQqP2dhkjWOyLU4n9oUO/m3jKZnihUd8LYZ/6FeP\n# rWfCMzKREyD8qSMUmm3ChEt2aATVcSxdIfqIDSb9Hy2RK+cBVU3ybTUogt/Za1y2\n# 1tmqgf1fzYO6Y53QIvypO0Jpso46tby0ng9exOosgoso/VMIlt21ASDR+aUY58Du\n# UXA34bYFSFJIbzjqw+hse0SEuwIDAQABo4IBoDCCAZwwEgYDVR0TAQH/BAgwBgEB\n# /wIBADBEBgNVHSAEPTA7MDkGC2CGSAGG+EUBBxcDMCowKAYIKwYBBQUHAgEWHGh0\n# dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9ycGEwMQYDVR0fBCowKDAmoCSgIoYgaHR0\n# cDovL2NybC52ZXJpc2lnbi5jb20vcGNhMy5jcmwwHQYDVR0lBBYwFAYIKwYBBQUH\n# AwIGCCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIBBjARBglghkgBhvhCAQEEBAMCAAEw\n# KQYDVR0RBCIwIKQeMBwxGjAYBgNVBAMTEUNsYXNzM0NBMjA0OC0xLTQzMB0GA1Ud\n# DgQWBBQI9VHo+/49PWQ2fGjPW3io37nFNzCBgAYDVR0jBHkwd6FjpGEwXzELMAkG\n# A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFz\n# cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ghBwuuQd\n# ENkpNLY4ynsDzLq/MA0GCSqGSIb3DQEBBQUAA4GBAK46F7hKe1X6ZFXsQKTtSUGQ\n# mZyJvK8uHcp4I/kcGQ9/62i8MtmION7cP9OJtD+xgpbxpFq67S4m0958AW4ACgCk\n# BpIRSAlA+RwYeWcjJOC71eFQrhv1Dt3gLoHNgKNsUk+RdVWKuiLy0upBdYgvY1V9\n# HlRalVnK2TSBwF9e9nq1MIIE/zCCA+egAwIBAgIQOpr7msrFf6pX5iXFUEeZ7TAN\n# BgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWdu\n# LCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQL\n# EzJUZXJtcyBvZiB1c2UgYXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAo\n# YykwNDEuMCwGA1UEAxMlVmVyaVNpZ24gQ2xhc3MgMyBDb2RlIFNpZ25pbmcgMjAw\n# NCBDQTAeFw0wODA5MDMwMDAwMDBaFw0wOTA5MDMyMzU5NTlaMIHCMQswCQYDVQQG\n# EwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEPMA0GA1UEBxMGSXJ2aW5lMRcwFQYD\n# VQQKFA5RdWVzdCBTb2Z0d2FyZTE+MDwGA1UECxM1RGlnaXRhbCBJRCBDbGFzcyAz\n# IC0gTWljcm9zb2Z0IFNvZnR3YXJlIFZhbGlkYXRpb24gdjIxGzAZBgNVBAsUEldp\n# bmRvd3MgTWFuYWdlbWVudDEXMBUGA1UEAxQOUXVlc3QgU29mdHdhcmUwgZ8wDQYJ\n# KoZIhvcNAQEBBQADgY0AMIGJAoGBAOzhy2kROZ+RmIQSWeVG7GGYZYCkUe6H7Qxa\n# SFvyUnbaft73CkQodnLYx5feVpazJFNQJlzUmcStao12VN8/SGRfa0trG61PwcP9\n# cdpA3OYMJUw3StEOkfwxHkG1r86AS0mLCPWHTzxlv+aVs6/k47p0JSPGXxFs6vwn\n# kyrXxfibAgMBAAGjggF/MIIBezAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDBA\n# BgNVHR8EOTA3MDWgM6Axhi9odHRwOi8vQ1NDMy0yMDA0LWNybC52ZXJpc2lnbi5j\n# b20vQ1NDMy0yMDA0LmNybDBEBgNVHSAEPTA7MDkGC2CGSAGG+EUBBxcDMCowKAYI\n# KwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZlcmlzaWduLmNvbS9ycGEwEwYDVR0lBAww\n# CgYIKwYBBQUHAwMwdQYIKwYBBQUHAQEEaTBnMCQGCCsGAQUFBzABhhhodHRwOi8v\n# b2NzcC52ZXJpc2lnbi5jb20wPwYIKwYBBQUHMAKGM2h0dHA6Ly9DU0MzLTIwMDQt\n# YWlhLnZlcmlzaWduLmNvbS9DU0MzLTIwMDQtYWlhLmNlcjAfBgNVHSMEGDAWgBQI\n# 9VHo+/49PWQ2fGjPW3io37nFNzARBglghkgBhvhCAQEEBAMCBBAwFgYKKwYBBAGC\n# NwIBGwQIMAYBAQABAf8wDQYJKoZIhvcNAQEFBQADggEBAAKkBGa0vkqJpeJonGIr\n# hCN+mC+cBCNpXuMe/nlxz6EiAfqipmX9AmIk5CuFtpHggLQTPqi9yHW7KdRwJil1\n# RUefvsat6zkDcKxIwq2asQeVuxJethSkYeb9gjQBC1ODPWyW7K4/GIzWrdXdBzIO\n# ynlt/cGb+DP4PlpkZoi4YJn10hvxz3vQyfiv9LB6nyDXygsnWJLN4oIXj+PLyzYt\n# FiEQpyO4NfvFHr8WUexVfr+S2pQflSh+RvYNbhrticMXNvUKQqnFpvAySIMyOeM1\n# zd3QjdKTtr35tsrhiREsfmJiVpU57850Cmv/18LKL95C/upPj1NNWvNZwIjpx8zT\n# sq8xggNkMIIDYAIBATCByTCBtDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlT\n# aWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYD\n# VQQLEzJUZXJtcyBvZiB1c2UgYXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3Jw\n# YSAoYykwNDEuMCwGA1UEAxMlVmVyaVNpZ24gQ2xhc3MgMyBDb2RlIFNpZ25pbmcg\n# MjAwNCBDQQIQOpr7msrFf6pX5iXFUEeZ7TAJBgUrDgMCGgUAoHAwEAYKKwYBBAGC\n# NwIBDDECMAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIB\n# CzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFHT5alNjTpzjgImInxhl\n# 44Xs67x7MA0GCSqGSIb3DQEBAQUABIGA5SASUw0SZpqvyLrNCToLCeo7/F6jTG1U\n# rfIvIXiBOWkQ39FoFU6tPBafuwJHP7OD7Ru/SMx7hBNKEauInMKGACWslI+byqsp\n# +yMgPJQ138a8LuuS1aykxyXYgTMx+TWC/Cao9kM9aRNZwjEgksw6bZFylHRbTVbN\n# +h+YdrwWInqhggF+MIIBegYJKoZIhvcNAQkGMYIBazCCAWcCAQEwZzBTMQswCQYD\n# VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzApBgNVBAMTIlZlcmlT\n# aWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0ECEDgl1/r4Ya+e9JDnJrXWWtUw\n# DAYIKoZIhvcNAgUFAKBZMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI\n# hvcNAQkFMQ8XDTA4MDkxMTIxMzc0NVowHwYJKoZIhvcNAQkEMRIEEJo7RCLvvOwC\n# k9kv2htRfn8wDQYJKoZIhvcNAQEBBQAEgYBtU1xVmpkVcfsHfYhpi0ItRdb+PdRq\n# kfviU+JSAOnitpacWrf8GG/5vcN+/ecnwodGAnRuScv1was+oIDdyEMxyjr+3TWb\n# Xr3qXCC5npIt3eJYB0tFkEWrDgTfKRJ2aLT6Gv7DvvBlwzk08VKR3AUjaQ472FRk\n# isAPwWAx5ottMw==\n# SIG # End signature block
|
PowerShellCorpus/PoshCode/PrinterQueStatistics.ps1
|
PrinterQueStatistics.ps1
|
#Printer Statistic checking script by Henrik Pedersen Ċmark
#This script is used to check how many times all printerques on the selected server has been used the latest X months
#First it gets all the events from the remote server's eventlog that are of ID 10 (successful print) and of the type "Print".
#Then it checks for the timestamps and filter away those that are older then X months.
#After the sorting it tries to match the printerque name against the message from the fort log line, if match it adds 1 to a counter and then take next line.
#If it doesnt match, it head to the next line.
#It will also write the statistics to a file.
#You will need admin rights to use this script
#
#Get todays date for creating filenames later
$date = Get-Date -UFormat %Y%m%d
#Finding out what host to check logs from
Write-Host "What server do you want to get the eventlog from?"
$hostname = Read-Host
Write-Host "Getting the eventlog from server"$hostname"."
Write-Host "Please wait... (this might take a few minutes)"
#Get Eventlog from a remote host
$events = gwmi -ComputerName $hostname -query "select * from win32_ntlogevent where logfile='system' and eventcode='10' and sourcename='print'" | Select-Object EventCode, Timegenerated, Message | sort Timegenerated
#Making a variable for the printerports
$printerports = gwmi -computername $hostname Win32_Printer | Select-Object Portname, name
#Converting newest logtimes to DateTime
$newest = [System.Management.ManagementDateTimeConverter]::ToDateTime($events[0].TimeGenerated)
Write-Host "Oldest logentry is from:" $newest
Write-Host "How many months back do you want to check?"
$months = Read-Host
#Checks is the path where the files gonna be added exists, it it dont, it creates it
if ((Test-Path -path $hostname) -ne $True)
{
New-Item -type directory -path $hostname
}
$counter = 0
$eventcounter = 0
#Taking one printerques at the time
while ($counter -ne ($printerports.count-1))
{
#Resetting quecounter so we don't get any old results
$quecounter = 0
#Looping through each line and checking for how old the events are and if they match the current printerquename
foreach ($line in $events)
{
#Converting current the Timegenerated to DateTime
$current = ([System.Management.ManagementDateTimeConverter]::ToDateTime($line.TimeGenerated))
if ($current -gt $(Get-Date).AddMonths(-$months) -and $line.message -match $printerports[$counter].name)
{
#Adding 1 to the counter if it is a match
$quecounter = $quecounter + 1
}
else
{
#Getting the next line
$eventcounter = $eventcounter + 1
}
}
Write-Host -ForegroundColor Green $printerports[$counter].name "has been used $($quecounter) times!"
#Writing to file
add-content -path $hostname\\Statistics_$date.txt -Value "Printerque name: $($printerports[$counter].name)"
add-content -path $hostname\\Statistics_$date.txt -Value "Number of times used: $quecounter"
Add-content -path $hostname\\Statistics_$date.txt -Value " "
#Adds 1 to the counter so the loop ends after all quenames are checked
$counter = $counter + 1
}
|
PowerShellCorpus/PoshCode/Set-AttachedProperty.ps1
|
Set-AttachedProperty.ps1
|
#function Set-AttachedProperty {
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true)
[System.Windows.DependencyProperty]
$Property
,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)
$Element
)
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 }) )
$Param1.ParameterType = $Property.PropertyType
$paramDictionary.Add("Value", $Param1)
return $paramDictionary
}
PROCESS {
$Element.SetValue($Property, $Param1.Value)
$Element
}
#}
#New-Alias sap Set-AttachedProperty
|
PowerShellCorpus/PoshCode/Enable PS Remoting_1.ps1
|
Enable PS Remoting_1.ps1
|
#Run winrm quickconfig defaults
echo Y | winrm quickconfig
#Run enable psremoting command with defaults
enable-psremoting -force
#Enabled Trusted Hosts for Universial Access
cd wsman:
cd localhost\\client
Set-Item TrustedHosts * -force
restart-Service winrm
echo "Complete"
|
PowerShellCorpus/PoshCode/40c64868-c29e-4233-90ad-5097bb26827e.ps1
|
40c64868-c29e-4233-90ad-5097bb26827e.ps1
|
Param($user,
$password = $(Read-Host "Enter Password" -asSec),
$filter = "(objectclass=user)",
$server = $(throw '$server is required'),
$path = $(throw '$path is required'),
[switch]$all,
[switch]$verbose)
function GetSecurePass ($SecurePassword) {
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SecurePassword)
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$password
}
if($verbose){$verbosepreference = "Continue"}
$DN = "LDAP://$server/$path"
Write-Verbose "DN = $DN"
$auth = [System.DirectoryServices.AuthenticationTypes]::FastBind
Write-Verbose "Auth = FastBind"
$de = New-Object System.DirectoryServices.DirectoryEntry($DN,$user,(GetSecurePass $Password),$auth)
Write-Verbose $de
Write-Verbose "Filter: $filter"
$ds = New-Object system.DirectoryServices.DirectorySearcher($de,$filter)
Write-Verbose $ds
if($all)
{
Write-Verbose "Finding All"
$ds.FindAll()
}
else
{
Write-Verbose "Finding One"
$ds.FindOne()
}
|
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_6.ps1
|
TabExpansion for V2CTP_6.ps1
|
## Tab-Completion
#################
## For V2CTP3.
## This won't work on V1 and V2CTP and V2CTP2.
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames and Type accelerators expansion
## [Dec<tab>
## [system.Man<tab>.auto<tab>.p<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.win<tab>.for<tab>.bu<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion (this also support default help function and man alias)
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion (this also support default help function and man alias)
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
## #Type accelerators expansion with no charactors
## [<tab>
## New-Object -typename <tab>
## New-Object <tab>
## # File glob expansion with '@'
## ls *.txt@<tab>
## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma
## ls * -Filter *.txt # 2 <tab> refactoring
## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern
## This can also use '^'(hat) or '~'(tilde) for Excluding
## ls <hat>*.txt@<tab>
## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma
## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring
## *.txt<tilde>foo*<tilde>bar*@<tab>
## ls file.txt # 1 <tab> expanding with comma
## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring
## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> )
## ls * -Filter * -Excluding foo*, bar*<Enter>
## #ls<tab>
## #1<tab>
## # Command buffer stack with ';'(semicolon)
## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1
## echo "PowerShell"<semicolon><tab> # push command2
## get-process<semicolon><tab> # push command3
## {COMMAND}<Enter> # execute another command
## get-process # Auto pop command3 from stack by LIFO
## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon)
## get-process; <semicolon><comma><tab>
## get-process; echo "PowerShell" # pop command2 from stack by LIFO
## # Function name expansion after 'function' or 'filter' keywords
## function cl<tab>
## #Switch syntax option expansion
## switch -w<tab> -f<tab>
## #Better powershell.exe option expansion with '-'
## powershell -no<tab> -<tab> -en<tab>
## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* )
## [par<tab>
## [cmd<tab>
## #Member expansion for CmdletBinding and Parameter attributes
## [Parameter(man<tab>,<tab>1,val<tab>$true)]
## [CmdletBinding( <tab>"foo", su<tab>$true)]
## #Several current date/time formats with Ctrl+D
## <Ctrl+D><tab><tab><tab><tab><tab>...
## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,')
## <command>;<tab> # push command
## <Ctrl+D><tab> # pop
## #Paste clipboard with Ctrl+V
## <Ctrl+V><tab>
## # Cut current line with Ctrl+X
## <command><Ctrl+X><tab>
## # Cut words with a charactor after Ctrl+X until the charactor
## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-'
## 2: PS > dir -
## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now
## # Cut last word in current line with Ctrl+Z
## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line
## 2: PS > Get-ChildItem
## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now
## #Help document's section name expansion at a line that has only spaces
## .syn<tab>
## .func<tab>
## #A part of history commands expansion with Ctrl+L (using split(";"),split("|"),split(";|") )
## ls -Force -Recurse -Filter *.txt | ? { $_.LastWriteTime -lt [DateTime]::Today } ; echo PowerShell
## ls<Ctrl+L><tab><tab>
## ?<Ctrl+L><tab><tab>
## ec<Ctrl+L><tab>
### Generate ProgIDs list...
if ( Test-Path $PSHOME\\ProgIDs.txt )
{
$_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0
}
else
{
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
$_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID.Add($_i.GetValue(""))
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose
}
### Generate TypeNames list...
if ( Test-Path $PSHOME\\TypeNames.txt )
{
$_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0
}
else
{
$_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames.Add($_type.FullName)
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose
}
if ( Test-Path $PSHOME\\TypeNames_System.txt )
{
$_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0
}
else
{
$_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.'
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose
}
### Generate WMIClasses list...
if ( Test-Path $PSHOME\\WMIClasses.txt )
{
$_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0
}
else
{
$_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_class in gwmi -List )
{
$_WMIClasses.Add($_class.Name)
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose
}
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null
$global:_cmdstack = New-Object Collections.Stack
$global:_snapin = $null
$global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort
$global:_cmdline = New-Object Collections.ArrayList
iex (@'
function prompt {
h -Count 1 -OutVariable line |
% { $_.CommandLine.Split("|"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";|") } |
Get-Unique | ? { $_ -ne $line.CommandLine -and $_ -notmatch '^\\s*$' } |
% { $_.Trim(" ") } |
? { $global:_cmdline -notcontains $_ } | % { Set-CommandLine $_ | Out-Null }
if ($_cmdstack.Count -gt 0) {
$line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
}
'@ + @"
${function:prompt}
}
"@)
function Write-ClassNames ( $data, $i, $prefix='', $sep='.' )
{
$preItem = ""
foreach ( $class in $data -like $_opt )
{
$Item = $class.Split($sep)
if ( $preItem -ne $Item[$i] )
{
if ( $i+1 -eq $Item.Count )
{
if ( $prefix -eq "[" )
{
$suffix = "]"
}
elseif ( $sep -eq "_" )
{
$suffix = ""
}
else
{
$suffix = " "
}
}
else
{
$suffix = ""
}
$prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix
$preItem = $Item[$i]
}
}
}
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member -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 Set-CommandLine ( [string]$script ) { $global:_cmdline.Add($script) }
function Get-CommandLine ( [string]$name ) {
$name = $name -replace '\\?','`?'
$global:_cmdline -like "$name*"
}
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$params = @{view = 'extended','adapted','base'}
}
else
{
$params = @{static=$true}
}
if ( $_val -is [Hashtable] )
{
[Object[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
}
if ( $_keys -ne $null )
{
$_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat})
} else {
$_members = (Get-Member @params -InputObject $_val $_pat)
}
foreach ($_m in $_members | Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
switch ([int]$line[-1])
{
# Ctrl+D several date/time formats
4 {
"[DateTime]::Now"
[DateTime]::Now
[DateTime]::Now.ToString("yyyyMMdd")
[DateTime]::Now.ToString("MMddyyyy")
[DateTime]::Now.ToString("yyyyMMddHHmmss")
[DateTime]::Now.ToString("MMddyyyyHHmmss")
'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) }
break;
}
# Ctrl+L ōoś^ŹŽé▌é╠āRā}āōāhé┼ɵō¬łĻÆvéĘéķéÓé╠é╔ĢŌŖ«
12 {
Get-CommandLine $lastWord.SubString(0, $lastword.Length-1)
break;
}
# Ctrl+P hand-operated pop from command buffer stack
16 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_base + $global:_cmdstack.Pop()
break;
}
# Ctrl+R $Host.UI.RawUI.
18 {
'$Host.UI.RawUI.'
'$Host.UI.RawUI'
break;
}
# Ctrl+V paste clipboard
22 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_clip = New-Object System.Windows.Forms.TextBox
$_clip.Multiline = $true
$_clip.Paste()
$_base + $_clip.Text
break;
}
# Ctrl+X cut current line
24 {
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $line.SubString(0, $line.Length-1)
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
break;
}
# Ctrl+Z cut last word in current line
26 {
$line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch ( [int]$line[-2] )
{
# Ctrl+X cut words with a charactor after Ctrl+X until the charactor
24 {
$line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle property and method expansion on [ScriptBlock] members...
# e.g. { 1+1 }.inv<tab>
'(^.*})\\.(\\w*)$' {
$_base = $matches[1]
$_pat = $matches[2] + '*'
foreach ( $_m in {} | Get-Member $_pat | sort membertype,name )
{
if ($_m.MemberType -eq "Method")
{
$_base + '.' + $_m.name + '('
}
else {
$_base + '.' + $_m.name
}
}
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[8] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[(\\w+(\\.\\w*)*)$' {
$_opt = $matches[1] + '*'
if ( $_opt -eq "*" )
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
}
else
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
"CmdletBinding", "Parameter", "Alias",
"ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength",
"ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange",
"ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" `
-like $_opt -replace '^(.*)$', '[$1('
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '['
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '['
}
break;
}
# Handle file/directory name which contains $env: variable
# e.g. $env:windir\\<tab>
'^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' {
$path = iex ('"' + $Matches[0] + '"')
if ( $Matches[2].Length -gt 1 )
{
$parent = Split-Path $path -Parent
$leaf = (Split-Path $path -Leaf) + '*'
}
else
{
$parent = $path
$leaf = '*'
}
if ( Test-Path $parent )
{
$i = $Matches[0].LastIndexOfAny("/\\")
$_base = $Matches[0].Substring(0,$i+1)
[IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') }
}
}
# Handle file glob expansion ...
# e.g. *.txt~about*@<tab>
'^(\\^?([^~]+))(~(.*))*@$' {
if ( $Matches[1] -notlike "^*" )
{
$include = $Matches[2] -replace '``','`'
if ( $Matches[3] )
{
$exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`'
}
}
else
{
$include = "*"
$exclude = $Matches[2] -replace '``','`'
}
$fse = [IO.Directory]::GetFileSystemEntries($PWD)
$fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1'
% -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } }
$fse = $fse -replace '^.*\\s.*$', ("'`$0'")
$fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'")
$fse = $fse -replace "''", "'"
$OFS = ", "; "$fse"
$OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"})
$Matches[0].Substring(0, $Matches[0].Length-1)
break;
}
# Handle command buffer stack...
'(.*);(.?)$' {
$_base = $Matches[1]
if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," )
{
if ( $_cmdstack.Count -gt 0 )
{
$_base + $global:_cmdstack.Pop()
}
else
{
""; break;
}
}
elseif ( $Matches[2] -eq "" )
{
$global:_cmdstack.Push($line.SubString(0,$line.Length-1))
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
""; break;
}
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_command = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_command -match '\\{([^\\{\\}]*)$')
{
$_command = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_command -match '\\(([^()]*)$')
{
$_command = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_command = $_command.Trim().Split()[0]
# now get the info object for it...
$_command = @(Get-Command -type 'All' $_command)[0]
# loop resolving aliases...
while ($_command.CommandType -eq 'alias')
{
$_command = @(Get-Command -type 'All' $_command.Definition)[0]
}
if ( $_command.name -eq "powershell.exe" )
{
if ( $global:_PSexeOption )
{
$global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort
}
else
{
($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort
}
break;
}
if ( $_command -ne $null )
{
# expand the parameter sets and emit the matching elements
foreach ($_n in $_command.Parameters.Keys | sort)
{
if ($_n -like $_pat) { '-' + $_n }
}
}
elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$')
{
$_pat = $Matches[2] + '*'
"regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1'
break;
}
else
{
"-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt",
|
PowerShellCorpus/PoshCode/Get-LocalGroupMember_3.ps1
|
Get-LocalGroupMember_3.ps1
|
function Get-LocalGroupMember
<#
.Synopsis
Get the local group membership.
.Description
Get the local group membership.
.Parameter ComputerName
Name of the Computer to get group members (Default localhost.)
.Parameter Group
Name of the group to get members from (Default Administrators.)
.Example
Get-LocalGroupMember
Description
-----------
Get Administrators group Members for the localhost
.Example
Get-LocalGroupMember -Computer MyPC -group User
Description
-----------
Get Members of Users Group from MyPC
.Example
$Servers | Get-LocalGroupMember -group "Remote Desktop Users"
Description
-----------
Get Members of Users Group from "Remote Desktop Users" on all $Servers
.OUTPUTS
PSCustomObject
.INPUTS
System.String
.Link
N/A
.Notes
NAME: Get-LocalGroupMember
AUTHOR: YetiCentral\\bshell
Website: www.bsonposh.com
LASTEDIT: 10/13/2009 18:25:15
#Requires -Version 2.0
#>
[Cmdletbinding()]
Param(
[alias('dnsHostName')]
[Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$ComputerName = $Env:COMPUTERNAME,
[Parameter()]
[string]$Group= "Administrators"
)
begin {
Write-Verbose " [Get-LocalGroupMember] :: Start Begin"
function GetGroupMembers($Server,$Group)
{
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Server = $Server"
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Group = $Group"
$GroupObject = Get-WMIObject win32_group -filter "LocalAccount='$true' AND Name='$Group'" -computername $Server -
$Query = "SELECT * FROM Win32_GroupUser WHERE GroupComponent = `"Win32_Group.Domain='$Server',Name='$Group'`""
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Query = $Query"
$GroupUsers = get-wmiobject -Query $Query -computername $Server -ea STOP
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: Processing Group Members "
if($GroupUsers)
{
foreach($User in $GroupUsers)
{
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$User.PartComponent = $($User.PartComponent
$RegEx = '\\\\\\\\{0}\\\\root\\\\cimv2\\:Win32_.*\\="(?<Domain>.*)",Name="(?<User>.*)"' -f $Server
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: RegEx = $RegEx "
$User.PartComponent -match $Regex | out-null
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: Creating Custom Object "
$myobj = @{}
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.ComputerName = $Server"
$myobj.ComputerName = $Server
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.UserName = $($matches.User)"
$myobj.UserName = $matches.User
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.Domain = $($matches.Domain)"
$myobj.Domain = $matches.Domain
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.Group = $Group"
$myobj.Group = $Group
$obj = New-Object PSObject -Property $myobj
$obj.PSTypeNames.Clear()
$obj.PSTypeNames.Add('BSonPosh.LocalGroup')
$obj
}
}
}
Write-Verbose " [Get-LocalGroupMember] :: End Begin"
}
process {
Write-Verbose " [Get-LocalGroupMember] :: Start Process"
if($ComputerName -match "(.*)(\\$)$")
{
$ComputerName = $ComputerName -replace "(.*)(\\$)$",'$1'
}
if(Test-Host $ComputerName -TCPPort 135)
{
Write-Verbose " [Get-LocalGroupMember] :: Processing Computer: $ComputerName"
try
{
GetGroupMembers $ComputerName $Group
}
catch
{
Write-Host " Host [$ComputerName] Failed with Error: $($Error[0])" -ForegroundColor Red
}
}
else
{
Write-Host " Host [$ComputerName] Failed Connectivity Test " -ForegroundColor Red
}
Write-Verbose " [Get-LocalGroupMember] :: End Process"
}
}
|
PowerShellCorpus/PoshCode/Import-Instapaper.ps1
|
Import-Instapaper.ps1
|
#
# # ##### # # # # # # ## # #
# # # # ## ## # ## # # # # ## #
# # # # # ## # # # # # # # # # # #
####### # # # # # # # # # ###### # # #
# # # # # # # # ## # # # # ##
# # ##### # # # # # # # # # #
## It's a quick little script to search instapaper csv
Function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.ShowHelp = $true
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
## Get the CSV File
$fileName = Get-FileName -initialDirectory "~"
$csv = Import-Csv $fileName
## I use this for a broad search or topic search
$search = Read-Host "Search Topic: "
$csv | Where-Object {$_.Title -like "*" + $search + "*"} | ft title
## This is the refined search that will open IE
$search = Read-Host "Open Title: "
$result = $csv | Where-Object {$_.Title -like "*" + $search + "*"}
$ie = New-Object -comobject "InternetExplorer.Application"
$ie.visible = $true
$ie.navigate($result.url)
|
PowerShellCorpus/PoshCode/Users_Contacts from CSV_1.ps1
|
Users_Contacts from CSV_1.ps1
|
#=============================================================================#
#=============================================================================#
#=============================================================================#
#
# SCRIPT : CreateOrUpdateUsersOrContacts.ps1
# LAST UPDATE : 9/18/2009
# VERSION : 1.00
#
#
# DESCRIPTION:
# PowerShell script for creating/updating mail-enabled Users or Contact objects
# in Active Directory for Exchange 2003. Uses a CSV source file.
#
#
# TO DO:
# * Logging.
# * Roll-back
# * Eliminate need to hard-code LDAP fields, use CSV header instead.
# * Confirm required LDAP fields are present and populated.
# * Incorporate command-line argument functionality
#
# (NOTE: NONE OF THESE HAVE BEEN IMPLEMENTED YET!!!)
#
# CSV input path and file name
# $File = $args[0] # -f <CSV File Name>
#
# Type of Active Directory object to target
# $ADObject = $args[1] # -a <AD Object Type>
#
# Where the Contacts should be created
# $OUPath = $args[2] # -o <Target OU Path>
#
# Which Exchange environment to create contacts in (CHI or LA)
# $Affiliate = $args[3] # -e <Exchange Environment>
#
# Test only -- Add 'what if' to New-QADObject
# $TestFlag = $args[4] # -t
#
# Domain and username of authentication credentials
# $UserName = $args[5] # -u <domain\\sAMAccountName>
#
# Password for above credentials
# $Password = $args[6] # -p <password>
#
#
# VERSION HISTORY:
# 1.00 - 8/18/2009
# * Initial Release.
#
#
# AUTHOR:
# Ken Knicker - kenknicker@gmail.com
#
#=============================================================================#
#=============================================================================#
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Functions
#=============================================================================#
#=============================================================================#
#=============================================================================#
Function Set_People_Attributes {
#=============================================================================#
$Input | Set-QADObject -ObjectAttributes @{
c = ($_.c);
co = ($_.co);
countryCode = ($_.countryCode);
comment = ($_.comment);
company = ($_.company);
description = ($_.description);
division = ($_.division);
employeeID = ($_.employeeID);
employeeType = ($_.employeeType);
extensionAttribute1 = ($_.extensionAttribute1);
extensionAttribute2 = ($_.extensionAttribute2);
extensionAttribute3 = ($_.extensionAttribute3);
extensionAttribute4 = ($_.extensionAttribute4);
extensionAttribute5 = ($_.extensionAttribute5);
extensionAttribute6 = ($_.extensionAttribute6);
extensionAttribute7 = ($_.extensionAttribute7);
extensionAttribute8 = ($_.extensionAttribute8);
extensionAttribute9 = ($_.extensionAttribute9);
extensionAttribute10 = ($_.extensionAttribute10);
extensionAttribute11 = ($_.extensionAttribute11);
extensionAttribute12 = ($_.extensionAttribute12);
extensionAttribute13 = ($_.extensionAttribute13);
extensionAttribute14 = ($_.extensionAttribute14);
extensionAttribute15 = ($_.extensionAttribute15);
facsimileTelephoneNumber = ($_.facsimileTelephoneNumber);
givenName = ($_.givenName);
info = ($_.info);
initials = ($_.initials);
l = ($_.l);
# memberOf = ($_.memberOf); # Group memberships
mobile = ($_.mobile);
physicalDeliveryOfficeName = ($_.physicalDeliveryOfficeName);
postalCode = ($_.postalCode);
sn = ($_.sn);
st = ($_.st);
streetAddress = ($_.streetAddress);
telephoneNumber = ($_.telephoneNumber);
title = ($_.title)
} -Verbose
}
#=============================================================================#
Function Set_User_Attributes {
#=============================================================================#
$Input | Set-QADUser -ObjectAttributes @{
homeDirectory = ($_.homeDirectory);
homeDrive = ($_.homeDrive);
# manager = ($_.manager); # Path of user's manager
mobile = ($_.mobile);
profilePath = ($_.profilePath);
sAMAccountName = ($_.sAMAccountName);
scriptPath = ($_.scriptPath);
userPrincipalName = ($_.sAMAccountName + $Domain);
wWWHomePage = ($_.wWWHomePage)
} -Verbose
}
#=============================================================================#
Function Set_Mail_Attributes {
#=============================================================================#
$Input | Set-QADObject -ObjectAttributes @{
legacyExchangeDN = ($Root_LegacyExchangeDN + $_.mailNickname);
mail = ($_.mail);
mailNickname = ($_.mailNickname);
# msExchHideFromAddressLists = ($_.msExchHideFromAddressLists); # TRUE or FALSE
# msExchHomeServerName = ($_.msExchHomeServerName); # Only for User objects
targetAddress = ($_.targetAddress)
} -Verbose
}
#=============================================================================#
#=============================================================================#
# Script Setup
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Load snap-in for Quest ActiveRoles cmdlets
#=============================================================================#
If (-not (Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue)) {
Add-PSSnapin Quest.ActiveRoles.ADManagement -Verbose
}
#=============================================================================#
# Initialize variables
#=============================================================================#
$CSVPath = "\\\\SERVER\\SharePath\\ListOfPeople.csv"
$PeopleList = Import-Csv $CSVPath -Verbose # CSV file containing people info
$MailEnable = $false
# Set these all to null to clear from last execution.
$ObjectType = $null
$Domain = $null
$OU = $null
$Root_LegacyExchangeDN = $null
$Server = $null
$UserName = $null
#=============================================================================#
# Affiliate Number 1 attributes
#=============================================================================#
$Affiliate1_Contact_OU = "OU=Contacts,DC=affiliate1,DC=com"
$Affiliate1_User_OU = "OU=Users,DC=affiliate1,DC=com"
$Affiliate1_Root_LegacyExchangeDN = "/O=Affiliate 1/OU=AFFILIATE1/cn=Recipients/cn="
$Affiliate1_Domain = "@affiliate1.com"
$Affiliate1_Server = "domaincontroller.affiliate1.com"
#=============================================================================#
# Affiliate Number 2 attributes
#=============================================================================#
$Affiliate2_Contact_OU = "OU=Contacts,DC=affiliate2,DC=com"
$Affiliate2_User_OU = "OU=Users,DC=affiliate2,DC=com"
$Affiliate2_Root_LegacyExchangeDN = "/O=Affiliate 2/OU=AFFILIATE2/cn=Recipients/cn="
$Affiliate2_Domain = "@affiliate2.com"
$Affiliate2_Server = "domaincontroller.affiliate2.com"
#=============================================================================#
# Credentials
#=============================================================================#
$Location = Read-Host "Affiliate location: ''A1'' for Affiliate 1, ''A2'' for Affiliate 2:"
$ObjectType = Read-Host "Object type? ''Contact'' or ''User'':"
If ($Location -eq "AF1") {
If ($ObjectType -eq "User") { $OU = $Affiliate1_User_OU }
Else { $OU = $CHI_Contact_OU }
$Root_LegacyExchangeDN = $Affiliate1_Root_LegacyExchangeDN
$Domain = $Affiliate1_Domain
$Server = $Affiliate1_Server
$UserName = $Affiliate1_UserName
}
If ($Location -eq "AF2") {
If ($ObjectType -eq "User") { $OU = $Affiliate2_User_OU }
Else { $OU = $CHI_Contact_OU }
$Root_LegacyExchangeDN = $Affiliate2_Root_LegacyExchangeDN
$Domain = $Affiliate2_Domain
$Server = $Affiliate2_Server
$UserName = $Affiliate2_UserName
}
$UserName = Read-Host "Enter username for the domain you are connecting to (''DOMAIN\\username''):"
$Password = Read-Host "Enter password for"$UserName -AsSecureString
Connect-QADService -Service $Server -ConnectionAccount $UserName -ConnectionPassword $Password -Verbose
#=============================================================================#
#=============================================================================#
# Main Script
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Create or update Contact or User objects from CSV records
#=============================================================================#
$PeopleList | ForEach-Object {
$Person = Get-QADObject -DisplayName $_.displayName -LdapFilter "(&(objectClass=$ObjectType))" -Verbose
If ($Person -eq $Null){
Write-Host "Creating Object for" $_.displayName -ForegroundColor Green -Verbose
If ($ObjectType -eq "Contact") {
$Person = New-QADObject -ParentContainer $OU -Name $_.cn -Type $ObjectType -DisplayName $_.displayName -Verbose
}
ElseIf ($ObjectType -eq "User") {
$Person = New-QADUser -ParentContainer $OU -Name $_.cn -DisplayName $_.displayName -SamAccountName $_.sAMAccountName -UserPrincipalName ($_.sAMAccountName+"$Domain") -Verbose
$Person | Set_User_Attributes
}
$Person | Set_People_Attributes
}
Else {
Write-Host "Updating Properties for" $_.displayName -ForegroundColor Red -Verbose
$Person | Set_People_Attributes
}
If ($MailEnable -eq $true) {
$Person | Set_Mail_Attributes
}
}
#=============================================================================#
# END SCRIPT
#=============================================================================#
|
PowerShellCorpus/PoshCode/Autoload (beta 8).ps1
|
Autoload (beta 8).ps1
|
#Requires -Version 2.0
## Version History
## beta 8 - 2010.09.20
## Finally fixed the problem with aliases that point at autoloaded functions!
## beta 7 - 2010.06.03
## Added some help, and a function to force loading "now"
## Added a function to load AND show the help...
## beta 6 - 2010.05.18
## Fixed a bug in output when multiple outputs happen in the END block
## beta 5 - 2010.05.10
## Fixed non-pipeline use using $MyInvocation.ExpectingInput
## beta 4 - 2010.05.10
## I made a few tweaks and bug fixes while testing it's use with PowerBoots.
## beta 3 - 2010.05.10
## fix for signed scripts (strip signature)
## beta 2 - 2010.05.09
## implement module support
## beta 1 - 2010.04.14
## Initial Release
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1)
## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile)
## 4) Dot-source this file, or include it as part of your profile
## 5) Add one line to your profile (or on the commandline):
<#
autoload Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
function Autoloaded {
#.Synopsis
# This function was autoloaded. It's help has not been parsed yet.
#.Description
# You are seeing this help because the command you typed was imported via the Autoload command from the Autoload module. The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the AutoloadHelp function.
#
# For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: AutoloadHelp Get-PerformanceHistory
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
return LoadNow $CommandName
}#DynamicParam
begin {
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Autoloaded Begin: $Alias -> $CommandName -> $FunctionName"
#Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
$global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function )
Write-Verbose "Autoloaded Command: $($Command|Out-String)"
$scriptCmd = {& $command @PSBoundParameters | Write-Output }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($myInvocation.ExpectingInput)
}
process
{
Write-Verbose "Autoloaded Process: $CommandName ($_)"
try {
if($_) {
$steppablePipeline.Process($_)
} else {
$steppablePipeline.Process()
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Autoloaded End: $CommandName"
}
}#AutoLoaded
function AutoloadHelp {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
$null = LoadNow $CommandName
Get-Help $CommandName
}
function LoadNow {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
if(!$ScriptName){ $ScriptName = $CommandName }
if(!$FunctionName){ $FunctionName = $CommandName }
if($ModuleName) {
$Module = Get-Module $ModuleName
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
ForEach($token in $tokens) {
if($prev -and $token.Content -eq "# SIG # Begin signature block") {
$script = $script.SubString(0, $token.Start )
}
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) {
$script = $script.Insert( $prev.Start, "global:" )
Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')"
}
$prev = $token
}
if($Module) {
$script = Invoke-Expression "{ $Script }"
Write-Verbose "Importing Function into $($Module) module."
&$Module $Script | Out-Null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
} else {
Invoke-Expression $script | out-null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
if($CommandName -eq $FunctionName) {
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)"
} else {
Set-Alias $CommandName $FunctionName -Scope Global
Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)"
}
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}
function Autoload {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName")]
$Alias = $Name
,
[Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
$Function = $Name
,
[Parameter(Position=3,Mandatory=$false)]
[String]$Module
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
)
begin {
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
process {
for($i=0;$i -lt $Name.Count;$i++){
if($Alias -is [Scriptblock]) {
$a = $Name[$i] | &$Alias
} elseif($Alias -is [Array]) {
$a = $Alias[$i]
} else {
$a = $Alias
}
if($Function -is [Scriptblock]) {
$f = $Name[$i] | &$Function
} elseif($Function -is [Array]) {
$f = $Function[$i]
} else {
$f = $Function
}
Write-Verbose "Set-Alias $Module\\$a Autoloaded -Scope $Scope"
Set-Alias $a Autoloaded -Scope $Scope
$Script:AutoloadHash[$a] = $Name[$i],$Module,$f
Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
}
}
}
$Script:AutoloadHash = @{}
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUGbQl7OEcctSs05yKtX/tlB53
# zLmggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD
# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk
# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo
# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg
# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG
# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3
# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv
# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj
# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG
# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA
# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF
# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q
# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h
# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B
# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5
# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1
# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4
# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV
# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki
# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp
# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR
# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB
# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0
# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW
# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC
# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD
# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0
# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2
# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU
# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC
# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE
# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ
# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq
# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD
# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud
# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC
# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg
# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g
# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG
# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0
# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB
# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j
# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A
# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb
# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27
# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n
# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j
# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D
# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT
# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj
# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ
# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBT8nOvmOVxX
# GqrHWhYusvvsCqBD9DANBgkqhkiG9w0BAQEFAASCAQAdEOJ4ATMY9n7cf66kQTx+
# RvYWhzH13u4MRJEktiIFDp1cXXOH5Rr1PAxTGyW/RTCNvjlWZus+6ovGKvyIe3z8
# A3YCmOWWpcW40Qp+7jk9NxLorn4dCqi6A6dNM2GpmqwVZeRcUUpD0zJKHQ2Bsjyz
# L8Ba5u7WQ2kRvRB4a81FcRc67VfB1veY8VPLo64IdTizRLHclFfceQn1S9iIMv3v
# 5QGzOCUz/K9z2U0+kLglEg2FVU5tEeE+Qk0DUngHVS8bTbLwbyIl/9B1fGtPid+o
# kNjm/K9HhnUTc7YVZ3yYr02jgLCuL/RVxCEoZrMipAcndnB8jzlquuL1ww+oyKAA
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-OnlineHelp_2.ps1
|
Get-OnlineHelp_2.ps1
|
## An update using New-WebServiceProxy to the MSDN ContentService instead of HttpRest
## See: http: //services.msdn.microsoft.com/ContentServices/ContentService.asmx
## This is a VERY EARLY prototype of a function that could retrieve cmdlet help from TechNet ...
## and hypothetically, other online help sites which used the same format (none)
## Version History
## 0.3 - 2010-03-25 - Fixed a buggy type check which failed on first run. THIS VERSION
## 0.2 - 2010-03-24 - Switched to using the ContentService Web Service. PoshCode.org/1723
## 0.1 - 2010-03-23 - Initial release depended on HttpRest. PoshCode.org/1719
param(
[Parameter(Mandatory=$true,Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false,Position=1)]
[String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description")
)
# http://poshcode.org/1718
function Select-Expand {
<#
.Synopsis
Like Select-Object -Expand, but with recursive iteration of a select chain
.Description
Takes a dot-separated series of properties to expand, and recursively iterates the output of each property ...
.Parameter Property
A collection of property names to expand.
Each property can be a dot-separated series of properties, and each one is expanded, iterated, and then evaluated against the next
.Parameter InputObject
The input to be selected from
.Parameter Unique
If set, this becomes a pipeline hold-up, and the total output is checked to ensure uniqueness
.Parameter EmptyToo
If set, Select-Expand will include empty/null values in it's output
.Example
Get-Help Get-Command | Select-Expand relatedLinks.navigationLink.uri -Unique
This will return the online-help link for Get-Command. It's the equivalent of running the following command:
C:\\PS> Get-Help Get-Command | Select-Object -Expand relatedLinks | Select-Object -Expand navigationLink | Select-Object -Expand uri | Where-Object {$_} | Select-Object -Unique
#>
param(
[Parameter(ValueFromPipeline=$false,Position=0)]
[string[]]$Property
,
[Parameter(ValueFromPipeline=$true)]
[Alias("IO")]
[PSObject[]]$InputObject
,
[Switch]$Unique
,
[Switch]$EmptyToo
)
begin {
if($unique) {
$output = @()
}
}
process {
foreach($io in $InputObject) {
foreach($prop in $Property -split "\\.") {
if($io -ne $null) {
$io = $io | Select-Object -Expand $prop
Write-Verbose $($io | out-string)
}
}
if(!$EmptyToo -and ($io -ne $null)) {
$io = $io | Where-Object {$_}
}
if($unique) {
$output += @($io)
}
else {
Write-Output $io
}
}
}
end {
if($unique) {
Write-Output $output | Select-Object -Unique
}
}
}
# New-Alias slep Select-Expand
# http://poshcode.org/1722
function Get-HttpResponseUri {
#.Synopsis
# Fetch the HEAD for a url and return the ResponseUri.
#.Description
# Does a HEAD request for a URL, and returns the ResponseUri. This is useful for resolving (in a service-independent way) shortened urls.
#.Parameter ShortUrl
# A (possibly) shortened URL to be resolved to its redirect location.
PARAM(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[Alias("Uri","Url")]
[string]$ShortUrl
)
$req = [System.Net.HttpWebRequest]::Create($ShortUrl)
$req.Method = "HEAD"
$response = $req.GetResponse()
Write-Output $response.ResponseUri
$response.Close() # clean up like a good boy
}
# New-Alias Resolve-ShortUri Select-Expand
if( -not("Mtps.ContentService" -as [type] -and $global:MtpsWebServiceProxy -as "Mtps.ContentService")) {
$global:MtpsWebServiceProxy = New-WebServiceProxy "http://services.msdn.microsoft.com/ContentServices/ContentService.asmx?wsdl" -Namespace Mtps
}
function Get-OnlineHelpContent {
param(
[Parameter(Mandatory=$true,Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false,Position=1)]
[String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description")
)
process {
$uri = Get-Help $Name | Select-Expand relatedLinks.navigationLink.uri -Unique | Get-HttpResponseUri
if(!$uri) { throw "Couldn't find online help URL for $Name" }
$id = [IO.Path]::GetFileNameWithoutExtension( $uri.segments[-1] )
write-verbose "Content Id: $id"
$content = $MtpsWebServiceProxy.GetContent( (New-Object 'Mtps.getContentRequest' -Property @{locale = $PSUICulture; contentIdentifier = $id; requestedDocuments = (New-Object Mtps.requestedDocument -Property @{Selector="Mtps.Failsafe"}) }) )
$global:OnlineHelpContent = $content.primaryDocuments |?{$_.primaryFormat -eq "Mtps.Failsafe"} | Select -Expand Any
$NameNode = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @class='topic']/*[local-name()='div' and @class='title']")
$NameNode.SetAttribute("header","NAME")
$global:OnlineHelpContent = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @id='mainBody']")
$Synopsis = $global:OnlineHelpContent.SelectSingleNode("*[local-name()='p']")
$Synopsis.SetAttribute("header","SYNOPSIS")
$headers = $OnlineHelpContent.h2 | ForEach-Object { $_.get_InnerText().Trim() }
$content = $OnlineHelpContent.div | ForEach-Object { $_ }
$global:help = @{Name=$NameNode; Synopsis=$Synopsis}
if($headers.Count -ne $content.Count) {
Write-Warning "Unmatched content"
foreach($header in $headers) {
$help.$header = $OnlineHelpContent.SelectNodes( "//*[preceding-sibling::*[1][local-name()='h2' and normalize-space()='$header']]" )
$help.$header.SetAttribute("header",$header.ToUpper())
}
}
else {
for($h=0;$h -lt $headers.Count; $h++){
$help.($headers[$h]) = $content[$h]
$help.($headers[$h]).SetAttribute("header",$headers[$h].ToUpper())
}
}
$help
$content[$Sections] | ForEach-Object {
Write-Output
Write-Output $_.Header
Write-Output
Write-Output ($_.get_InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$')
}
}
}
Get-OnlineHelpContent $Name | out-null
$help[$Sections] | ForEach-Object {
Write-Host
Write-Host $_.Header -Fore Cyan
Write-Host
Write-Host ($_.get_InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$')
}
|
PowerShellCorpus/PoshCode/Get-RemoteRegistry_2.ps1
|
Get-RemoteRegistry_2.ps1
|
## Get-RemoteRegistry
########################################################################################
## Version: 2.1
## + Fixed a pasting bug
## + I added the "Properties" parameter so you can select specific registry values
## NOTE: you have to have access, and the remote registry service has to be running
########################################################################################
## USAGE:
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"
## * Returns a list of subkeys (because this key has no properties)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727"
## * Returns a list of subkeys and all the other "properties" of the key
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Version"
## * Returns JUST the full version of the .Net SP2 as a STRING (to preserve prior behavior)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version
## * Returns a custom object with the property "Version" = "2.0.50727.3053" (your version)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version,SP
## * Returns a custom object with "Version" and "SP" (Service Pack) properties
##
## For fun, get all .Net Framework versions (2.0 and greater)
## and return version + service pack with this one command line:
##
## Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" |
## Select -Expand Subkeys | ForEach-Object {
## Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\$_" Version,SP
## }
##
########################################################################################
# Function Get-RemoteRegistry {
param(
[string]$computer = $(Read-Host "Remote Computer Name")
,[string]$Path = $(Read-Host "Remote Registry Path (must start with HKLM,HKCU,etc)")
,[string[]]$Properties
,[switch]$Verbose
)
if ($Verbose) { $VerbosePreference = 2 } # Only affects this script.
$root, $last = $Path.Split("\\")
$last = $last[-1]
$Path = $Path.Substring($root.Length + 1,$Path.Length - ( $last.Length + $root.Length + 2))
$root = $root.TrimEnd(":")
#split the path to get a list of subkeys that we will need to access
# ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
switch($root) {
"HKCR" { $root = "ClassesRoot"}
"HKCU" { $root = "CurrentUser" }
"HKLM" { $root = "LocalMachine" }
"HKU" { $root = "Users" }
"HKPD" { $root = "PerformanceData"}
"HKCC" { $root = "CurrentConfig"}
"HKDD" { $root = "DynData"}
default { return "Path argument is not valid" }
}
#Access Remote Registry Key using the static OpenRemoteBaseKey method.
Write-Verbose "Accessing $root from $computer"
$rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($root,$computer)
if(-not $rootkey) { Write-Error "Can't open the remote $root registry hive" }
Write-Verbose "Opening $Path"
$key = $rootkey.OpenSubKey( $Path )
if(-not $key) { Write-Error "Can't open $($root + '\\' + $Path) on $computer" }
$subkey = $key.OpenSubKey( $last )
$output = new-object object
if($subkey -and $Properties -and $Properties.Count) {
foreach($property in $Properties) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
} elseif($subkey) {
Add-Member -InputObject $output -Type NoteProperty -Name "Subkeys" -Value @($subkey.GetSubKeyNames())
foreach($property in $subkey.GetValueNames()) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
}
else
{
$key.GetValue($last)
}
# }
|
PowerShellCorpus/PoshCode/Xml Module 4.1.ps1
|
Xml Module 4.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-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
if(!$xlr8r::Get["Stack"]) {
$xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["Dictionary"]) {
$xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
function Format-XML {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Indent
# The indent level (defaults to 2 spaces)
Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[xml]$xml
,
[Parameter(Mandatory=$false)]
$indent=2
)
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}
Set-Alias fxml Format-Xml
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter XPath
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
#.Parameter RemoveNamespace
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Hashtable]$Namespace
,
[Switch]$RemoveNamespace
)
BEGIN {
function Select-Node {
PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager)
BEGIN {
foreach($node in $xml) {
if($NamespaceManager -is [Hashtable]) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Namespace.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
}
foreach($path in $xpath) {
$node.SelectNodes($path, $NamespaceManager)
} } } }
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
$node = Remove-XmlNamespace $node
}
Select-Node $node $XPath $NSM
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
}
Set-Alias slxml Select-Xml
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias cvxml Convert-Xml
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
Convert-Node -Xml $Xml $StyleSheet
}
}
"Xml" {
$Xml | Convert-Node $StyleSheet
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias rmns Remove-XmlNamespace
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
# [string]$xml = New-XDocument rss -dc $dc -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# dc:language {"en"}
# dc:creator {"Jaykul@HuddledMasses.org"}
# dc:rights {"Copyright 2009, CC-BY"}
# dc:date {(Get-Date -f u) -replace " ","T"}
#
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# $xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# $xml.ToString()
#
#
# OUTPUT: (NOTE: I added the space in the http: to paste it on PoshCode -- those aren't in the output)
#
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss xmlns:dc="http ://purl.org/dc/elements/1.1" version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <dc:language>en</dc:language>
# <dc:creator>Jaykul@HuddledMasses.org</dc:creator>
# <dc:rights>Copyright 2009, CC-BY</dc:rights>
# <dc:date>2009-07-26T00:50:08Z</dc:date>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#.Example
# This time with a default namespace
## IMPORTANT! ## NOTE that I use the "xe" shortcut which is redefined when you specify a namespace
## ## for the root element, so that all child elements (by default) inherit that.
## ## You can still control the prefixes by passing the namespace as a parameter
## ## e.g.: -atom $atom
## The `: in the http`: is still only there for PoshCode, you can just use http: ...
#
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
#
# OUTPUT: (NOTE: I added the spaces again to the http: to paste it on PoshCode)
#
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
Write-Verbose "Preparsed DSL: $attrib"
$attrib = DSL $attrib
Write-Verbose "Reparsed DSL: $attrib"
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
$value = DSL $value
&$value
} elseif ( $value -is [XNamespace]) {
Write-Host "Namespace: $value" -Fore Green
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-"), $value)
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
))
}
}
Set-Alias xml New-XDocument
Set-Alias New-Xml New-XDocument
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute
Set-Alias New-XmlAttribute New-XAttribute
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
# BEGIN {
# if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
# $tag = $($script:NameSpaceStack.Peek()) + $tag
# if( $script:NameSpaceStack.Count -gt 0 ) {
# $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() )
# } else {
# $script:NameSpaceStack.Push( $null )
# }
# } else {
# $script:NameSpaceStack.Push( $tag.Namespace )
# }
# }
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) { # then it's content
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-"), $value)
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
)
}
# END {
# $null = $script:NameSpaceStack.Pop()
# }
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function DSL {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and ($(Get-Command $_.Content -EA 0) -eq $Null) }
[Array]::Reverse( $duds )
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml
|
PowerShellCorpus/PoshCode/Del. TrailingBlank (ISE).ps1
|
Del. TrailingBlank (ISE).ps1
|
function Delete-TrailingBlanks
{
$editor = $psISE.CurrentFile.Editor
$caretLine = $editor.CaretLine
# First trial. Works.
# $newText = @()
# foreach ( $line in $editor.Text.Split("`n") )
# {
# $newText += $line -replace ("\\s+$", "")
# }
# $editor.Text = [String]::Join("`n", $newText)
# 2nd trial, but deletes empty lines too \\s matches `r and `n
# $editor.Text = $editor.Text -replace '(?m)\\s*$', ''
# 3rd working again, but doesn't it look like perl ?
# $editor.Text = $editor.Text -replace '(?m)[ \\t]+(?:\\r?)$', ''
# the solution is so simple
$editor.Text = $editor.Text -replace '(?m)\\s*?$', ''
$editor.SetCaretPosition($caretLine, 1)
}
|
PowerShellCorpus/PoshCode/New-ODataServiceProxy.ps1
|
New-ODataServiceProxy.ps1
|
function New-ODataServiceProxy {
#.Synopsis
# Creates a proxy class for an odata web service
# YOU NEED TO BE VERY CAREFUL NOT TO OUTPUT THE PROXY OBJECT TO THE POWERSHELL HOST!
#.Description
# Uses the data service client utility (DataSvcUtil.exe) to generate a proxy class (and types for all objects) for an OData web service.
# WARNING: Outputting this object to the PowerShell host will result in queriying all the object collections on the service.
#.Parameter URI
# The URI for the web service
#.Parameter Passthru
# Causes the method to output all of the types defined by the service metadata as well as the actual service object.
#.Example
# $proxy = New-ODataServiceProxy http://odata.netflix.com/Catalog/
# $AdventuresInOdyssey = $proxy.Titles.AddQueryOption('$filter',"substringof('Adventures in Odyssey',Name)")
# $AdventuresInOdyssey | Format-List Name, ReleaseYear, Url, Synopsis
#.Link http://msdn.microsoft.com/en-us/library/ee383989.aspx
#.Notes
# I can't stress enough that you should not output the object or any property that returns a System.Data.Services.Client.DataServiceQuery[T] without a filter unless you're sure that's what you want.
#
# ADO.NET Data Service Client Utility http://msdn.microsoft.com/en-us/library/ee383989.aspx
# AddQueryOption http://msdn.microsoft.com/en-us/library/cc646860.aspx
# NetFlix Catalog http://developer.netflix.com/docs/oData_Catalog
# Data Services Update for .Net 3.5 SP1 http://support.microsoft.com/kb/982307
#
param( $URI = "http://odata.netflix.com/Catalog/", [switch]$Passthru )
## You can only use this on .Net 4 or .Net 3.5 SP1
## For .Net 3.5 SP1 you need to download http://support.microsoft.com/kb/982307
## If you don't have it, this won't succeed
[Reflection.Assembly]::Load("System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") | Out-Null
## Find the right DataSvcUtil for this version of .Net
switch($PSVersionTable.ClrVersion.Major) {
4 { # PoshConsole and modded .Net4 PowerShell_ISE etc.
Set-Alias Get-ODataServiceDefinition (Get-ChildItem ([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) DataSvcUtil.exe)
break
}
2 { # PowerShell.exe and everyone else
$FrameworkPath = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() | Split-Path
Set-Alias Get-ODataServiceDefinition (Get-ChildItem $FrameworkPath\\v3.5\\DataSvcUtil.exe)
break
}
}
## Get the service definition into a string via a temp file
$temp = [IO.Path]::GetTempFileName()
Get-ODataServiceDefinition -out:$temp -uri:$URI -nologo | Out-Null
$code = @(Get-Content $temp) -join "`n" # -Delim ([char]0)
Remove-Item $temp
$Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" -Language CSharpVersion3 -Passthru
$ContextType = $Types | Where-Object { $_.BaseType -eq [System.Data.Services.Client.DataServiceContext] }
$ctx = new-object $ContextType $URI
Write-Output $ctx
if($Passthru) { Write-Output $types }
}
|
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_4.ps1
|
TabExpansion for V2CTP_4.ps1
|
## Tab-Completion
#################
## For V2CTP3.
## This won't work on V1 and V2CTP and V2CTP2.
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames and Type accelerators expansion
## [Dec<tab>
## [system.Man<tab>.auto<tab>.p<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.win<tab>.for<tab>.bu<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion (this also support default help function and man alias)
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion (this also support default help function and man alias)
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
## #Type accelerators expansion with no charactors
## [<tab>
## New-Object -typename <tab>
## New-Object <tab>
## # File glob expansion with '@'
## ls *.txt@<tab>
## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma
## ls * -Filter *.txt # 2 <tab> refactoring
## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern
## This can also use '^'(hat) or '~'(tilde) for Excluding
## ls <hat>*.txt@<tab>
## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma
## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring
## *.txt<tilde>foo*<tilde>bar*@<tab>
## ls file.txt # 1 <tab> expanding with comma
## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring
## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> )
## ls * -Filter * -Excluding foo*, bar*<Enter>
## #ls<tab>
## #1<tab>
## # Command buffer stack with ';'(semicolon)
## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1
## echo "PowerShell"<semicolon><tab> # push command2
## get-process<semicolon><tab> # push command3
## {COMMAND}<Enter> # execute another command
## get-process # Auto pop command3 from stack by LIFO
## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon)
## get-process; <semicolon><comma><tab>
## get-process; echo "PowerShell" # pop command2 from stack by LIFO
## # Function name expansion after 'function' or 'filter' keywords
## function cl<tab>
## #Switch syntax option expansion
## switch -w<tab> -f<tab>
## #Better powershell.exe option expansion with '-'
## powershell -no<tab> -<tab> -en<tab>
## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* )
## [par<tab>
## [cmd<tab>
## #Member expansion for CmdletBinding and Parameter attributes
## [Parameter(man<tab>,<tab>1,val<tab>$true)]
## [CmdletBinding( <tab>"foo", su<tab>$true)]
## #Several current date/time formats with Ctrl+D
## <Ctrl+D><tab><tab><tab><tab><tab>...
## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,')
## <command>;<tab> # push command
## <Ctrl+D><tab> # pop
## #Paste clipboard with Ctrl+V
## <Ctrl+V><tab>
### Generate ProgIDs list...
if ( Test-Path $PSHOME\\ProgIDs.txt )
{
$_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0
}
else
{
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
$_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID.Add($_i.GetValue(""))
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose
}
### Generate TypeNames list...
if ( Test-Path $PSHOME\\TypeNames.txt )
{
$_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0
}
else
{
$_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames.Add($_type.FullName)
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose
}
if ( Test-Path $PSHOME\\TypeNames_System.txt )
{
$_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0
}
else
{
$_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.'
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose
}
### Generate WMIClasses list...
if ( Test-Path $PSHOME\\WMIClasses.txt )
{
$_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0
}
else
{
$_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_class in gwmi -List )
{
$_WMIClasses.Add($_class.Name)
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose
}
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null
$global:_cmdstack = New-Object Collections.Stack
$global:_snapin = $null
$global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort
iex (@'
function prompt {
if ($_cmdstack.Count -gt 0) {
$line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
}
'@ + @"
${function:prompt}
}
"@)
function Write-ClassNames ( $data, $i, $prefix='', $sep='.' )
{
$preItem = ""
foreach ( $class in $data -like $_opt )
{
$Item = $class.Split($sep)
if ( $preItem -ne $Item[$i] )
{
if ( $i+1 -eq $Item.Count )
{
if ( $prefix -eq "[" )
{
$suffix = "]"
}
elseif ( $sep -eq "_" )
{
$suffix = ""
}
else
{
$suffix = " "
}
}
else
{
$suffix = ""
}
$prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix
$preItem = $Item[$i]
}
}
}
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member 'NoteProperty' CommandType $f.CommandType -P |
Add-Member 'NoteProperty' Definition $a.Definition -P |
Add-Member 'NoteProperty' Description $a.Description -P |
Add-Member 'NoteProperty' Key $e.Key -P |
Add-Member 'NoteProperty' Location $c.Location -P |
Add-Member 'NoteProperty' LocationName $c.LocationName -P |
Add-Member 'NoteProperty' Options $a.Options -P |
Add-Member 'NoteProperty' ReferencedCommand $a.ReferencedCommand -P |
Add-Member 'NoteProperty' ResolvedCommand $a.ResolvedCommand -P |
Add-Member 'NoteProperty' ScriptBlock $f.ScriptBlock -P |
Add-Member 'NoteProperty' StoreNames $c.StoreNames -P |
Add-Member 'NoteProperty' SubKeyCount $h.SubKeyCount -P |
Add-Member 'NoteProperty' Value $e.Value -P |
Add-Member 'NoteProperty' ValueCount $h.ValueCount -P |
Add-Member 'NoteProperty' Visibility $a.Visibility -P |
Add-Member 'NoteProperty' Property $h.Property -P |
Add-Member 'NoteProperty' ResolvedCommandName $a.ResolvedCommandName -P |
Add-Member 'ScriptMethod' Close {} -P |
Add-Member 'ScriptMethod' CreateSubKey {} -P |
Add-Member 'ScriptMethod' DeleteSubKey {} -P |
Add-Member 'ScriptMethod' DeleteSubKeyTree {} -P |
Add-Member 'ScriptMethod' DeleteValue {} -P |
Add-Member 'ScriptMethod' Flush {} -P |
Add-Member 'ScriptMethod' GetSubKeyNames {} -P |
Add-Member 'ScriptMethod' GetValue {} -P |
Add-Member 'ScriptMethod' GetValueKind {} -P |
Add-Member 'ScriptMethod' GetValueNames {} -P |
Add-Member 'ScriptMethod' IsValidValue {} -P |
Add-Member 'ScriptMethod' OpenSubKey {} -P |
Add-Member 'ScriptMethod' SetValue {} -P
}
if ( $global:_mix -eq $null )
{
$f = gi $PSHOME\\powershell.exe
$t = [type]
$s = ""
$global:_mix = `
Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Mode $f.Mode -P |
Add-Member 'NoteProperty' Assembly $t.Assembly -P |
Add-Member 'NoteProperty' AssemblyQualifiedName $t.AssemblyQualifiedName -P |
Add-Member 'NoteProperty' Attributes $f.Attributes -P |
Add-Member 'NoteProperty' BaseType $t.BaseType -P |
Add-Member 'NoteProperty' ContainsGenericParameters $t.ContainsGenericParameters -P |
Add-Member 'NoteProperty' CreationTime $f.CreationTime -P |
Add-Member 'NoteProperty' CreationTimeUtc $f.CreationTimeUtc -P |
Add-Member 'NoteProperty' DeclaringMethod $t.DeclaringMethod -P |
Add-Member 'NoteProperty' DeclaringType $t.DeclaringType -P |
Add-Member 'NoteProperty' Exists $f.Exists -P |
Add-Member 'NoteProperty' Extension $f.Extension -P |
Add-Member 'NoteProperty' FullName $f.FullName -P |
Add-Member 'NoteProperty' GenericParameterAttributes $t.GenericParameterAttributes -P |
Add-Member 'NoteProperty' GenericParameterPosition $t.GenericParameterPosition -P |
Add-Member 'NoteProperty' GUID $t.GUID -P |
Add-Member 'NoteProperty' HasElementType $t.HasElementType -P |
Add-Member 'NoteProperty' IsAbstract $t.IsAbstract -P |
Add-Member 'NoteProperty' IsAnsiClass $t.IsAnsiClass -P |
Add-Member 'NoteProperty' IsArray $t.IsArray -P |
Add-Member 'NoteProperty' IsAutoClass $t.IsAutoClass -P |
Add-Member 'NoteProperty' IsAutoLayout $t.IsAutoLayout -P |
Add-Member 'NoteProperty' IsByRef $t.IsByRef -P |
Add-Member 'NoteProperty' IsClass $t.IsClass -P |
Add-Member 'NoteProperty' IsCOMObject $t.IsCOMObject -P |
Add-Member 'NoteProperty' IsContextful $t.IsContextful -P |
Add-Member 'NoteProperty' IsEnum $t.IsEnum -P |
Add-Member 'NoteProperty' IsExplicitLayout $t.IsExplicitLayout -P |
Add-Member 'NoteProperty' IsGenericParameter $t.IsGenericParameter -P |
Add-Member 'NoteProperty' IsGenericType $t.IsGenericType -P |
Add-Member 'NoteProperty' IsGenericTypeDefinition $t.IsGenericTypeDefinition -P |
Add-Member 'NoteProperty' IsImport $t.IsImport -P |
Add-Member 'NoteProperty' IsInterface $t.IsInterface -P |
Add-Member 'NoteProperty' IsLayoutSequential $t.IsLayoutSequential -P |
Add-Member 'NoteProperty' IsMarshalByRef $t.IsMarshalByRef -P |
Add-Member 'NoteProperty' IsNested $t.IsNested -P |
Add-Member 'NoteProperty' IsNestedAssembly $t.IsNestedAssembly -P |
Add-Member 'NoteProperty' IsNestedFamANDAssem $t.IsNestedFamANDAssem -P |
Add-Member 'NoteProperty' IsNestedFamily $t.IsNestedFamily -P |
Add-Member 'NoteProperty' IsNestedFamORAssem $t.IsNestedFamORAssem -P |
Add-Member 'NoteProperty' IsNestedPrivate $t.IsNestedPrivate -P |
Add-Member 'NoteProperty' IsNestedPublic $t.IsNestedPublic -P |
Add-Member 'NoteProperty' IsNotPublic $t.IsNotPublic -P |
Add-Member 'NoteProperty' IsPointer $t.IsPointer -P |
Add-Member 'NoteProperty' IsPrimitive $t.IsPrimitive -P |
Add-Member 'NoteProperty' IsPublic $t.IsPublic -P |
Add-Member 'NoteProperty' IsSealed $t.IsSealed -P |
Add-Member 'NoteProperty' IsSerializable $t.IsSerializable -P |
Add-Member 'NoteProperty' IsSpecialName $t.IsSpecialName -P |
Add-Member 'NoteProperty' IsUnicodeClass $t.IsUnicodeClass -P |
Add-Member 'NoteProperty' IsValueType $t.IsValueType -P |
Add-Member 'NoteProperty' IsVisible $t.IsVisible -P |
Add-Member 'NoteProperty' LastAccessTime $f.LastAccessTime -P |
Add-Member 'NoteProperty' LastAccessTimeUtc $f.LastAccessTimeUtc -P |
Add-Member 'NoteProperty' LastWriteTime $f.LastWriteTime -P |
Add-Member 'NoteProperty' LastWriteTimeUtc $f.LastWriteTimeUtc -P |
Add-Member 'NoteProperty' MemberType $t.MemberType -P |
Add-Member 'NoteProperty' MetadataToken $t.MetadataToken -P |
Add-Member 'NoteProperty' Module $t.Module -P |
Add-Member 'NoteProperty' Name $t.Name -P |
Add-Member 'NoteProperty' Namespace $t.Namespace -P |
Add-Member 'NoteProperty' Parent $f.Parent -P |
Add-Member 'NoteProperty' ReflectedType $t.ReflectedType -P |
Add-Member 'NoteProperty' Root $f.Root -P |
Add-Member 'NoteProperty' StructLayoutAttribute $t.StructLayoutAttribute -P |
Add-Member 'NoteProperty' TypeHandle $t.TypeHandle -P |
Add-Member 'NoteProperty' TypeInitializer $t.TypeInitializer -P |
Add-Member 'NoteProperty' UnderlyingSystemType $t.UnderlyingSystemType -P |
Add-Member 'NoteProperty' PSChildName $f.PSChildName -P |
Add-Member 'NoteProperty' PSDrive $f.PSDrive -P |
Add-Member 'NoteProperty' PSIsContainer $f.PSIsContainer -P |
Add-Member 'NoteProperty' PSParentPath $f.PSParentPath -P |
Add-Member 'NoteProperty' PSPath $f.PSPath -P |
Add-Member 'NoteProperty' PSProvider $f.PSProvider -P |
Add-Member 'NoteProperty' BaseName $f.BaseName -P |
Add-Member 'ScriptMethod' Clone {} -P |
Add-Member 'ScriptMethod' CompareTo {} -P |
Add-Member 'ScriptMethod' Contains {} -P |
Add-Member 'ScriptMethod' CopyTo {} -P |
Add-Member 'ScriptMethod' Create {} -P |
Add-Member 'ScriptMethod' CreateObjRef {} -P |
Add-Member 'ScriptMethod' CreateSubdirectory {} -P |
Add-Member 'ScriptMethod' Delete {} -P |
Add-Member 'ScriptMethod' EndsWith {} -P |
Add-Member 'ScriptMethod' FindInterfaces {} -P |
Add-Member 'ScriptMethod' FindMembers {} -P |
Add-Member 'ScriptMethod' GetAccessControl {} -P |
Add-Member 'ScriptMethod' GetArrayRank {} -P |
Add-Member 'ScriptMethod' GetConstructor {} -P |
Add-Member 'ScriptMethod' GetConstructors {} -P |
Add-Member 'ScriptMethod' GetCustomAttributes {} -P |
Add-Member 'ScriptMethod' GetDefaultMembers {} -P |
Add-Member 'ScriptMethod' GetDirectories {} -P |
Add-Member 'ScriptMethod' GetElementType {} -P |
Add-Member 'ScriptMethod' GetEnumerator {} -P |
Add-Member 'ScriptMethod' GetEvent {} -P |
Add-Member 'ScriptMethod' GetEvents {} -P |
Add-Member 'ScriptMethod' GetField {} -P |
Add-Member 'ScriptMethod' GetFields {} -P |
Add-Member 'ScriptMethod' GetFiles {} -P |
Add-Member 'ScriptMethod' GetFileSystemInfos {} -P |
Add-Member 'ScriptMethod' GetGenericArguments {} -P |
Add-Member 'ScriptMethod' GetGenericParameterConstraints {} -P |
Add-Member 'ScriptMethod' GetGenericTypeDefinition {} -P |
Add-Member 'ScriptMethod' GetInterface {} -P |
Add-Member 'ScriptMethod' GetInterfaceMap {} -P |
Add-Member 'ScriptMethod' GetInterfaces {} -P |
Add-Member 'ScriptMethod' GetLifetimeService {} -P |
Add-Member 'ScriptMethod' GetMember {} -P |
Add-Member 'ScriptMethod' GetMembers {} -P |
Add-Member 'ScriptMethod' GetMethod {} -P |
Add-Member 'ScriptMethod' GetMethods {} -P |
Add-Member 'ScriptMethod' GetNestedType {} -P |
Add-Member 'ScriptMethod' GetNestedTypes {} -P |
Add-Member 'ScriptMethod' GetObjectData {} -P |
Add-Member 'ScriptMethod' GetProperties {} -P |
Add-Member 'ScriptMethod' GetProperty {} -P |
Add-Member 'ScriptMethod' GetTypeCode {} -P |
Add-Member 'ScriptMethod' IndexOf {} -P |
Add-Member 'ScriptMethod' IndexOfAny {} -P |
Add-Member 'ScriptMethod' InitializeLifetimeService {} -P |
Add-Member 'ScriptMethod' Insert {} -P |
Add-Member 'ScriptMethod' InvokeMember {} -P |
Add-Member 'ScriptMethod' IsAssignableFrom {} -P |
Add-Member 'ScriptMethod' IsDefined {} -P |
Add-Member 'ScriptMethod' IsInstanceOfType {} -P |
Add-Member 'ScriptMethod' IsNormalized {} -P |
Add-Member 'ScriptMethod' IsSubclassOf {} -P |
Add-Member 'ScriptMethod' LastIndexOf {} -P |
Add-Member 'ScriptMethod' LastIndexOfAny {} -P |
Add-Member 'ScriptMethod' MakeArrayType {} -P |
Add-Member 'ScriptMethod' MakeByRefType {} -P |
Add-Member 'ScriptMethod' MakeGenericType {} -P |
Add-Member 'ScriptMethod' MakePointerType {} -P |
Add-Member 'ScriptMethod' MoveTo {} -P |
Add-Member 'ScriptMethod' Normalize {} -P |
Add-Member 'ScriptMethod' PadLeft {} -P |
Add-Member 'ScriptMethod' PadRight {} -P |
Add-Member 'ScriptMethod' Refresh {} -P |
Add-Member 'ScriptMethod' Remove {} -P |
Add-Member 'ScriptMethod' Replace {} -P |
Add-Member 'ScriptMethod' SetAccessControl {} -P |
Add-Member 'ScriptMethod' Split {} -P |
Add-Member 'ScriptMethod' StartsWith {} -P |
Add-Member 'ScriptMethod' Substring {} -P |
Add-Member 'ScriptMethod' ToCharArray {} -P |
Add-Member 'ScriptMethod' ToLower {} -P |
Add-Member 'ScriptMethod' ToLowerInvariant {} -P |
Add-Member 'ScriptMethod' ToUpper {} -P |
Add-Member 'ScriptMethod' ToUpperInvariant {} -P |
Add-Member 'ScriptMethod' Trim {} -P |
Add-Member 'ScriptMethod' TrimEnd {} -P |
Add-Member 'ScriptMethod' TrimStart {} -P |
Add-Member 'NoteProperty' Chars $s.Chars -P
}
if ( "Add-Member" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Compare-Object" -eq $_cmdlet )
{
$global:_dummy = (Compare-Object 1 2)[0]
}
if ( "ConvertFrom-SecureString" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "ConvertTo-SecureString" -eq $_cmdlet )
{
$global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force
}
if ( "ForEach-Object" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Acl" -eq $_cmdlet )
{
$global:_dummy = Get-Acl
}
if ( "Get-Alias" -eq $_cmdlet )
{
$global:_dummy = (Get-Alias)[0]
}
if ( "Get-AuthenticodeSignature" -eq $_cmdlet )
{
$global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe
}
if ( "Get-ChildItem" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-Command" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-Content" -eq $_cmdlet )
{
$global:_dummy = (type $PSHOME\\profile.ps1)[0]
}
if ( "Get-Credential" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Culture" -eq $_cmdlet )
{
$global:_dummy = Get-Culture
}
if ( "Get-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( "Get-Event" -eq $_cmdlet )
{
$global:_dummy = (Get-Event)[0]
}
if ( "Get-EventLog" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-ExecutionPolicy" -eq $_cmdlet )
{
$global:_dummy = Get-ExecutionPolicy
}
if ( "Get-Help" -eq $_cmdlet )
{
$global:_dummy = Get-Help Add-Content
}
if ( "Get-History" -eq $_cmdlet )
{
$global:_dummy = Get-History -Count 1
}
if ( "Get-Host" -eq $_cmdlet )
{
$global:_dummy = Get-Host
}
if ( "Get-Item" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-ItemProperty" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Location" -eq $_cmdlet )
{
$global:_dummy = Get-Location
}
if ( "Get-Member" -eq $_cmdlet )
{
$global:_dummy = (1|Get-Member)[0]
}
if ( "Get-Module" -eq $_cmdlet )
{
$global:_dummy = (Get-Module)[0]
}
if ( "Get-PfxCertificate" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Process" -eq $_cmdlet )
{
$global:_dummy = ps powershell
}
if ( "Get-PSBreakpoint" -eq $_cmdlet )
{
$global:_dummy =
Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Action '' -P |
Add-Member 'NoteProperty' Command '' -P |
Add-Member 'NoteProperty' Enabled '' -P |
Add-Member 'NoteProperty' HitCount '' -P |
Add-Member 'NoteProperty' Id '' -P |
Add-Member 'NoteProperty' Script '' -P
}
if ( "Get-PSCallStack" -eq $_cmdlet )
{
$global:_dummy = Get-PSCallStack
}
if ( "Get-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Function
}
if ( "Get-PSProvider" -eq $_cmdlet )
{
$global:_dummy = Get-PSProvider FileSystem
}
if ( "Get-PSSnapin" -eq $_cmdlet )
{
$global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core
}
if ( "Get-Service" -eq $_cmdlet )
{
$global:_dummy = (Get-Service)[0]
}
if ( "Get-TraceSource" -eq $_cmdlet )
{
$global:_dummy = Get-TraceSource AddMember
}
if ( "Get-UICulture" -eq $_cmdlet )
{
$global:_dummy = Get-UICulture
}
if ( "Get-Variable" -eq $_cmdlet )
{
$global:_dummy = Get-Variable _
}
if ( "Get-WmiObject" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Group-Object" -eq $_cmdlet )
{
$global:_dummy = 1 | group
}
if ( "Measure-Command" -eq $_cmdlet )
{
$global:_dummy = Measure-Command {}
}
if ( "Measure-Object" -eq $_cmdlet )
{
$global:_dummy = Measure-Object
}
if ( "New-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Alias
}
if ( "New-TimeSpan" -eq $_cmdlet )
{
$global:_dummy = New-TimeSpan
}
if ( "Resolve-Path" -eq $_cmdlet )
{
$global:_dummy = $PWD
}
if ( "Select-String" -eq $_cmdlet )
{
$global:_dummy = " " | Select-String " "
}
if ( "Set-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( $property -ne $null)
{
foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) )
{
$global:_dummy = @($global:_dummy.$name)[0]
}
}
}
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$params = @{view = 'extended','adapted','base'}
}
else
{
$params = @{static=$true}
}
if ( $_val -is [Hashtable] )
{
[Object[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
}
if ( $_keys -ne $null )
{
$_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat})
} else {
$_members = (Get-Member @params -InputObject $_val $_pat)
}
foreach ($_m in $_members | Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
$host.UI.RawUI.WindowTitle = "Windows PowerShell V2 (CTP2)" + $lastword
switch ([int]$line[-1])
{
# Ctrl+D several date/time formats
4 {
"[DateTime]::Now"
[DateTime]::Now
[DateTime]::Now.ToString("yyyyMMdd")
[DateTime]::Now.ToString("MMddyyyy")
[DateTime]::Now.ToString("yyyyMMddHHmmss")
[DateTime]::Now.ToString("MMddyyyyHHmmss")
'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) }
break;
}
# Ctrl+P hand-operated pop from command buffer stack
16 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_base + $global:_cmdstack.Pop()
break;
}
# Ctrl+R $Host.UI.RawUI.
18 {
'$Host.UI.RawUI.'
'$Host.UI.RawUI'
break;
}
# Ctrl+V paste clipboard
22 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$global:_clip = New-Object System.Windows.Forms.TextBox
$global:_clip.Multiline = $true
$global:_clip.Paste()
$_base + $global:_clip.Text
break;
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[8] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[(\\w+(\\.\\w*)*)$' {
$_opt = $matches[1] + '*'
if ( $_opt -eq "*" )
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
}
else
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]'
"CmdletBinding", "Parameter", "Alias",
"ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength",
"ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange",
"ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" `
-like $_opt -replace '^(.*)$', '[$1('
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '['
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '['
}
break;
}
# Handle file/directory name which contains $env: variable
# e.g. $env:windir\\<tab>
'^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' {
$path = iex ('"' + $Matches[0] + '"')
if ( $Matches[2].Length -gt 1 )
{
$parent = Split-Path $path -Parent
$leaf = (Split-Path $path -Leaf) + '*'
}
else
{
$parent = $path
$leaf = '*'
}
if ( Test-Path $parent )
{
$i = $Matches[0].LastIndexOfAny("/\\")
$_base = $Matches[0].Substring(0,$i+1)
[IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') }
}
}
# Handle file glob expansion ...
# e.g. *.txt~about*@<tab>
'^(\\^?([^~]+))(~(.*))*@$' {
if ( $Matches[1] -notlike "^*" )
{
$include = $Matches[2] -replace '``','`'
if ( $Matches[3] )
{
$exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`'
}
}
else
{
$include = "*"
$exclude = $Matches[2] -replace '``','`'
}
$fse = [IO.Directory]::GetFileSystemEntries($PWD)
$fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1'
% -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } }
$fse = $fse -replace '^.*\\s.*$', ("'`$0'")
$fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'")
$fse = $fse -replace "''", "'"
$OFS = ", "; "$fse"
$OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"})
$Matches[0].Substring(0, $Matches[0].Length-1)
break;
}
# Handle command buffer stack...
'(.*);(.?)$' {
$_base = $Matches[1]
if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," )
{
if ( $_cmdstack.Count -gt 0 )
{
$_base + $global:_cmdstack.Pop()
}
else
{
""; break;
}
}
elseif ( $Matches[2] -eq "" )
{
$global:_cmdstack.Push($line.SubString(0,$line.Length-1))
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
""; break;
}
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_command = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_command -match '\\{([^\\{\\}]*)$')
{
$_command = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_command -match '\\(([^()]*)$')
{
$_command = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_command = $_command.Trim().Split()[0]
# now get the info object for it...
$_command = @(Get-Command -type 'All' $_command)[0]
# loop resolving aliases...
while ($_command.CommandType -eq 'alias')
{
$_command = @(Get-Command -type 'All' $_command.Definition)[0]
}
if ( $_command.name -eq "powershell.exe" )
{
if ( $global:_PSexeOption )
{
$global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort
}
else
{
($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort
}
break;
}
if ( $_command -ne $null )
{
# expand the parameter sets and emit the matching elements
foreach ($_n in $_command.Parameters.Keys | sort)
{
if ($_n -like $_pat) { '-' + $_n }
}
}
elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$')
{
$_pat = $Matches[2] + '*'
"regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1'
break;
}
else
{
"-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt",
"-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge",
"-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike",
"-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains",
"-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat"
}
break;
}
# Tab complete against history either #<pattern> or #<id>
'^#(\\w*)' {
$_pattern = $matches[1]
if ($_pattern -match '^[0-9]+$')
{
Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine }
}
else
{
$_pattern = '*' + $_pattern + '*'
Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern }
}
break;
}
# try to find a matching command...
default {
# parse the script...
$_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null)
if ( $_tokens )
{
$_lastToken = $_tokens[$_tokens.count - 1]
if ($_lastToken.Type -eq 'Member')
{
$_pat = $_lastToken.Content + '*'
$i=$_tokens.count; do { $i-- } until ( $_tokens[$i].Type -eq "Attribute")
if ( $lastWord -match "^(.*)([\\(,])\\w*$" )
{
$_base = $matches[1] + $matches[2]
}
switch ( $_tokens[$i].Content )
{
'Parameter' {
[System.Management.Automation.ParameterAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" }
}
'CmdletBinding' {
[System.Management.Automation.CmdletBindingAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" }
}
}
break;
}
if ( $_tokens[1].Type -eq "Attribute")
{
if ( $line.Split("(").Count -gt $line.Split(")").Count )
{
if ( $lastWord -match "^(.*)([\\(,])\\w*$" )
{
$_base = $matches[1] + $matches[2]
}
switch ( $_tokens[1].Content )
{
'Parameter' {
[System.Management.Automation.ParameterAttribute].GetProperties() | % { $_base + $_.Name + "=" }
}
'CmdletBinding' {
[System.Management.Automation.CmdletBindingAttribute].GetProperties() | % { $_base + $_.Name + "=" }
}
}
}
break;
}
}
$lastex = [regex]::Split($line, '[|;]')[-1]
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' )
{
if ( $Matches[6] -ne $nul )
{
$brackets = "[]"
}
'['+ $global:_enum + $brackets + ']'
break;
}
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' )
{
$_pat = $Matches[7] + '*'
$_type = @(iex $Matches[1])[0].GetType()
if ( $_type.IsEnum )
{
$global:_enum = $_type.FullName
[Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"'
break;
}
}
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$')
{
'['+ $global:_enum + ']'
}
elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' )
{
$_method = $Matches[1]
if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" )
{
$continuous = $true
$_opt = $Matches[5] + '*'
$_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1'
$position = $Matches[1].Split(",").Length
}
else
{
$continuous = $false
$_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*"
$position = $Matches[3].Split(",").Length
}
if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null )
{
$tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }')
}
foreach ( $def in $_mdefs )
{
[void] ($def -match '\\((.*)\\)')
foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] )
{
if ($param -eq $null -or $param -eq "")
{
continue;
}
$type = $param.split()[0]
if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" )
{
continue;
}
$fullname = @($_typenames -like "*$type*")
foreach ( $name in $fullname )
{
if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$global:_enum = $name
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"'
$output | sort
}
}
}
}
if ( $output -ne $null )
{
break;
}
}
if ( $line -match '(function|filter)\\s+(\\w*)$')
{
$_pat = 'function:\\' + $Matches[2] + '*'
Get-ChildItem $_pat| % { $_.Name }
break;
}
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeAccelerators
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | gm -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
# 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,function' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeAccelerators -like $_opt
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1)
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1)
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_'
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
#$_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 -or "help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_'
break;
}
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name -and "Property" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Select-Object" -eq $_cmdlet.Name )
{
if ( "ExcludeProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "ExpandProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ($_tokens)
{
$_lastToken = $_tokens[$_tokens.count - 1]
if ($_lastToken.Type -eq 'Command')
{
$_cmd = $_lastToken.Content
# don't look for paths...
if ($_cmd.IndexOfAny('/\\') -eq -1)
{
# handle parsing errors - the last token string should be the last
# string in the line...
if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd)
{
$_pat = $_cmd + '*'
$_base = $lastword.substring(0, $lastword.length-$_cmd.length)
"begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (",
"end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ",
"param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" `
-like $_pat | % {'{0}{1}' -f $_base,$_ }
$ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) |
Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ }
}
}
}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Add-ObjectCollector.ps1
|
Add-ObjectCollector.ps1
|
##############################################################################\n##\n## Add-ObjectCollector\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\nAdds a new Out-Default command wrapper to store up to 500 elements from\nthe previous command. This wrapper stores output in the $ll variable.\n\n.EXAMPLE\n\nPS >Get-Command $pshome\\powershell.exe\n\nCommandType Name Definition\n----------- ---- ----------\nApplication powershell.exe C:\\Windows\\System32\\Windo...\n\nPS >$ll.Definition\nC:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\n\n.NOTES\n\nThis command builds on New-CommandWrapper, also included in the Windows\nPowerShell Cookbook.\n\n#>\n\nSet-StrictMode -Version Latest\n\nNew-CommandWrapper Out-Default `\n -Begin {\n $cachedOutput = New-Object System.Collections.ArrayList\n } `\n -Process {\n ## If we get an input object, add it to our list of objects\n if($_ -ne $null) { $null = $cachedOutput.Add($_) }\n while($cachedOutput.Count -gt 500) { $cachedOutput.RemoveAt(0) }\n } `\n -End {\n ## Be sure we got objects that were not just errors (\n ## so that we don't wipe out the saved output when we get errors\n ## trying to work with it.)\n ## Also don't caputre formatting information, as those objects\n ## can't be worked with.\n $uniqueOutput = $cachedOutput | Foreach-Object {\n $_.GetType().FullName } | Select -Unique\n $containsInterestingTypes = ($uniqueOutput -notcontains `\n "System.Management.Automation.ErrorRecord") -and\n ($uniqueOutput -notlike `\n "Microsoft.PowerShell.Commands.Internal.Format.*")\n\n ## If we actually had output, and it was interesting information,\n ## save the output into the $ll variable\n if(($cachedOutput.Count -gt 0) -and $containsInterestingTypes)\n {\n $GLOBAL:ll = $cachedOutput | % { $_ }\n }\n }
|
PowerShellCorpus/PoshCode/New-Choice.ps1
|
New-Choice.ps1
|
function New-Choice {
<#
.SYNOPSIS
The New-Choice function is used to provide extended control to a script author who writing code
that will prompt a user for information.
.PARAMETER Choices
An Array of Choices, ie Yes, No and Maybe
.PARAMETER Caption
Caption to present to end user
.EXAMPLE
PS C:\\> New-Choice -Choices 'Yes','No' -Caption "PowerShell makes choices easy"
.NOTES
Author: Andy Schneider
Date: 5/6/2011
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$True, ValueFromPipeline=$True)]
$Choices,
[Parameter(Position=1)]
$Caption,
[Parameter(Position=2)]
$Message
)
process {
$resulthash += @{}
for ($i = 0; $i -lt $choices.count; $i++)
{
$ChoiceDescriptions += @(New-Object System.Management.Automation.Host.ChoiceDescription $choices[$i])
$resulthash.$i = $choices[$i]
}
$AllChoices = [System.Management.Automation.Host.ChoiceDescription[]]($ChoiceDescriptions)
$result = $Host.UI.PromptForChoice($Caption,$Message, $AllChoices, 1)
$resulthash.$result
}
}
|
PowerShellCorpus/PoshCode/lazywinadmin.com.ps1
|
lazywinadmin.com.ps1
|
Get-WmiObject Win32_Service -ComputerName . |`
where {($_.startmode -like "*auto*") -and `
($_.state -notlike "*running*")}|`
select DisplayName,Name,StartMode,State|ft -AutoSize
|
PowerShellCorpus/PoshCode/Get-StructFromMemory.ps1
|
Get-StructFromMemory.ps1
|
function Get-StructFromMemory
{
<#
.SYNOPSIS
Marshals data from an unmanaged block of memory in an arbitrary process to a newly allocated managed object of the specified type.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
.DESCRIPTION
Get-StructFromMemory is similar to the Marshal.PtrToStructure method but will parse and return a structure from any process.
.PARAMETER Id
Process ID of the process whose virtual memory space you want to access.
.PARAMETER MemoryAddress
The address containing the structure to be parsed.
.PARAMETER StructType
The type (System.Type) of the desired structure to be parsed.
.EXAMPLE
C:\\PS> Get-Process | ForEach-Object { Get-StructFromMemory -Id $_.Id -MemoryAddress $_.MainModule.BaseAddress -StructType ([PE+_IMAGE_DOS_HEADER]) }
Description
-----------
Parses the DOS headers of every loaded process. Note: In this example, this assumes that [PE+_IMAGE_DOS_HEADER] is defined. You can get the code to define [PE+_IMAGE_DOS_HEADER] here: http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html
.NOTES
Be sure to enclose the StructType parameter with parenthesis in order to force PowerShell to cast it as a Type object.
Get-StructFromMemory does a good job with error handling however it will crash if the structure contains fields that attempt to marshal pointers. For example, if a field has a custom attribute of UnmanagedType.LPStr, when the structure is parsed, it will attempt to dererence a string pointer for virtual memory in another process and access violate.
.LINK
http://www.exploit-monday.com/
#>
[CmdletBinding()] Param (
[Parameter(Position = 0, Mandatory = $True)]
[Alias('ProcessId')]
[Alias('PID')]
[UInt16]
$Id,
[Parameter(Position = 1, Mandatory = $True)]
[IntPtr]
$MemoryAddress,
[Parameter(Position = 2, Mandatory = $True)]
[Alias('Type')]
[Type]
$StructType
)
Set-StrictMode -Version 2
$PROCESS_VM_READ = 0x0010 # The process permissions we'l ask for when getting a handle to the process
# Get a reference to the private GetProcessHandle method is System.Diagnostics.Process
$GetProcessHandle = [Diagnostics.Process].GetMethod('GetProcessHandle', [Reflection.BindingFlags] 'NonPublic, Instance', $null, @([Int]), $null)
try
{
# Make sure user didn't pass in a non-existent PID
$Process = Get-Process -Id $Id -ErrorVariable GetProcessError
# Get the default process handle
$Handle = $Process.Handle
}
catch [Exception]
{
throw $GetProcessError
}
if ($Handle -eq $null)
{
throw "Unable to obtain a handle for PID $Id. You will likely need to run this script elevated."
}
# Get a reference to MEMORY_BASIC_INFORMATION. I don't feel like making the structure myself
$mscorlib = [AppDomain]::CurrentDomain.GetAssemblies() | ? { $_.FullName.Split(',')[0].ToLower() -eq 'mscorlib' }
$Win32Native = $mscorlib.GetTypes() | ? { $_.FullName -eq 'Microsoft.Win32.Win32Native' }
$MEMORY_BASIC_INFORMATION = $Win32Native.GetNestedType('MEMORY_BASIC_INFORMATION', [Reflection.BindingFlags] 'NonPublic')
if ($MEMORY_BASIC_INFORMATION -eq $null)
{
throw 'Unable to get a reference to the MEMORY_BASIC_INFORMATION structure.'
}
# Get references to private fields in MEMORY_BASIC_INFORMATION
$ProtectField = $MEMORY_BASIC_INFORMATION.GetField('Protect', [Reflection.BindingFlags] 'NonPublic, Instance')
$AllocationBaseField = $MEMORY_BASIC_INFORMATION.GetField('BaseAddress', [Reflection.BindingFlags] 'NonPublic, Instance')
$RegionSizeField = $MEMORY_BASIC_INFORMATION.GetField('RegionSize', [Reflection.BindingFlags] 'NonPublic, Instance')
try { $NativeUtils = [NativeUtils] } catch [Management.Automation.RuntimeException] # Only build the assembly if it hasn't already been defined
{
# Build dynamic assembly in order to use P/Invoke for interacting with the following Win32 functions: ReadProcessMemory, VirtualQueryEx
$DynAssembly = New-Object Reflection.AssemblyName('MemHacker')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('MemHacker', $False)
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('NativeUtils', $Attributes, [ValueType])
$TypeBuilder.DefinePInvokeMethod('ReadProcessMemory', 'kernel32.dll', [Reflection.MethodAttributes] 'Public, Static', [Reflection.CallingConventions]::Standard, [Bool], @([IntPtr], [IntPtr], [IntPtr], [UInt32], [UInt32].MakeByRefType()), [Runtime.InteropServices.CallingConvention]::Winapi, 'Auto') | Out-Null
$TypeBuilder.DefinePInvokeMethod('VirtualQueryEx', 'kernel32.dll', [Reflection.MethodAttributes] 'Public, Static', [Reflection.CallingConventions]::Standard, [UInt32], @([IntPtr], [IntPtr], $MEMORY_BASIC_INFORMATION.MakeByRefType(), [UInt32]), [Runtime.InteropServices.CallingConvention]::Winapi, 'Auto') | Out-Null
$NativeUtils = $TypeBuilder.CreateType()
}
# Request a handle to the process in interest
try
{
$SafeHandle = $GetProcessHandle.Invoke($Process, @($PROCESS_VM_READ))
$Handle = $SafeHandle.DangerousGetHandle()
}
catch
{
throw $Error[0]
}
# Create an instance of MEMORY_BASIC_INFORMATION
$MemoryBasicInformation = [Activator]::CreateInstance($MEMORY_BASIC_INFORMATION)
# Confirm you can actually read the address you're interested in
$NativeUtils::VirtualQueryEx($Handle, $MemoryAddress, [Ref] $MemoryBasicInformation, [Runtime.InteropServices.Marshal]::SizeOf($MEMORY_BASIC_INFORMATION)) | Out-Null
$PAGE_EXECUTE_READ = 0x20
$PAGE_EXECUTE_READWRITE = 0x40
$PAGE_READONLY = 2
$PAGE_READWRITE = 4
$Protection = $ProtectField.GetValue($MemoryBasicInformation)
$AllocationBaseOriginal = $AllocationBaseField.GetValue($MemoryBasicInformation)
$GetPointerValue = $AllocationBaseOriginal.GetType().GetMethod('GetPointerValue', [Reflection.BindingFlags] 'NonPublic, Instance')
$AllocationBase = $GetPointerValue.Invoke($AllocationBaseOriginal, $null).ToInt64()
$RegionSize = $RegionSizeField.GetValue($MemoryBasicInformation).ToUInt64()
Write-Verbose "Protection: $Protection"
Write-Verbose "AllocationBase: $AllocationBase"
Write-Verbose "RegionSize: $RegionSize"
if (($Protection -ne $PAGE_READONLY) -and ($Protection -ne $PAGE_READWRITE) -and ($Protection -ne $PAGE_EXECUTE_READ) -and ($Protection -ne $PAGE_EXECUTE_READWRITE))
{
$SafeHandle.Close()
throw 'The address specified does not have read access.'
}
$StructSize = [Runtime.InteropServices.Marshal]::SizeOf($StructType)
$EndOfAllocation = $AllocationBase + $RegionSize
$EndOfStruct = $MemoryAddress.ToInt64() + $StructSize
if ($EndOfStruct -gt $EndOfAllocation)
{
$SafeHandle.Close()
throw 'You are attempting to read beyond what was allocated.'
}
try
{
# Allocate unmanaged memory. This will be used to store the memory read from ReadProcessMemory
$LocalStructPtr = [Runtime.InteropServices.Marshal]::AllocHGlobal($StructSize)
}
catch [OutOfMemoryException]
{
throw Error[0]
}
Write-Verbose "Memory allocated at 0x$($LocalStructPtr.ToString("X$([IntPtr]::Size * 2)"))"
# Zero out the memory that was just allocated. According to MSDN documentation:
# "When AllocHGlobal calls LocalAlloc, it passes a LMEM_FIXED flag, which causes the allocated memory to be locked in place. Also, the allocated memory is not zero-filled."
# http://msdn.microsoft.com/en-us/library/s69bkh17.aspx
$ZeroBytes = New-Object Byte[]($StructSize)
[Runtime.InteropServices.Marshal]::Copy($ZeroBytes, 0, $LocalStructPtr, $StructSize)
$BytesRead = [UInt32] 0
if ($NativeUtils::ReadProcessMemory($Handle, $MemoryAddress, $LocalStructPtr, $StructSize, [Ref] $BytesRead))
{
$SafeHandle.Close()
[Runtime.InteropServices.Marshal]::FreeHGlobal($LocalStructPtr)
throw ([ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error())
}
Write-Verbose "Struct Size: $StructSize"
Write-Verbose "Bytes read: $BytesRead"
$ParsedStruct = [Runtime.InteropServices.Marshal]::PtrToStructure($LocalStructPtr, $StructType)
[Runtime.InteropServices.Marshal]::FreeHGlobal($LocalStructPtr)
$SafeHandle.Close()
Write-Output $ParsedStruct
}
|
PowerShellCorpus/PoshCode/Get-Parameter_5.ps1
|
Get-Parameter_5.ps1
|
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon ) {
foreach ($paramset in (Get-Command $Cmdlet).ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
if ( !$ShowCommon ) {
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob") { continue }
}
$process = "" | Select-Object Name, ParameterSet, Aliases, Position, IsMandatory
$process.Name = $param.Name
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
if ( $param.Position -lt 0 ) { $process.Position = $null }
else { $process.Position = $param.Position }
$process.IsMandatory = $param.IsMandatory
$output += $process
}
Write-Output $Output
}
}
|
PowerShellCorpus/PoshCode/New-GenericObject.ps1
|
New-GenericObject.ps1
|
##############################################################################\n##\n## New-GenericObject\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\nCreates an object of a generic type:\n\n.EXAMPLE\n\nPS >New-GenericObject System.Collections.ObjectModel.Collection System.Int32\nCreates a simple generic collection\n\n.EXAMPLE\n\nPS >New-GenericObject System.Collections.Generic.Dictionary `\n System.String,System.Int32\nCreates a generic dictionary with two types\n\n.EXAMPLE\n\nPS >$secondType = New-GenericObject System.Collections.Generic.List Int32\nPS >New-GenericObject System.Collections.Generic.Dictionary `\n System.String,$secondType.GetType()\nCreates a generic list as the second type to a generic dictionary\n\n.EXAMPLE\n\nPS >New-GenericObject System.Collections.Generic.LinkedListNode `\n System.String "Hi"\nCreates a generic type with a non-default constructor\n\n#>\n\nparam(\n ## The generic type to create\n [Parameter(Mandatory = $true)]\n [string] $TypeName,\n\n ## The types that should be applied to the generic object\n [Parameter(Mandatory = $true)]\n [string[]] $TypeParameters,\n\n ## Arguments to be passed to the constructor\n [object[]] $ConstructorParameters\n)\n\nSet-StrictMode -Version Latest\n\n## Create the generic type name\n$genericTypeName = $typeName + '`' + $typeParameters.Count\n$genericType = [Type] $genericTypeName\n\nif(-not $genericType)\n{\n throw "Could not find generic type $genericTypeName"\n}\n\n## Bind the type arguments to it\n[type[]] $typedParameters = $typeParameters\n$closedType = $genericType.MakeGenericType($typedParameters)\nif(-not $closedType)\n{\n throw "Could not make closed type $genericType"\n}\n\n## Create the closed version of the generic type\n,[Activator]::CreateInstance($closedType, $constructorParameters)
|
PowerShellCorpus/PoshCode/Start-Presentation_1.ps1
|
Start-Presentation_1.ps1
|
if(-not(get-command New-System.Windows.Window -EA 0)){ Import-Module PowerBoots }
Add-BootsTemplate $PSScriptRoot\\PresentationFrame.xaml
$name = [System.Windows.Navigation.JournalEntry]::NameProperty
[double]$global:zoomLevel = 1
$SlideCount = 0
function Start-Zoom {
PARAM(
[Parameter(Position=0)]
$Zoom = 0
,
[Parameter(ValueFromPipeline=$true)]
$Root = $($global:Frame)
,
[Parameter()]
$Window = $presentationTitle
)
$null = Invoke-BootsWindow $Window {
Param($Window,$Root)
if(!$Root.RenderTransform.Children) {
$Root.RenderTransform = TransformGroup {
ScaleTransform -ScaleX $zoomLevel -ScaleY $zoomLevel
TranslateTransform
}
$BootsWindow.Add_MouseDown( {
if($zoomLevel -ne 1) {
trap { Write-Host $( $_ | fl * | out-string ) }
$global:MouseDownPoint = [System.Windows.Input.Mouse]::GetPosition($BootsWindow)
$this.CaptureMouse()
}
} )
$BootsWindow.Add_MouseUp( {
if($zoomLevel -ne 1) {
trap { Write-Host $( $_ | fl * | out-string ) }
$this.ReleaseMouseCapture()
}
} )
$BootsWindow.Add_MouseMove( {
if($zoomLevel -ne 1) {
trap { Write-Host $( $_ | fl * | out-string ) }
if($_.LeftButton -eq "Pressed") {
$newPos = [System.Windows.Input.Mouse]::GetPosition($BootsWindow)
$this.Content.RenderTransform.Children[1].SetValue(
[System.Windows.Media.TranslateTransform]::XProperty,
$this.Content.RenderTransform.Children[1].Value.OffsetX + ($newPos.X - $MouseDownPoint.X) )
$this.Content.RenderTransform.Children[1].SetValue(
[System.Windows.Media.TranslateTransform]::YProperty,
$this.Content.RenderTransform.Children[1].Value.OffsetY + ($newPos.Y - $MouseDownPoint.Y) )
$global:MouseDownPoint = $newPos;
}
}
} )
}
} $Root
}
function Set-Zoom {
PARAM(
[Parameter(Position=0)]
$Zoom = 0
,
[Parameter()]
$Root = $global:Frame
,
[Parameter()]
$Window = $presentationTitle
)
if($Zoom -gt 0) {
$global:zoomLevel *= (1+($Zoom/10))
} elseif($Zoom -lt 0) {
$global:zoomLevel /= (1+($Zoom/-10))
} else {
$global:zoomLevel = 1.0
}
$null = Invoke-BootsWindow $Window {
Param($Window,$Root)
$Root.RenderTransform.Children[0].SetValue(
[System.Windows.Media.ScaleTransform]::ScaleXProperty, $zoomLevel )
$Root.RenderTransform.Children[0].SetValue(
[System.Windows.Media.ScaleTransform]::ScaleYProperty, $zoomLevel )
## Note that we have to account for rounding errors ;)
if([Math]::Round($zoomLevel, 10) -eq 1.0 ) {
$Root.NavigationUIVisibility = "Visible"
$Root.RenderTransform.Children[1].SetValue(
[System.Windows.Media.TranslateTransform]::XProperty, 0.0 )
$Root.RenderTransform.Children[1].SetValue(
[System.Windows.Media.TranslateTransform]::YProperty, 0.0 )
} else {
$Root.NavigationUIVisibility = "Hidden"
}
} $Root
}
function Show-Url {
[CmdletBinding()]
PARAM(
[Parameter(Position=0, ValueFromPipeline=$true)]
[Uri]$Content
,
[Parameter()]
$Window = $presentationTitle
)
Invoke-BootsWindow $Window {
$global:Frame.Navigate( $Content )
}
}
New-Alias Navigate Show-Url # backwards compat
function Add-Slide {
#.Synopsis
# Add a slide to the presentation
#.Description
# Add any .net object as a slide to a presentation, wrapping it in a Page to set the title.
[CmdletBinding(DefaultParameterSetName="Script")]
PARAM(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Name")]
[String]$Title = "Slide $SlideCount"
, [Parameter(Position=1, ValueFromPipeline=$true, Mandatory=$true)]
$Content
, [Parameter()]
$Window = $presentationTitle
)
PROCESS {
$SlideCount++
Invoke-BootsWindow $Window {
Param($Frame, $Content, $Title)
$Frame.Content = Page -Content $Content -Title $Title
} $global:Frame $Content $Title
}
}
function Add-TextSlide {
#.Synopsis
# Add a text slide to the presentation
#.Description
# Add a textual slide to the presentation with a header and several points
[CmdletBinding()]
PARAM(
[Parameter(Position=0)]
$Title = "Slide $SlideCount"
, [Parameter(Position=1, ValueFromPipeline=$true)]
[string[]]$Content = @("Several bullet points", "Which are equally important")
, [Parameter()]
$Window = $presentationTitle
)
BEGIN { [string[]]$global:Points = @() }
PROCESS { [string[]]$global:Points += $Content }
END {
Add-Slide -Title $Title -Window $Window -Content {
StackPanel -Margin 10 {
grid {
TextBlock $Title -FontSize 85 -FontFamily Impact -Foreground White -Effect { BlurEffect -Radius 15 } -TextAlign Center
TextBlock $Title -FontSize 85 -FontFamily Impact -Foreground $global:TitleBrush -TextAlign Center
}
write-host "Points: $Points"
$Points | % {
TextBlock $_ -FontSize 64 -FontWeight Bold -Foreground "White" -TextWrapping Wrap -Effect { DropShadowEffect -BlurRadius 15 }
}
}
}.GetNewClosure()
}
}
function Add-TitleSlide {
#.Synopsis
# Add a text slide to the presentation
#.Description
# Add a textual slide to the presentation with a header and several points
[CmdletBinding()]
PARAM(
[Parameter(Position=0)]
$Title
, [Parameter()]
$Window = $presentationTitle
)
BEGIN { [string[]]$Points = @() }
PROCESS { [string[]]$Points += $Content }
END {
Add-Slide -Title $Title -Window $Window -Content {
Grid {
TextBlock $Title `
-FontSize 125 -FontFamily Impact -Foreground White `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
-Effect { BlurEffect -Radius 20 }
TextBlock $Title `
-FontSize 125 -FontFamily Impact -Foreground White `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
-Effect { BlurEffect -Radius 20 }
TextBlock $Title `
-FontSize 125 -FontFamily Impact -Foreground $global:TitleBrush `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
-Effect {DropShadowEffect -Color White -Radius 15}
}
}
}
}
function Remove-Slide {
#.Synopsis
# Removes the specified slide from the deck (history)
#.Description
# Takes an index or name, and removes that slide, except that you CANNOT remove the last slide.
PARAM(
[Parameter(ParameterSetName="ByIndex", Mandatory=$true, Position=0)]
[int]$index
, [Parameter(ParameterSetName="ByTitle", Mandatory=$true, Position=0)]
[Alias("Name")]
[string]$Title
, [Parameter()]
$Window = $presentationTitle
)
$null = Invoke-BootsWindow $Window {
# Figure out where we are now, because we'll need to come back
$global:currentSlide = @($global:Frame.BackStack.GetEnumerator()).Count
# Activate the slide they want to delete ...
[int]$removable = Set-Slide @PsBoundParameters -passthru
}
# Separate Invoke's are required for the window to register what's going on?
$global:removable = $true
$null = Invoke-BootsWindow $Window {
if($global:Frame.CanGoForward) {
$global:Frame.GoForward()
} else {
$global:removable = $false
Write-Host "Sorry, you can't remove the last slide in the deck." -Fore Red
}
}
if($global:removable) {
# Separate Invoke's are required for the window to register what's going on?
Invoke-BootsWindow $Window {
$null = $global:Frame.RemoveBackEntry()
Set-Slide $currentSlide
}
}
}
function Show-Slide {
#.Synopsis
# Set the active slide in a deck
#.Description
# Sets the active slide by index or name (title)
[CmdletBinding(DefaultParameterSetName="ByIndex")]
PARAM(
[Parameter(ParameterSetName="ByIndex", Mandatory=$true, Position=0)]
[int]$index
, [Parameter(ParameterSetName="ByTitle", Mandatory=$true, Position=0)]
[Alias("Name")]
[string]$Title
, [Parameter()]
$Window = $presentationTitle
, [Parameter()]
[Switch]$Passthru
)
switch($PSCmdlet.ParameterSetName) {
"ByIndex" {
$null = Invoke-BootsWindow $Window {
# Figure out where we are now...
[int]$global:current = @($global:Frame.BackStack.GetEnumerator()).Count
# Then go where we need to
for(;$current -lt $index -and $global:Frame.CanGoForward ;$global:current++) {
$global:Frame.GoForward()
}
for(;$current -gt $index -and $global:Frame.CanGoBack ;$global:current--) {
$global:Frame.GoBack()
}
}
if($Passthru) { return $global:current }
}
"ByTitle" {
[int]$global:result = -1
[int]$global:current = -1
$null = Invoke-BootsWindow $Window {
# Figure out where we are now...
$global:current = @($global:Frame.BackStack.GetEnumerator()).Count
# Start with backward history ('cause it's more likely)
[int]$i = 0;
foreach($page in $global:Frame.BackStack) {
if($page.Name -eq $Title) {
$global:result = $current - $i - 1
for(;$i -gt $0 -and $global:Frame.CanGoBack;$i--) {
$global:Frame.GoBack()
}
break;
}
$i++
}
# Failing that, try forward history
[int]$i = 0;
foreach($page in $global:Frame.ForwardStack) {
if($page.Name -eq $Title) {
$global:result = $current + $i + 1
for(;$i -gt $0 -and $global:Frame.CanGoForward ;$i--) {
$global:Frame.GoForward()
}
break;
}
$i++
}
}
if($Passthru) {
if($global:result -ge 0) {
return $global:result
} else {
return $global:current
}
}
}
}
}
New-Alias Set-Slide Show-Slide # backwards compat
function Move-NextSlide {
#.Synopsis
# Navigates to the next slide (if there is another)
PARAM(
[Parameter()]
$Window = $presentationTitle
,
[Parameter()]
[Switch]$Passthru
)
$DidGo = Invoke-BootsWindow $Window {
Write-Output $global:Frame.CanGoForward
if($global:Frame.CanGoForward) {
$global:Frame.GoForward()
}
}
if($Passthru){ $DidGo }
}
New-Alias Next-Slide Move-NextSlide # backwards compat
function Move-PreviousSlide {
#.Synopsis
# Navigates to the previous slide (if there is another)
PARAM(
[Parameter()]
$Window = $presentationTitle
,
[Parameter()]
[Switch]$Passthru
)
$DidGo = Invoke-BootsWindow $Window {
Write-Output $global:Frame.CanGoForward
if($global:Frame.CanGoBack) {
$global:Frame.GoBack()
}
}
if($Passthru){ $DidGo }
}
New-Alias Prev-Slide Move-PreviousSlide
New-Alias Previous-Slide Move-PreviousSlide # backwards compat
function Start-Presentation {
#.Synopsis
# Start a presentation window
#.Description
# This is the kick-off function you have to call to create the presentation window
PARAM(
$PresentationTitle = "PowerShell Presentation"
, $BackgroundImagePath = $(Get-ItemProperty "HKCU:\\Control Panel\\Desktop" | Select -Expand Wallpaper | Get-ChildItem)
)
$BackgroundImagePath = Convert-Path (Resolve-Path $BackgroundImagePath)
$global:PresentationTitle = $PresentationTitle
## Finally, make the slide window
Boots -Title $PresentationTitle `
-Height $([System.Windows.SystemParameters]::PrimaryScreenHeight) `
-Width $([System.Windows.SystemParameters]::PrimaryScreenWidth) `
{
$global:TitleBrush = LinearGradientBrush -Start "0.5,0" -End "0.5,1" {
GradientStop -Color "#FF084670" -Offset 0
GradientStop -Color "#FF084670" -Offset 0.6
GradientStop -Color "#FF000000" -Offset 0.6
}
$global:Frame = Frame -Content {
Page -Title "Welcome" {
Grid {
TextBlock $PresentationTitle `
-FontSize 125 -FontFamily Impact -Foreground White `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
-Effect { BlurEffect -Radius 30 }
TextBlock $PresentationTitle `
-FontSize 125 -FontFamily Impact -Foreground White `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
-Effect { BlurEffect -Radius 30 }
TextBlock $PresentationTitle `
-FontSize 125 -FontFamily Impact -Foreground $global:TitleBrush `
-VerticalAlignment Center -TextAlignment Center `
-HorizontalAlignment Stretch -TextWrapping Wrap `
}
}
}
#Start-Zoom -Root $global:Frame
$global:Frame
} -Async -Popup -On_SourceInitialized {
if(Test-Path $BackgroundImagePath) {
$this.Background = ImageBrush -ImageSource $BackgroundImagePath
}
$this.WindowState = "Maximized"
} -On_KeyDown {
trap { Write-Host $( $_ | fl * | Out-String ) }
switch -regex ($_.Key) {
"Escape" {
Set-Zoom 0; break;
}
"OemPlus|Add" {
Set-Zoom +1; break;
}
"OemMinus|Subtract" {
Set-Zoom -1; break;
}
"MediaNextTrack|BrowserForward|Right" {
Next-Slide; break;
}
"MediaPreviousTrack|BrowserBack|Left" {
Previous-Slide; break;
}
}
} -On_MouseWheel {
if($_.Delta -gt 0 ) {
Set-Zoom +1
} else {
Set-Zoom -1
}
}
# -WindowStyle None -AllowsTransparency $true
}
function Test-Presentation {
Start-Presentation "PowerShell for Developers"
Add-TextSlide "Overview" "What is PowerShell?", "How can it help me?", "Should I code for it?", "How do I ..."
Add-TextSlide "What is PowerShell?" "A .Net Console","A new .Net Language","An admin scripting tool","An app automation engine", "All of the above"
ls ~\\Pictures\\Comix | Add-Slide
Set-Slide 0
## The simple, automatic, force-my-hand slide timer.
## One slide, every 20 seconds:
## go forward and check if we can go forward again
while( Move-NextSlide -Passthru ) {
# note that we have to sleep outside the invoke...
# otherwise the window can't update
sleep 20
}
}
Export-ModuleMember -Function * -Alias *
|
PowerShellCorpus/PoshCode/Set Active Sync DeviceID.ps1
|
Set Active Sync DeviceID.ps1
|
# Requires a connection to Exchange Server, or Exchange Management Shell
$s = New-PSSession -ConfigurationName Microsoft.Exchange -Name ExchMgmt -ConnectionUri http://ex14.domain.local/PowerShell/ -Authentication Kerberos
Import-PSSession $s
# Get all Client Access Server properties for all mailboxes with an ActiveSync Device Partnership
$Mailboxes = Get-CASMailbox -Filter {HasActivesyncDevicePartnership -eq $true} -ResultSize Unlimited
# Get DeviceID for all mailboxes
$EASMailboxes = $Mailboxes | Select-Object PrimarySmtpAddress,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}}
# Set the ActiveSyncAllowedDeviceIDs attribute of all Mailboxes
$EASMailboxes | foreach {Set-CASMailbox $_.PrimarySmtpAddress -ActiveSyncAllowedDeviceIDs $_.DeviceID}
|
PowerShellCorpus/PoshCode/Upgrade VM's to v7.ps1
|
Upgrade VM's to v7.ps1
|
Function PowerOn-VM($vm){
Start-VM -VM $vm -Confirm:$false -RunAsync | Out-Null
do {
$vmview = get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
Write-Host $vm is starting! -ForegroundColor Yellow
sleep 5
}until(($status -match "toolsOld") -or ($status -match "toolsOk"))
if ($status -match "Ok"){
$Startup = "Ok"}
elseif($status -match "toolsOld"){
$Startup = "ToolsOld"}
else{
$Startup = "Not Ready"}
return $Startup
}
Function PowerOff-VM($vm){
sleep 20
Shutdown-VMGuest -VM $vm -Confirm:$false | Out-Null
do {
$vmview = Get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
Write-Host $vm is stopping! -ForegroundColor Yellow
sleep 5
}until($status -match "toolsNotRunning")
if ($status -match "toolsNotRunning"){
$Shutdown = "Ok"}
else{
$Shutdown = "Not Ready"}
return $Shutdown
}
Function Check-ToolsStatus($vm){
$vmview = get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
if ($status -match "toolsOld"){
$vmTools = "Old"}
elseif($status -match "toolsNotRunning"){
$vmTools = "Not Running"}
else{
$vmTools = "Ok"}
return $vmTools
}
Function Check-VMHardwareVersion($vm){
$vmView = get-VM $vm | Get-View
$vmVersion = $vmView.Config.Version
$v4 = "vmx-04"
$v7 = "vmx-07"
if ($vmVersion -eq $v4){
$vmHardware = "Old"}
elseif($vmVersion -eq $v7){
$vmHardware = "Ok"}
else{Write-Host "Error!!" -ForegroundColor Red
$vmHardware = "Error"}
return $vmHardware
}
Function Upgrade-VMHardware($vm){
$vmview = Get-VM $vm | Get-View
$vmVersion = $vmView.Config.Version
$v4 = "vmx-04"
$v7 = "vmx-07"
if ($vmVersion -eq $v4){
Write-Host "Version 4 detected" -ForegroundColor Red
# Update Hardware
Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
Get-View ($vmView.UpgradeVM_Task($v7)) | Out-Null
}
}
Function CreateBeforeList{
Write-Host "Creating a CSV File with VM info" -ForegroundColor Yellow
$MyCol = @()
ForEach ($vm in Get-Folder $Folder | Get-VM )
{
$vmview = get-VM $vm | Get-View
$myObj = "" | Select Host, VMName, PowerState, IPAddress, MacAddress, Nics, VMToolsVersion, VMToolsStatus, VMToolsRunningStatus
$myObj.Host = $VM.Host.Name
$myObj.VMName = $VM.Name
$myObj.PowerState = $VM.PowerState
$myObj.IPAddress = [String]($vmview.Guest.Net| ForEach {$_.IpAddress})
$myObj.MacAddress = [String]($vmview.Guest.Net | ForEach {$_.MacAddress})
$myObj.Nics = $vmview.Guest.Net.Count
$myObj.VMToolsVersion = $vmview.Config.Tools.ToolsVersion
$myObj.VMToolsStatus = $vmview.Guest.ToolsStatus
$myObj.VMToolsRunningStatus = $vmview.Guest.ToolsRunningStatus
$myCol += $myObj
}
$myCol | Export-Csv C:\\beforeHWchange.csv -NoTypeInformation
}
Function CreateAfterList{
Write-Host "Creating a CSV and an Excel File with VM info" -ForegroundColor Yellow
$xlCSV = 6
$xlXLS = 56
$csvfile = "C:\\afterHWchange.csv"
$xlsfile = "C:\\afterHWchange.xls"
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
$Sheet.Cells.Item(1,1) = "VMName"
$Sheet.Cells.Item(1,2) = "IPAddress"
$Sheet.Cells.Item(1,3) = "Settings"
$intRow = 2
$WorkBook = $Sheet.UsedRange
$WorkBook.Interior.ColorIndex = 19
$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True
$import = Import-Csv "C:\\beforeHWchange.csv"
$vms = Get-Folder $Folder | Get-VM
foreach($vm in $vms){
$vmview = $vm | Get-View
foreach($item in $import){
$oldIp = $item.IPAddress
$newIP = $vm.Guest.IPAddress
if($item.VMName -eq $vm){
if($oldIp -eq $newIP){
$Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name
$Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress
$Sheet.Cells.Item($intRow, 3) = "Good"
$Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 4
}
else{
$Sheet.Cells.Item($intRow, 1) = [String]$vmview.Name
$Sheet.Cells.Item($intRow, 2) = [String]$vm.Guest.IPAddress
$Sheet.Cells.Item($intRow, 3) = "Wrong"
$Sheet.Cells.Item($intRow, 3).Interior.ColorIndex = 3
}
}
}
$intRow = $intRow + 1}
$WorkBook.EntireColumn.AutoFit()
sleep 5
$Sheet.SaveAs($xlsfile,$xlXLS)
$Sheet.SaveAs($csvfile,$xlCSV)
}
$vCenter = Read-Host "Enter your vCenter servername"
$Folder = Read-Host "Enter the name of the folder where the VMs are stored"
Connect-VIServer $vCenter
$vms = Get-Folder $Folder | Get-VM | Get-View | Where-Object {-not $_.config.template -and $_.Config.Version -eq "vmx-04" } | Select Name
CreateBeforeList
foreach($item in $vms){
$vm = $item.Name
$vmHardware = Check-VMHardwareVersion $vm
$vmToolsStatus = Check-ToolsStatus $vm
Write-Host "Hardware is old on:" $vm -ForegroundColor Red
if($vmToolsStatus -eq "Old"){
Write-Host "The VMware Tools are old on:" $vm -ForegroundColor Red
Sleep 20
Get-VMGuest $vm | Update-Tools
Sleep 120
Write-Host "VMware Tools are installed on:" $vm -ForegroundColor Cyan
$vmToolsStatus = Check-ToolsStatus $vm
if($vmToolsStatus -eq "Ok"){
$PowerOffVM = PowerOff-VM $vm
if($PowerOffVM -eq "Ok"){
Write-Host $vm "is down" -ForegroundColor Yellow
Upgrade-VMHardware $vm
PowerOn-VM $vm
Write-Host $vm "is up to date" -ForegroundColor Green
}
}
}
else{
$PowerOffVM = PowerOff-VM $vm
if($PowerOffVM -eq "Ok"){
Upgrade-VMHardware $vm
PowerOn-VM $vm
Write-Host $vm "is up to date" -ForegroundColor Green
}
}
}
Sleep 40
CreateAfterList
Disconnect-VIServer -Confirm:$false
|
PowerShellCorpus/PoshCode/Select-TextOutput.ps1
|
Select-TextOutput.ps1
|
##############################################################################\n##\n## Select-TextOutput\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\nSearches the textual output of a command for a pattern.\n\n.EXAMPLE\n\nGet-Service | Select-TextOutput audio\nFinds all references to "Audio" in the output of Get-Service\n\n#>\n\nparam(\n ## The pattern to search for\n $Pattern\n)\n\nSet-StrictMode -Version Latest\n$input | Out-String -Stream | Select-String $pattern
|
PowerShellCorpus/PoshCode/WCF code coverage.ps1
|
WCF code coverage.ps1
|
param($msBuildTarget, $configurationName, [bool]$deleteInstrumentedAssemblies)
#-------------------------------------
# Script to compile coverage for a WCF
# solution running in IIS.
# See:
# http://geekswithblogs.net/EltonStoneman/archive/2011/10/14/end-to-end-wcf-code-coverage-with-powershell.aspx
#-------------------------------------
#-------------------------------------
# Function to get the running app pool
#-------------------------------------
function get-apppool{
[regex]$pattern="-ap ""($appPoolName)"""
gwmi win32_process -filter 'name="w3wp.exe"' | % {
$name=$_.name
$cmd = $pattern.Match($_.commandline).Groups[1].Value
$procid = $_.ProcessId
New-Object psobject | Add-Member -MemberType noteproperty -PassThru Name $name |
Add-Member -MemberType noteproperty -PassThru AppPoolID $cmd |
Add-Member -MemberType noteproperty -PassThru PID $procid
}
}
#---------------------------------------
# Function to get the id of the app pool
#---------------------------------------
function get-apppoolpid{
$appPoolPid = 0
$appPools = get-apppool
foreach ($appPool in $appPools){
if ($appPool.AppPoolID -eq "$appPoolName"){
$appPoolPid = $appPool.PID
}
}
write-host "$solutionFriendlyName app pool PID: $appPoolPID"
return $appPoolPid
}
#------------------------------------------------
# Starts the app pool by making a service request
#------------------------------------------------
function start-apppool{
#ping the service to start a new app pool process:
$uri = new-object System.Uri("$wakeUpServiceUrl")
$client = new-object System.Net.WebClient
$client.DownloadString($uri) | out-null
}
#-------------------
# Kills the app pool
#-------------------
function kill-apppool{
$procId = get-apppoolpid
if ($procId -ne 0){
write-host "Killing app pool process"
$proc = [System.Diagnostics.Process]::GetProcessById($procId)
$proc.Kill()
}
}
#------------------------------------------------------------------------------
# Instruments an assembly for code coverage, excluding the specified namespaces
#------------------------------------------------------------------------------
function instrument2([string]$assemblyName, [string[]]$excludes){
$assy = "$websiteBinDirectory\\$assemblyName"
$excludeLine = ""
if ($excludes -ne $null){
foreach ($x in $excludes){
write-host "Excluding: $x.*"
$excludeLine = "$excludeLine-exclude:$x.* "
}
}
$cmd = "C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe"
write-host "Executing $cmd /coverage $excludeLine $assy"
& $cmd /coverage "$excludeLine" "$assy"
}
#------------------------------------------------------------------------------
# Instruments an assembly for code coverage, excluding the specified namespaces
#------------------------------------------------------------------------------
function instrument([string]$assemblyName, [string[]]$excludes){
$assy = "$websiteBinDirectory\\$assemblyName"
#ES - this doesn't work as the ":" in exlucde gets parsed out by PS:
#$excludeParms = ""
#$args
#foreach($exclude in $args){
# $excludeParms = $excludeParms + '/exclude:' + $exclude + '.* '
#}
#$excludeParms
#& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $excludeParms $assy
if ($excludes -eq $null){
write-host "Excluding 0 funcspecs"
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $assy
}
elseif ($excludes.Length -eq 0){
write-host "Excluding 0 funcspecs"
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $assy
}
elseif ($excludes.Length -eq 1){
write-host "Excluding 1 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $assy
}
elseif ($excludes.Length -eq 2){
write-host "Excluding 2 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
$exclude2 = '-exclude:' + $excludes[1]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $exclude2 $assy
}
elseif ($excludes.Length -eq 3){
write-host "Excluding 3 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
$exclude2 = '-exclude:' + $excludes[1]
$exclude3 = '-exclude:' + $excludes[2]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $exclude2 $exclude3 $assy
}
elseif ($excludes.Length -eq 4){
write-host "Excluding 4 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
$exclude2 = '-exclude:' + $excludes[1]
$exclude3 = '-exclude:' + $excludes[2]
$exclude4 = '-exclude:' + $excludes[3]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $exclude2 $exclude3 $exclude4 $assy
}
elseif ($excludes.Length -eq 5){
write-host "Excluding 5 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
$exclude2 = '-exclude:' + $excludes[1]
$exclude3 = '-exclude:' + $excludes[2]
$exclude4 = '-exclude:' + $excludes[3]
$exclude5 = '-exclude:' + $excludes[4]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $exclude2 $exclude3 $exclude4 $exclude5 $assy
}
elseif ($excludes.Length -eq 6){
write-host "Excluding 6 funcspecs"
$exclude1 = '-exclude:' + $excludes[0]
$exclude2 = '-exclude:' + $excludes[1]
$exclude3 = '-exclude:' + $excludes[2]
$exclude4 = '-exclude:' + $excludes[3]
$exclude5 = '-exclude:' + $excludes[4]
$exclude6 = '-exclude:' + $excludes[5]
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsinstr.exe' /coverage $exclude1 $exclude2 $exclude3 $exclude4 $exclude5 $exclude6 $assy
}
}
#-----------------------------------
# Starts instrumenting W3WP app pool
#------------------------------------
function start-instrumentation{
#set instrumentation on:
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfclrenv' /globaltraceon
#restart the app pool and store the ID:
kill-apppool
start-apppool
$procId = get-apppoolpid
#start instrumenting:
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfcmd' /START:COVERAGE /OUTPUT:$coverageOutputPath /CS /USER:$appPoolIdentity
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfcmd' /ATTACH:$procId
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfcmd' /status
}
#--------------------
# Stops instrumenting
#--------------------
function stop-instrumentation{
#stop instrumenting & reset app pool:
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfcmd' /DETACH
kill-apppool
& 'C:\\Program Files\\Microsoft Visual Studio 10.0\\Team Tools\\Performance Tools\\vsperfcmd' /SHUTDOWN
}
#------------------------
# Exports coverage to XML
#------------------------
function export-coverage{
#export the coverage file to XML:
[System.Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE\\PrivateAssemblies\\Microsoft.VisualStudio.Coverage.Analysis.dll")
$coverage = [Microsoft.VisualStudio.Coverage.Analysis.CoverageInfo]::CreateFromFile("$coverageOutputPath")
$dataSet = $coverage.BuildDataSet()
$dataSet.WriteXml("$coverageOutputPath" + 'xml')
}
#----------------------------------------------------------------------------------
# Deletes instrumented assemblies, and reinstates original un-instrumented versions
#----------------------------------------------------------------------------------
function delete-intstrumentedassemblies{
$dir = new-object IO.DirectoryInfo($websiteBinDirectory)
$originalAssemblies = $dir.GetFiles("*.dll.orig")
foreach ($originalAssembly in $originalAssemblies){
$targetName = $originalAssembly.FullName.TrimEnd(".orig".ToCharArray())
#overwrite the instrumented DLL with the original:
[IO.File]::Copy($originalAssembly.FullName, $targetName, $true)
[IO.File]::Delete($originalAssembly.FullName)
#delete the instrumented PDB:
$instrumentedPdbName = $originalAssembly.FullName.TrimEnd(".dll.orig".ToCharArray()) + ".instr.pdb"
[IO.File]::Delete($instrumentedPdbName)
}
}
#--------------
# Script begins
#--------------
#set variables:
$solutionFriendlyName = 'XYZ'
$wakeUpServiceUrl = 'http://localhost/x.y.z/Service.svc'
$appPoolName = 'ap_XYZ'
$appPoolIdentity = 'domain\\svc_user'
$websiteBinDirectory = 'c:\\websites\\xyz\\x.y.z.Services\\bin'
$coverageOutputPath = "Test.coverage"
#instrument assemblies:
# - instrument assembly so ALL namespaces are included in coverage
instrument "x.y.z.Services.dll"
# - instrument assembly so anything from the Ignore1 and Ignore2 namespaces are excluded from coverage
instrument "x.y.z.Core.dll" 'x.y.z.Core.Ignore1.*' , 'x.y.z.Core.Ignore2.*'
write-host "Before starting instrumentation, last exit code: $LASTEXITCODE"
#instrument W3WP, run tests & export results:
start-instrumentation
write-host "Before running tests, last exit code: $LASTEXITCODE"
& 'C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe' Build.proj /t:$msBuildTarget /p:ConfigurationName=$configurationName
$realExitCode = $LASTEXITCODE
write-host "Before stopping instrumentation, last exit code: $LASTEXITCODE, real exit code: $realExitCode"
stop-instrumentation
export-coverage
export-coverage
if ($deleteInstrumentedAssemblies -eq $true){
delete-intstrumentedassemblies
}
write-host "Before existing, last exit code: $LASTEXITCODE, real exit code: $realExitCode"
exit $realExitCode
#------------
# Script ends
#------------
|
PowerShellCorpus/PoshCode/38d536b5-87f9-4725-b346-64260dcc55ec.ps1
|
38d536b5-87f9-4725-b346-64260dcc55ec.ps1
|
function Invoke-JQuery
{
<#
.SYNOPSIS
Function to Invoke JQuery commands via IE COM
.DESCRIPTION
Invokes JQuery (or plain Javascript) commands via InternetExplorer.Application COM object,
after initial injection of JQuery reference in header section.
Useful to utilize JQuery selectors and functions for IE automation.
.PARAMETER IE
Initialized InternetExplorer.Application COM object
.PARAMETER Command
JQuery/Javascript to Invoke
.PARAMETER Function
Function to add in header section
.PARAMETER Initialize
Switch to initially inject JQuery in header section.
.EXAMPLE
$ie = new-object -com internetexplorer.application
$ie.visible = $true
$ie.navigate2("http://www.example.com")
# Wait for page load
while($ie.busy) {start-sleep 1}
#add addtional div to store results
$div="<div id='myResult'>"
$ie.Document.body.innerHTML += $div
#hide anchor tags
Invoke-JQuery $ie '$("a").hide();' -Initialize
#change innerhtml of div
Invoke-JQuery $ie 'var str=$("p:first").text();$("#myResult").html(str);'
#retrieve the value
$result = $ie.document.getElementById("myResult").innerHtml
$jFunc=@"
function SelectText(element) {
var text = document.getElementById(element);
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
"@
Invoke-JQuery $ie -Function $jFunc
Invoke-JQuery $ie 'SelectText("myResult");'
#>
[cmdletbinding()]
param(
[parameter(position=0, mandatory=$true)]
$IE,
[parameter(position=1,mandatory=$false)]
$Command,
[parameter()]
$Function,
[parameter()]
[switch]$Initialize
)
if ($Initialize -or $Function){
$url='http://code.jquery.com/jquery-1.4.2.min.js'
$document = $IE.document
$head = @($document.getElementsByTagName("head"))[0]
$script = $document.createElement('script')
$script.type = 'text/javascript'
}
if ($Initialize){
$script.src = $url
$head.appendChild($script) | Out-Null
}
if ($Command){$IE.document.parentWindow.execScript("$Command","javascript")}
if ($Function){
$script.text = $Function
$head.appendChild($script) | Out-Null
}
}
|
PowerShellCorpus/PoshCode/New-MAML.ps1
|
New-MAML.ps1
|
#Requires -version 2.0
#Generates External MAML Powershell help file for any loaded cmdlet or function
#Note: Requires Joel Bennet's New-XML script from http: //www.poshcode.com/1244
#place New-XML in same directory as New-MAML
#Once the XML/MAML file is generated, you'll need to fill in the TODO items and the parameters options
#that are defaulted to false. The position parameter option will need to be changed in the generated MAML also.
#Example Usage to generate a test-ispath.ps1-help.xml file:
#PS C:\\Users\\u00\\bin> $xml = ./new-maml test-ispath
#PS C:\\Users\\u00\\bin> $xml.Declaration.ToString() | out-file ./test-ispath.ps1-help.xml -encoding "UTF8"
#PS C:\\Users\\u00\\bin> $xml.ToString() | out-file ./test-ispath.ps1-help.xml -encoding "UTF8" -append
#For compiled cmdlets place the MAML file in the same directory as the binary module or snapin dll
#For script modules/functions include a reference to the External MAML file for each function
#Note: You can use the same MAML file for multiple functions, example:
#
## .ExternalHelp C:\\Users\\u00\\bin\\test-ispath.ps1-help.xml
## function test-ipath
param ($commandName)
$scriptRoot = Split-Path (Resolve-Path $myInvocation.MyCommand.Path)
. $scriptRoot\\New-XML.ps1
[XNamespace]$helpItems="http://msh"
[XNamespace]$maml="http://schemas.microsoft.com/maml/2004/10"
[XNamespace]$command="http://schemas.microsoft.com/maml/dev/command/2004/10"
[XNamespace]$dev="http://schemas.microsoft.com/maml/dev/2004/10"
$parameters = get-command $commandName | %{$commandName=$_.Name;$_.parameters} | %{$_.Values}
New-Xml helpItems -schema "maml" {
xe ($command + "command") -maml $maml -command $command -dev $dev {
xe ($command + "details") {
xe ($command + "name") {"$commandName"}
xe ($maml + "description") {
xe ($maml + "para") {"TODO Add Short description"}
}
xe ($maml + "copyright") {
xe ($maml + "para") {}
}
xe ($command + "verb") {"$(($CommandName -split '-')[0])"}
xe ($command + "noun") {"$(($commandName -split '-')[1])"}
xe ($dev + "version") {}
}
xe ($maml + "description") {
xe ($maml + "para") {"TODO Add Long description"}
}
xe ($command + "syntax") {
xe ($command + "syntaxItem") {
$parameters | foreach {
xe ($command + "name") {"$commandName"}
xe ($command + "parameter") -require "false" -variableLength "false" -globbing "false" -pipelineInput "false" -postion "0" {
xe ($maml + "name") {"$($_.Name)"}
xe ($maml + "description") {
xe ($maml + "para") {"TODO Add $($_.Name) Description"}
}
xe ($command + "parameterValue") -required "false" -variableLength "false" {"$($_.ParameterType.Name)"}
}
}
}
}
xe ($command + "parameters") {
$parameters | foreach {
xe ($command + "parameter") -required "false" -variableLength "false" -globbing "false" -pipelineInput "false (ByValue)" -position "0" {
xe ($maml + "name") {"$($_.Name)"}
xe ($maml + "description") {
xe ($maml + "para") {"TODO Add $($_.Name) Description"}
}
xe ($command + "parameterValue") -required "true" -variableLength "false" {"$($_.ParameterType.Name)"}
xe ($dev + "type") {
xe ($maml + "name") {"$($_.ParameterType.Name)"}
xe ($maml + "uri"){}
}
xe ($dev + "defaultValue") {}
}
}
}
xe ($command + "inputTypes") {
xe ($command + "inputType") {
xe ($dev + "type") {
xe ($maml + "name") {"TODO Add $commandName inputType"}
xe ($maml + "uri") {}
xe ($maml + "description") {
xe ($maml + "para") {}
}
}
xe ($maml + "description") {}
}
}
xe ($command + "returnValues") {
xe ($command + "returnValue") {
xe ($dev + "type") {
xe ($maml + "name") {"TODO Add $commandName returnType"}
xe ($maml + "uri") {}
xe ($maml + "description") {
xe ($maml + "para") {}
}
}
xe ($maml + "description") {}
}
}
xe ($command + "terminatingErrors") {}
xe ($command + "nonTerminatingErrors") {}
xe ($maml + "alertSet") {
xe ($maml + "title") {}
xe ($maml + "alert") {
xe ($maml + "para") {}
}
}
xe ($command + "examples") {
xe ($command + "example") {
xe ($maml + "title") {"-------------- EXAMPLE 1 --------------"}
xe ($maml + "introduction") {
xe ($maml + "para") {"C:\\PS>"}
}
xe ($dev + "code") {"TODO Add $commandName Example code"}
xe ($dev + "remarks") {
xe ($maml + "para") {"TODO Add $commandName Example Comment"}
xe ($maml + "para") {}
xe ($maml + "para") {}
xe ($maml + "para") {}
xe ($maml + "para") {}
}
xe ($command + "commandLines") {
xe ($command + "commandLine") {
xe ($command + "commandText") {}
}
}
}
}
xe ($maml + "relatedLinks") {
xe ($maml + "navigationLink") {
xe ($maml + "linkText") {"$commandName"}
xe ($maml + "uri") {}
}
}
}
}
|
PowerShellCorpus/PoshCode/LibraryMSCS_1.ps1
|
LibraryMSCS_1.ps1
|
# ------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Defines functions for working with Microsoft Cluster Service (MSCS)
### </Description>
### <Usage>
### . ./LibraryMSCS.ps1
### </Usage>
### </Script>
# ------------------------------------------------------------------------
#######################
function Get-Cluster
{
param($cluster)
gwmi -class "MSCluster_Cluster" -namespace "root\\mscluster" -computername $cluster
} #Get-Cluster
#######################
function Get-ClusterName
{
param($cluster)
Get-Cluster $cluster | select -ExpandProperty name
} #Get-ClusterName
#######################
function Get-ClusterNode
{
param($cluster)
gwmi -class MSCluster_Node -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster
} #Get-ClusterNode
#######################
function Get-ClusterSQLVirtual
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "SQL Server"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='VirtualServerName';e={$_.PrivateProperties.VirtualServerName}}, @{n='InstanceName';e={$_.PrivateProperties.InstanceName}}, `
@{n='ServerInstance';e={("{0}\\{1}" -f $_.PrivateProperties.VirtualServerName,$_.PrivateProperties.InstanceName).TrimEnd('\\')}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterSQLVirtual
#######################
function Get-ClusterNetworkName
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "Network Name"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='NetworkName';e={$_.PrivateProperties.Name}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterNetworkName
#######################
function Get-ClusterResource
{
param($cluster)
gwmi -ComputerName $cluster -Namespace "root\\mscluster" -Class MSCluster_Resource | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty Group `
{ gwmi -ComputerName $cluster -Namespace "root\\mscluster" -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToResource" | Select -ExpandProperty Name }
} #Get-ClusterResource
#######################
function Get-ClusterGroup
{
param($cluster)
gwmi -class MSCluster_ResourceGroup -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveGroup" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty PreferredNodes `
{ @(,(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToPreferredNode" | Select -ExpandProperty Name)) }
} #Get-ClusterGroup
|
PowerShellCorpus/PoshCode/Connect-AccessDB_1.ps1
|
Connect-AccessDB_1.ps1
|
# Functions for connecting to and working with Access databases
# Matt Wilson
# May 2009
function Connect-AccessDB ($global:dbFilePath) {
# Test to ensure valid path to database file was supplied
if (-not (Test-Path $dbFilePath)) {
Write-Error "Invalid Access database path specified. Please supply full absolute path to database file!"
}
# TO-DO: Add check to ensure file is either MDB or ACCDB
# Create a new ADO DB connection COM object, which will give us useful methods & properties such as "Execute"!
$global:AccessConnection = New-Object -ComObject ADODB.Connection
# Actually open the database so we can start working with its contents
# Access 00-03 (MDB) format has a different connection string than 2007
if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.mdb$") {
Write-Host "Access 2000-2003 format (MDB) detected! Using Microsoft.Jet.OLEDB.4.0."
$AccessConnection.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source= $dbFilePath")
}
# Here's the check for if 2007 connection is necessary
if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.accdb$") {
Write-Host "Access 2007 format (ACCDB) detected! Using Microsoft.Ace.OLEDB.12.0."
$AccessConnection.Open("Provider = Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; Data Source= $dbFilePath")
}
}
function Open-AccessRecordSet ($global:SqlQuery) {
# Ensure SQL query isn't null
if ($SqlQuery.length -lt 1) {
Throw "Please supply a SQL query for the recordset selection!"
}
# Variables used for the connection itself. Leave alone unless you know what you're doing.
$adOpenStatic = 3
$adLockOptimistic = 3
# Create the recordset object using the ADO DB COM object
$global:AccessRecordSet = New-Object -ComObject ADODB.Recordset
# Finally, go and get some records from the DB!
$AccessRecordSet.Open($SqlQuery, $AccessConnection, $adOpenStatic, $adLockOptimistic)
}
function Get-AccessRecordSetStructure {
# TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records
# Cycle through the fields in the recordset, but only pull out the properties we care about
Write-Output $AccessRecordSet.Fields | Select-Object Name,Attributes,DefinedSize,type
}
function Convert-AccessRecordSetToPSObject {
# TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records
# Get an array of field names which we will later use to create custom PoSh object names
$fields = Get-AccessRecordSetStructure
# Move to the very first record in the RecordSet before cycling through each one
$AccessRecordSet.MoveFirst()
# Cycle through each RECORD in the set and create that record to an object
do {
# Create a SINGLE blank object we can use in a minute to add properties/values to
$record = New-Object System.Object
# For every FIELD in the DB, lookup the CURRENT value of that field and add a new PoSh object property with that name and value
foreach ($field in $fields) {
$fieldName = $field.Name # This makes working with the name a LOT easier in Write-Host, etc.
#Write-Host "Working with field: $fieldName"
#Write-Host "Preparing to set value to: $($AccessRecordset.Fields.Item($fieldName).Value)"
$record | Add-Member -type NoteProperty -name $fieldName -value $AccessRecordSet.Fields.Item($fieldName).Value
}
# Output the custom object we just created
Write-Output $record
# Tell the recordset to advance forward one before doing this again with another object
$AccessRecordset.MoveNext()
} until ($AccessRecordset.EOF -eq $True)
}
function Execute-AccessSQLStatement ($query) {
$AccessConnection.Execute($query)
}
function Convert-AccessTypeCode ([string]$typeCode) {
# Build some lookup tables for our Access type codes so we can convert values pretty easily
$labelLookupHash = @{"AutoNumber"="3"; "Text"="202"; "Memo"="203"; "Date/Time"="7"; "Currency"="6"; "Yes/No"="11"; "OLE Object"="205"; "Byte"="17"; "Integer"="2"; "Long Integer"="3"; "Single"="4"; "Double"="5"}
$codeLookupHash = @{"3"="AutoNumber"; "202"="Text"; "203"="Memo"; "7"="Date/Time"; "6"="Currency"; "11"="Yes/No"; "205"="OLE Object"; "17"="Byte"; "2"="Integer"; "3"="Long Integer"; "4"="Single"; "5"="Double"}
# Convert a value depending on what type of data was supplied
if ($typeCode -match [regex]"^\\d{1,3}$") {
$valueFound = $codeLookupHash.$typeCode
if ($valueFound) {
Write-Output $valueFound
} else { Write-Output "Unknown" }
} else {
$valueFound = $labelLookupHash.$typeCode
if ($valueFound) {
Write-Output $valueFound
} else { Write-Output "Unknown" }
}
}
function Close-AccessRecordSet {
$AccessRecordSet.Close()
}
function Disconnect-AccessDB {
$AccessConnection.Close()
}
# Connect-AccessDB "C:\\fso\\ConfigurationMaintenance.accdb"
# Open-AccessRecordSet "SELECT * FROM printers"
# $printersDB = Convert-AccessRecordSetToPSObject | Select-Object caption,driverName | Format-Table -AutoSize; $printersDB
# Close-AccessRecordSet
# Disconnect-AccessDB
|
PowerShellCorpus/PoshCode/running regions in ISE.ps1
|
running regions in ISE.ps1
|
function invoke-caretline
{
invoke-expression $([Regex]::Split($psISE.CurrentOpenedFile.Editor.text,"`r`n" )[$psISE.CurrentOpenedFile.Editor.caretline-1])
}
$psISE.CustomMenu.Submenus.Add("Run single line", {invoke-caretline} , 'f7')
function invoke-region([int] $num)
{
$ed = $psISE.CurrentOpenedFile.Editor
$lines = [Regex]::Split($ed.text,"`r`n" )
$foundfirst = -1
$foundlast = -1
for($count = 0;$count -le $lines.length-1;$count++)
{
if ($lines[$count].startswith("#region") -and $lines[$count].contains("@$num"))
{ $foundfirst = $count;break}
}
if($foundfirst -gt -1)
{
for ($count = $foundfirst; $count -le $lines.length-1;$count++)
{
if ($lines[$count].startswith("#endregion") )
{ $foundlast = $count;break}
}
if ($foundlast -gt -1)
{
$torun = ""
$lines[$foundfirst..$foundlast] | % { $torun+=$_ + "`r`n"}
invoke-expression $torun
}
}
}
$psISE.CustomMenu.Submenus.Add("run region 1", {invoke-region 1 }, 'ctrl+1')
$psISE.CustomMenu.Submenus.Add("run region 2", {invoke-region 2 }, 'ctrl+2')
$psISE.CustomMenu.Submenus.Add("run region 3", {invoke-region 3 }, 'ctrl+3')
$psISE.CustomMenu.Submenus.Add("run region 4", {invoke-region 4 }, 'ctrl+4')
$psISE.CustomMenu.Submenus.Add("run region 5", {invoke-region 5 }, 'ctrl+5')
|
PowerShellCorpus/PoshCode/Clear-XCAttributes.ps1
|
Clear-XCAttributes.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[ValidateNotNullorEmpty()] $User,
[switch]$ClearXCAttributes
)
begin{
$Global:LegacyXCUsers = @()
# attributes to be nulled according to:
# http://blogs.technet.com/b/exchange/archive/2006/10/13/3395089.aspx
$XCattributes=@(
"adminDisplayName","altRecipient","authOrig","autoReplyMessage","deletedItemFlags","delivContLength","deliverAndRedirect","displayNamePrintable",
"dLMemDefault","dLMemRejectPerms","dLMemSubmitPerms","extensionAttribute1","extensionAttribute10","extensionAttribute11","extensionAttribute12",
"extensionAttribute13","extensionAttribute14","extensionAttribute15","extensionAttribute2","extensionAttribute3","extensionAttribute4","extensionAttribute5",
"extensionAttribute6","extensionAttribute7","extensionAttribute8","extensionAttribute9","folderPathname","garbageCollPeriod","homeMDB","homeMTA",
"internetEncoding","legacyExchangeDN","mail","mailNickname","mAPIRecipient","mDBOverHardQuotaLimit","mDBOverQuotaLimit","mDBStorageQuota","mDBUseDefaults",
"msExchADCGlobalNames","msExchControllingZone","msExchExpansionServerName","msExchFBURL","msExchHideFromAddressLists","msExchHomeServerName",
"msExchMailboxGuid","msExchMailboxSecurityDescriptor","msExchPoliciesExcluded","msExchPoliciesIncluded","msExchRecipLimit","msExchResourceGUID",
"protocolSettings","proxyAddresses","publicDelegates","securityProtocol","showInAddressBook","submissionContLength","targetAddress","textEncodedORAddress",
"unauthOrig"
)
}
process{
$Global:LegacyXCUsers += (get-aduser -Identity $User -Properties *)
if ($ClearXCAttributes){
write-verbose "all XC attributes will be cleared for $user"
set-aduser -Identity $User -Clear $XCattributes
}
}
end{
$Global:LegacyXCUsers
}
|
PowerShellCorpus/PoshCode/get-uuid_allHVs_1.ps1
|
get-uuid_allHVs_1.ps1
|
#The PowerShell Talk
#Building a HyperVisor Independent Script
#
#This script will take a VM (or host) object from the pipline,
#and from that determine if you're connected to XenServer
#or VMware, and return the apropriate UUID.
Begin {
#VMware VM Host (ESX) UUID
$VMHost_UUID = @{
Name = "VMHost_UUID"
Expression = { $_.Summary.Hardware.Uuid }
}
#XenServer Host UUID
$XenHost_UUID = @{
Name = "XenHost_UUID"
Expression = { $_.Uuid }
}
}
Process {
#Get the type of object we have
$InputTypeName = $_.GetType().Name
#Do something with that object
#is it VMware?
if ( $InputTypeName -eq "VMHostImpl" ) {
$output = $_ | Get-View | Select-Object $VMHost_UUID
#is it Xen?
} elseif ($InputTypeName -eq "Host"){
$output = $_ | Select-Object $XenHost_UUID
#Otherwise throw an error
} else {
Write-Host "`nPlease pass this script either a VMHost or VM object on the pipeline.`n"
}
$output
}
|
PowerShellCorpus/PoshCode/Get-WMIVersions_1.ps1
|
Get-WMIVersions_1.ps1
|
#Requires -Version 2
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/Send-HTMLFormattedEmail_2.ps1
|
Send-HTMLFormattedEmail_2.ps1
|
##################################################
# cmdlets
##################################################
#-------------------------------------------------
# Send-HTMLFormattedEmail
#-------------------------------------------------
# Usage: Send-HTMLFormattedEmail -?
#-------------------------------------------------
function Send-HTMLFormattedEmail {
<#
.Synopsis
Used to send an HTML Formatted Email.
.Description
Used to send an HTML Formatted Email that is based on an XSLT template.
.Parameter To
Email address or addresses for whom the message is being sent to.
Addresses should be seperated using ;.
.Parameter ToDisName
Display name for whom the message is being sent to.
.Parameter CC
Email address if you want CC a recipient.
Addresses should be seperated using ;.
.Parameter BCC
Email address if you want BCC a recipient.
Addresses should be seperated using ;.
.Parameter From
Email address for whom the message comes from.
.Parameter FromDisName
Display name for whom the message comes from.
.Parameter Subject
The subject of the email address.
.Parameter Content
The content of the message (to be inserted into the XSL Template).
.Parameter Relay
FQDN or IP of the SMTP relay to send the message to.
.XSLPath
The full path to the XSL template that is to be used.
#>
param(
[Parameter(Mandatory=$True)][String]$To,
[Parameter(Mandatory=$True)][String]$ToDisName,
[String]$CC,
[String]$BCC,
[Parameter(Mandatory=$True)][String]$From,
[Parameter(Mandatory=$True)][String]$FromDisName,
[Parameter(Mandatory=$True)][String]$Subject,
[Parameter(Mandatory=$True)][String]$Content,
[Parameter(Mandatory=$True)][String]$Relay,
[Parameter(Mandatory=$True)][String]$XSLPath
)
try {
# Load XSL Argument List
$XSLArg = New-Object System.Xml.Xsl.XsltArgumentList
$XSLArg.Clear()
$XSLArg.AddParam("To", $Null, $ToDisName)
$XSLArg.AddParam("Content", $Null, $Content)
# Load Documents
$BaseXMLDoc = New-Object System.Xml.XmlDocument
$BaseXMLDoc.LoadXml("<root/>")
$XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform
$XSLTrans.Load($XSLPath)
#Perform XSL Transform
$FinalXMLDoc = New-Object System.Xml.XmlDocument
$MemStream = New-Object System.IO.MemoryStream
$XMLWriter = [System.Xml.XmlWriter]::Create($MemStream)
$XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter)
$XMLWriter.Flush()
$MemStream.Position = 0
# Load the results
$FinalXMLDoc.Load($MemStream)
$Body = $FinalXMLDoc.Get_OuterXML()
# Create Message Object
$Message = New-Object System.Net.Mail.MailMessage
# Now Populate the Message Object.
$Message.Subject = $Subject
$Message.Body = $Body
$Message.IsBodyHTML = $True
# Add From
$MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName
$Message.From = $MessFrom
# Add To
$To = $To.Split(";") # Make an array of addresses.
$To | foreach {$Message.To.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
# Add CC
if ($CC){
$CC = $CC.Split(";") # Make an array of addresses.
$CC | foreach {$Message.CC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
}
# Add BCC
if ($BCC){
$BCC = $BCC.Split(";") # Make an array of addresses.
$BCC | foreach {$Message.BCC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
}
# Create SMTP Client
$Client = New-Object System.Net.Mail.SmtpClient $Relay
# Send The Message
$Client.Send($Message)
}
catch {
throw $_
}
}
##################################################
# Main
##################################################
Export-ModuleMember Send-HTMLFormattedEmail
### XSLT Template Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output media-type="xml" omit-xml-declaration="yes" />
<xsl:param name="To"/>
<xsl:param name="Content"/>
<xsl:template match="/">
<html>
<head>
<title>My First Formatted Email</title>
</head>
<body>
<div width="400px">
<p>Dear <xsl:value-of select="$To" />,</p>
<p></p>
<p><xsl:value-of select="$Content" /></p>
<p></p>
<p><strong>Please do not respond to this email!</strong><br />
An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p>
<p></p>
<Address>
Many thanks from your:<br />
Really Cool IT Team<br />
</Address>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
PowerShellCorpus/PoshCode/WinFirewall-Disabled.ps1
|
WinFirewall-Disabled.ps1
|
function WinFirewall-Disabled(){
param (
$computer
)
c:\\PsTools\\PsExec.exe \\\\"$computer" sc config sharedaccess start= disabled
}
|
PowerShellCorpus/PoshCode/chkhash_5.ps1
|
chkhash_5.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)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=$args
$nu = 0
$errs = 0
$fc = 0
$upd = $false
$create = $false
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"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"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++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
if ($i -ge $args2.count) {break}
$exclude+=@($args2[$i]) # collect array of excluded directories.
if (($i+1) -ge $args2.count) {break}
} while ($args2[$i+1] -notlike "-*")
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath) # Load database
}
else
{
$xfiles=@(import-clixml $hashespath) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database."}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$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)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
$xfiles+=@($f) # then add file + hash to list
continue
}
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Write-Twilight.ps1
|
Write-Twilight.ps1
|
#Write-Twilight
while(1){
$wc = Get-Random -Minimum (Get-Random -Minimum 1 -Maximum 3) -Maximum (Get-Random -Minimum 4 -Maximum 14)
for($y=0; $y-lt$wc; $y++){
$word = ""
$max = Get-Random -Minimum 5 -Maximum 11
$wl = Get-Random -Minimum 1 -Maximum $max
for($i=0;$i-lt$wl;$i++){
$num = Get-Random -Minimum 97 -Maximum 122;
$char= [char][int]$num;
$word += [string]$char
Start-Sleep -Milliseconds (Get-Random -Maximum 150 -Minimum 3)
}
#.\\readwords.ps1 $word #From previous script
Write-Host -NoNewline "$word "
#Start-Sleep -MilliSeconds (Get-Random -Maximum 1000 -Minimum 500)
}
switch (Get-Random -Minimum 1 -Maximum 11){
1 {Write-Host -NoNewline ","}
2 {Write-Host -NoNewline ".`nGril: "}
3 {Write-Host -NoNewline "!`nBella: "}
4 {Write-Host -NoNewline "?`nShovel Face: "}
5 {Write-Host -NoNewline ";"}
6 {Write-Host -NoNewline ":"}
7 {Write-Host -NoNewline "`""}
8 {Write-Host -NoNewline "'"}
11 {Write-Host -NoNewline ".`nMouth Breath: "}
10 {Write-Host -NoNewline "!`nFish Face: "}
9 {Write-Host -NoNewline "?`nThing: "}
}
Start-Sleep -Seconds 1
}
|
PowerShellCorpus/PoshCode/Resizer of pictures.ps1
|
Resizer of pictures.ps1
|
[reflection.assembly]::LoadWithPartialName(”System.Drawing”)
$SizeLimit=1280 # required size of picture's long side
$logfile=”resizelog.txt” # log file for errors
$toresize=$args[0] # list of directories to find and resize images. can be empty
if ([string]$toresize -eq “”) { # if script startup parameter empty, use some default values
$toresize=@(’n:\\path1′, ‘n:\\path2\\’, ’s:\\path3′)
}
echo $toresize # visual control
#Write-Host -NoNewLine (”Press any key.”) # Optional "Press any key"
#$null = $Host.UI.RawUI.ReadKey(”NoEcho,IncludeKeyDown”)
#Write-Host “”
$error.clear()
# first part. find and resize jpgs
Get-ChildItem -recurse $toresize -include *.jpg | foreach {
$OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open found jpg
if ($error.count -ne 0) { # error handling
$error | out-file $logfile -append -encoding default
$error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default
echo $_>>$logfile
$error.clear()
}
$LongSide=$OldBitmap.Width # locating long side of picture
if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height }
if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process jpg
if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculate dimensions of picture resize to
$newH=$SizeLimit
$newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height)
} else {
$newW=$SizeLimit
$newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width)
}
$NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap
$g=[System.Drawing.Graphics]::FromImage($NewBitmap)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic # use high quality resize algorythm
$g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # resize our picture
$name=$_.DirectoryName+"\\"+$_.name+".new" # generating name for new picture
$NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save newly created resized jpg
$NewBitmap.Dispose() # cleaning up our mess
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if resized jpg has greater size than original
Write-host -NoNewLine "+" # draw "+"
$n.delete() # and delete it
} else { # if resized jpg is smaller than original
if ($n.Exists -and $_.Exists) {
$name=$_.FullName
$_.Delete() # delete original
$n.MoveTo($name) # rename new file to original name (replace old file with new)
echo ($Name + " " + $LongSide) # write its name for visual control
}
}
} else { # if long side is smaller than limit, draw dot for visual
Write-host -NoNewLine "."
$OldBitmap.Dispose()
}
}
#second part. process other than jpgs bitmaps
Get-ChildItem -recurse $toresize -include *.bmp, *.tif, *.gif | foreach {
$OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open picture
if ($error.count -ne 0) { # handle errors if any
$error | out-file $logfile -append -encoding default
$error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default
$error.clear()
}
$LongSide=$OldBitmap.Width # find picture's long side
if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height }
if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process picture
if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculating new dimensions
$newH=$SizeLimit
$newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height)
} else {
$newW=$SizeLimit
$newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width)
}
$NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap
$g=[System.Drawing.Graphics]::FromImage($NewBitmap)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # copy resized image to it
$name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" # generating new name, jpg extension
$NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save new file
$NewBitmap.Dispose()
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if new file is longer than original,
$n.delete() # delete new file
Write-host -NoNewLine "+" # and draw "+" for beauty
} else { # if new file is shorter than original (as we expect)
echo ($Name + " " + $LongSide) # draw its name
$_.Delete() # delete oroginal
}
} else { # if long side is less than our limit, try to recompress it to jpg
$name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg"
$OldBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg))
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if new jpg is greater than original
$n.delete() # delete new jpg
Write-host -NoNewLine "-" # draw "-" for visual control
} else {
echo ($Name + " " + $LongSide) # draw new file name
$_.Delete() # delete original
}
}
}
|
PowerShellCorpus/PoshCode/Write-DataTable_4.ps1
|
Write-DataTable_4.ps1
|
#######################
<#
.SYNOPSIS
Writes data only to SQL Server tables.
.DESCRIPTION
Writes data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.
.INPUTS
None
You cannot pipe objects to Write-DataTable
.OUTPUTS
None
Produces no output
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"
Write-DataTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -Data $dt
This example loads a variable dt of type DataTable from query and write the datatable to another database
.NOTES
Write-DataTable uses the SqlBulkCopy class see links for additional information on this class.
Version History
v1.0 - Chad Miller - Initial release
v1.1 - Chad Miller - Fixed error message
.LINK
http://msdn.microsoft.com/en-us/library/30c3y597%28v=VS.90%29.aspx
#>
function Write-DataTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [string]$TableName,
[Parameter(Position=3, Mandatory=$true)] $Data,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000,
[Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0,
[Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15
)
$conn=new-object System.Data.SqlClient.SQLConnection
if ($Username)
{ $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
else
{ $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout }
$conn.ConnectionString=$ConnectionString
try
{
$conn.Open()
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = $tableName
$bulkCopy.BatchSize = $BatchSize
$bulkCopy.BulkCopyTimeout = $QueryTimeOut
$bulkCopy.WriteToServer($Data)
$conn.Close()
}
catch
{
$ex = $_.Exception
Write-Error "$ex.Message"
continue
}
} #Write-DataTable
|
PowerShellCorpus/PoshCode/MoveJunkEmail.ps1
|
MoveJunkEmail.ps1
|
<######################################################
Name: MoveJunkEmail.ps1
Author: Shawn Harris
Date: 15 Oct 2012
Purpose: Move specified messages from JunkEmail to another
folder. Criteria can be filtered with the restricted property.
######################################################>
#Assembly can be added by either method
Add-Type -AssemblyName microsoft.office.interop.outlook
#[Reflection.Assembly]::LoadWithPartialname("Microsoft.Office.Interop.Outlook") | out-null
#Call API Enumerated Constant values instead of hard-coding
#Reference http://blogs.technet.com/b/heyscriptingguy/archive/2009/01/26/how-do-i-use-windows-powershell-to-work-with-junk-e-mail-in-office-outlook.aspx
#Loads default Outlook Folder names with the Static GetNames() method
<#
olFolderDeletedItems olFolderSyncIssues
olFolderLocalFailures olFolderServerFailures
olFolderJunk olFolderRssFeeds
olFolderToDo olFolderManagedEmail
olFolderOutbox olFolderSentMail
olFolderInbox olFolderCalendar
olFolderContacts olFolderJournal
olFolderNotes olFolderTasks
olFolderDrafts olPublicFoldersAllPublicFolders
olFolderConflicts
#>
$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
#Create object
#Reference http://msdn.microsoft.com/en-us/library/bb176630.aspx
$outlook = New-Object -ComObject outlook.application
#Use the GetNameSpace method to access the MAPI type
$namespace = $Outlook.GetNameSpace("mapi")
#Folder to search
$inbox = $namespace.getDefaultFolder($olFolders::olFolderInbox)
#$inbox = $namespace.getDefaultFolder($olFolders::olFolderJunk)
#Destination Folder
#$MoveTarget = $inbox.Folders.item("PowerShell")
$mvTarget = $inbox
#Finite filtering
#$onedayback = (get-date).AddDays(-10)
#Collection of folder contents
$items = $inbox.items
#Finite folder items
#$filter = "[ReceivedTime] > '#10/15/2012#'"
$filter = "[SenderName] = 'Shawn Harris'"
#Filter search with nameSpace filter property
#("[Unread]=true") ("[From] = 'Ken Myer'") ("[FlagStatus] = 2")
#("[Unread] = True AND [From] = 'Ken Myer'")
#("[Categories] = 'Contacts 2009'") ("[Subject] = 'Project Proposal'")
$inbox = $namespace.GetDefaultFolder($olFolders::olFolderJunk).Items.Restrict($filter)
#Construct loop incrementor
$inbox.count
#Loop with filter property
#This could be removed if a finite search pattern is not needed
#Example if date and string filters are needed
#Create array with expanded restrictions
$messages = $inbox.Restrict("[From] = Shawn Harris")
#Loop
for ($inc = $messages.count; $inc -gt 0 ; $inc --)
{
Write-Output $messages.Item($inc).Subject
#Execute move method
[void]$messages.Item($inc).Move($mvTarget) | out-null
}
|
PowerShellCorpus/PoshCode/Logger.psm1 0.3.ps1
|
Logger.psm1 0.3.ps1
|
<#
Name : Universal Log4Net Logging Module (Logger.psm1)
Version : 0.3
Author : Joel Bennett (MVP)
Site : http://www.HuddledMasses.org/
Version History:
0.3 - Cleanupable release.
Added Udp, Email, Xml and RollingXml, as well as a "Chainsaw":http`://logging.apache.org/log4j/docs/chainsaw.html logger based on "Szymon Kobalczyk's configuration":http`://geekswithblogs.net/kobush/archive/2005/07/15/46627.aspx.
Note: there is a "KNOWN BUG with Log4Net UDP":http`://odalet.wordpress.com/2007/01/13/log4net-ip-parsing-bug-when-used-with-framework-net-20/ which can be patched, but hasn't been released.
Added a Close-Logger method to clean up the Xml logger
NOTE: the Rolling XML Logger produces invalid XML, and the XML logger only produces valid xml after it's been closed...
I did contribute an "XSLT stylesheet for Log4Net":http`://poshcode.org/1746 which you could use as well
0.2 - Configless release.
Now configures with inline XML, and supports switches to create "reasonable" default loggers
Changed all the functions to Write-*Log so they don't overwrite the cmdlets
Added -Logger parameter to take the name of the logger to use (it must be created beforehand via Get-Logger)
Created aliases for Write-* to override the cmdlets -- these are easy for users to remove without breaking the module
** NEED to write some docs, but basically, this is stupid simple to use, just:
Import-Module Logger
Write-Verbose "This message will be saved in your profile folder in a file named PowerShellLogger.log (by default)"
To change the defaults for your system, edit the last line in the module!!
0.1 - Initial release. http`://poshcode.org/1744 (Required config: http`://poshcode.org/1743)
Uses Log4Net : http`://logging.apache.org/log4net/download.html
Documentation: http`://logging.apache.org/log4net/release/sdk/
NOTES:
By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host.
This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts)
To avoid this behavior, remove the aliases after importing it
Import-Module Logger; Remove-Item Alias:Write-*
Write-Warning "This is your warning"
Write-Debug "You should know that..."
Write-Verbose "Everything would be logged, otherwise"
***** NOTE: IT ONLY OVERRIDES THE DEFAULTS FOR SCRIPTS *****
It currently has no effect on error/verbose/warning that is logged from cmdlets.
#>
Add-Type -Path $PSScriptRoot\\log4net.dll
function Get-Logger {
param(
[Parameter(Mandatory=$false)]
[string]$LoggerName = "*"
,
[Parameter(Mandatory=$false)]
[ValidateSet("DEBUG","INFO","WARN","ERROR","FATAL","VERBOSE","HOST","WARNING")]
[string]$LogLevel = "DEBUG"
,
[Parameter(Mandatory=$false)]
$MessagePattern = "%date %-5level %logger [%property{NDC}] - %message%newline"
,
[Parameter(Mandatory=$false)]
[string]$LogFolder = $PSScriptRoot
, [String]$EmailTo
, [Switch]$Force
, [Switch]$Console
, [Switch]$EventLog
, [Switch]$Trace
, [Switch]$DebugAppender
, [Switch]$File
, [Switch]$RollingFile
, [Switch]$Xml
, [Switch]$RollingXml
, [Switch]$Udp
, [Switch]$Chainsaw
)
Remove-Variable Loggers -EA 0
[log4net.LogManager]::GetCurrentLoggers() | Where-Object { $_.Logger.Name -Like $LoggerName } | Tee-Object -Variable Loggers
if(!$Loggers -or $Force -and $LoggerName -ne "*") {
if($LogLevel -eq "VERBOSE") { $LogLevel = "INFO" }
if($LogLevel -eq "HOST") { $LogLevel = "INFO" }
if($LogLevel -eq "WARNING") { $LogLevel = "WARN" }
$AppenderRefs = ''
if($Email) {
if(!$PSEmailServer) { throw "You need to specify your SMTP mail server by setting the global $PSEmailServer variable" }
$AppenderRefs += "<appender-ref ref=""SmtpAppender"" />`n"
$Null,$Domain = $email -split "@",2
}
if($EventLog) { $AppenderRefs += "<appender-ref ref=""EventLogAppender"" />`n" }
if($Trace) { $AppenderRefs += "<appender-ref ref=""TraceAppender"" />`n" }
if($DebugAppender){ $AppenderRefs += "<appender-ref ref=""DebugAppender"" />`n" }
if($File) { $AppenderRefs += "<appender-ref ref=""FileAppender"" />`n" }
if($RollingFile) { $AppenderRefs += "<appender-ref ref=""RollingFileAppender"" />`n" }
if($Udp) { $AppenderRefs += "<appender-ref ref=""UdpAppender"" />`n" }
if($Chainsaw) { $AppenderRefs += "<appender-ref ref=""UdpLog4JAppender"" />`n" }
if($Xml) { $AppenderRefs += "<appender-ref ref=""XmlAppender"" />`n" }
if($RollingXml) { $AppenderRefs += "<appender-ref ref=""RollingXmlAppender"" />`n" }
if($Console -or ($AppenderRefs.Length -eq 0)) { $AppenderRefs += "<appender-ref ref=""ColoredConsoleAppender"" />`n" }
[log4net.LogManager]::GetLogger($LoggerName) | Tee-Object -Variable Script:Logger
[xml]$config = @"
<log4net>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="FATAL" />
<foreColor value="Red, HighIntensity" />
<backColor value="White, HighIntensity" />
</mapping>
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Green, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="Cyan, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="$LoggerName" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="$LogFolder\\$LoggerName.Log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="XmlAppender" type="log4net.Appender.FileAppender">
<file value="$LogFolder\\$LoggerName.xml" />
<appendToFile value="false" />
<layout type="log4net.Layout.XmlLayout">
<Header value="<?xml version='1.0' ?>
<?xml-stylesheet type="text/xsl" href="log4net.xslt"?>
<events version='1.2' xmlns='http://logging.apache.org/log4net/schemas/log4net-events-1.2'>
"/>
<Footer value="</events>"/>
<Prefix value="" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="$LogFolder\\$LoggerName.Log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="RollingXmlAppender" type="log4net.Appender.RollingFileAppender">
<file value="$LogFolder\\$LoggerName.xml" />
<appendToFile value="true" />
<maximumFileSize value="500KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.XmlLayout">
<Prefix value="" />
</layout>
</appender>
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<param name="RemoteAddress" value="localhost" />
<param name="RemotePort" value="8080" />
<param name="Encoding" value="utf-8" />
<layout type="log4net.Layout.XmlLayout">
<param name="Prefix" value="" />
</layout>
<param name="threshold" value="DEBUG" />
</appender>
<appender name="UdpLog4JAppender" type="log4net.Appender.UdpAppender">
<param name="RemoteAddress" value="127.0.0.1" />
<param name="RemotePort" value="8080" />
<param name="Encoding" value="utf-8" />
<layout type="log4net.Layout.XmlLayoutSchemaLog4j, log4net" />
<param name="threshold" value="DEBUG" />
</appender>
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="$Email" />
<from value="PoshLogger@$Domain" />
<subject value="PowerShell Logger Message" />
<smtpHost value="$PSEmailServer" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline$MessagePattern%newline%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
</root>
<logger name="$LoggerName">
<level value="$LogLevel" />
$AppenderRefs
</logger>
</log4net>
"@
[log4net.Config.XmlConfigurator]::Configure( $config.log4net )
}
}
function Set-Logger {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[log4net.Core.LogImpl]$Logger
)
$script:Logger = $Logger
}
function Close-Logger {
param(
[Parameter(Mandatory=$false, ValueFromPipeline=$true)]
[log4net.Core.LogImpl]$Logger
)
PROCESS {
if($Logger) {
$Logger.Logger.CloseNestedAppenders()
$Logger.Logger.RemoveAllAppenders()
} else {
[log4net.LogManager]::Shutdown()
}
}
}
function Push-LogContext {
param(
[Parameter(Mandatory=$true)]
[string]$Name
)
[log4net.NDC]::Push($Name)
}
function Pop-LogContext {
[log4net.NDC]::Pop()
}
function Write-DebugLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.debug($Message) #Write-Debug
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Debug
.ForwardHelpCategory Cmdlet
#>
}
function Write-VerboseLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info($Message)
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Verbose
.ForwardHelpCategory Cmdlet
#>
}
function Write-WarningLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.warn($Message) #Write-Warning
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Warning
.ForwardHelpCategory Cmdlet
#>
}
function Write-ErrorLog {
[CmdletBinding(DefaultParameterSetName='NoException')]
param(
[Parameter(ParameterSetName='WithException', Mandatory=$true)]
[System.Exception]
${Exception},
[Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Parameter(ParameterSetName='WithException')]
[Alias('Msg')]
[AllowNull()]
[AllowEmptyString()]
[System.String]
${Message},
[Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)]
[System.Management.Automation.ErrorRecord]
${ErrorRecord},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Management.Automation.ErrorCategory]
${Category},
[Parameter(ParameterSetName='WithException')]
[Parameter(ParameterSetName='NoException')]
[System.String]
${ErrorId},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Object]
${TargetObject},
[System.String]
${RecommendedAction},
[Alias('Activity')]
[System.String]
${CategoryActivity},
[Alias('Reason')]
[System.String]
${CategoryReason},
[Alias('TargetName')]
[System.String]
${CategoryTargetName},
[Alias('TargetType')]
[System.String]
${CategoryTargetType}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.error($Message,$Exception) #Write-Error
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Error
.ForwardHelpCategory Cmdlet
#>
}
function Write-HostLog {
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[System.Object]
${Object},
[Switch]
${NoNewline},
[System.Object]
${Separator} = $OFS,
[System.ConsoleColor]
${ForegroundColor},
[System.ConsoleColor]
${BackgroundColor}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info(($Object -join $Separator)) #Write-Verbose
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Host
.ForwardHelpCategory Cmdlet
#>
}
Set-Alias Write-Debug Write-DebugLog
Set-Alias Write-Verbose Write-VerboseLog
Set-Alias Write-Warning Write-WarningLog
Set-Alias Write-Error Write-ErrorLog
#Set-Alias Write-Host Write-HostLog
Export-ModuleMember -Function * -Alias *
$script:Logger = Get-Logger "PowerShellLogger" -RollingFile -LogFolder (Split-Path $Profile.CurrentUserAllHosts)
## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
|
PowerShellCorpus/PoshCode/New-PInvoke.ps1
|
New-PInvoke.ps1
|
function New-PInvoke
{
<#
.Synopsis
Generate a powershell function alias to a Win32|C api function
.Description
Creates C# code to access a C function, and exposes it via a powershell function
.Example
New-PInvoke -Library User32.dll -Signature "int GetSystemMetrics(uint Metric)"
.Parameter Library
A C Library containing code to invoke
.Parameter Signature
The C# signature of the external method
.Parameter OutputText
If Set, retuns the source code for the pinvoke method.
If not, compiles the type.
#>
param(
[Parameter(Mandatory=$true,
HelpMessage="The C Library Containing the Function, i.e. User32")]
[String]
$Library,
[Parameter(Mandatory=$true,
HelpMessage="The Signature of the Method, i.e.: int GetSystemMetrics(uint Metric)")]
[String]
$Signature,
[Switch]
$OutputText
)
process {
if ($Library -notlike "*.dll*") {
$Library+=".dll"
}
if ($signature -notlike "*;") {
$Signature+=";"
}
if ($signature -notlike "public static extern*") {
$signature = "public static extern $signature"
}
$name = $($signature -replace "^.*?\\s(\\w+)\\(.*$",'$1')
$MemberDefinition = "[DllImport(`"$Library`")]`n$Signature"
if (-not $OutputText) {
$type = Add-Type -PassThru -Name "PInvoke$(Get-Random)" -MemberDefinition $MemberDefinition
iex "New-Item Function:Global:$name -Value { [$($type.FullName)]::$name.Invoke( `$args ) }"
} else {
$MemberDefinition
}
}
}
|
PowerShellCorpus/PoshCode/vibackup-lx_2.ps1
|
vibackup-lx_2.ps1
|
Param (
$viServer,
$bakVM,
$lxDest
)
#region check
if (!$viServer) { $viServer = Read-Host -Prompt "VI Server " }
if (!$bakVM) { $bakVM = Read-Host -Prompt "VM to Backup " }
if (!$lxDest) { $lxDest = Read-Host -Prompt "Backup Path (ex. /srv/backup) " }
#endregion
#region globalvars
$encoding = "OEM"
$version = "0.7.1"
$scriptout = @()
[regex]$curlpat = "(\\s{1})+(.*vmdk$)"
[regex]$vmxpat = "(\\s{1})+(.*vmx$)"
#endregion
#region stkmvars
$viUser = "vmware"
$viPass = "vmware"
#endregion
Write-Host "viBackup Script Generator - " $version
Write-Host "--------------------------------------------"
if (($vmCon = Connect-VIServer -Protocol https $viServer) -eq "") { exit }
$vm = Get-VM $bakVM -Server $vmCon -ErrorAction SilentlyContinue
if (!$vm) {
Write-Host "No VM found."
Write-Host "Enter the Display Name from the VI Center:" -NoNewline
$tvm = Read-Host
if (!($vm=Get-VM $tvm -ErrorAction SilentlyContinue)) {
return $false
exit
}
Write-Host "You have entered 2 different Names. Please check that the VMX and the VM Name are the same!"
Write-Host -ForegroundColor yellow "Entered VMX Name: {$bakVM}"
Write-Host -ForegroundColor yellow "Entered VM Name: {$tvm}"
Write-Host -ForegroundColor yellow "Returned VM Name: {$vm}"
Write-Host -ForegroundColor yellow "IS THIS CORRECT (Yes/No)?:" -NoNewline
$sure = Read-Host
if ($sure -ne "yes") { exit }
}
#check Snapshots
if ((Get-Snapshot -VM $vm -Server $vmCon)) {
Write-Host "VM has Snapshots. No Backup possible."
return $false
exit
}
#check HardDisk Mode
foreach ($hd in $vm.harddisks) {
if ($hd.Persistence -ne "Persistent") {
write-host "Hard Disk is not Persistent - no Snapshot allowed."
return $false
exit
}
}
#write script
$scriptname = $vm.name + ".sh"
$vmname = $vm.name
$vmhost = $vm.Host
$vmview= Get-View $vm.id
$vmvname = $vmview.config.files.vmpathname
#generate Text
$header = "#!/bin/bash"
$user = "USER=`"${viUser}`""
$pass = "PASS=`"${viPass}`""
$dest = "DEST=`"${lxDest}`""
$lxVM = "VM=`"${vmname}`""
$dcPath = $vm | Get-Datacenter
#region writefile
$scriptout += $header
$scriptout += $user
$scriptout += $pass
$scriptout += $dest
$scriptout += $lxvm
$scriptout += ""
$scriptout += "BKUP=`"${vmvname}`""
$scriptout += "SNAPCHECK=``vmware-cmd -H ${viserver} -T ${vmhost} -U `${USER} -P `${PASS} `"`${BKUP}`" hassnapshot`` "
$scriptout += "if [ `"`$SNAPCHECK`" != `"hassnapshot () =`" ]; then `n echo 'VM has a Snapshot. Aborting...' `n exit `n fi"
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} snapshot `"`${BKUP}`" vmBackup"
# Hard Disk
foreach ($hd in $vm.Harddisks) {
$hdname = $hd.Filename
$patstr = $curlpat.split($hdname)
#dirty hack
$patstr[0] = $patstr[0].replace("[","")
$patstr[0] = $patstr[0].replace("]","")
$dsPath = $patstr[0].replace(" ","%20")
$vmdkpath = $patstr[2].replace(" ","%20")
$vmdkflatpath = $patstr[2].replace(".vmdk","-flat.vmdk")
#curl options
$vmdk = "curl --user `${USER}:`${PASS} -o `${DEST}/${vmdkpath} `"https://${viserver}/folder/${vmdkpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure "
$vmdkflat = "curl --user `${USER}:`${PASS} -o `${DEST}/${vmdkflatpath} `"https://${viserver}/folder/${vmdkflatpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure"
#$vmdk = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname```" `${DEST}/`${VM}.vmdk "
#$vmdkflat = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname | sed 's/.vmdk/-flat.vmdk/g'```" `${DEST}/`${VM}-flat.vmdk "
$scriptout += $vmdk
$scriptout += $vmdkflat
}
#VMX
$vmg = get-view $vm.id
$vmxfile = $vmxpat.split($vmg.config.files.vmpathname)
$vmxfile = $vmxfile[2]
$scriptout += "curl --user `${USER}:`${PASS} -o `${DEST}/${vmxfile} `"https://${viserver}/folder/${vmxfile}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure "
#Remove Snapshot
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} deleteSnapshot `"`${BKUP}`" vmBackup"
$scriptout | Out-File $scriptname -Encoding $encoding
#endregion
Write-Host "Finished"
Write-Host "Don't forget to convert the script under *nix/Linux with dos2unix!"
|
PowerShellCorpus/PoshCode/Convert-BounceToX_8.ps1
|
Convert-BounceToX_8.ps1
|
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $
# $Revision: 610 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
#.Example
# "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress
)
BEGIN
{
Add-Type -AssemblyName System.Web|Out-Null
}
PROCESS
{
if($_) {$bounceAddress = $_}
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
}
|
PowerShellCorpus/PoshCode/UIAutomation 1.8.ps1
|
UIAutomation 1.8.ps1
|
## UI Automation v 1.8 -- REQUIRES the Reflection module (current version: http://poshcode.org/3174 )
##
# WASP 2.0 is getting closer, but this is still just a preview:
# -- a lot of the commands have weird names still because they're being generated ignorantly
# -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke
# v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit
# v 1.8 - Fixes .Net version problems: specifying CSharpVersion3 when in PowerShell 2
# IF your PowerShell is running in .Net 4
if($PSVersionTable.CLRVersion -gt "4.0") {
$Language = "CSharp" # Version 4
Add-Type -AssemblyName "UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
} else {
# In PowerShell 2, we need to use the .Net 3 version
$Language = "CSharpVersion3"
Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
$SWA = "System.Windows.Automation"
# Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
# Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue
# Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue
# Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue
# Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
# Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
# This is what requires the Reflection module:
Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue
Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue
##### Conditions
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
##### IDentifiers
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
##### Patterns:
$patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern
#| Where { $_ -ne [System.Windows.Automation.InvokePattern] }
Add-Type -Language $Language -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StaticFieldAttribute : ArgumentTransformationAttribute {
private Type _class;
public override string ToString() {
return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName);
}
public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) {
if(inputData is string && !string.IsNullOrEmpty(inputData as string)) {
System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public);
if(field != null) {
return field.GetValue(null);
}
}
return inputData;
}
public StaticFieldAttribute( Type ofClass ) {
OfClass = ofClass;
}
public Type OfClass {
get { return _class; }
set { _class = value; }
}
}
public static class UIAutomationHelper {
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow (string lpClassName, string lpWindowName);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetForegroundWindow (IntPtr hWnd);
public static AutomationElement RootElement {
get { return AutomationElement.RootElement; }
}
///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis>
public static bool SetForeground(this AutomationElement element)
{
if(element == null) {
throw new ArgumentNullException("element");
}
// Get handle to the element
IntPtr other = FindWindow (null, element.Current.Name);
// // Get the Process ID for the element we are trying to
// // set as the foreground element
// int other_id = GetWindowThreadProcessId (other, IntPtr.Zero);
//
// // Get the Process ID for the current process
// int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero);
//
// // Attach the current process's input to that of the
// // given element. We have to do this otherwise the
// // WM_SETFOCUS message will be ignored by the element.
// bool success = AttachThreadInput(this_id, other_id, true);
// Make the Win32 call
IntPtr previous = SetForegroundWindow(other);
return !IntPtr.Zero.Equals(previous);
}
}
"@
## TODO: Write Get-SupportedPatterns or rather ...
## Get-SupportedFunctions (to return the names of the functions for the supported patterns)
## TODO: Support all the "Properties" too
## TODO: Figure out why Notepad doesn't support SetValue
## TODO: Figure out where the menus support went
ForEach($pattern in $patterns){
$pattern | Add-Accelerator
$PatternFullName = $pattern.FullName
$PatternName = $Pattern.Name -Replace "Pattern","."
$newline = "`n`t`t"
New-Item "Function:ConvertTo-$($Pattern.Name)" -Value "
param(
[Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject
)
process {
trap {
if(`$_.Exception.Message -like '*Unsupported Pattern.*') {
Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue;
}
}
Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current
}"
$pattern.GetMethods() |
Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } |
ForEach {
$FunctionName = "Function:Invoke-$PatternName$($_.Name)"
$Position = 1
if (test-path $FunctionName) { remove-item $FunctionName }
$Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+
"$newline[Alias('Parent','Element','Root','AutomationElement')]"+
"$newline[AutomationElement]`$InputObject"
) +
@(
"[Parameter()]$newline[Switch]`$Passthru"
) +
@($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" })
$Parameters = $Parameters -Join "$newline,$newline"
$ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $')
$definition = @"
param(
$Parameters
)
process {
## trap { Write-Warning "`$(`$_)"; break }
`$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues }))
}
if(`$passthru) {
`$InputObject
}
}
"@
trap {
Write-Warning $_
Write-Host $definition -fore cyan
}
New-Item $FunctionName -value $definition
}
$pattern.GetProperties() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} |
ForEach {
$FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.')
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$pattern.'$($_.Name)'
}
}"
}
## So far this seems to be restricted to Text (DocumentRange) elements
$pattern.GetFields() |
Where { $_.FieldType.Name -like "*TextAttribute"} |
ForEach {
$FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name))
}"
}
$pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } |
ForEach {
$Name = $_.Name -replace 'Event$'
$FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
,
[System.Windows.Automation.TreeScope]`$TreeScope = 'Element'
,
[ScriptBlock]`$EventHandler
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
[Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler )
}"
}
}
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
$AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties()
Set-Alias Invoke-UIElement Invoke-Invoke.Invoke
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Get-ClickablePoint {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
)
process {
$InputObject.GetClickablePoint()
}
}
function Show-Window {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
Set-UIFocus $InputObject
if($passthru) {
$InputObject
}
}
}
function Set-UIFocus {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
try {
[UIAutomationHelper]::SetForeground( $InputObject )
$InputObject.SetFocus()
} catch {
Write-Verbose "SetFocus fail, trying SetForeground"
}
if($passthru) {
$InputObject
}
}
}
function Send-UIKeys {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Keys
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
,
[Parameter()]
[Switch]$Async
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
Set-UIFocus $InputObject
if($Async) {
[SendKeys]::Send( $Keys )
} else {
[SendKeys]::SendWait( $Keys )
}
if($passthru) {
$InputObject
}
}
}
function Set-UIText {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$valuePattern = $null
if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) {
Write-Verbose "Set via ValuePattern!"
$valuePattern.SetValue( $Text )
}
elseif($InputObject.Current.IsKeyboardFocusable)
{
Set-UIFocus $InputObject
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
if($passthru) {
$InputObject
}
}
}
function Select-UIElement {
[CmdletBinding(DefaultParameterSetName="FromParent")]
PARAM (
[Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)]
[Alias("MainWindowHandle","hWnd","Handle","Wh")]
[IntPtr[]]$WindowHandle=[IntPtr]::Zero
,
[Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)]
[System.Windows.Point[]]$Point
,
[Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)]
[System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement
,
[Parameter(ParameterSetName="FromParent", Position="0")]
[Alias("WindowName")]
[String[]]$Name
,
[Parameter(ParameterSetName="FromParent", Position="1")]
[Alias("Type","Ct")]
[System.Windows.Automation.ControlType]
[StaticField(([System.Windows.Automation.ControlType]))]$ControlType
,
[Parameter(ParameterSetName="FromParent")]
[Alias("UId")]
[String[]]$AutomationId
,
## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle
[Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )]
[Alias("Id")]
[Int[]]$PID
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Pn")]
[String[]]$ProcessName
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Cn")]
[String[]]$ClassName
,
[switch]$Recurse
,
[switch]$Bare
)
process {
Write-Debug "Parameters Found"
Write-Debug ($PSBoundParameters | Format-Table | Out-String)
$search = "Children"
if($Recurse) { $search = "Descendants" }
$condition = [System.Windows.Automation.Condition]::TrueCondition
Write-Verbose $PSCmdlet.ParameterSetName
switch -regex ($PSCmdlet.ParameterSetName) {
"FromWindowHandle" {
Write-Verbose "Finding from Window Handle $HWnd"
$Element = $(
foreach($hWnd in $WindowHandle) {
[System.Windows.Automation.AutomationElement]::FromHandle( $hWnd )
}
)
continue
}
"FromPoint" {
Write-Verbose "Finding from Point $Point"
$Element = $(
foreach($pt in $Point) {
[System.Windows.Automation.AutomationElement]::FromPoint( $pt )
}
)
continue
}
"FromParent" {
Write-Verbose "Finding from Parent!"
## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition
[ScriptBlock[]]$filters = @()
if($AutomationId) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($aid in $AutomationId) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($PID) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in $PID) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($ProcessName) {
if($ProcessName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in Get-Process -Name $ProcessName) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($Name) {
Write-Verbose "Name: $Name"
if($Name -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($n in $Name){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ClassName) {
if($ClassName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ClassName){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ControlType) {
if($ControlType -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ControlType){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($conditions.Length -gt 1) {
[System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions
} elseif($conditions) {
[System.Windows.Automation.Condition]$condition = $conditions[0]
} else {
[System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition
}
If($VerbosePreference -gt "SilentlyContinue") {
function Write-Condition {
param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0)
process {
Write-Debug ($Condition | fl * | Out-String)
if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name )
$condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4)
} elseif($condition -is [System.Windows.Automation.PropertyCondition]) {
Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")")
} else {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")")
}
}
}
Write-Verbose "CONDITIONS ============="
$global:LastCondition = $condition
foreach($c in $condition) {
Write-Condition $c
}
Write-Verbose "============= CONDITIONS"
}
if($filters.Count -gt 0) {
$Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item }
} else {
$Element = $Parent.FindAll( $search, $condition )
}
}
}
Write-Verbose "Element Count: $(@($Element).Count)"
if($Element) {
foreach($el in $Element) {
if($Bare) {
Write-Output $el
} else {
$e = New-Object PSObject $el
foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName)
{
## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property
$propName = [System.Windows.Automation.Automation]::PropertyName($prop)
Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0
}
foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName)
{
Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0
}
Write-Output $e
}
}
}
}
}
# [Cmdlet(VerbsCommon.Add, "UIAHandler")]
# public class AddUIAHandlerCommand : PSCmdlet
# {
# private AutomationElement _parent = AutomationElement.RootElement;
# private AutomationEvent _event = WindowPattern.WindowOpenedEvent;
# private TreeScope _scope = TreeScope.Children;
#
# [Parameter(ValueFromPipeline = true)]
# [Alias("Parent", "Element", "Root")]
# public AutomationElement InputObject { set { _parent = value; } get { return _parent; } }
#
# [Parameter()]
# public AutomationEvent Event { set { _event = value; } get { return _event; } }
#
# [Parameter()]
# public AutomationEventHandler ScriptBlock { set; get; }
#
# [Parameter()]
# public SwitchParameter Passthru { set; get; }
#
# [Parameter()]
# public TreeScope Scope { set { _scope = value; } get { return _scope; } }
#
# protected override void ProcessRecord()
# {
# Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock);
#
# if (Passthru.ToBool())
# {
# WriteObject(InputObject);
# }
#
# base.ProcessRecord();
# }
# }
Export-ModuleMember -cmdlet * -Function * -Alias *
|
PowerShellCorpus/PoshCode/finddupe_6.ps1
|
finddupe_6.ps1
|
None
|
PowerShellCorpus/PoshCode/cd command with history.ps1
|
cd command with history.ps1
|
########################################################
# Custom 'cd' command to maintain directory history
#
# Usage:
# cd no args means cd $home
# cd <name> changes to the directory specified by <name>
# cd -l list your directory history
# cd -# change to the history entry specified by #
#
if( test-path alias:\\cd ) { remove-item alias:\\cd }
$global:PWD = get-location;
$global:CDHIST = [System.Collections.Arraylist]::Repeat($PWD, 1);
function cd {
$cwd = get-location;
$l = $global:CDHIST.count;
if ($args.length -eq 0) {
set-location $HOME;
$global:PWD = get-location;
$global:CDHIST.Remove($global:PWD);
if ($global:CDHIST[0] -ne $global:PWD) {
$global:CDHIST.Insert(0,$global:PWD);
}
$global:PWD;
}
elseif ($args[0] -like "-[0-9]*") {
$num = $args[0].Replace("-","");
$global:PWD = $global:CDHIST[$num];
set-location $global:PWD;
$global:CDHIST.RemoveAt($num);
$global:CDHIST.Insert(0,$global:PWD);
$global:PWD;
}
elseif ($args[0] -eq "-l") {
for ($i = $l-1; $i -ge 0 ; $i--) {
"{0,6} {1}" -f $i, $global:CDHIST[$i];
}
}
elseif ($args[0] -eq "-") {
if ($global:CDHIST.count -gt 1) {
$t = $CDHIST[0];
$CDHIST[0] = $CDHIST[1];
$CDHIST[1] = $t;
set-location $global:CDHIST[0];
$global:PWD = get-location;
}
$global:PWD;
}
else {
set-location "$args";
$global:PWD = pwd;
for ($i = ($l - 1); $i -ge 0; $i--) {
if ($global:PWD -eq $CDHIST[$i]) {
$global:CDHIST.RemoveAt($i);
}
}
$global:CDHIST.Insert(0,$global:PWD);
$global:PWD;
}
$global:PWD = get-location;
}
|
PowerShellCorpus/PoshCode/Out-DataTable_5.ps1
|
Out-DataTable_5.ps1
|
#######################
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Fixed Issue with Properties
v1.2 - Vadims Podans - fixed column data type instead of using default System.String
.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)
{
$DT.Columns.Add(new-object Data.DataColumn $property.Name, $property.Value.GetType())
}
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/VHDFunctions.psm1.ps1
|
VHDFunctions.psm1.ps1
|
<#
Name: VHDFunctions.psm1
Author: Rich Kusak (rkusak@cbcag.edu)
Created: 2009-10-23
LastEdit: 2009-11-02 15:54
Included Functions:
Dismount-VHD
Initialize-VHD
Mount-VHD
New-VHD
Set-VHDBootConfiguration
Test-VHD
#>
<#
.SYNOPSIS
Dismount a VHD file from the system.
.DESCRIPTION
This function wraps the consistancy of PowerShell around the Diskpart utility.
A Diskpart script is created to automate the dismount (detach) of a VHD file from the system.
Optionally, the VHD file can be deleted following detachment.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER Remove
Removes (deletes) the VHD file after dismounting it.
.PARAMETER NoConfirm
Supresses the delete confirmation prompt.
.PARAMETER DiskpartScript
Specifies the path location of the Diskpart script file.
Default location is $env:SystemDrive
This file is deleted at the conclusion of the script.
.PARAMETER Rescan
Instructs Diskpart to rescan the system for available storage resources.
.EXAMPLE
Dismount-VHD -Path C:\\test.vhd
Dismounts the specified VHD file.
.EXAMPLE
Dismount-VHD -Path C:\\test.vhd -Remove
Dismounts the specified VHD file and then deletes it.
.NOTES
Name: Dismount-VHD.ps1
Author: Rich Kusak
Created: 2009-10-22
LastEdit: 2009-10-26 11:35
#Requires -Version 2.0
#>
function Dismount-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[switch]$Remove,
[switch]$NoConfirm,
[string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
function RemoveVHD {
switch ($NoConfirm) {
$false {
## Prompt for confirmation to delete the VHD file ##
"" ; Write-Warning "Are you sure you want to delete the file ""$Path""?"
$Prompt = Read-Host "Type ""YES"" to continue or anything else to break"
if ($Prompt -ceq 'YES') {
Remove-Item -Path $Path -Force
"" ; Write-Host "VHD ""$Path"" deleted!" ; ""
} else {
"" ; Write-Host "Script terminated without deleting the VHD file." ; ""
}
}
$true {
## Confirmation prompt suppressed ##
Remove-Item -Path $Path -Force
"" ; Write-Host "VHD ""$Path"" deleted!" ; ""
}
}
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."}
}
process{
## DiskPart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Select VDisk File="$Path"`nDetach VDisk
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
}
end {
if ($Remove) {RemoveVHD}
Remove-Item -Path $DiskpartScript -Force ; ""
}
}
Export-ModuleMember -Function Dismount-VHD
<#
.SYNOPSIS
Initialize a VHD by preparing it for use.
.DESCRIPTION
This function wraps the consistancy of PowerShell around the Diskpart utility.
A Diskpart script is created to automate initializing a VHD.
The script creates a partition, assigns a drive letter, and formats a mounted VHD.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER Drive
A drive letter to assign to the mounted VHD.
If not specified the system will auto assign the next available drive letter.
.PARAMETER Label
A volume label to assign to the mounted VHD.
.PARAMETER DiskpartScript
Specifies the path location of the Diskpart script file.
Default location is $env:SystemDrive
This file is deleted at the conclusion of the script.
.PARAMETER Rescan
Instructs Diskpart to rescan the system for available storage resources.
.EXAMPLE
Initialize-VHD C:\\test.vhd X: TestVHD
Initializes the VHD at path C:\\test.vhd assign it to drive letter X: and give it the volume label "TestVHD".
.NOTES
Name: Initialize-VHD
Author: Rich Kusak
Created: 2009-10-22
LastEdit: 2009-10-26 15:11
#Requires -Version 2.0
#>
function Initialize-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)]
[string]$Drive,
[Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false)]
[string]$Label,
[Parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false)]
[string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt",
[switch]$NoConfirm,
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."}
## Validate -Drive parameter ##
if ($Drive) {
$Reserved = @('A:','B:','C:')
$Reserved += (Get-WmiObject win32_LogicalDisk -Property DeviceID | ForEach-Object {$_.DeviceID})
switch ($Drive) {
{($_ -notmatch "^[a-z]$") -and ($_ -notmatch "^[a-z]:$")} {throw "The drive letter ""$_"" is invalid."}
{$_ -notmatch ":"} {$Drive += ":"}
{$Reserved -contains $Drive} {throw "The drive letter ""$_"" is reserved."}
}
}
if (!$NoConfirm) {
"" ; Write-Warning "The VHD ""$Path"" is about to initialized. Any existing data will be destroyed!`nAre you sure you want to continue?" ; ""
$Prompt = Read-Host "Type ""YES"" to continue or anything else to break"
if ($Prompt -cne 'YES') {Write-Host "Function terminated by user."; "" ; break}
}
}
process {
## Diskpart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Select VDisk File="$Path"
Clean
Create Partition Primary
Format Quick FS=NTFS $(if ($Label) {"Label=""$Label"""})
$(if ($Drive) {"Assign Letter=$Drive"} else {'Assign'})
Detail VDisk
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
}
end {
InvokeDiskpart
Remove-Item -Path $DiskpartScript -Force ; ""
Write-Host "The VHD ""$Path"" has been successfully initialized." ; ""
}
}
Export-ModuleMember -Function Initialize-VHD
<#
.SYNOPSIS
Mount a VHD to the system.
.DESCRIPTION
This function wraps the consistancy of PowerShell around the Diskpart utility.
A Diskpart script is created to automate mounting (attach) a VHD file to the system.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER DiskpartScript
Specifies the path location of the Diskpart script file.
Default location is $env:SystemDrive
This file is deleted at the conclusion of the script.
.PARAMETER Rescan
Instructs Diskpart to rescan the system for available storage resources.
.NOTES
Name: Mount-VHD.ps1
Author: Rich Kusak
Created: 2009-10-22
LastEdit: 2009-10-26 09:25
#Requires -Version 2.0
#>
function Mount-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."}
}
process{
## Diskpart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Select VDisk File="$Path"`nAttach VDisk
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
}
end {
Remove-Item -Path $DiskpartScript -Force ; ""
Write-Host "The VHD ""$Path"" has been successfully mounted." ; ""
}
}
Export-ModuleMember -Function Mount-VHD
<#
.SYNOPSIS
Create a new VHD file.
.DESCRIPTION
This function wraps the consistancy of PowerShell around the Diskpart utility.
A Diskpart script is created to automate the creation of the VHD.
Optionally, the VHD can be mounted immediately following the creation process.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER Maximum
The maximum space allocated for the VHD to use.
.PARAMETER Fixed
Creates a fixed disk VHD file. By default a dynamically expanding VHD file is created.
.PARAMETER Mount
Mount (attach) the VHD to the system making it available to Windows.
.PARAMETER Prepare
Prepares the VHD for use by partitioning, Mount (attach) the VHD to the system making it available to Windows.
.PARAMETER NoConfirm
Supresses the maximum validation warning confirmation prompt.
.PARAMETER DiskpartScript
Specifies the path location of the Diskpart script file.
Default location is $env:SystemDrive
This file is deleted at the conclusion of the script.
.PARAMETER Rescan
Instructs Diskpart to rescan the system for available storage resources.
.NOTES
Name: New-VHD
Author: Rich Kusak
Created: 2009-05-27
LastEdit: 2009-10-26 10:06
#Requires -Version 2.0
#>
function New-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[int]$Maximum,
[switch]$Fixed,
[switch]$Mount,
[switch]$NoConfirm,
[string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
function TestMaximum {
## Validates the -Maximum parameter against the specified disk's available space ##
$Drive = Split-Path $Path -Qualifier
$LogicalDisk = Get-WmiObject win32_LogicalDisk -Filter "DeviceID = '$Drive'"
$FreeSpace = [math]::Truncate(($LogicalDisk.FreeSpace)/1MB)
$Percent = [math]::Round(($Maximum/$FreeSpace)*100,0)
switch ($Maximum) {
{$_ -gt 2088960} {throw "The -Maximum parameter value ""$Maximum"" exceeds the allowable VHD size."}
{$_ -ge $FreeSpace -and $Fixed} {throw "The -Maximum parameter value ""$Maximum"" exceeds available disk space."}
{$_ -ge $FreeSpace} {
"" ; Write-Warning "The VHD maximum size exceeds available disk space."
if (!$NoConfirm) {
Write-Host "Are you sure you want to continue?"
$Prompt = Read-Host "Type ""YES"" to continue or anything else to break"
if ($Prompt -cne 'YES') {
"" ; Write-Host "Script terminiated by user." ; ""
return
}
}
}
{$Percent -ge 80} {
"" ; Write-Warning "The VHD maximum size is $Percent% of the available disk space."
if (!$NoConfirm) {
Write-Host "Are you sure you want to continue?"
$Prompt = Read-Host "Type ""YES"" to continue or anything else to break"
if ($Prompt -cne 'YES') {
"" ; Write-Host "Script terminiated by user." ; ""
return
}
}
}
}
## Validate Operating System Version ##
if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."}
}
}
process {
TestMaximum
## Diskpart Script Content ## Here-String statement purposefully not indented ##
@"
$(if ($Rescan) {'Rescan'})
Create VDisk File="$Path" Maximum=$Maximum $(if ($Fixed) {'Type=Fixed'} else {'Type=Expandable'})
$(if ($Mount) {"Select VDisk File=""$Path""`nAttach VDisk"})
Exit
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
}
end {
Remove-Item -Path $DiskpartScript -Force ; ""
Write-Host "A new VHD has been created at ""$Path""." ; ""
if ($Mount) {Write-Host "The VHD has been successfully mounted." ; ""}
}
}
Export-ModuleMember -Function New-VHD
<#
.SYNOPSIS
Set the system boot configuration to boot from a VHD.
.DESCRIPTION
This function wraps the consistancy of PowerShell around the BCDEdit tool.
The Boot Configuration DataStore Editor (BCDEdit) is used to set the necessary
boot configuration entry to optionally boot to a VHD during startup.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER Description
Description for the boot configuration entry.
.EXAMPLE
Set-VHDBootConfiguration
.NOTES
Name: Set-VHDBootConfiguration
Author: Rich Kusak
Created: 2009-10-22
LastEdit: 2009-10-26 10:14
#Requires -Version 2.0
#>
function Set-VHDBootConfiguration {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true)]
[string]$Path,
[Parameter(Position=1,Mandatory=$true)]
[string]$Description
)
begin {
if (!(Test-Path -Path $Path -Include "*.vhd")) {throw "The path ""$Path"" is invalid or does not contain a VHD file."}
$Drive = Split-Path -Path $Path -Qualifier
$UnQualifiedPath = Split-Path -Path $Path -NoQualifier
}
process {
$Copy = bcdedit /copy '{current}' /d $Description
$CLSID = $Copy | ForEach-Object {$_.Remove(0,37).Replace(".","")}
bcdedit /set $CLSID device vhd=[$Drive]""$UnQualifiedPath""
bcdedit /set $CLSID osdevice vhd=[$Drive]""$UnQualifiedPath""
bcdedit /set $CLSID detecthal on
New-Object PSObject | Add-Member -MemberType NoteProperty -Name 'Identifier' -Value $CLSID -PassThru |
}
end {
Write-Host "The VHD ""$Path"" has been prepared for boot operation." ; ""
}
}
Export-ModuleMember -Function Set-VHDBootConfiguration
<#
.SYNOPSIS
Test a VHD.
.DESCRIPTION
This script wraps the consistancy of PowerShell around the Diskpart utility.
A Diskpart script is created to automate initializing a VHD.
The script creates a partition, assigns a drive letter, and formats a mounted VHD.
.PARAMETER Path
Specifies the full path to the VHD file.
.PARAMETER DiskpartScript
Specifies the path location of the Diskpart script file.
Default location is $env:SystemDrive
This file is deleted at the conclusion of the script.
.PARAMETER Rescan
Instructs Diskpart to rescan the system for available storage resources.
.NOTES
Name: Test-VHD.ps1
Author: Rich Kusak
Created: 2009-10-23
LastEdit: 2009-10-26 10:17
#Requires -Version 2.0
#>
function Test-VHD {
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[string]$Path,
[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)]
[string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt",
[switch]$Rescan
)
begin {
function InvokeDiskpart {
Diskpart.exe /s $DiskpartScript
}
if (!(Test-Path -Path $Path -Include "*.vhd")) {throw "The path ""$Path"" is not valid or does not contain a VHD file."}
}
process {
@"
Select VDisk File="$Path"
Detail VDisk
"@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force
InvokeDiskpart
}
end {
Remove-Item -Path $DiskpartScript -Force ; ""
}
}
Export-ModuleMember -Function Test-VHD
|
PowerShellCorpus/PoshCode/Get-Parameter_3.ps1
|
Get-Parameter_3.ps1
|
param($Cmdlet) foreach ($paramset in (Get-Command $Cmdlet).ParameterSets) {
$Output = @()
foreach ($param in $paramset.Parameters) {
$process = "" | Select-Object Name, ParameterSet, Aliases, IsMandatory, CommonParameter
$process.Name = $param.Name
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
$process.IsMandatory = $param.IsMandatory
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob") { $process.CommonParameter = $TRUE }
else { $process.CommonParameter = $FALSE }
$output += $process
}
Write-Output $Output
}
|
PowerShellCorpus/PoshCode/Set-PowerGUIWelcomePage.ps1
|
Set-PowerGUIWelcomePage.ps1
|
########################################################
# Modifies the default PowerGUI admin console
# welcome screen to the mht file you supply
# Details available at:
# http://dmitrysotnikov.wordpress.com/2009/02/11/rebranding-powergui-consolerebranding-powergui-console/
########################################################
# Usage:
# & .\\Set-PowerGUIWelcomePage.ps1 \\\\server\\share\\my.mht
########################################################
# (c) Dmitry Sotnikov, Oleg Shevnin
# v1, Feb 11, 2009
########################################################
param ($mhtpath)
# this should be path (local or UNC) to the new welcome page
# verify that the new file exists and is mht
if ( $mhtpath -eq $null ) {
$mhtpath = Read-Host "Please provide path to the MHT file."
}
$mhtfile = Get-ChildItem $mhtpath
if ( $mhtfile -eq $null) {
throw "MHT file $mhtpath not found. Please verify the script parameter."
}
if ( $mhtfile.Extension -ne ".mht" ) {
throw "File $mhtpath is not an MHT file. Only MHT files are supported."
}
# Locate PowerGUI configuration for current user on this computer
$cfgpath = "$($env:APPDATA)\\Quest Software\\PowerGUI\\quest.powergui.xml"
# Create backup
Copy-Item $cfgpath "$cfgpath.backupconfig"
# Read the file
$xml = [xml]$(Get-Content $cfgpath)
# If the section for custom welcome page does not exist - create it
$node = $xml.SelectSingleNode("//container[@id='4b510268-a4eb-42e0-9276-06223660291d']")
if ($node -eq $null) {
$node = $xml.CreateElement("container")
$node.SetAttribute("id", "4b510268-a4eb-42e0-9276-06223660291d")
$node.SetAttribute("name", "Home Page")
$node.AppendChild($xml.CreateElement("value"))
$xml.SelectSingleNode("/configuration/items").AppendChild($node)
}
# Set the new value and save the file
$node.Value = $mhtpath
$xml.Save($cfgpath)
|
PowerShellCorpus/PoshCode/Set-Computername_11.ps1
|
Set-Computername_11.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/Report-DecomVMs.ps1
|
Report-DecomVMs.ps1
|
#========================================================================
# Created on: 6/8/2012 9:45 AM
# Created by: Clint Jones
# Organization: Virtually Genius!
# Filename: Report-DecomVMs
#========================================================================
#Load PowerCLI
Add-PSSnapin VMware.VimAutomation.Core
#Connect to vCenter
Connect-VIServer -Server <viserver> -Credential (Get-Credential)
#variables
$deletenow = @()
$deletesoon = @()
#Check to see what VMs are labeled DNR and have been powered off
$dnrvms = Get-VM | Where-Object {($_.Name.Contains("DNR")) -and ($_.PowerState -eq "PoweredOff")}
foreach ($dnrvm in $dnrvms)
{
#Make sure that the VM has been powered off for more than 14 days
[array]$poweroffs = Get-VM -Name $dnrvm.Name | Get-VIEvent -Start (Get-Date).AddDays(-14) | Where-Object {$_.FullFormattedMessage -like "*is powered off"}
if ($poweroffs -eq $null)
{
#this vm has been off more than 14 days - take action
$deletenow += $dnrvm.Name
}
else
{
#this vm has not been off more than 14 days - report but do not take action
$deletesoon += $dnrvm.Name
}
}
#Remove duplications
$deletesoon = $deletesoon | Select-Object -Unique
$deletenow = $deletenow | Select-Object -Unique
|
PowerShellCorpus/PoshCode/Findup_16.ps1
|
Findup_16.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static System.String[] paths = new string[0];
public static System.String[] excpaths = new string[0];
public static System.String[] incpaths = new string[0];
public static System.Boolean noerr = false;
public static System.Boolean useregex = false;
public static System.Boolean includeflag = false;
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine(" ");
System.Boolean recurse = false;
System.Boolean exc = false;
System.Boolean inc = false;
List<FileInfo> files = new List<FileInfo>();
long numOfDupes = 0; // number of duplicate files found.
long dupeBytes = 0; // number of bytes in duplicates.
int i = 0;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-noerr] [-x] <files/directories/regx> [-regex]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help message.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -noerr - discards error messages.");
Console.WriteLine(" -x - eXcludes all directories\\\\files (or RegEx if -regex used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -i - Include only directories\\\\files (or RegEx if -regex used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -regex - Use Regex notation for exclude (-x) and include (-i) option.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -regx");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in it as specified by the Regex item \\"(?:jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -i \\"(?:smith)\\" -regx");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with 'jim' in it as specified by the Regex items \\"(?:jim)\\",\\"(?:smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-regex", true) == 0)
{
useregex = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-noerr", true) == 0)
{
noerr = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-i", true) == 0)
{
inc = true;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-x", true) == 0)
{
exc = true;
inc = false;
continue;
}
if (exc == true)
{
Array.Resize(ref excpaths, excpaths.Length + 1);
excpaths[excpaths.Length - 1] = args[i];
continue;
}
if (inc == true)
{
Array.Resize(ref incpaths, incpaths.Length + 1);
incpaths[incpaths.Length - 1] = args[i];
includeflag = true;
continue;
}
else
{
Array.Resize(ref paths, paths.Length + 1);
paths[paths.Length - 1] = args[i];
}
}
if (paths.Length == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help");
return;
}
Console.Write("Getting file info...");
getFiles(paths, "*.*", recurse, files);
Console.WriteLine("Completed!");
if (files.Count < 2)
{
WriteErr("Findup.exe needs at least 2 files to compare. Try findup.exe -help");
return;
}
Console.Write("Sorting file list...");
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Computing SHA512 & Size matches...");
var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>();
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) { continue; }
var breakout = false;
while (true)
{
var _SHA512 = SHA512.Create();
try
{
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string SHA512string = enc.GetString(_SHA512.Hash);
if (SizeHashName.ContainsKey(files[i].Length))
{
if (!SizeHashName[files[i].Length].ContainsKey(SHA512string))
{
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
}
else
{
SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>());
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName);
}
catch (Exception e)
{
WriteErr("Hash error: " + e.Message);
}
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
if (files[i].Length != files[i + 1].Length) { breakout = true; }
}
}
Console.WriteLine("Completed!");
foreach (var SizeGroup in SizeHashName)
{
foreach (var HashGroup in SizeHashName[SizeGroup.Key])
{
if (HashGroup.Value.Count > 1)
{
Console.WriteLine("Duplicates (size: {0:N0} Bytes) - ", (long)SizeGroup.Key);
foreach (var FileName in HashGroup.Value)
{
Console.WriteLine(FileName);
numOfDupes++;
dupeBytes += (long)SizeGroup.Key;
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
return; // Exit after displaying statistics.
}
private static void WriteErr(string Str)
{
if (noerr == false)
Console.WriteLine(Str);
}
private static Boolean CheckExcludes(string Path)
{
foreach (var x in excpaths)
{
if (useregex == true)
{
try
{
Regex rgx = new Regex(x);
if (rgx.IsMatch(Path))
return false;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + x + " exception: " + e);
}
continue;
}
if (Path.ToLower().StartsWith(x.ToLower()))
return false;
}
return true;
}
private static Boolean CheckIncludes(string Path)
{
if (!includeflag) { return true; }
foreach (var i in incpaths)
{
if (useregex == true)
{
try
{
Regex rgx = new Regex(i);
if (rgx.IsMatch(Path))
return true;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + i + " exception: " + e);
}
continue;
}
if (Path.ToLower().StartsWith(i.ToLower()))
return true;
}
return false;
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec)
{
getFiles(d, searchPattern, recursiveFlag, returnList);
}
return;
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
catch (Exception e)
{
WriteErr("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e)
{
WriteErr("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList);
}
catch (Exception e)
{
WriteErr("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart) && CheckExcludes(dirPart) && CheckIncludes(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Quest Dynamic Group 004.ps1
|
Quest Dynamic Group 004.ps1
|
<#
2012.07.06
Information will be uploaded shortly.
#>
|
PowerShellCorpus/PoshCode/SqlProxy_5.psm1.ps1
|
SqlProxy_5.psm1.ps1
|
# ---------------------------------------------------------------------------
### <Author>
### Chad Miller
### </Author>
### <Description>
### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering
### SQL Server logins, users, and roles. Designed to be used with PS Remoting.
### All actions audited to a custom Eventlog.
### See Write-SqlProxyLog for log setup details
### </Description>
# ---------------------------------------------------------------------------
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9}
try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9}
try
{
try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop}
}
catch {Write-Warning "SMOExtended not available"}
$EventID = @{
"Add-SqlDatabaseRoleMember"=0
"Add-SqlLogin"=1
"Add-SqlServerRoleMember"=2
"Add-SqlUser"=3
"Remove-SqlDatabaseRoleMember"=4
"Remove-SqlLogin"=5
"Remove-SqlServerRoleMember"=6
"Remove-SqlUser"=7
"Rename-SqlLogin"=8
"Set-SqlLogin"=9
"Set-SqlLoginDefaultDatabase"=10
}
#######################
<#
.SYNOPSIS
Gets a ServerConnection.
.DESCRIPTION
The Get-SqlConnection function gets a ServerConnection to the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlConnection
.OUTPUTS
Microsoft.SqlServer.Management.Common.ServerConnection
Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlConnection
#>
function Get-SqlConnection
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password
)
Write-Verbose "Get-SqlConnection $sqlserver"
try {
if($Username -and $Password)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver }
$con.Connect()
Write-Output $con
}
catch { $message = $_.Exception.GetBaseException().Message
write-error $message
}
} #Get-ServerConnection
#######################
<#
.SYNOPSIS
Gets an SMO Server object.
.DESCRIPTION
The Get-SqlServer function gets a SMO Server object for the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlServer
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Server
Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8"
This command gets an SMO Server object for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlServer
#>
function Get-SqlServer
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password,
[Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0
)
#When $sqlserver passed in from the SMO Name property, brackets
#are automatically inserted which then need to be removed
$sqlserver = $sqlserver -replace "\\[|\\]"
Write-Verbose "Get-SqlServer $sqlserver"
$con = Get-SqlConnection $sqlserver $Username $Password
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
#Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited
$server.ConnectionContext.StatementTimeout = $StatementTimeout
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject")
#trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect()
Write-Output $server
} #Get-SqlServer
#######################
<#
.SYNOPSIS
Gets an SMO Database object.
.DESCRIPTION
The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects.
.INPUTS
None
You cannot pipe objects to Get-SqlDatabase
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Database
Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object.
.EXAMPLE
Get-SqlDatabase "Z002\\sql2K8"
This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs"
This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlDatabase
#>
function Get-SqlDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$dbname
)
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Get-SqlDatabase $($server.Name) $dbname"
if ($dbname)
{ if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible)
{$server.Databases[$dbname]}
else
{throw "Database $dname does not exist or is not accessible."}
}
else
{ $server.Databases | where {$_.IsAccessible -eq $true} }
} # Get-SqlDatabase
#######################
<#
.SYNOPSIS
Executes a query and returns an array of System.Data.DataRow.
.DESCRIPTION
The Get-SqlData function executes a query and returns an array of System.Data.DataRow.
.INPUTS
None
You cannot pipe objects to Get-SqlData
.OUTPUTS
System.Data.DataRow
Get-SqlData returns an array of System.Data.DataRow.
.EXAMPLE
Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Get-SqlData $server "pubs" "select * from authors"
This command executes the specified SQL query using SQL authentication.
.LINK
Get-SqlData
#>
function Get-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)"
$ds = $database.ExecuteWithResults("$qry")
$ds.Tables | foreach { $_.Rows}
}# Get-SqlData
#######################
<#
.SYNOPSIS
Executes a query that does not return a result set.
.DESCRIPTION
The Set-SqlData function executes a query that does not return a result set.
.INPUTS
None
You cannot pipe objects to Set-SqlData
.OUTPUTS
None
Set-SqlData does not produce any output.
.EXAMPLE
Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using SQL authentication.
.LINK
Set-SqlData
#>
function Set-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)"
$database.ExecuteNonQuery("$qry")
}# Set-SqlData
#######################
<#
.SYNOPSIS
Adds a login to a SQL Server.
.DESCRIPTION
The Add-SqlLogin function adds a new login to the specified SQL server.
.INPUTS
None
You cannot pipe objects to Add-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.LINK
Add-SqlLogin
#>
function Add-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password,
[Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser',
[Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master',
[Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled,
[Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced,
[Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=8, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlLogin $($server.Name) $name"
try {
$login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name
$login.DefaultDatabase = $defaultDatabase
$login.LoginType = $logintype
if ($logintype -eq 'SqlLogin')
{
if ($server.Information.Version.Major -ne '8')
{
$login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent)
$login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent)
}
$login.Create($password)
}
else {
$login.Create()
}
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Add-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Remove-SqlLogin function removes a login from the specified SQL server.
.INPUTS
None
You cannot pipe objects to Remove-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlLogin $server "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.LINK
Remove-SqlLogin
#>
function Remove-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=3, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlLogin $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLogin function changes a SQL Login Password.
.INPUTS
None
You cannot pipe objects to Set-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$pwd_secure_string = read-host "Enter a Password:" -assecurestring
Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string
This command sets the password for TestPSUnit login.
.LINK
Set-SqlLogin
#>
function Set-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$password,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLogin $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.ChangePassword($password,$true,$false)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLoginDefaultDatabase function changes a SQL Login default database.
.INPUTS
None
You cannot pipe objects to Set-SqlLoginDefaultDatabase
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master'
This command sets the default database for TestPSUnit login.
.LINK
Set-SqlLoginDefaultDatabase
#>
function Set-SqlLoginDefaultDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.DefaultDatabase = $DefaultDatabase
$login.Alter()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLoginDefaultDatabase
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Rename-SqlLogin function renames a SQL Login.
.INPUTS
None
You cannot pipe objects to Rename-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit"
This command renames the login TestPSUnit.
.LINK
Rename-SqlLogin
#>
function Rename-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$newname,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.Rename("$newName")
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Rename-SqlLogin
#######################
<#
.SYNOPSIS
Adds a new user to a database.
.DESCRIPTION
The Add-SqlUser function adds a new user to the specified database.
.INPUTS
None
You cannot pipe objects to Add-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlUser -dbname $database "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.LINK
Add-SqlUser
#>
function Add-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$false)] [string]$login=$name,
[Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo',
[Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=6, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlUser $($database.Name) $name"
try {
$user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name
$user.Login = $login
$loginObject = $sqlserver.Logins["$login"]
if ($database.parent.Information.Version.Major -ne '8' -and $loginObject.LoginType -ne "WindowsGroup" )
{ $user.DefaultSchema = $defaultschema }
$user.Create()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Add-SqlUser
#######################
<#
.SYNOPSIS
Removes a user from a database.
.DESCRIPTION
The Remove-SqlUser function removes a user from the specified database.
.INPUTS
None
You cannot pipe objects to Remove-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlUser -dbname $database "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.LINK
Remove-SqlUser
#>
function Remove-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlUser $($database.Name) $name"
try {
$user = $database.Users[$name]
if ($user) {
$user.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "User $name does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlUser
#######################
<#
.SYNOPSIS
Adds a login to a server role.
.DESCRIPTION
The Add-SqlServerRoleMember function adds a login to the specified server role.
.INPUTS
None
You cannot pipe objects to Add-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.LINK
Add-SqlServerRoleMember
#>
function Add-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name"
if($server.Logins["$loginame"])
{
try {
$svrole = $server.Roles["$rolename"]
if ($svrole) {
$svrole.AddMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Add-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Removes a login from a server role.
.DESCRIPTION
The Remove-SqlServerRoleMember function removes a login from the specified server role.
.INPUTS
None
You cannot pipe objects to Remove-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.LINK
Remove-SqlServerRoleMember
#>
function Remove-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name"
if($server.Logins["$loginame"])
{
try {
$svrole = $server.Roles["$rolename"]
if ($svrole) {
$svrole.DropMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Remove-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Adds a user or role to a database role.
.DESCRIPTION
The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role.
.INPUTS
None
You cannot pipe objects to Add-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Add-SqlDatabaseRoleMember
#>
function Add-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if ($database.Users["$name"])
{
try {
$role = $database.Roles["$rolename"]
if ($role) {
$role.AddMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "User $name does not exist in database $($database.Name)." }
} #Add-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Removes a user or role from a database role.
.DESCRIPTION
The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role.
.INPUTS
None
You cannot pipe objects to Remove-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Remove-SqlDatabaseRoleMember
#>
function Remove-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if ($database.Users["$name"])
{
try {
$role = $database.Roles["$rolename"]
if ($role) {
$role.DropMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "User $name does not exist in database $($database.Name)." }
} #Remove-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Writes an entry to SqlProxy Log File.
.DESCRIPTION
The Write-SqlProxyLog function writes an entry to the SqlProxy Log File.
.INPUTS
None
You cannot pipe objects to Write-SqlProxyLog
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message
This command writes a message to the SQLProxy Log
.NOTES
This must be run as administrator to create the new EventLog and EventLog Source!!!
New-EventLog -LogName SqlProxy -Source SqlProxy
.LINK
Write-SqlProxyLog
#>
function Write-SqlProxyLog
{
param(
[Parameter(Position=0, Mandatory=$true)] $EventID,
[Parameter(Position=1, Mandatory=$true)] $Message,
[Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit'
)
write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType
} #Write-SqlProxyLog
|
PowerShellCorpus/PoshCode/Join-Collections.ps1
|
Join-Collections.ps1
|
#requires -version 2.0
#.Note
# Depends on ConvertFrom-HashTable http://poshcode.org/1118
#.Synopsis
# Performs an inner join on two collections of objects based on a common key column.
#.Description
# Takes two sets of objects where there are multiple "rows" and where each set has a shared column where the values match, and generates new objects with all the values from each.
#.Parameter GroupOnColumn
# The name of the property to merge on. Items with the same value in this column will be combined.
#.Parameter FirstCollection
# The first set of data
#.Parameter FirstJoinColumn
# The name of the key id column in the first set
#.Parameter SecondCollection
# The second set of data
#.Parameter SecondJoinColumn
# The name of the matching key id column in the second set
# OPTIONAL. Defaults to the same as FirstJoinColum
#.Example
# Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value
#
# Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects.
#
#.Example
# $FirstCollection = @"
# FirstName, LastName, MailingAddress, EmployeeID
# John, Doe, 123 First Ave, J8329029
# Susan Q., Public, 3025 South Street, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# $SecondCollection = @"
# ID, Week, HrsWorked, PayRate, EmployeeID
# 12276, 12, 40, 55, J8329029
# 12277, 13, 40, 55, J8329029
# 12278, 14, 42, 55, J8329029
# 12279, 12, 35, 40, K4367143
# 12280, 13, 32, 40, K4367143
# 12281, 14, 48, 40, K4367143
#"@.Split("`n") | ConvertFrom-Csv
#
# Join-Collections $FirstCollection EmployeeID $SecondCollection | ft
#
#.Notes
# Author: Joel Bennett
# function Join-Collections {
PARAM(
$FirstCollection
, [string]$FirstJoinColumn
, $SecondCollection
, [string]$SecondJoinColumn=$FirstJoinColumn
)
PROCESS {
$properties = $FirstCollection[0] | gm -type Properties
$properties += $SecondCollection[0] | gm -type Properties |
Where { $_.Name -ne $SecondJoinColumn } | ForEach { if($Properties -contains $_) { "__$_" } else { $_ } }
foreach($first in $FirstCollection) {
foreach($second in $SecondCollection | Where{ $_."$SecondJoinColumn" -eq $first."$FirstJoinColumn" } ) {
[string]$join = $first | gm -type Properties | select -expand Definition | %{($_ -split " ",2)[1]}
$join += $second | gm -type Properties | select -expand Definition | %{($_ -split " ",2)[1]}
ConvertFrom-StringData $join | ConvertFrom-Hashtable
}
}
}
#}
|
PowerShellCorpus/PoshCode/Easy Migration Tool v_1.1.ps1
|
Easy Migration Tool v_1.1.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: Richard Yaw
# Generated On: 09/12/2010
#
# Easy Migration Script for VMware (Version 2.1)
# - Added a "Reload Tasks" feature.
# - Fixed issue with the Undo feature for SVMotions.
# - Added snapshot check before doing SVMotions.
# - Added ability to VMotion VMs between clusters.
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$MigrationForm = New-Object System.Windows.Forms.Form
$Header = new-object System.Windows.Forms.Label
$MigrateButton = New-Object System.Windows.Forms.Button
$ClusterListBox = New-Object System.Windows.Forms.ListBox
$SourceHostListBox = New-Object System.Windows.Forms.ListBox
$SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox
$SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox
$DestinationListBox = New-Object System.Windows.Forms.ListBox
$vCenterLabel = New-Object System.Windows.Forms.Label
$VCTextBox = New-Object System.Windows.Forms.TextBox
$LoginButton = New-Object System.Windows.Forms.Button
$ClearMsgButton = New-Object System.Windows.Forms.Button
$UndoButton = New-Object System.Windows.Forms.Button
$UndoALLButton = New-Object System.Windows.Forms.Button
$ReloadTaskButton = New-Object System.Windows.Forms.Button
$SaveTaskButton = New-Object System.Windows.Forms.Button
$ClusterLabel = New-Object System.Windows.Forms.Label
$HostToHostButton = New-Object System.Windows.Forms.Button
$VMToHostButton = New-Object System.Windows.Forms.Button
$DBtoDBButton = New-Object System.Windows.Forms.Button
$VMtoDBButton = New-Object System.Windows.Forms.Button
$AllClustersCheckbox = New-Object System.Windows.Forms.CheckBox
$SourceButton = New-Object System.Windows.Forms.Button
$DestinationButton = New-Object System.Windows.Forms.Button
$ResetButton = New-Object System.Windows.Forms.Button
$ChangeVCButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$MessagesLabel = New-Object System.Windows.Forms.Label
$MessagesListBox = New-Object System.Windows.Forms.ListBox
$TaskLabel = New-Object System.Windows.Forms.Label
$TaskListBox = New-Object System.Windows.Forms.ListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$LoginButton_Click=
{
#TODO: Place custom script here
If ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $VCTextBox.Text -ErrorAction SilentlyContinue
If (!$?)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show($($error[0]))
}
Else
{
$ClusterListBox.Enabled = $true
#Get Cluster
Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) }
If ($ClusterListBox.items -ne $null)
{
$LoginButton.Enabled = $false
$VCTextBox.Enabled = $false
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$ResetButton.Enabled = $true
$ChangeVCButton.Enabled = $true
$ReloadTaskButton.Enabled = $true
#Generate a log file for this session
#$logfile = "C:\\TEMP\\EasyMigrate{0:dd-MM-yyyy_HHmmss}" -f (Get-Date) + ".log"
#$logheader = "Easy Migration Tool v2.1 - Log generated on " + (Get-Date)
#Out-File -InputObject $logheader -FilePath $logfile
#Out-File -InputObject "" -Append -FilePath $logfile
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$HostToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$SourceHostListBox.Enabled = $true
$SourceHostListBox.Items.Clear()
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select One Host'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$HostToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$VMToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$DBtoDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceDBListBox)
$SourceDBListBox.Enabled = $true
$SourceDBListBox.Items.Clear()
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select a Datastore'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$SourceButton_OnClick=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
If ($SourceHostname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Source Host.')
}
Else
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceHostListBox.Enabled = $false
$SourceButton.Enabled = $false
$AllClustersCheckbox.Enabled = $true
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$SourceVMname = $SourceVMListBox.SelectedItem
If ($SourceVMname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.')
}
Else
{
if ($DestinationButton.Text -like "Destination Host")
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) }
}
$DestinationListBox.Enabled = $true
$SourceVMListBox.Enabled = $false
$SourceButton.Enabled = $false
$AllClustersCheckbox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -like "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
If ($SourceDBname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One Datastore.')
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceDBListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
}
$AllClustersCheckbox_Click=
{
#TODO: Place custom script here
$DestinationListBox.Items.Clear()
#List the hosts in all the clusters
Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
$AllClustersCheckbox.Enabled = $False
}
$DestinationButton_OnClick=
{
#TODO: Place custom script here
$DestinationName = $DestinationListBox.SelectedItem
If ($DestinationName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Destination.')
}
Else
{
$AllClustersCheckbox.Enabled = $False
$DestinationListBox.Enabled = $False
$DestinationButton.Enabled = $False
$MigrateButton.Enabled = $True
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$MigrateButton_OnClick=
{
#TODO: Place custom script here
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-VMHost $SourceHostname | Get-VM
foreach($VM in $VMs)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$DestinationName = $DestinationListBox.SelectedItem
If($DestinationButton.Text -eq "Destination Host")
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceName to $DestinationName."
[void]$TaskListBox.items.add($line)
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
Else
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-Datastore -Name $SourceDBname | Get-VM
If($VMs.count -gt 0)
{
foreach($VM in $VMs)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBFreeSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
}
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - No VM is present on the source datastore $SourceDBname."
[void]$MessagesListBox.items.add($MsgLine)
}
$SourceDBListBox.enabled = $true
$SourceButton.enabled = $true
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$MigrateButton.Enabled = $false
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
$RESETButton_OnClick=
{
#TODO: Place custom script here
$ClusterListBox.Enabled = $true
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
}
$ChangeVCButton_OnClick=
{
#TODO: Place custom script here
$VCTextBox.Text = ""
$VCTextBox.Enabled = $true
$LoginButton.Enabled = $true
$ClusterListBox.Items.Clear()
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$ResetButton.Enabled = $false
$ChangeVCButton.Enabled = $false
$MessagesListBox.Items.Clear()
$TaskListBox.Items.Clear()
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
If ($VCTextBox.Text -ne "")
{
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
#Close Form
$MigrationForm.close()
}
$ClearMsgButton_Click=
{
#TODO: Place custom script here
If($MessagesListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('No messages to clear.')
}
Else
{
$MessagesListBox.items.clear()
}
}
$UndoButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
If ($TaskListBox.SelectedItems.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please select one or more tasks.')
}
Else
{
foreach($Task in $TaskListBox.SelectedItems)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
While($TaskListBox.SelectedItems.Count -gt 0)
{
$TaskListBox.Items.Remove($TaskListBox.SelectedItems[0])
}
}
}
}
$UndoALLButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
foreach($Task in $TaskListBox.Items)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$TaskListBox.Items.Clear()
}
}
$SaveTaskButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Nothing to save to log file.')
}
Else
{
$SaveFileD = new-object System.Windows.Forms.SaveFileDialog
$SaveFileD.Filter = "Log Files (*.log)|*.log";
$SaveFileD.Title = "Save to a log file";
$SaveFileD.FilterIndex = 2;
$SaveFileD.RestoreDirectory = $true;
if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $SaveFileD.FileName
$Tasks = $TaskListBox.items
$logheader = "Easy Migration Tool v2.1 - Log generated on " + (Get-Date)
#Save a log file for this session to a location selected by the user
Out-File -InputObject $logheader -FilePath $Filename
Out-File -InputObject "" -Append -FilePath $FileName
Out-File -InputObject $Tasks -Append -FilePath $FileName
}
}
}
$ReloadTaskButton_Click=
{
#TODO: Place custom script here
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
#$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Log Files (*.log)|*.log"
if ($OpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $OpenFileDialog.FileName
$LinesCount = (Get-Content $FileName).Count
$LogLines = Get-Content $FileName | Select -Last ($LinesCount - 2)
$TaskListBox.Items.Clear()
foreach ($LogLine in $LogLines)
{
[void]$TaskListBox.items.add($LogLine)
}
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
#----------------------------------------------
#region Generated Form Code
# Start Main Form
$MigrationForm.Text = 'Easy Migration Tool v2.1'
$MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MigrationForm.Name = 'EasyMigrationForm'
$MigrationForm.StartPosition = "CenterScreen"
$MigrationForm.FormBorderStyle = "FixedDialog"
$MigrationForm.MaximizeBox = $false
$MigrationForm.MinimizeBox = $false
$MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1030
$System_Drawing_Size.Height = 500
$MigrationForm.ClientSize = $System_Drawing_Size
# End Main Form
#Start Easy_Migration Header
$Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold)
$Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$Header.Text = 'Easy Migration Tool v2.1'
$Header.Location = new-object System.Drawing.Point(150,15)
$Header.Size = new-object System.Drawing.Size(230, 20)
$MigrationForm.Controls.Add($Header)
#End Easy_Migration Header
# Start vCenter Server Label
$vCenterLabel.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$vCenterLabel.Size = $System_Drawing_Size
$vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$vCenterLabel.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 15
$System_Drawing_Point.Y = 50
$vCenterLabel.Location = $System_Drawing_Point
$vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$vCenterLabel.Name = 'vCenterLabel'
$MigrationForm.Controls.Add($vCenterLabel)
# End vCenter Server Label
# Start vCenter Textbox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 20
$VCTextBox.Size = $System_Drawing_Size
$VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8)
$VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$VCTextBox.Name = 'VCTextBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 50
$VCTextBox.Location = $System_Drawing_Point
$VCTextBox.TabIndex = 1
$MigrationForm.Controls.Add($VCTextBox)
# End vCenter Textbox
# Start Login Button
$LoginButton.TabIndex = 0
$LoginButton.Name = 'LoginButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$LoginButton.Size = $System_Drawing_Size
$LoginButton.Font = new-object System.Drawing.Font("Tahoma",8)
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.Text = 'Login'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 48
$LoginButton.Location = $System_Drawing_Point
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$LoginButton.add_Click($LoginButton_Click)
$MigrationForm.Controls.Add($LoginButton)
# End Login Button
# Start Change VC Button
$ChangeVCButton.TabIndex = 19
$ChangeVCButton.Name = 'ChangeVCButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$ChangeVCButton.Size = $System_Drawing_Size
$ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ChangeVCButton.UseVisualStyleBackColor = $True
$ChangeVCButton.Text = 'Change vCenter'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 355
$System_Drawing_Point.Y = 48
$ChangeVCButton.Location = $System_Drawing_Point
$ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ChangeVCButton.add_Click($ChangeVCButton_OnClick)
$ChangeVCButton.Enabled = $false
$MigrationForm.Controls.Add($ChangeVCButton)
# End Change VC Button
# Start Cluster Listbox
$ClusterLabel.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 85
$System_Drawing_Size.Height = 20
$ClusterLabel.Size = $System_Drawing_Size
$ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$ClusterLabel.Text = 'Select Cluster:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 90
$ClusterLabel.Location = $System_Drawing_Point
$ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterLabel.Name = 'ClusterLabel'
$MigrationForm.Controls.Add($ClusterLabel)
$ClusterListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 100
$ClusterListBox.Size = $System_Drawing_Size
$ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterListBox.Name = 'ClusterListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 90
$ClusterListBox.Location = $System_Drawing_Point
$ClusterListBox.MultiColumn = $false
$ClusterListBox.TabIndex = 5
$ClusterListBox.Sorted = $True
$MigrationForm.Controls.Add($ClusterListBox)
# End Cluster Listbox
# Start Host to Host Button
$HostToHostButton.TabIndex = 3
$HostToHostButton.Name = 'HostToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$HostToHostButton.Size = $System_Drawing_Size
$HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$HostToHostButton.UseVisualStyleBackColor = $True
$HostToHostButton.Text = 'Host to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 90
$HostToHostButton.Location = $System_Drawing_Point
$HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$HostToHostButton.add_Click($HostToHostButton_Click)
$HostToHostButton.Enabled = $False
$MigrationForm.Controls.Add($HostToHostButton)
# End Host to Host Button
# Start All Clusters Checkbox
$AllClustersCheckbox.TabIndex = 4
$AllClustersCheckbox.Name = 'AllClustersCheckbox'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 150
$System_Drawing_Size.Height = 20
$AllClustersCheckbox.Size = $System_Drawing_Size
$AllClustersCheckbox.Font = new-object System.Drawing.Font("Tahoma",8)
$AllClustersCheckbox.UseVisualStyleBackColor = $True
$AllClustersCheckbox.Text = 'Show Hosts in All Clusters'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 190
$AllClustersCheckbox.Location = $System_Drawing_Point
$AllClustersCheckbox.DataBindings.DefaultDataSourceUpdateMode = 0
$AllClustersCheckbox.add_Click($AllClustersCheckbox_Click)
$AllClustersCheckbox.Enabled = $False
$MigrationForm.Controls.Add($AllClustersCheckbox)
# End All Clusters Checkbox
# Start VM to Host Button
$VMToHostButton.TabIndex = 3
$VMToHostButton.Name = 'VMToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMToHostButton.Size = $System_Drawing_Size
$VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMToHostButton.UseVisualStyleBackColor = $True
$VMToHostButton.Text = 'VM to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 115
$VMToHostButton.Location = $System_Drawing_Point
$VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMToHostButton.add_Click($VMToHostButton_Click)
$VMToHostButton.Enabled = $false
$MigrationForm.Controls.Add($VMToHostButton)
# End VM to Host Button
# Start Datastore to Datastore Button
$DBtoDBButton.TabIndex = 3
$DBtoDBButton.Name = 'DBtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$DBtoDBButton.Size = $System_Drawing_Size
$DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DBtoDBButton.UseVisualStyleBackColor = $True
$DBtoDBButton.Text = 'Datastore to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 140
$DBtoDBButton.Location = $System_Drawing_Point
$DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DBtoDBButton.add_Click($DBtoDBButton_Click)
$DBtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($DBtoDBButton)
# End Datastore to Datastore Button
# Start VM to Datastore Button
$VMtoDBButton.TabIndex = 3
$VMtoDBButton.Name = 'VMtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMtoDBButton.Size = $System_Drawing_Size
$VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMtoDBButton.UseVisualStyleBackColor = $True
$VMtoDBButton.Text = 'VM to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 165
$VMtoDBButton.Location = $System_Drawing_Point
$VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMtoDBButton.add_Click($VMtoDBButton_Click)
$VMtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($VMtoDBButton)
# End VM to Datastore Button
# Start Source Host List Box
$SourceHostListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceHostListBox.Size = $System_Drawing_Size
$SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceHostListBox.Name = 'SourceHostListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceHostListBox.Location = $System_Drawing_Point
$SourceHostListBox.MultiColumn = $false
$SourceHostListBox.TabIndex = 5
$SourceHostListBox.Sorted = $True
$MigrationForm.Controls.Add($SourceHostListBox)
# End Source Host List Box
# Start Source Datastore List Box
$SourceDBListBox.FormattingEnabled = $True
$SourceDBListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceDBListBox.Size = $System_Drawing_Size
$SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceDBListBox.Name = 'SourceDBListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceDBListBox.Location = $System_Drawing_Point
$SourceDBListBox.MultiColumn = $false
$SourceDBListBox.HorizontalScrollBar = $true
$SourceDBListBox.TabIndex = 5
$SourceDBListBox.Sorted = $True
# End Source Datastore List Box
# Start Source VM List Box
$SourceVMListBox.FormattingEnabled = $True
$SourceVMListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceVMListBox.Size = $System_Drawing_Size
$SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceVMListBox.Name = 'SourceVMListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceVMListBox.Location = $System_Drawing_Point
$SourceVMListBox.MultiColumn = $false
$SourceVMListBox.TabIndex = 5
$SourceVMListBox.Sorted = $True
# End Source VM List Box
# Start Source Button
$SourceButton.TabIndex = 7
$SourceButton.Name = 'Source Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$SourceButton.Size = $System_Drawing_Size
$SourceButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceButton.UseVisualStyleBackColor = $True
$SourceButton.Text = 'Source'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 415
$SourceButton.Location = $System_Drawing_Point
$SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceButton.add_Click($SourceButton_OnClick)
$SourceButton.Enabled = $false
$MigrationForm.Controls.Add($SourceButton)
# End Source Button
# Start Destination List Box
$DestinationListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$DestinationListBox.Size = $System_Drawing_Size
$DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationListBox.Name = 'DestinationListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 210
$DestinationListBox.Location = $System_Drawing_Point
$DestinationListBox.HorizontalScrollBar = $true
$DestinationListBox.MultiColumn = $false
$DestinationListBox.TabIndex = 5
$DestinationListBox.Sorted = $True
$MigrationForm.Controls.Add($DestinationListBox)
# End Destination List Box
# Start Destination Button
$DestinationButton.TabIndex = 7
$DestinationButton.Name = 'Destination Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$DestinationButton.Size = $System_Drawing_Size
$DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationButton.UseVisualStyleBackColor = $True
$DestinationButton.Text = 'Destination'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 415
$DestinationButton.Location = $System_Drawing_Point
$DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationButton.add_Click($DestinationButton_OnClick)
$DestinationButton.Enabled = $false
$MigrationForm.Controls.Add($DestinationButton)
# End Destination Button
# Start Migrate Button
$MigrateButton.TabIndex = 7
$MigrateButton.Name = 'MigrateButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$MigrateButton.Size = $System_Drawing_Size
$MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8)
$MigrateButton.UseVisualStyleBackColor = $True
$MigrateButton.Text = 'Migrate'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 450
$MigrateButton.Location = $System_Drawing_Point
$MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0
$MigrateButton.add_Click($MigrateButton_OnClick)
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Add($MigrateButton)
# End Migrate Button
# Start RESET Button
$ResetButton.TabIndex = 19
$ResetButton.Name = 'ResetButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 140
$System_Drawing_Size.Height = 25
$ResetButton.Size = $System_Drawing_Size
$ResetButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ResetButton.UseVisualStyleBackColor = $True
$ResetButton.Text = 'Reset'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 450
$ResetButton.Location = $System_Drawing_Point
$ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ResetButton.add_Click($ResetButton_OnClick)
$ResetButton.Enabled = $false
$MigrationForm.Controls.Add($ResetButton)
# End RESET Button
# Start CLOSE Button
$CloseButton.TabIndex = 19
$CloseButton.Name = 'CloseButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$CloseButton.Size = $System_Drawing_Size
$CloseButton.Font = new-object System.Drawing.Font("Tahoma",8)
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.Text = 'Close'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 320
$System_Drawing_Point.Y = 450
$CloseButton.Location = $System_Drawing_Point
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$CloseButton.add_Click($CloseButton_OnClick)
$MigrationForm.Controls.Add($CloseButton)
# End CLOSE Button
# Start Messages ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$MessagesLabel.Size = $System_Drawing_Size
$MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MessagesLabel.Text = 'Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 50
$MessagesLabel.Location = $System_Drawing_Point
$MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesLabel.Name = 'MessagesLabel'
$MigrationForm.Controls.Add($MessagesLabel)
$MessagesListBox.FormattingEnabled = $True
$MessagesListBox.SelectionMode = "None"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 140
$MessagesListBox.Size = $System_Drawing_Size
$MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesListBox.Name = 'MessagesListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 70
$MessagesListBox.Location = $System_Drawing_Point
$MessagesListBox.MultiColumn = $false
$MessagesListBox.HorizontalScrollbar = $true
$MigrationForm.Controls.Add($MessagesListBox)
# End Messages ListBox
# Start Task ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$TaskLabel.Size = $System_Drawing_Size
$TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$TaskLabel.Text = 'Recent Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 215
$TaskLabel.Location = $System_Drawing_Point
$TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskLabel.Name = 'TaskLabel'
$MigrationForm.Controls.Add($TaskLabel)
$TaskListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 200
$TaskListBox.Size = $System_Drawing_Size
$TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskListBox.Name = 'TaskListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 235
$TaskListBox.Location = $System_Drawing_Point
$TaskListBox.MultiColumn = $false
$TaskListBox.HorizontalScrollbar = $true
$TaskListBox.SelectionMode = "MultiExtended"
$MigrationForm.Controls.Add($TaskListBox)
# End Task ListBox
# Start Clear Messages Button
$ClearMsgButton.TabIndex = 0
$ClearMsgButton.Name = 'ClearMsgButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ClearMsgButton.Size = $System_Drawing_Size
$ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ClearMsgButton.UseVisualStyleBackColor = $True
$ClearMsgButton.Enabled = $false
$ClearMsgButton.Text = 'Clear Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 450
$ClearMsgButton.Location = $System_Drawing_Point
$ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ClearMsgButton.add_Click($ClearMsgButton_Click)
$MigrationForm.Controls.Add($ClearMsgButton)
# End Clear Messages Button
# Start Undo Button
$UndoButton.TabIndex = 0
$UndoButton.Name = 'UndoButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoButton.Size = $System_Drawing_Size
$UndoButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoButton.UseVisualStyleBackColor = $True
$UndoButton.Enabled = $false
$UndoButton.Text = 'Undo'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 588
$System_Drawing_Point.Y = 450
$UndoButton.Location = $System_Drawing_Point
$UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoButton.add_Click($UndoButton_Click)
$MigrationForm.Controls.Add($UndoButton)
# End Undo Button
# Start UndoALL Button
$UndoALLButton.TabIndex = 0
$UndoALLButton.Name = 'UndoALLButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoALLButton.Size = $System_Drawing_Size
$UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoALLButton.UseVisualStyleBackColor = $True
$UndoALLButton.Enabled = $false
$UndoALLButton.Text = 'Undo ALL'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 696
$System_Drawing_Point.Y = 450
$UndoALLButton.Location = $System_Drawing_Point
$UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoALLButton.add_Click($UndoALLButton_Click)
$MigrationForm.Controls.Add($UndoALLButton)
# End UndoALL Button
# Start Save Task Button
$SaveTaskButton.TabIndex = 0
$SaveTaskButton.Name = 'SaveTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$SaveTaskButton.Size = $System_Drawing_Size
$SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SaveTaskButton.UseVisualStyleBackColor = $True
$SaveTaskButton.Enabled = $false
$SaveTaskButton.Text = 'Save Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 804
$System_Drawing_Point.Y = 450
$SaveTaskButton.Location = $System_Drawing_Point
$SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SaveTaskButton.add_Click($SaveTaskButton_Click)
$MigrationForm.Controls.Add($SaveTaskButton)
# End Save Task Button
# Start Load Task Button
$ReloadTaskButton.TabIndex = 0
$ReloadTaskButton.Name = 'ReloadTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ReloadTaskButton.Size = $System_Drawing_Size
$ReloadTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ReloadTaskButton.UseVisualStyleBackColor = $True
$ReloadTaskButton.Enabled = $false
$ReloadTaskButton.Text = 'Reload Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 912
$System_Drawing_Point.Y = 450
$ReloadTaskButton.Location = $System_Drawing_Point
$ReloadTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ReloadTaskButton.add_Click($ReloadTaskButton_Click)
$MigrationForm.Controls.Add($ReloadTaskButton)
# End Load Task Button
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $MigrationForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$MigrationForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$MigrationForm.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/ConvertTo-Hex.ps1
|
ConvertTo-Hex.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/Function Run-Script_3.ps1
|
Function Run-Script_3.ps1
|
#################################################################################
# This function should be included in the PowerShell ISE profile.ps1 and it will
# display the start and end times of any scripts started by clicking 'Run Script'
# in the Add-ons Menu, or F2; additionally they will be logged to the Scripts
# Event Log (which needs creating first) and also to a text log file. This
# defaults to that created by the Windows Script Monitor Service (available from
# www.SeaStarDevelopment.Bravehost.com) which normally indicates the full command
# line used to start each script.
# V2.0 Use Try/Catch to trap (child) script errors & change Hotkey to F2.
# v3.0 Arguments entered on the command line will now be passed to the script.
#################################################################################
function Run-Script {
$script = $psISE.CurrentFile.DisplayName
if ($script.StartsWith("Untitled") -or $script.Contains("profile.") -or `
($host.Name -ne 'Windows PowerShell ISE Host' )) {
return
}
$psISE.CurrentFile.Save()
$logfile = "$env:programfiles\\Sea Star Development\\" +
"Script Monitor Service\\ScriptMon.txt" #Change to suit.
if (!(Test-Path env:\\JobCount)) {
$env:JobCount = 1 #This will work across multi Tab sessions.
}
$number = $env:JobCount.PadLeft(4,'0')
$startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$startTime [$script] start. --> PSE $($myInvocation.Line)"
if (Test-Path $logfile) {
$tag | Out-File $logfile -encoding 'Default' -Append
}
"$startTime [$script] started."
Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PSE$number) started."
#Now grab any parameters entered from the command line...
$parms = $psISE.CurrentPowerShellTab.CommandPane.Text
try {
Invoke-Expression "$pwd\\$script $parms"
}
catch {
Write-Host -ForegroundColor Red ">>> ERROR: $_"
}
$endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$endTime [$script] ended. --> PSE $($myInvocation.Line)"
if (Test-Path $logfile) {
$tag | Out-File $logfile -encoding 'Default' -Append
}
"$endTime [$script] ended."
Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PSE$number) ended."
$env:JobCount = [int]$env:JobCount+1
}
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Run Script",{Run-Script}, "F2") | Out-Null
|
PowerShellCorpus/PoshCode/Hack ESXi_4.ps1
|
Hack ESXi_4.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/Assert.ps1
|
Assert.ps1
|
function Assert {
#.Example
# set-content C:\\test2\\Documents\\test2 "hi"
# C:\\PS>assert { get-item C:\\test2\\Documents\\test2 } "File wasn't created by Set-Content!"
#
[CmdletBinding()]
param(
[Parameter(Position=0,ParameterSetName="Script",Mandatory=$true)]
[ScriptBlock]$condition
,
[Parameter(Position=0,ParameterSetName="Bool",Mandatory=$true)]
[bool]$success
,
[Parameter(Position=1,Mandatory=$true)]
[string]$message
)
$message = "ASSERT FAILED: $message"
if($PSCmdlet.ParameterSetName -eq "Script") {
try {
$ErrorActionPreference = "STOP"
$success = &$condition
} catch {
$success = $false
$message = "$message`nEXCEPTION THROWN: $($_.Exception.GetType().FullName)"
}
}
if(!$success) {
throw $message
}
}
|
PowerShellCorpus/PoshCode/VMWare VMNET Adapters.ps1
|
VMWare VMNET Adapters.ps1
|
# see http://msdn2.microsoft.com/en-us/library/bb201634.aspx
#
# *NdisDeviceType
#
# The type of the device. The default value is zero, which indicates a standard
# networking device that connects to a network.
#
# Set *NdisDeviceType to NDIS_DEVICE_TYPE_ENDPOINT (1) if this device is an
# endpoint device and is not a true network interface that connects to a network.
# For example, you must specify NDIS_DEVICE_TYPE_ENDPOINT for devices such as
# smart phones that use a networking infrastructure to communicate to the local
# computer system but do not provide connectivity to an external network.
#
# Usage: run in an elevated shell (vista/longhorn) or as adminstrator (xp/2003).
#
# PS> .\\fix-vmnet-adapters.ps1
# boilerplate elevation check
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object Security.Principal.WindowsPrincipal $identity
$elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $elevated) {
$error = "Sorry, you need to run this script"
if ([System.Environment]::OSVersion.Version.Major -gt 5) {
$error += " in an elevated shell."
} else {
$error += " as Administrator."
}
throw $error
}
function confirm {
$host.ui.PromptForChoice("Continue", "Process adapter?",
[Management.Automation.Host.ChoiceDescription[]]@("&No", "&Yes"), 0) -eq $true
}
# adapters key
pushd 'hklm:\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}'
# ignore and continue on error
dir -ea 0 | % {
$node = $_.pspath
$desc = gp $node -name driverdesc
if ($desc -like "*vmware*") {
write-host ("Found adapter: {0} " -f $desc.driverdesc)
if (confirm) {
new-itemproperty $node -name '*NdisDeviceType' -propertytype dword -value 1
}
}
}
popd
# disable/enable network adapters
gwmi win32_networkadapter | ? {$_.name -like "*vmware*" } | % {
# disable
write-host -nonew "Disabling $($_.name) ... "
$result = $_.Disable()
if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." }
# enable
write-host -nonew "Enabling $($_.name) ... "
$result = $_.Enable()
if ($result.ReturnValue -eq -0) { write-host " success." } else { write-host " failed." }
}
|
PowerShellCorpus/PoshCode/Paint board.ps1
|
Paint board.ps1
|
function frmMain_Show {
Add-Type -AssemblyName PresentationFramework
$win = New-Object Windows.Window
$ink = New-Object Windows.Controls.InkCanvas
#
#ink
#
$ink.MinWidth = $ink.MinHeight = 450
#
#win
#
$win.Content = $ink
$win.SizeToContent = "WidthAndHeight"
$win.Title = "Paint board"
$win.WindowStartupLocation = "CenterScreen"
[void]$win.ShowDialog()
}
frmMain_Show
|
PowerShellCorpus/PoshCode/Find Local Group Members_6.ps1
|
Find Local Group Members_6.ps1
|
# Author: Hal Rottenberg
# Purpose: Find matching members in a local group
# Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx
# Change these two to suit your needs
$ChildGroups = "Domain Admins", "Group Two"
$LocalGroup = "Administrators"
$MemberNames = @()
# uncomment this line to grab list of computers from a file
# $Servers = Get-Content serverlist.txt
$Servers = $env:computername # for testing on local computer
foreach ( $Server in $Servers ) {
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
$Members = @($Group.psbase.Invoke("Members"))
$Members | ForEach-Object {
$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$ChildGroups | ForEach-Object {
$output = "" | Select-Object Server, Group, InLocalAdmin
$output.Server = $Server
$output.Group = $_
$output.InLocalAdmin = $MemberNames -contains $_
Write-Output $output
}
}
|
PowerShellCorpus/PoshCode/Change-ServicePassword_1.ps1
|
Change-ServicePassword_1.ps1
|
Param([string]$server,[string]$service,[string]$user,[string]$password)
Begin{
function ChangeServicePassword{
Param([string]$srv,[string]$ms,[string]$usr,[string]$pwd)
# Setup for WMI
$class = "Win32_Service"
$method = "change"
$computer = $srv
$filter = "Name=`'$ms`'"
# Getting Service Via WMI
$MyService = get-WmiObject $class -computer $computer -filter $filter
# Setting Parameters for Change Method
$inparams = $MyService.psbase.GetMethodParameters($method)
$inparams["StartName"] = $usr
$inparams["StartPassword"] = $pwd
# Calling Change Method and Return $results
$result = $MyService.psbase.InvokeMethod($method,$inparams,$null)
if($result.ReturnValue -eq 0)
{
return $true
}
else
{
return $false
}
}
Write-Host
$process = @()
}
Process{
if($_){
if($_.ServerName)
{
$process += $_.ServerName
}
else
{
$process += $_
}
}
}
End{
if($Server){$Process += $Server}
if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME}
foreach($s in $process)
{
if(ChangeServicePass -Srv $s -ms $service -usr $user -pwd $password)
{
Write-host "Service [$Service] changed on Server [$s] now using [$user]"
}
else
{
Write-Host "Service Change Failed on Server[$s]"
}
Write-Host
}
}
|
PowerShellCorpus/PoshCode/Monitor-FileSize_3.ps1
|
Monitor-FileSize_3.ps1
|
function Monitor-FileSize
{
<#
.Synopsis
Checks the file size of a given file until it reaches the specified size
.Description
Checks the file size of a given file until it reaches the specified size. AT that point, it alerts the user as to what the original file-size-boundry was and what it currently is. The interval at which the script runs can be specified by the user.
.Parameter FilePath
Path of the file that will be monitored. If not pointed to a specific file, the script will montior all sub-directories as well. ie. if pointed to C:\\ drive, will monitor ALL files on C:\\ drive
.Parameter Size
File size is monitored against this value. When file size is equal or greater than this value, user alert is triggered. Enter size constraints as integer values (ex: -Size 100 NOT -Size 100kb)
.Parameter Interval
The wait interval between the executions of the function. The value of this parameter is in seconds and default value is 5 seconds
.Example
Monitor-FileSize -FilePath C:\\Test -Size 100
Returns a message to the user alerting them when at least 100kb worth of memory is stored in the selected location.
.Example
Monitor-FileSize -FilePath C:\\Test -Size 100 -Interval 20
Checking the size of the file and all sub-directories every 20 seconds
.Notes
This script cannot be run as a background job and so must have a separate PowerShell window on which it can be running.
Author: Paul Kiri.
#>
param
(
[Parameter(mandatory=$true,position=0)]
[string[]]$FilePath
,
[Parameter(mandatory=$true,position=1)]
[int]$Size
,
[Parameter(mandatory=$false)]
[int]$Interval=5
)
if((Test-Path $FilePath))
{
While($FS -le $Size)
{
Start-Sleep -Seconds $Interval
$FileSize = get-childitem $FilePath -Recurse -Include *.* | foreach-object -Process { $_.length / 1024 } | Measure-Object -Sum | Select-Object -Property Sum
$FS = $FileSize.Sum
}
}
if (Test-Path $FilePath)
{
Write-Output "The files at location, $FilePath , have exceeded $Size kb and are now $('{0:N4}' -f $FileSize.Sum) kb in size."
}
else{"The path '$FilePath' could not be reached or does not exist. Please check the path name."}
}
|
PowerShellCorpus/PoshCode/TabExpansion_1.ps1
|
TabExpansion_1.ps1
|
## Tab-Completion
#################
## 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>
## $foo[0].<tab>
## $foo[0].n.b<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 expansion
## [Dec<tab>
## [Microsoft.PowerShell.Com<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.Management.Auto<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 -Err <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 -Error 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>
## $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>
### Generate ProgIDs list...
if ($_ProgID -eq $null) {
$_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
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\ProgIDs.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Import-Clixml -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;'
}
### Generate TypeNames list...
if ( $_TypeNames -eq $null ) {
[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
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\TypeNames.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Import-Clixml -Path $PSHOME\\TypeNames.txt;'
}
if ( $_TypeNames_System -eq $null ) {
[Object[]] $_TypeNames_System = $null
foreach ( $_type in $_TypeNames -like "System.*" )
{
$_TypeNames_System += $_type.Substring(7)
}
'$_TypeNames_System was updated...' | Out-Host
Export-Clixml -InputObject $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Import-Clixml -Path $PSHOME\\TypeNames_System.txt;'
}
### Generate WMIClasses list...
if ( $_WMIClasses -eq $null ) {
[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
}
$global:_snapin = $null
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)
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
) | sort MemberType,Name -Unique
foreach ($_m in $members)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
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...
# e.g. foo[0].a<tab>
'(^.*)(\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
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[$matches.Count-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] + '*'
foreach ( $_exp in $_TypeNames_System -like $_opt )
{
'[' + $_exp
}
foreach ( $_exp in $_TypeNames -like $_opt )
{
'[' + $_exp
}
break;
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_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' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
# expand the parameter sets and emit the matching elements
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
# try to find a matching command...
default {
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ( $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
}
foreach ( $def in iex ($_method + ".OverloadDefinitions") )
{
[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 -match "System.\\w+$" -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',("[$name]::" + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$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 )
{
$_TypeNames_System
$_TypeNames
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 ( $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 '\\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 )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
$_WMIClasses -like $_opt
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 ( $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' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
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 )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
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 )
{
$_WMIClasses -like $_opt
break;
}
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord
$pattern = $command + "*"
gcm -Name $pattern -CommandType All | % { $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Make a phone call.ps1
|
Make a phone call.ps1
|
<#
.NOTES
AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com)
WEBSITE: http://tekout.wordpress.com
VERSION: 0.1
CREATED: 17th April, 2012
LASTEDIT: 17th April, 2012
Requires: PowerShell v2 or better
.CHANGELOG
4/17/2012 Try passing powershell objects to PROTO API and pass the variables to .JS file
Pass other system variables and check if text to speech can translate double or a double-to-char conversion is required.
.SYNOPSIS
Make a phone call from Powershell.
.DESCRIPTION
The script demonstrates how you can collect state-data in powershell and pass it as an argument to a REST API call and alert a System Admin.
For this example, TROPO REST API's were used. (www.tropo.com)
The phone-number will receive a Call with the following text To speech
Please check the server $this.
The percent Free Space on C Drive is $inDecimals.
This is a proof of concept. V 0.1
There are numerous areas of improvement.
.IMPORTANT
Please create a new account and setup your application in tropo. Its free for dev use. http://www.tropo.com
Copy and replace the TOKEN in your application with the TOKEN below to initiate a call.
.OTHER
JAVASCRIPT (Hosted on Tropo)
TropoTest.js
call('+' + numToCall , {
timeout:30,
callerID:'19172688401',
onAnswer: function() {
say("Houston ! We have a problem ");
say("Please check the server" + sourceServer );
say("The percent Free Space on C Drive is" + freeCDisk );
say("Goodbye.");
log("Call logged Successfully");
},
onTimeout: function() {
log("Call timed out");
},
onCallFailure: function() {
log("Call could not be completed as dialed");
}
});
#>
# Proto API section. Please replace protoToken with your own Application Token,
# I am posting my API token here so that someone can download and run the script by editing just the cell # field.
$baseUrl = "https://api.tropo.com/1.0/sessions?action=create&"
# Modify these variables.
$protoToken = "10b0026696a79f448eb21d8dbc69d78acf12e2f1f62f291feecec8f2b8d1eac76da63d91dd317061a5a9eeb0"
#US 10 Digit only for now.
$myCell = '1234567890'
# Functions
Function get-FreeDiskPercentForC {
$disk = Get-DiskUsage
$free = $disk[0].FreeSpace / $disk[0].TotalSize
$freeDiskCPercent = [System.Math]::Round($free, 2)
$freeDiskCPercent
}
# Get some more parameters here.
$sourceServer =hostname
$cDisk = get-FreeDiskPercentForC
# Concatenate and form the Proto API string. I am sure someone can figure out a better way to do this than just adding.
$callThis = $baseUrl+ 'token=' + $protoToken + '&numToCall=' + $myCell + '&sourceServer=' + $sourceServer + '&freeCDisk=' + $cDisk
# Call the Proto API
# I could have tested this with Invoke-RestMethod, but I didn't see the point. I am not receiving any data from the URL.
$newClient = new-object System.Net.WebClient
$newClient.DownloadString($callThis)
|
PowerShellCorpus/PoshCode/The other Post.ps1
|
The other Post.ps1
|
$insParm = '/s /v"/qn /norestart"'
$updList = get-cluster -name $YouClusterNameHere | get-vm |
where-object {$_.powerstate -eq "PoweredON"} |
foreach-object { get-view $_.ID } |
where { $_.guest.toolsstatus -match "toolsOld" }
foreach ($uVM in $updList)
{
$uVM.name
$uVM.UpgradeTools_Task($insParm)
#Wait 30 seconds before starting another update task
Start-sleep -s 30
}
|
PowerShellCorpus/PoshCode/SharePoint Large Lists.ps1
|
SharePoint Large Lists.ps1
|
[reflection.assembly]::loadwithpartialname("Microsoft.SharePoint")
$cs = [microsoft.sharepoint.administration.spwebservice]::ContentService
$global:largeListThreshhold = 2000
function Is-Admin([Microsoft.SharePoint.SPRoleAssignment]$roleAssignment)
{
return (($roleAssignment.roledefinitionbindings | where { ($_.BasePermissions.ToString() -match "ManageLists|ManageWeb|FullMask") }) -ne $null)
}
function Write-ListDetails($list,$web,$site)
{
$fields = @()
$fields += $list.Title
$fields += $list.RootFolder
$fields += ($list.ContentTypes | select -first 1).Name
$fields += ($list.ContentTypes | select -first 1).Id.ToString()
$fields += ($list.ContentTypes | select -first 1).Id.Parent.ToString()
$fields += $list.Items.NumberOfFields
$fields += $list.Items.Count
$fields += $list.Created
$fields += $list.LastItemModifiedDate
$listAdmins = @()
$listAdmins += $list.RoleAssignments | where { Is-Admin $_ }
if ($listAdmins.Count -gt 0)
{
$fields += $listAdmins[0].Member.Name
$fields += $listAdmins[0].Member.Email
$fields += [string]::Join("; ", @($listAdmins | % { $_.Member.ToString() } ))
} else {
$fields += ""
$fields += ""
$fields += ""
}
$fields += $web.Url
$fields += $web.Title
$fields += $site.Url
[string]::Join("`t", $fields)
}
function Enumerate-LargeListsInSite($siteCollection)
{
foreach ($web in $siteCollection.AllWebs) {
$web.Lists | where { $_.Items.Count -gt $global:largeListThreshhold } | foreach { Write-ListDetails -list $_ -web $web -site $siteCollection }
$web.Dispose()
}
}
function List-FieldNames
{
$fieldNames = @()
$fieldNames += "ListTitle"
$fieldNames += "ListRootFolderURL"
$fieldNames += "ContentType1Name"
$fieldNames += "ContentType1ID"
$fieldNames += "ContentType1ParentID"
$fieldNames += "NumberOfFields"
$fieldNames += "Items"
$fieldNames += "CreatedDate"
$fieldNames += "LastItemModifiedDate"
$fieldNames += "ListAdmin1Name"
$fieldNames += "ListAdmin1Email"
$fieldNames += "AllListAdmins"
$fieldNames += "WebURL"
$fieldNames += "WebTitle"
$fieldNames += "SiteURL"
return [string]::Join("`t", $fieldNames)
}
function Enumerate-LargeLists
{
List-FieldNames
$webApplications = $cs.WebApplications | foreach { $_ }
foreach ($webApplication in $webApplications) {
$webApplication.Sites | foreach {
Enumerate-LargeListsInSite -siteCollection $_
$_.Dispose()
}
}
}
@@#USAGE: paste contents into PowerShell window; call "Enumerate-LargeLists > yourtextfilename.txt"
@@#then paste contents of text file into Excel spreadsheet. Output is
@@#intended to be perused and analyzed in Excel.
|
PowerShellCorpus/PoshCode/Auto ISE Preferences.ps1
|
Auto ISE Preferences.ps1
|
##############################################################
#Author: Ravikanth Chaganti (http://www.ravichaganti.com/blog)
#Script: SaveISEPrefs.ps1
#Description: PowerShell ISE profile script to automatically
# archive changes to ISE preferences such as color
# schemes, font, etc
##############################################################
#Add System.XML namespace
Add-Type -AssemblyName System.XML
#Initialize XML serializer
$xmlSerializer = New-Object System.Xml.Serialization.XmlSerializer($PSISE.Options.GetType())
#Path to ISE Preferences xml file. This will be created on first use
$file = $("$env:APPDATA\\isePreferences.xml")
#This function will be called when PropertyChanged event gets fired
function New-EventAction {
param ([System.Management.Automation.PSEventArgs]$objEvent)
$changedProperty = ($objEvent.SourceEventArgs.PropertyName).ToString()
Write-Host "Value of $changedProperty changed to $($objEvent.SourceArgs.Get(0).$changedProperty)"
$xmlWriter = [System.Xml.XmlTextWriter]::Create($file)
$xmlSerializer.Serialize($xmlWriter,$psISE.Options)
$xmlWriter.Close()
}
#This function gets called everytime we open ISE to restore the ISE prefernces from $File
function Update-ISEOptions {
If (!(Get-Item $file -ea SilentlyContinue)) {
Write-Host "$file not found"
return
}
$xmlReader = New-Object System.Xml.XmlTextReader($file)
$newISEOptions = $xmlSerializer.Deserialize($xmlReader)
$psISE.Options.SelectedScriptPaneState=$newISEOptions.SelectedScriptPaneState
$psISE.Options.ShowToolBar=$newISEOptions.ShowToolBar
$psISE.Options.FontSize=$newISEOptions.FontSize
$psISE.Options.FontName=$newISEOptions.FontName
$psISE.Options.ErrorForegroundColor=$newISEOptions.ErrorForegroundColor
$psISE.Options.ErrorBackgroundColor=$newISEOptions.ErrorBackgroundColor
$psISE.Options.WarningForegroundColor=$newISEOptions.WarningForegroundColor
$psISE.Options.WarningBackgroundColor=$newISEOptions.WarningBackgroundColor
$psISE.Options.VerboseForegroundColor=$newISEOptions.VerboseForegroundColor
$psISE.Options.VerboseBackgroundColor=$newISEOptions.VerboseBackgroundColor
$psISE.Options.DebugForegroundColor=$newISEOptions.DebugForegroundColor
$psISE.Options.DebugBackgroundColor=$newISEOptions.DebugBackgroundColor
$psISE.Options.OutputPaneBackgroundColor=$newISEOptions.OutputPaneBackgroundColor
$psISE.Options.OutputPaneTextBackgroundColor=$newISEOptions.OutputPaneTextBackgroundColor
$psISE.Options.OutputPaneForegroundColor=$newISEOptions.OutputPaneForegroundColor
$psISE.Options.CommandPaneBackgroundColor=$newISEOptions.CommandPaneBackgroundColor
$psISE.Options.ScriptPaneBackgroundColor=$newISEOptions.ScriptPaneBackgroundColor
$psISE.Options.ScriptPaneForegroundColor=$newISEOptions.ScriptPaneForegroundColor
$psISE.Options.ShowWarningForDuplicateFiles=$newISEOptions.ShowWarningForDuplicateFiles
$psISE.Options.ShowWarningBeforeSavingOnRun=$newISEOptions.ShowWarningBeforeSavingOnRun
$psISE.Options.UseLocalHelp=$newISEOptions.UseLocalHelp
$psISE.Options.CommandPaneUp = $newISEOptions.CommandPaneUp
$xmlReader.Close()
}
#Check for $psISE and then register the event subscriber
if ($psise) {
Update-ISEOptions
Register-ObjectEvent -InputObject $psISE.Options -EventName PropertyChanged -Action { New-EventAction $Event } | Out-Null
}
|
PowerShellCorpus/PoshCode/TabExpansion_8.ps1
|
TabExpansion_8.ps1
|
## Tab-Completion
#################
## 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 = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref",
"Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml"
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 = Get-EventLog Windows` PowerShell -Newest 1
}
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 '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
)
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
}
$members += [Object[]]$_keys | ? { $_.Name -like $_pat }
}
foreach ($_m in $members | sort membertype,name -Unique)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -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 $_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]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
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.
$_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 ( $_cmdlet.CommandType -eq "Cmdlet" )
{
# expand the parameter sets and emit the matching elements
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace `
'^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ }
}
break;
}
elseif ( $_command -eq $null )
{
"-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+))\\((.*)$' )
#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 | Get-Member -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)
# 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,ExternalScript,Filter,Function' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_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;
}
}
if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
$Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" |
% { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } |
? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ }
}
break;
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$pattern = $command + "*"
"begin {", "break", "catch {", "continue", "data {", "do {", "else {", "elseif (",
"end {", "exit", "filter ", "for (", "foreach ", "from", "function ", "if (", "in",
"param (", "process {", "return", "switch ", "throw ", "trap ", "until (", "while (" `
-like $pattern | % { $_base + $_ }
gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-DirSize.ps1
|
Get-DirSize.ps1
|
function Get-DirSize {
<#
.Synopsis
Gets a list of directories and sizes.
.Description
This function recursively walks the directory tree and returns the size of
each directory found.
.Parameter path
The path of the root folder to start scanning.
.Example
# Get the largest folder under the user profile
PS> (Get-DirSize $env:userprofile | sort Size)[-1]
.Example
# Get the folder sizes of all folders under each folder in $folders
PS> $folders | Get-DirSize
.Example
# Create a tab-separated text file of Folders and Sizes
PS> 'Folder', 'Size' -join "`t" > folder_sizes.txt
PS> Get-DirSize C:\\MyFolder | Sort-Object Size -desc |
>> %{$_.Folder, $_.Size -join "`t"} >> folder_sizes.txt
.ReturnValue
An object with Folder and Size properties.
#>
param([Parameter(Mandatory = $true, ValueFromPipeline = $true)][string]$path)
BEGIN {}
PROCESS{
$size = 0
$folders = @()
foreach ($file in (Get-ChildItem $path -Force -ea SilentlyContinue)) {
if ($file.PSIsContainer) {
$subfolders = @(Get-DirSize $file.FullName)
$size += $subfolders[-1].Size
$folders += $subfolders
} else {
$size += $file.Length
}
}
$object = New-Object -TypeName PSObject
$object | Add-Member -MemberType NoteProperty -Name Folder `
-Value (Get-Item $path).FullName
$object | Add-Member -MemberType NoteProperty -Name Size -Value $size
$folders += $object
Write-Output $folders
}
END {}
}
|
PowerShellCorpus/PoshCode/NTFS ACLs Folder Tree_4.ps1
|
NTFS ACLs Folder Tree_4.ps1
|
#######################################
# TITLE: listACL.ps1 #
# AUTHOR: Santiago Fernandez Muñoz #
# #
# DESC: This script generate a HTML #
# report show all ACLs asociated with #
# a Folder tree structure starting in #
# root specified by the user #
#######################################
param ([string] $computer = 'localhost',
[string] $path = $(if ($help -eq $false) {Throw "A path is needed."}),
[int] $level = 0,
[string] $scope = 'administrator',
[switch] $help = $false,
[switch] $debug = $false
)
#region Initializations and previous checkings
#region Initialization
$allowedLevels = 10
$Stamp = get-date -uformat "%Y%m%d"
$report = "$PWD\\$computer.html"
$comparison = ""
$UNCPath = "\\\\" + $computer + "\\" + $path + "\\"
#endregion
#region Previous chekings
#require -version 2.0
if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."}
if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path }
switch ($scope) {
micro {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")'
}
user {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")'
}
}
#endregion
#endregion
#region Function definitions
function drawDirectory([ref] $directory) {
$dirHTML = '
<div class="'
if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level }
$dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div>
<div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div>
<div class="container">
<div class="heACL">
<table class="info3" cellpadding="0" cellspacing="0">
<thead>
<th scope="col"><b>Owner</b></th>
<th scope="col"><b>Privileges</b></th>
</thead>
<tbody>'
foreach ($itemACL in $directory.value.ACL) {
$acls = $null
if ($itemACL.AccessToString -ne $null) {
$acls = $itemACL.AccessToString.split("`n")
}
$dirHTML += '<tr><td>' + $itemACL.Owner + '</td>
<td>
<table>
<thead>
<th>User</th>
<th>Control</th>
<th>Privilege</th>
</thead>
<tbody>'
foreach ($acl in $acls) {
$temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}")
if ($debug) {
write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp
}
if ($temp.count -eq 1) {
continue
}
if ($scope -ne 'administrator') {
if ( Invoke-Expression $comparison ) {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
} else {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
}
$dirHTML += '</tbody>
</table>
</td>
</tr>'
}
$dirHTML += '
</tbody>
</table>
</div>
</div>
</div>'
return $dirHTML
}
#endregion
#region Printing help message
if ($help) {
Write-Host @"
/··················································\\
· Script gather access control lists per directory ·
\\··················································/
USAGE: ./listACL -computer <machine or IP>
-path <path>
-level <0-10>
-help:[$false]
PARAMETERS:
computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost)
path [REQUIRED] - Folder's path to query.
level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels.
0 show that there's no limit in the going down (Default: 0)
scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are:
· user, show important information to the user.
· micro, show user scope information plus important information for the IT Department.
· administrator, show all information.
help [OPTIONAL] - This help.
"@
exit 0
}
#endregion
if (Test-Path $report)
{
Remove-item $report
}
#To normalize I check if last character in the path is the folder separator character
if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) }
#region Header, style and javascript functions needed by the html report
@"
<html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
<title>Access Control List for $path in $computer</title>
<!-- Styles -->
<style type="text/css">
body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; }
table{ font-size:100%; table-layout:fixed; width:100%; }
td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; }
.title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; }
.he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; }
.he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; }
.he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; }
.he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; }
.he0 .expando{ font-size:100%; }
.info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; }
.disalign TD{ padding-bottom:5px; padding-right:10px; }
.info TD{ padding-right:10px; width:50%; }
.info3 TD{ padding-right:10px; width:33%; }
.info4 TD, .info4 TH{ padding-right:10px; width:25%; }
.info5 TD, .info5 TH{ padding-right:0px; width:20%; }
.info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; }
.subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; }
.subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; }
.subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; }
.subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; }
.subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; }
.explainlink{ color:#000000; text-decoration:none; cursor:pointer; }
.explainlink:hover{ color:#0000FF; text-decoration:underline; }
.spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; }
.filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; }
.container{ display:block; position:relative; }
.rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; }
.rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; }
#uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; }
#dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; }
#objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; }
#gposummary { display:block; }
#gpoinformation { display:block; }
</style>
</head>
<body>
<table class="title" cellpadding="0" cellspacing="0">
<tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr>
<tr>
<td id="dtstamp">Data obtained on: $(Get-Date)</td>
<td><div id="objshowhide" tabindex="0"></div></td>
</tr>
</table>
<div class="filler"></div>
"@ | Set-Content $report
#endregion
#region Information gathering
$colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName
$colACLs = @()
#We start going through the path pointed out by the user
foreach($file in $colFiles)
{
#To control the current level in the tree we are in it's needed to count the number of separator characters
#contained in the path. However in order to make the count correctly it's needed to delete the path
#provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be
#string used to do the level count.
#It's needed to use a REGEX object to get ALL separator character matches.
$matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count
if ($level -ne 0 -and ($matches - 1) -gt $level) {
continue
}
if ($debug) {
Write-Host $file.FullName "->" $file.Mode
}
if ($file.Mode -notlike "d*") {
continue
}
$myobj = "" | Select-Object Folder,ACL,level
$myobj.Folder = $file
$myobj.ACL = Get-Acl $file.FullName
$myobj.level = $matches - 1
$colACLs += $myobj
}
#endregion
#region Setting up the report
'<div class="gposummary">' | Add-Content $report
for ($i = 0; $i -lt $colACLs.count; $i++) {
drawDirectory ([ref] $colACLs[$i]) | Add-Content $report
}
'</div></body></html>' | Add-Content $report
#endregion
|
PowerShellCorpus/PoshCode/Get-CertificationAuthori.ps1
|
Get-CertificationAuthori.ps1
|
#####################################################################
# Get-CertificationAuthority.ps1
# Version 1.0
#
# Retrieves all Enterprise Certification Authorities in cuurent AD forest
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
####################################################################
function Get-CertificationAuthority ([string]$CAName) {
$domain = ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).Name
$domain = "DC=" + $domain -replace '\\.', ", DC="
$CA = [ADSI]"LDAP://CN=Enrollment Services, CN=Public Key Services, CN=Services, CN=Configuration, $domain"
$CAs = $CA.psBase.Children | %{
$current = "" | Select CAName, Computer
$current.CAName = $_ | %{$_.Name}
$current.Computer = $_ | %{$_.DNSHostName}
$current
}
if ($CAName) {$CAs = @($CAs | ?{$_.CAName -eq $CAName})}
if ($CAs.Count -eq 0) {throw "Sorry, here is no CA that match your search"}
$CAs
}
|
PowerShellCorpus/PoshCode/ConvertTo-Hashtable.ps1
|
ConvertTo-Hashtable.ps1
|
Param([Parameter(ValueFromPipeline=$true)]$object,[switch]$AsString,[switch]$jagged)
BEGIN { $headers = @() }
PROCESS {
if(!$headers -or $jagged) {
$headers = $object | get-member -type Properties | select -expand name
}
$output = @{}
if($AsString) {
foreach($col in $headers) {
$output.$col = $object.$col | out-string -Width 9999 | % { $_.Trim() }
}
} else {
foreach($col in $headers) {
$output.$col = $object.$col
}
}
$output
}
|
PowerShellCorpus/PoshCode/HuddledTricks_1.ps1
|
HuddledTricks_1.ps1
|
#Requires -version 2.0
## Stupid PowerShell Tricks
###################################################################################################
## Usage:
## ps Notepad | Hide-App
## Hide-App -Name PowerShell; Wiggle-Mouse 75 100
###################################################################################################
add-type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
public static void ShowWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,5); }
public static void HideWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,0); }
}
"@
$dictionary = [System.Collections.Generic.Dictionary``2]
$list = [System.Collections.Generic.List``1]
$string = [String]
$intPtr = [IntPtr]
$intPtrList = $list.AssemblyQualifiedName -replace "1,","1[[$($intPtr.AssemblyQualifiedName)]],"
$windows = new-object ($dictionary.AssemblyQualifiedName -replace "2,","2[[$($string.AssemblyQualifiedName)],[$intPtrList]],")
function Hide-Window {
<#
.SYNOPSIS
Hide a window
.DESCRIPTION
Hide a window by handle or by process name. Hidden windows are gone: they don't show up in alt+tab, or on the taskbar, and they're invisible. The only way to get them back is with ShowWindow.
Windows hidden by Hide-Window are pushed onto a stack so they can be retrieved by Show-Window. Since they're invisible, they're very hard to find otherwise.
.NOTES
See also Show-Window
.PARAMETER WindowHandle
The window handle to a specific window we want to hide.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
.LINK
http://HuddledMasses.org/stupid-powershell-tricks
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
)
PROCESS {
(Push-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::HideWindow( $_ ) }
}
}
function Show-Window {
<#
.SYNOPSIS
Show a window
.DESCRIPTION
Show a window by handle or by process name. If you call it without any parameters, will show all hidden windows.
.NOTES
See also Hide-Window
.PARAMETER WindowHandle
The window handle to a specific window we want to show.
.PARAMETER Name
The name of a running process whos windows you want to show.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
.LINK
http://HuddledMasses.org/stupid-powershell-tricks
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
)
PROCESS {
(Pop-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::ShowWindow( $_ ) }
}
}
## PRIVATE
FUNCTION Push-Window {
[CmdletBinding()]
PARAM ([IntPtr]$Handle,[String]$ProcessName)
[IntPtr[]]$Handles = @($Handle)
if(!$ProcessName) { $ProcessName = "--Unknown--" }
if(!$Windows.ContainsKey($ProcessName)) {
$windows.Add($ProcessName, (New-Object $intPtrList))
}
if($Handle -eq [IntPtr]::Zero) {
[IntPtr[]]$Handles = @(Get-Process $ProcessName | % { $_.MainWindowHandle } )
}
$windows[$ProcessName].AddRange($Handles)
write-output $Handles
}
## PRIVATE
FUNCTION Pop-Window {
[CmdletBinding()]
PARAM ([IntPtr]$Handle,[String]$ProcessName)
[IntPtr[]]$Handles = @($Handle)
if(!$ProcessName) { $ProcessName = "--Unknown--" }
if(($Handle -eq [IntPtr]::Zero) -and $windows[$ProcessName] ) {
write-output $windows[$ProcessName]
$Null = $windows[$ProcessName].Clear()
} elseif($Handle -ne [IntPtr]::Zero){
$Null = $windows[$ProcessName].Remove( $Handle )
}
write-output $Handles
}
Add-Type -Assembly System.Windows.Forms
function Wiggle-Mouse {
<#
.SYNOPSIS
Wiggle the mouse until you Ctrl+Break to stop the script.
.DESCRIPTION
Wiggle-Mouse randomly moves the mouse by a few pixels every few milliseconds until you stop the script.
.PARAMETER Variation
The maximum distance to move the mosue in any direction. Values that are too small aren't noticeable, and values that are too big make the user "loose" the mouse and they have no idea what happened.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Wiggle-Mouse -Duration 5; Get-Process PowerShell | Show-Window
Hides the PowerShell window and wiggle the mouse for five seconds ... :D
.LINK
http://HuddledMasses.org/stupid-powershell-tricks
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0)][Int]$Variation=80,
[Parameter(Position=1)][Int]$Sleep=400,
[Parameter(Position=2)][Int]$Duration=0
)
if(!$Duration) { Write-Host "Ctrl+C to stop wiggling :)" }
$screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$random = new-object Random
$Duration *= -1000
While($Duration -le 0) {
[Windows.Forms.Cursor]::Position ="$(
$random.Next( [Math]::Max( $screen.Left, ([System.Windows.Forms.Cursor]::Position.X - $Variation) ),
[Math]::Min( $screen.Right, ([System.Windows.Forms.Cursor]::Position.X + $Variation) ) )
),$(
$random.Next( [Math]::Max( $screen.Top, ([System.Windows.Forms.Cursor]::Position.Y - $Variation) ),
[Math]::Min( $screen.Bottom, ([System.Windows.Forms.Cursor]::Position.Y + $Variation) ) )
)"
sleep -milli $Sleep
$Duration += $Sleep
}
}
Export-ModuleMember Show-Window, Hide-Window, Wiggle-Mouse
|
PowerShellCorpus/PoshCode/Manage ASP_2.NET Providers.ps1
|
Manage ASP_2.NET Providers.ps1
|
# Manage_ASP_NET_Providers.ps1
# by Chistian Glessner
# http://iLoveSharePoint.com
# have to be initialized. 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]
}
}
|
PowerShellCorpus/PoshCode/Windows Startup Script_3.ps1
|
Windows Startup Script_3.ps1
|
<#======================================================================================
File Name : Startup.ps1
Original Author : Kenneth C. Mazie
:
Description : This is a Windows startup script with pop-up notification and checks to
: assure things are not exectuted if already running or set. It can be run
: as a personal startup script or as a domain startup (with some editing).
: It is intended to be executed from the Start Menu "All Programs\\Startup" folder.
:
: The script will Start programs, map shares, set routes, and can email the results
: if desired. The email subroutine is commented out. You'll need to edit it yourself.
: When run with the "debug" variable set to TRUE it also displays staus in the
: PowerShell command window. Other wise all operation statuses are displayed in pop-up
: ballons near the system tray.
:
: To call the script use the following in a shortcut or in the RUN registry key.
: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden –Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}"
: Change the script name and path as needed to suit your environment.
:
: Be sure to edit all sections to suit your needs before executing. Be sure to
: enable sections you wish to run by uncommenting them at the bottom of the script.
:
: Route setting is done as a function of selecting a specific Network Adapter with the intent
: of manually altering your routes for hardline or WiFi connectivity. This section you will
: need to customize to suit your needs or leave commented out. This allowed me to
: alter the routing for my office (Wifi) or lab (hardline) by detecting whether my
: laptop was docked or not. The hardline is ALWAYS favored as written.
:
: To identify process names to use run "get-process" by itself to list process
: names that PowerShell will be happy with, just make sure each app you want to
: identify a process name for is already running first.
:
: A 2 second sleep delay is added to smooth out processing but can be removed if needed.
:
Notes : Sample script is safe to run as written, it will only load taskmanager and firefox.
: In general, I did not write this script for ease of readability. Most commands are
: one-liner style, sorry if that causes you grief.
:
Warnings : Drive mapping passwords are clear text within the script.
:
:
Last Update by : Kenneth C. Mazie (kcmjr AT kcmjr.com to report issues)
Version History : v1.0 - 05-03-12 - Original
Change History : v2.0 - 11-15-12 - Minor edits
: v3.0 - 12-10-12 - Converted application commands to arrays
: v4.0 - 02-14-13 - Converted all other sections to arrays
: v4.1 - 02-17-13 - Corrected error with pop-up notifications
=======================================================================================#>
clear-host
$Debug = $True
$CloudStor = $False
$ScriptName = "Startup Script"
#--[ Prep Pop-up Notifications ]--
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Icon = [System.Drawing.SystemIcons]::Information
$Notify = new-object system.windows.forms.notifyicon
$Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none
$Notify.visible = $true
#--[ Force to execute with admin priviledge ]--
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object Security.Principal.WindowsPrincipal $identity
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) {$Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path;Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs;exit}
if ($debug){write-host "`n------[ Running with Admin Privileges ]------`n" -ForegroundColor DarkCyan}
$Notify.ShowBalloonTip(2500,$ScriptName,"Script is running with full admin priviledges",[system.windows.forms.tooltipicon]::Info)
if ($debug){write-host "Running in DEBUG Mode..." -ForegroundColor DarkCyan}
function Pause-Host { #--[ Only use if you need a countdown timer ]--
param($Delay = 10)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($Delay-- -ne $counter )) #--count down
#While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay )) #--count up
{
clear-host
if ($debug){Write-Host "testing... $Delay"} #--count down
#Write-Host "testing... $counter" #--count up
[Threading.Thread]::Sleep(1000)
}
}
Function SetRoutes { #--[ Array consists of Network, Mask ]--
$RouteArray = @()
$RouteArray += , @("10.0.0.0","255.0.0.0")
$RouteArray += , @("172.1.0.0","255.255.0.0")
$RouteArray += , @("192.168.1.0","255.255.255.0")
#--[ Add more route entries here... ]--
$Index = 0
Do {
$RouteNet = $ShareArray[$Index][0]
$RouteMask = $ShareArray[$Index][1]
iex "route delete $RouteNet"
Sleep (2)
iex "route add $RouteNet mask $RouteMask $IP"
Sleep (2)
$Index++
}
While ($Index -lt $RouteArray.length)
}
Function SetMappings { #--[ Array consists of Drive Letter, Path, User, and Password ]--
$ShareArray = @()
$ShareArray += , @("J:","\\\\192.168.1.250\\Share1","username","password")
$ShareArray += , @("K:","\\\\192.168.1.250\\Share2","username","password")
#--[ Add more mapping entries here... ]--
$Index = 0
Do {
$MapDrive = $ShareArray[$Index][0]
$MapPath = $ShareArray[$Index][1]
$MapUser = $ShareArray[$Index][2]
$MapPassword = $ShareArray[$Index][3]
$net = $(New-Object -Com WScript.Network)
if ( Exists-Drive $MapDrive){$Notify.ShowBalloonTip(2500,$ScriptName,"Drive $MapDrive is already mapped...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Drive $MapDrive already mapped" -ForegroundColor DarkRed}}else{if (test-path $MapPath){$net.MapNetworkDrive($MapDrive, $MapPath, "False",$MapUser,$MapPassword);$Notify.ShowBalloonTip(2500,$ScriptName,"Mapping Drive $MapDrive...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Mapping Drive $MapDrive" -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Cannot Map Drive $MapDrive - Target Not Found...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cannot Map Drive $MapDrive - Target Not Found" -ForegroundColor DarkRed}}}
Sleep (2)
$Index++
}While ($Index -lt $ShareArray.length)
}
Function Exists-Drive {
param($driveletter)
(New-Object System.IO.DriveInfo($driveletter)).DriveType -ne 'NoRootDirectory'
}
Function LoadApps { #--[ Array consists of Process Name, File Path, Arguements, Title ]--
$AppArray = @()
$AppArray += , @("firefox","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe","https://www.google.com","FireFox")
#--[ Add more app entries here... ]--
#--[ Cloud Storage Provider Subsection ]--
if (!$CloudStor ){$Notify.ShowBalloonTip(2500,$ScriptName,"Cloud Providers Bypassed...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cloud Providers Bypassed..." -ForegroundColor Magenta;}}
else
{
$AppArray += , @("googledrivesync","C:\\Program Files (x86)\\Google\\Drive\\googledrivesync.exe","/autostart","GoogleDrive")
#--[ Add more cloud entries here... ]--
}
$AppArray += , @("taskmgr","C:\\Windows\\System32\\taskmgr.exe"," ","Task Manager")
#--[ Add more app entries here... ]--
$Index = 0
Do {
$AppProcess = $AppArray[$Index][0]
$AppExe = $AppArray[$Index][1]
$AppArgs = $AppArray[$Index][2]
$AppName = $AppArray[$Index][3]
If((get-process -Name $AppProcess -ea SilentlyContinue) -eq $Null){start-process -FilePath $AppExe -ArgumentList $AppArgs ;$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is loading...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Loading" $AppName "..." -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is already running...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "$AppName Already Running..." -ForegroundColor DarkRed } }
Sleep (2)
$Index++
}
While ($Index -lt $AppArray.length)
}
<#
function SendMail {
#param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
param($To, $From, $Subject, $Body, $smtpServer)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $From
$msg.To.Add($To)
$msg.Subject = $Subject
$msg.IsBodyHtml = 1
$msg.Body = $Body
$smtp.Send($msg)
}
#>
Function IdentifyNics {
$Domain1 = "LabDomain.com"
$Domain2 = "OfficeDomain.com"
#--[ Detect Network Adapters ]--
$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" }
#--[ Alternate detection methods]--
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } | where {$_.DNSDomainSuffixSearchOrder -match $Domain2}
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller" }
$WiredIP = ([string]$Wired.IPAddress).split(" ")
$WiredDesc = $Wired.Description
if ($debug){
write-host "Name: " $Wired.Description`n"DNS Domain: " $Wired.DNSDomainSuffixSearchOrder`n"IPv4: " $WiredIP[0]`n"IPv6: " $WiredIP[1]`n""
if ($WiredIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiredDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Hardline not detected",[system.windows.forms.tooltipicon]::Info)}
}
sleep (2)
$WiFi = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Intel(R) Centrino(R) Advanced-N 6250 AGN" }
$WiFiIP = ([string]$WiFi.IPAddress).split(" ")
$WiFiDesc = $WiFi.Description
write-host "Name: " $WiFi.Description`n"DNS Domain: " $WiFi.DNSDomainSuffixSearchOrder`n"IPv4: " $WiFiIP[0]`n"IPv6: " $WiFiIP[1]
if ($WiFiIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiFiDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"WiFi not detected",[system.windows.forms.tooltipicon]::Info)}
sleep (2)
#--[ Set Routes ]--
if ($WiredIP[0]) { #--[ The hardline is connected. Favor the hardline if both connected ]--
$IP = $WiredIP[0]
if ($Wired.DNSDomainSuffixSearchOrder -like $Domain1 -or $Wired.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ the hardline is connected ]--
write-host ""`n"Setting routes for hardline"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for hardline...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
} else {
if ($WiFiIP[0]) {
if ($WiFi.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ The wifi is connected --]
$IP = $WiFiIP[0]
write-host ""`n"Setting routes for wifi"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for wifi...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
}
}
}
#Write-Host $IP
#IdentifyNics
#SetMappings
#Pause-Host
LoadApps
If ($debug){write-host "Completed All Operations..." -ForegroundColor DarkCyan}
|
PowerShellCorpus/PoshCode/Resolve-Aliases _5.7.ps1
|
Resolve-Aliases _5.7.ps1
|
#requires -version 2.0
## ResolveAliases Module v 1.7
########################################################################################################################
## Sample Use:
## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1
## ls *.ps1 | Resolve-Aliases -Inplace
########################################################################################################################
## Version History
## 1.0 - First Version. "It worked on my sample script"
## 1.1 - Now it parses the $(...) blocks inside strings
## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts)
## 1.3 - I went back to processing the whole script at once (instead of a line at a time)
## Processing a line at a time makes it impossible to handle Here-Strings...
## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it
## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is
## 1.4 - Now resolves parameters too
## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem)
## - Refactored the Resolve-Line filter right out of existence
## - Created a test script for validation, and
## 1.6 - Added resolving parameter ALIASES instead of just short-forms
## 1.7 - Minor tweak to make it work in CTP3
##
## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path
## * *TODO:* Add an option to put #requires statements at the top for each snapin used
########################################################################################################################
function which {
PARAM( [string]$command )
# aliases, functions, cmdlets, scripts, executables, normal files
$cmds = @(Get-Command $command -EA "SilentlyContinue")
if($cmds.Count -gt 1) {
$cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0]
} else {
$cmd = $cmds[0]
}
if(!$cmd) {
$cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0]
}
if( $cmd.CommandType -eq "Alias" ) {
$cmd = which $cmd.Definition
}
return $cmd
}
function Resolve-Aliases
{
[CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")]
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")]
[string]$Line
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")]
[Alias("FullName","PSChildName","PSPath")]
[IO.FileInfo]$File
,
[Parameter(Position=1, ParameterSetName="Files")]
[Switch]$InPlace
)
BEGIN {
Write-Debug $PSCmdlet.ParameterSetName
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "Files") {
if($File -is [System.IO.FileInfo]){
$Line = ((Get-Content $File) -join "`n")
} else {
throw "We can't resolve a whole folder at once yet"
}
}
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null)
for($t = $Tokens.Count; $t -ge 0; $t--) {
$token = $Tokens[$t]
# DEBUG $token | fl * | out-host
switch($token.Type) {
"Command" {
$cmd = which $token.Content
Write-Debug "Command $($token.Content) => $($cmd.Name)"
#if($cmd.CommandType -eq "Alias") {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name )
#}
}
"CommandParameter" {
Write-Debug "Parameter $($token.Content)"
for($c = $t; $c -ge 0; $c--) {
if( $Tokens[$c].Type -eq "Command" ) {
$cmd = which $Tokens[$c].Content
# if($cmd.CommandType -eq "Alias") {
# $cmd = @(which $cmd.Definition)[0]
# }
$short = $token.Content -replace "^-?","^"
Write-Debug "Parameter $short"
$parameters = $cmd.ParameterSets | Select -expand Parameters
$param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique)
if($param.Count -eq 1) {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" )
}
break
}
}
}
}
}
switch($PSCmdlet.ParameterSetName) {
"Text" {
$Line
}
"Files" {
switch($File.GetType()) {
"System.IO.FileInfo" {
if($InPlace) {
$Line | Set-Content $File
} else {
$Line
}
}
default { throw "We can't resolve a whole folder at once yet" }
}
}
default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" }
}
}
}
|
PowerShellCorpus/PoshCode/Copy-GroupMembership.ps1
|
Copy-GroupMembership.ps1
|
<#
.SYNOPSIS
Copy group membership between two accounts.
.DESCRIPTION
This script will copy the group membership from an existing user
account to a new user account.
.PARAMETER ADSPath
This is the LDAP URL to where your user accounts are stored
.PARAMETER NewUser
The username of the new user account
.PARAMETER SearchFilter
The searchFilter to pass on to AD, I'm using FSPs so it defaults
to foreignSecurityPrincipal, but it could be Person if you're
working with user accounts all within the same ActiveDirectory domain.
.PARAMETER ExistingUser
The username of the existing user account
.PARAMETER Verbose
Enable the debugging statements
.EXAMPLE
.\\New-StudentWorker.ps1 -NewUser 'Newton' -ExistingUser 'Oldson' -ADSPath 'CN=ForeignSecurityPrincipals,DC=company,DC=com'
GroupDN UserDN Added
------- ------ -----
LDAP://CN=IGroup,OU=Profile,OU... LDAP://CN=S-1-5-21-57989841-1... The object already exists. (E...
LDAP://CN=ECSStaffProfessional... LDAP://CN=S-1-5-21-57989841-1... True
Description
-----------
This sample shows the syntax and working against FSPs, as well as a potential error you might encounter.
.EXAMPLE
.\\New-StudentWorker.ps1 -NewUser 'Guest' -ExistingUser 'krbtgt' -ADSPath 'DC=company,DC=com' -SearchFilter '(objectCategory=Person)'
GroupDN UserDN Added
------- ------ -----
LDAP://CN=Denied RODC Password... LDAP://CN=Guest,CN=Users,DC=c... True
Description
-----------
This example shows the syntax for copying group membership between accounts in the same domain.
.NOTES
ScriptName : Copy-GroupMembership
Created By : jspatton
Date Coded : 09/22/2011 10:17:53
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
ErrorCodes
100 = Success
101 = Error
102 = Warning
104 = Information
.LINK
#>
Param
(
[Parameter(Mandatory=$true)]$ADSPath,
[Parameter(Mandatory=$true)]$NewUser,
$SearchFilter = '(objectCategory=foreignSecurityPrincipal)',
$ExistingUser
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
if ($Verbose)
{
$DebugPreference = "Continue"
$VerbosePreference = $DebugPreference
}
# Dotsource in the functions you need.
. .\\includes\\ActiveDirectoryManagement.ps1
}
Process
{
if ($SearchFilter -like "*foreignSecurityPrincipal*")
{
Write-Verbose "Need to get a list of FSP objects and convert them to sAMAccountNames"
$Users = Get-ADObjects -ADSPath $ADSPath -SearchFilter $SearchFilter |foreach {$_.Properties.name |Convert-FspToUsername}
$NewUser = $Users |Where-Object {$_.sAMAccountName -like "*$($NewUser)"}
$ExistingUser = $Users |Where-Object {$_.sAMAccountName -like "*$($ExistingUser)"}
Write-Verbose "Found $($NewUser.sAMAccountName)"
Write-Verbose "Found $($ExistingUser.sAMAccountName)"
Write-Verbose "Get the group membership for CN=$($ExistingUser.Sid),$($ADSPath)"
$UserGroups = Get-UserGroupMembership -UserDN "CN=$($ExistingUser.Sid),$($ADSPath)"
foreach ($UserGroup in $UserGroups)
{
Write-Verbose "Try adding $($NewUser.sAMAccountName) to $UserGroup.GroupDN"
Add-UserToGroup -GroupDN $UserGroup.GroupDN -UserDN "LDAP://CN=$($NewUser.Sid),$($ADSPath)"
}
}
else
{
Write-Verbose "Get a list of user objects"
$Users = Get-ADObjects -ADSPath $ADSPath -SearchFilter $SearchFilter
$NewUser = $Users |Where-Object {$_.Properties.name -like "*$($NewUser)"}
$ExistingUser = $Users |Where-Object {$_.Properties.name -like "*$($ExistingUser)"}
Write-Verbose "Found $($NewUser.Properties.name)"
Write-Verbose "Found $($ExistingUser.Properties.name)"
Write-Verbose "Get the group membership for $($ExistingUser.Path)"
$UserGroups = Get-UserGroupMembership -UserDN $ExistingUser.Path
foreach ($UserGroup in $UserGroups)
{
Write-Verbose "Try adding $($NewUser.Properties.name) to $UserGroup.GroupDN"
Add-UserToGroup -GroupDN $UserGroup.GroupDN -UserDN $NewUser.Path
}
}
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
if ($Verbose)
{
$DebugPreference = "SilentlyContinue"
$VerbosePreference = $DebugPreference
}
}
|
PowerShellCorpus/PoshCode/Backup all ESXi.ps1
|
Backup all ESXi.ps1
|
# Change this to where you would like your backups to go.
# There is no versioning so backup theses backups with real backup software (e.g. on an SMB share).
$backupDir = "c:\\backups"
# Get just your ESXi hosts.
$esxiHosts = Get-VMHost | Where { $_ | Get-View -Property Config | Where { $_.Config.Product.ProductLineId -eq "embeddedEsx" } }
# Back them all up.
$esxiHosts | Foreach {
$fullPath = $backupDir + ¡°\\¡± + $_.Name
mkdir $fullPath -ea SilentlyContinue | Out-Null
Set-VMHostFirmware -VMHost $_ ¨CBackupConfiguration ¨CDestinationPath $fullPath
}
|
PowerShellCorpus/PoshCode/SQL-Update.ps1
|
SQL-Update.ps1
|
<#
.SYNOPSIS
Author:...Vidrine
Date:.....2012/04/08
.DESCRIPTION
Function uses the Microsoft SQL cmdlets 'Invoke-SQLcmd' to connect to a SQL database and run an UPDATE statement.
The target record that will be updated is queried based on a table/column named 'ID'. Simply change this to query based on another value.
.PARAM server
Hostname/IP of the server hosting the SQL database.
.PARAM database
Name of the SQL database to connect to.
.PARAM table
Name of the table within the specified SQL database.
.PARAM dataField
Field/Column name from the specified table. This is the field/column that will be updated.
.PARAM dataValue
The new value of the field/column that will be updated.
.PARAM updateID
The ID of the target record to update.
.EXAMPLE
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
#>
function SQL-Update {
param(
[string]$server,
[string]$database,
[string]$table,
[string]$dataField,
[string]$dataValue,
[string]$updateID
)
$sqlQuery = @"
UPDATE $database.$table
SET $dataField='$dataValue'
WHERE id=$updateID
"@
try {
Invoke-SQLcmd -ServerInstance $server -Database $database -Query $sqlQuery
}
catch {
}
}
|
PowerShellCorpus/PoshCode/Find-String_1.ps1
|
Find-String_1.ps1
|
<#
.Synopsis
Searches text files by pattern and displays the results.
.Description
Searches text files by pattern and displays the results.
.Notes
Based on versions from http://weblogs.asp.net/whaggard/archive/2007/03/23/powershell-script-to-find-strings-and-highlight-them-in-the-output.aspx and from http://poshcode.org/426
Makes use of Out-ColorMatchInfo found at http://poshcode.org/1095.
#>
#requires -version 2
param (
[Parameter(Mandatory=$true)]
[regex] $pattern,
[string] $filter = "*.*",
[switch] $recurse = $true,
[switch] $caseSensitive = $false,
[int[]] $context = 0
)
if ((-not $caseSensitive) -and (-not $pattern.Options -match "IgnoreCase")) {
$pattern = New-Object regex $pattern.ToString(),@($pattern.Options,"IgnoreCase")
}
Get-ChildItem -recurse:$recurse -filter:$filter |
Select-String -caseSensitive:$caseSensitive -pattern:$pattern -AllMatches -context $context |
Out-ColorMatchInfo
|
PowerShellCorpus/PoshCode/Reverse filename sequenc_1.ps1
|
Reverse filename sequenc_1.ps1
|
# Reverse filename sequence v 0.9
# Author: Sean Wendt
#
# This script will rename a sequenced set of files in a directory.
# For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg
# -- it will reverse the order, so the last file is now 01, the second to last 02, etc..
#
# Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars.
# -It's hardcoded to only support 5 digit numbers right now.
# -Similarly, it will only support a file sequence with up to 5 digits.
# This is the first script I've written, I know it's not great! ;)
# Help to make it better would be appreciated. Thanks.
#
$file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt"
$file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.."
$files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders
$idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg)
for ($ctr=$files.count; $ctr -gt 0 ; --$ctr)
{
if (($idx -ge 0) -and ($idx -le 9))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension)
}
elseif (($idx -ge 10) -and ($idx -le 99))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension)
}
elseif (($idx -ge 100) -and ($idx -le 999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension)
}
elseif (($idx -ge 1000) -and ($idx -le 9999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension)
}
elseif (($idx -ge 10000) -and ($idx -le 99999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension)
}
$idx #prints the index # it just completed
}
|
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP2).ps1
|
Set-Wallpaper (CTP2).ps1
|
#requires -version 2.0
## Set-Wallpaper - set your windows desktop wallpaper
###################################################################################################
## Usage:
## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Others Stock\\Potter Wasp.jpg" "Stretched"
## ls *.jpg | get-random | Set-Wallpaper
###################################################################################################
add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tiled, Centered, Stretched
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretched :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Centered :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tiled :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
}
key.Close();
}
}
}
"@
cmdlet Set-Wallpaper {
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$true)]
[Wallpaper.Style]
$Style
)
[Wallpaper.Setter]::SetWallpaper( (Convert-Path $Path), $Style )
}
|
PowerShellCorpus/PoshCode/Get-Checksum GUI.ps1
|
Get-Checksum GUI.ps1
|
<#
.NOTES
Name : Get-Checksum GUI
Author : Bryan Jaudon <bryan.jaudon@gmail.com>
Version : 1.2
Date : 9/14/2012
.SYNOPSIS
GUI file checksum calculation script.
#>
#requires -version 2
$ScriptVersion="1.2"
#Check if Powershell is running in MTA or STA mode. STA is required for DragDrop registration.
if ([threading.thread]::CurrentThread.GetApartmentState() -eq "MTA") {
Write-Warning "Powershell running as Multi Thread Apartment (MTA). Calling new instance in Single Thread Apartment (STA)."
& $env:SystemRoot\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -sta -noprofile -nologo -file $MyInvocation.MyCommand.Path
return
}
$code = @"
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System
{
public class IconExtractor
{
public static Icon Extract(string file, int number, bool largeIcon)
{
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try
{
return Icon.FromHandle(largeIcon ? large : small);
}
catch
{
return null;
}
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}
}
"@
Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing
$os=Get-WmiObject win32_OperatingSystem
if ($os.version[0] -ge 6) { $icon=[System.IconExtractor]::Extract("shell32.dll",144,$true) } #Checkmark icon in Windows Vista/7/8
else { $icon=[System.IconExtractor]::Extract("shell32.dll",253,$true) } #File checkmark icon in Windows XP
#Generated Form Function
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()
#endregion
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 9/10/2012 1:51 PM
# Generated By: bjaudon
########################################################################
#region Generated Form Objects
$frmGetChecksum = New-Object System.Windows.Forms.Form
$lblComputing = New-Object System.Windows.Forms.Label
$btnCompute = New-Object System.Windows.Forms.Button
$btnExit = New-Object System.Windows.Forms.Button
$gbCommandOutput = New-Object System.Windows.Forms.GroupBox
$rtbCommandOutput = New-Object System.Windows.Forms.RichTextBox
$lblMatchHash = New-Object System.Windows.Forms.Label
$tbMatchHash = New-Object System.Windows.Forms.TextBox
$gbAlgorithms = New-Object System.Windows.Forms.GroupBox
$rbRIPEMD160 = New-Object System.Windows.Forms.RadioButton
$rbSHA512 = New-Object System.Windows.Forms.RadioButton
$rbSHA384 = New-Object System.Windows.Forms.RadioButton
$rbSHA256 = New-Object System.Windows.Forms.RadioButton
$rbSHA1 = New-Object System.Windows.Forms.RadioButton
$rbMD5 = New-Object System.Windows.Forms.RadioButton
$btnBrowse = New-Object System.Windows.Forms.Button
$tbSourceFile = New-Object System.Windows.Forms.TextBox
$lblSourceFile = New-Object System.Windows.Forms.Label
$lblVersion = New-Object System.Windows.Forms.Label
$openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog
$pbIcon = New-Object System.Windows.Forms.PictureBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$btnCompute_OnClick=
{
if ($rbMD5.Checked) { $HashAlgorithm="MD5" }
elseif ($rbSHA1.Checked) { $HashAlgorithm="SHA1" }
elseif ($rbSHA256.Checked) { $HashAlgorithm="SHA256" }
elseif ($rbSHA384.Checked) { $HashAlgorithm="SHA384" }
elseif ($rbSHA512.Checked) { $HashAlgorithm="SHA512" }
elseif ($rbRIPEMD160.Checked) { $HashAlgorithm="RIPEMD160" }
else { $HashAlgorithm="MD5" }
$SplatParameter=@{
"FileName"=$tbSourceFile.Text
"HashAlgorithm"=$HashAlgorithm
"MatchHash"=$tbMatchHash.Text
}
DisableButtons
Start-Sleep -Milliseconds .25
try { $Output=Get-Checksum @SplatParameter }
catch { [System.Windows.Forms.MessageBox]::Show($Error[1],"Get-Checksum GUI","OK","Error");EnableButtons;Return }
$FontBold = new-object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Bold' )
$fontNormal = new-object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Regular')
$rtbCommandOutput.Font = $fontNormal
$rtbCommandOutput.DetectUrls = $False
$outputmembers = $output | Get-Member | Where-Object {$_.MemberType -eq "NoteProperty"} | Select Name
$outputmembers | foreach {
$rtbCommandOutput.SelectionFont = $FontBold
$rtbCommandOutput.AppendText("$($_.Name)`t")
if ($_.Name -eq "Length") { $rtbCommandOutput.AppendText("`t") }
$rtbCommandOutput.SelectionFont = $fontNormal
$rtbCommandOutput.AppendText(" : $($output.($_.Name))")
if ($_.Name -eq "Length") { $rtbCommandOutput.AppendText(" bytes") }
$rtbCommandOutput.AppendText("`n")
}
for ($i=231;$i -le 393; $i++) {
$System_Drawing_Size.Height = $i
$System_Drawing_Size.Width = 585
$frmGetChecksum.ClientSize = $System_Drawing_Size
Start-Sleep -Milliseconds .1
}
EnableButtons
$btnBrowse.Focus()
}
$btnBrowse_OnClick=
{
#TODO: Place custom script here
$tbSourceFile.Text=OpenFile-Dialog
if ($tbSourceFile.Text -eq "") { $btnCompute.Enabled = $false }
else { $btnCompute.Enabled = $True }
}
$OnLoadForm_StateCorrection=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$frmGetChecksum.WindowState = $InitialFormWindowState
$btnBrowse.Focus()
}
#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 231
$System_Drawing_Size.Width = 585
$frmGetChecksum.ClientSize = $System_Drawing_Size
$frmGetChecksum.DataBindings.DefaultDataSourceUpdateMode = 0
$frmGetChecksum.FormBorderStyle = 1
$frmGetChecksum.MaximizeBox = $False
$frmGetChecksum.Name = "frmGetChecksum"
$frmGetChecksum.Text = "Get-Checksum GUI"
$frmGetChecksum.Icon = $icon
$frmGetChecksum.AllowDrop = $true #Parameter requires STA mode
$frmGetChecksum.Add_DragEnter({ProcessDragDrop($_)})
$pbIcon.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 13
$pbIcon.Location = $System_Drawing_Point
$pbIcon.Name = "pictureBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 32
$System_Drawing_Size.Width = 32
$pbIcon.Size = $System_Drawing_Size
$pbIcon.TabIndex = 0
$pbIcon.TabStop = $False
$pbIcon.Image = $icon
$frmGetChecksum.Controls.Add($pbIcon)
$lblComputing.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 19
$System_Drawing_Point.Y = 197
$lblComputing.Location = $System_Drawing_Point
$lblComputing.Name = "lblComputing"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 157
$lblComputing.Size = $System_Drawing_Size
$lblComputing.TabIndex = 10
$lblComputing.Text = "Computing, Please Wait..."
$lblComputing.Visible = $false
$lblComputing.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0)
$lblComputing.ForeColor = [System.Drawing.Color]::FromArgb(255,255,0,0)
$frmGetChecksum.Controls.Add($lblComputing)
$btnCompute.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 415
$System_Drawing_Point.Y = 197
$btnCompute.Location = $System_Drawing_Point
$btnCompute.Name = "btnCompute"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$btnCompute.Size = $System_Drawing_Size
$btnCompute.TabIndex = 10
$btnCompute.Text = "&Compute"
$btnCompute.UseVisualStyleBackColor = $True
$btnCompute.Enabled = $false
$btnCompute.add_Click($btnCompute_OnClick)
$btnCompute.FlatStyle = 0
$frmGetChecksum.Controls.Add($btnCompute)
$btnExit.DataBindings.DefaultDataSourceUpdateMode = 0
$btnExit.DialogResult = 2
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 496
$System_Drawing_Point.Y = 197
$btnExit.Location = $System_Drawing_Point
$btnExit.Name = "btnExit"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$btnExit.Size = $System_Drawing_Size
$btnExit.TabIndex = 11
$btnExit.Text = "E&xit"
$btnExit.UseVisualStyleBackColor = $True
$btnExit.FlatStyle = 0
$frmGetChecksum.Controls.Add($btnExit)
$gbCommandOutput.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 226
$gbCommandOutput.Location = $System_Drawing_Point
$gbCommandOutput.Name = "gbCommandOutput"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 156
$System_Drawing_Size.Width = 558
$gbCommandOutput.Size = $System_Drawing_Size
$gbCommandOutput.TabIndex = 99
$gbCommandOutput.TabStop = $False
$gbCommandOutput.Text = "Command Output"
$gbCommandOutput.Visible = $False
$frmGetChecksum.Controls.Add($gbCommandOutput)
$rtbCommandOutput.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 9
$System_Drawing_Point.Y = 20
$rtbCommandOutput.Location = $System_Drawing_Point
$rtbCommandOutput.Name = "rtbCommandOutput"
$rtbCommandOutput.ReadOnly = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 125
$System_Drawing_Size.Width = 539
$rtbCommandOutput.Size = $System_Drawing_Size
$rtbCommandOutput.TabIndex = 100
$rtbCommandOutput.Text = ""
$rtbCommandOutput.TabStop = $False
$rtbCommandOutput.BorderStyle = 0
$gbCommandOutput.Controls.Add($rtbCommandOutput)
$lblMatchHash.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 165
$lblMatchHash.Location = $System_Drawing_Point
$lblMatchHash.Name = "lblMatchHash"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 80
$lblMatchHash.Size = $System_Drawing_Size
$lblMatchHash.TabIndex = 99
$lblMatchHash.Text = "Match Hash:"
$lblMatchHash.add_Click($handler_label3_Click)
$frmGetChecksum.Controls.Add($lblMatchHash)
$tbMatchHash.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 96
$System_Drawing_Point.Y = 163
$tbMatchHash.Location = $System_Drawing_Point
$tbMatchHash.Name = "tbMatchHash"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 475
$tbMatchHash.Size = $System_Drawing_Size
$tbMatchHash.TabIndex = 8
$tbMatchHash.BorderStyle = 1
$frmGetChecksum.Controls.Add($tbMatchHash)
$gbAlgorithms.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 96
$gbAlgorithms.Location = $System_Drawing_Point
$gbAlgorithms.Name = "gbAlgorithms"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 56
$System_Drawing_Size.Width = 558
$gbAlgorithms.Size = $System_Drawing_Size
$gbAlgorithms.TabIndex = 2
$gbAlgorithms.TabStop = $False
$gbAlgorithms.Text = "Hash Algorithms"
$frmGetChecksum.Controls.Add($gbAlgorithms)
$rbRIPEMD160.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 412
$System_Drawing_Point.Y = 20
$rbRIPEMD160.Location = $System_Drawing_Point
$rbRIPEMD160.Name = "rbRIPEMD160"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 104
$rbRIPEMD160.Size = $System_Drawing_Size
$rbRIPEMD160.TabIndex = 7
$rbRIPEMD160.TabStop = $True
$rbRIPEMD160.Text = "&RIPEMD160"
$rbRIPEMD160.UseVisualStyleBackColor = $True
$rbRIPEMD160.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbRIPEMD160)
$rbSHA512.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 329
$System_Drawing_Point.Y = 20
$rbSHA512.Location = $System_Drawing_Point
$rbSHA512.Name = "rbSHA512"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 72
$rbSHA512.Size = $System_Drawing_Size
$rbSHA512.TabIndex = 6
$rbSHA512.TabStop = $True
$rbSHA512.Text = "SHA&512"
$rbSHA512.UseVisualStyleBackColor = $True
$rbSHA512.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbSHA512)
$rbSHA384.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 247
$System_Drawing_Point.Y = 20
$rbSHA384.Location = $System_Drawing_Point
$rbSHA384.Name = "rbSHA384"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 76
$rbSHA384.Size = $System_Drawing_Size
$rbSHA384.TabIndex = 5
$rbSHA384.TabStop = $True
$rbSHA384.Text = "SHA&384"
$rbSHA384.UseVisualStyleBackColor = $True
$rbSHA384.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbSHA384)
$rbSHA256.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 169
$System_Drawing_Point.Y = 20
$rbSHA256.Location = $System_Drawing_Point
$rbSHA256.Name = "rbSHA256"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 72
$rbSHA256.Size = $System_Drawing_Size
$rbSHA256.TabIndex = 4
$rbSHA256.TabStop = $True
$rbSHA256.Text = "SHA&256"
$rbSHA256.UseVisualStyleBackColor = $True
$rbSHA256.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbSHA256)
$rbSHA1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 99
$System_Drawing_Point.Y = 20
$rbSHA1.Location = $System_Drawing_Point
$rbSHA1.Name = "rbSHA1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 64
$rbSHA1.Size = $System_Drawing_Size
$rbSHA1.TabIndex = 3
$rbSHA1.TabStop = $True
$rbSHA1.Text = "SHA&1"
$rbSHA1.UseVisualStyleBackColor = $True
$rbSHA1.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbSHA1)
$rbMD5.Checked = $True
$rbMD5.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 36
$System_Drawing_Point.Y = 20
$rbMD5.Location = $System_Drawing_Point
$rbMD5.Name = "rbMD5"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 57
$rbMD5.Size = $System_Drawing_Size
$rbMD5.TabIndex = 2
$rbMD5.TabStop = $True
$rbMD5.Text = "M&D5"
$rbMD5.UseVisualStyleBackColor = $True
$rbMD5.FlatStyle = 1
$gbAlgorithms.Controls.Add($rbMD5)
$btnBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 496
$System_Drawing_Point.Y = 65
$btnBrowse.Location = $System_Drawing_Point
$btnBrowse.Name = "btnBrowse"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$btnBrowse.Size = $System_Drawing_Size
$btnBrowse.TabIndex = 1
$btnBrowse.Text = "&Browse..."
$btnBrowse.UseVisualStyleBackColor = $True
$btnBrowse.add_Click($btnBrowse_OnClick)
$btnBrowse.FlatStyle = 0
$frmGetChecksum.Controls.Add($btnBrowse)
$tbSourceFile.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 96
$System_Drawing_Point.Y = 67
$tbSourceFile.Location = $System_Drawing_Point
$tbSourceFile.Name = "tbSourceFile"
$tbSourceFile.ReadOnly = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 394
$tbSourceFile.Size = $System_Drawing_Size
$tbSourceFile.TabIndex = 99
$tbSourceFile.TabStop = $False
$tbSourceFile.BorderStyle = 1
$tbSourceFile.AccessibleDescription
$frmGetChecksum.Controls.Add($tbSourceFile)
$lblSourceFile.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 67
$lblSourceFile.Location = $System_Drawing_Point
$lblSourceFile.Name = "lblSourceFile"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 77
$lblSourceFile.Size = $System_Drawing_Size
$lblSourceFile.TabIndex = 1
$lblSourceFile.Text = "Source File:"
$lblSourceFile.add_Click($handler_label2_Click)
$frmGetChecksum.Controls.Add($lblSourceFile)
$lblVersion.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 50
$System_Drawing_Point.Y = 20
$lblVersion.Location = $System_Drawing_Point
$lblVersion.Name = "lblVersion"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 500
$lblVersion.Size = $System_Drawing_Size
$lblVersion.TabIndex = 0
$lblVersion.Text = "PowerShell Get-Checksum GUI v.$scriptversion"
$lblVersion.Font = New-Object System.Drawing.Font("Trebuchet MS",9,1,3,0)
$frmGetChecksum.Controls.Add($lblVersion)
$openFileDialog1.DefaultExt = "*.*"
$openFileDialog1.Filter = "All Files (*.*)|*.*"
$openFileDialog1.Title = "Get-Checksum: Select File"
$openFileDialog1.ShowHelp = $True
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $frmGetChecksum.WindowState
#Init the OnLoad event to correct the initial state of the form
$frmGetChecksum.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$frmGetChecksum.ShowDialog()| Out-Null
} #End Function
function DisableButtons {
$System_Drawing_Size.Height = 231
$System_Drawing_Size.Width = 585
$frmGetChecksum.ClientSize = $System_Drawing_Size
$rtbCommandOutput.Text=$null
$rtbCommandOutput.Visible = $false
$gbCommandOutput.Visible = $false
$lblComputing.Visible = $True
$lblComputing.Update()
$lblMatchHash.Enabled = $False
$lblMatchHash.Update()
$tbMatchHash.Enabled = $False
$tbMatchHash.Update()
$btnBrowse.Enabled = $False
$btnBrowse.Update()
$lblSourceFile.Enabled = $False
$lblSourceFile.Update()
$tbSourceFile.Enabled = $False
$tbSourceFile.Update()
$btnExit.Enabled = $False
$btnExit.Update()
$btnCompute.Enabled = $False
$btnCompute.Update()
$gbAlgorithms.Enabled = $False
$gbAlgorithms.Update()
$rbMD5.Enabled = $False
$rbMD5.Update()
$rbSHA1.Enabled = $False
$rbSHA1.Update()
$rbSHA256.Enabled = $False
$rbSHA256.Update()
$rbSHA384.Enabled = $False
$rbSHA384.Update()
$rbSHA512.Enabled = $False
$rbSHA512.Update()
$rbRIPEMD160.Enabled = $False
$rbRIPEMD160.Update()
}
Function EnableButtons {
$lblComputing.Visible = $False
$lblComputing.Update()
$lblMatchHash.Enabled = $True
$lblMatchHash.Update()
$tbMatchHash.Enabled = $True
$tbMatchHash.Update()
$btnBrowse.Enabled = $True
$btnBrowse.Update()
$lblSourceFile.Enabled = $True
$lblSourceFile.Update()
$tbSourceFile.Enabled = $True
$tbSourceFile.Update()
$btnExit.Enabled = $True
$btnExit.Update()
$btnCompute.Enabled = $True
$btnCompute.Update()
$gbAlgorithms.Enabled = $True
$gbAlgorithms.Update()
$rbMD5.Enabled = $True
$rbMD5.Update()
$rbSHA1.Enabled = $True
$rbSHA1.Update()
$rbSHA256.Enabled = $True
$rbSHA256.Update()
$rbSHA384.Enabled = $True
$rbSHA384.Update()
$rbSHA512.Enabled = $True
$rbSHA512.Update()
$rbRIPEMD160.Enabled = $True
$rbRIPEMD160.Update()
$rtbCommandOutput.Visible = $true
$gbCommandOutput.Visible = $true
}
Function OpenFile-Dialog {
$open=$OpenFileDialog1.ShowDialog()
#If the Open button is pressed
if ($open -eq "OK") {
#Set our source to the chosen file
return $OpenFileDialog1.FileName
}
#If cancel is pressed
else { return }
}
Function Get-Checksum {
[CmdletBinding()]
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0,ValueFromPipelineByPropertyName=$true)]
[alias("FullName","Name")]
[string]$FileName,
[parameter(Mandatory=$false,ValueFromPipeline=$true,Position=1,ValueFromPipelineByPropertyName=$true)]
[ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160")]
[string]$HashAlgorithm="MD5",
[parameter(Mandatory=$false,ValueFromPipeline=$false,Position=2,ValueFromPipelineByPropertyName=$false)]
[string]$MatchHash
)
if (!(Test-Path -Path $FileName)) { throw "Cannot find path '$FileName' because it does not exist." }
if (Test-Path -Path $FileName -PathType Container) { throw "The object specified in the FileName parameter is a directory. Please specify a path to a file.";break }
function Process-CryptoChecksum {
Param(
[string]$file,
[string]$Crypto
)
switch ($Crypto) {
MD5 { $crypto_provider = new-object 'System.Security.Cryptography.MD5CryptoServiceProvider' }
SHA1 { $crypto_provider = new-object 'System.Security.Cryptography.SHA1Managed' }
SHA256 { $crypto_provider = new-object 'System.Security.Cryptography.SHA256Managed' }
SHA384 { $crypto_provider = new-object 'System.Security.Cryptography.SHA384Managed' }
SHA512 { $crypto_provider = new-object 'System.Security.Cryptography.SHA512Managed' }
RIPEMD160 { $crypto_provider = new-object 'System.Security.Cryptography.RIPEMD160Managed' }
}
$file_info=get-item $file -Force
trap { break }
$stream=$file_info.OpenRead()
if ($? -eq $false) { return $null }
$fileleaf=Split-Path -Path $file -Leaf
$bytes= $crypto_provider.ComputeHash($stream)
$checksum=""
foreach ($byte in $bytes) {
$checksum+=$byte.ToString('x2')
}
$stream.close() | out-null
return $checksum
}
function Compare-Hash {
param(
[string]$string1,
[string]$string2
)
if ($String1 -eq $String2) { return [bool]$True }
else { return [bool]$False }
}
$CheckSumvalue=New-Object System.Object
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name FileName -Value (Resolve-Path $FileName | Select -ExpandProperty ProviderPath)
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name HashAlgorithm -Value $HashAlgorithm.ToUpper()
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name Checksum -Value (Process-CryptoChecksum -file $FileName -Crypto $HashAlgorithm).ToUpper()
if ($MatchHash) { Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name MatchHash -Value (Compare-Hash $MatchHash $CheckSumvalue.Checksum) }
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name Length -Value (Get-Item $FileName -force | Select -Expand Length)
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name CreationTime -Value (get-date -Format G (Get-Item $FileName -force | Select -Expand CreationTime))
Add-Member -Force -InputObject $CheckSumvalue -MemberType NoteProperty -Name Timestamp -Value (get-date -Format G)
return $CheckSumvalue
}
function ProcessDragDrop ( $object ){
$file=$object.Data.GetFileDropList()
if (-NOT ((Get-ItemProperty $file[0]).Attributes -match "Directory")) {
$tbSourceFile.Text = $file[0]
$btnCompute.Enabled = $true
}
}
#Call the Main Functions
GenerateForm
|
PowerShellCorpus/PoshCode/Get-WmiClassKeyProperty..ps1
|
Get-WmiClassKeyProperty..ps1
|
##############################################################################\n##\n## Get-WmiClassKeyProperty\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\nGet all of the properties that you may use in a WMI filter for a given class.\n\n.EXAMPLE\n\nGet-WmiClassKeyProperty Win32_Process\nHandle\n\n#>\n\nparam(\n ## The WMI class to examine\n [WmiClass] $WmiClass\n)\n\nSet-StrictMode -Version Latest\n\n## WMI classes have properties\nforeach($currentProperty in $wmiClass.Properties)\n{\n ## WMI properties have qualifiers to explain more about them\n foreach($qualifier in $currentProperty.Qualifiers)\n {\n ## If it has a 'Key' qualifier, then you may use it in a filter\n if($qualifier.Name -eq "Key")\n {\n $currentProperty.Name\n }\n }\n}
|
PowerShellCorpus/PoshCode/Compile-Help.ps1
|
Compile-Help.ps1
|
# Compile-Help.ps1
# by Jeff Hillman
#
# this script uses the text and XML PowerShell help files to generate HTML help
# for all PowerShell Cmdlets, PSProviders, and "about" topics. the help topics
# are compiled into a .chm file using HTML Help Workshop.
param( [string] $outDirectory = ".\\PSHelp", [switch] $GroupByPSSnapIn )
function Html-Encode( [string] $value )
{
# System.Web.HttpUtility.HtmlEncode() doesn't quite get everything, and
# I don't want to load the System.Web assembly just for this. I'm sure
# I missed something here, but these are the characters I saw that needed
# to be encoded most often
$value = $value -replace "&(?![\\w#]+;)", "&"
$value = $value -replace "<(?!!--)", "<"
$value = $value -replace "(?<!--)>", ">"
$value = $value -replace "’", "'"
$value = $value -replace '["“”]', """
$value = $value -replace "\\n", "<br />"
$value
}
function Capitalize-Words( [string] $value )
{
$capitalizedString = ""
# convert the string to lower case and split it into individual words. for each one,
# capitalize the first character, and append it to the converted string
[regex]::Split( $value.ToLower(), "\\s" ) | ForEach-Object {
$capitalizedString += ( [string]$_.Chars( 0 ) ).ToUpper() + $_.SubString( 1 ) + " "
}
$capitalizedString.Trim()
}
function Get-ParagraphedHtml( [string] $xmlText )
{
$value = ""
if ( $xmlText -match "<(\\w+:)?para" )
{
$value = ""
$options = [System.Text.RegularExpressions.RegexOptions]::Singleline
foreach ( $match in [regex]::Matches( $xmlText,
"<(?:\\w+:)?para[^>]*>(?<Text>.*?)</(?:\\w+:)?para>", $options ) )
{
$value += "<p>$( Html-Encode $match.Groups[ 'Text' ].Value )</p>"
}
}
else
{
$value = Html-Encode $xmlText
}
$value
}
function Get-SyntaxHtml( [xml] $syntaxXml )
{
$syntaxHtml = ""
# generate the HTML for each form of the Cmdlet syntax
foreach ( $syntaxItem in $syntaxXml.syntax.syntaxItem )
{
if ( $syntaxHtml -ne "" )
{
$syntaxHtml += "<br /><br />`n"
}
$syntaxHtml += " $( $syntaxItem.name.get_InnerText().Trim() ) "
if ( $syntaxItem.parameter )
{
foreach ( $parameter in $syntaxItem.parameter )
{
$required = [bool]::Parse( $parameter.required )
$syntaxHtml += "<nobr>[-$( $parameter.name.get_InnerText().Trim() )"
if ( $required )
{
$syntaxHtml += "]"
}
if ( $parameter.parameterValue )
{
$syntaxHtml +=
" <$( $parameter.parameterValue.get_InnerText().Trim() )>"
}
if ( !$required )
{
$syntaxHtml += "]"
}
$syntaxHtml += "</nobr> "
}
}
$syntaxHtml += " <nobr>[<CommonParameters>]</nobr>"
}
$syntaxHtml.Trim()
}
function Get-ParameterHtml( [xml] $parameterXml )
{
$parameterHtml = ""
# generate HTML for each parameter
foreach ( $parameter in $parameterXml.parameters.parameter )
{
if ( $parameterHtml -ne "" )
{
$parameterHtml += " <br /><br />`n"
}
$parameterHtml +=
" <nobr><span class=`"boldtext`">-$( $parameter.name.get_InnerText().Trim() )"
if ( $parameter.parameterValue )
{
$parameterHtml += " <$( $parameter.parameterValue.get_InnerText().Trim() )>"
}
$parameterHtml += "</span></nobr>`n"
$parameterHtml += @"
<br />
<div id="contenttext">
$( Get-ParagraphedHtml $parameter.description.get_InnerXml().Trim() )
"@
if ( $parameter.possibleValues )
{
foreach ( $possibleValue in $parameter.possibleValues.possibleValue )
{
$parameterHtml += @"
$( $possibleValue.value.Trim() )<br />
"@
if ( $possibleValue.description.get_InnerText().Trim() -ne "" )
{
$parameterHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() )
</div>
"@
}
}
}
$parameterHtml += @"
<br />
</div>
<table class="parametertable">
<tr>
<td>Required</td>
<td>$( $parameter.required )</td>
</tr>
<tr>
<td>Position</td>
<td>$( $parameter.position )</td>
</tr>
<tr>
<td>Accepts pipeline input</td>
<td>$( $parameter.pipelineInput )</td>
</tr>
<tr>
<td>Accepts wildcard characters</td>
<td>$( $parameter.globbing )</td>
</tr>
"@
if ( $parameter.defaultValue )
{
if( $parameter.defaultValue.get_InnerText().Trim() -ne "" )
{
$parameterHtml += @"
<tr>
<td>Default Value</td>
<td>$( $parameter.defaultValue.get_InnerText().Trim() )</td>
</tr>
"@
}
}
$parameterHtml += @"
</table>
"@
}
if ( $parameterHtml -ne "" )
{
$parameterHtml += " <br /><br />`n"
}
$parameterHtml += @"
<nobr><span class="boldtext"><CommonParameters></span></nobr>
<br />
<div id="contenttext">
<p>
For more information about common parameters, type "Get-Help about_commonparameters".
</p>
</div>
"@
$parameterHtml.Trim()
}
function Get-InputHtml( [xml] $inputXml )
{
$inputHtml = ""
$inputCount = 0
# generate HTML for each input type
foreach ( $inputType in $inputXml.inputTypes.inputType )
{
if ( $inputHtml -ne "" )
{
$inputHtml += " <br /><br />`n"
}
if ( $inputType.type.name.get_InnerText().Trim() -ne "" -or
$inputType.type.description.get_InnerText().Trim() -ne "" )
{
$inputHtml += " $( $inputType.type.name.get_InnerText().Trim() )`n"
$inputHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $inputType.type.description.get_InnerXml().Trim() )
</div>
"@
$inputCount++
}
}
$inputHtml.Trim()
$inputCount
}
function Get-ReturnHtml( [xml] $returnXml )
{
$returnHtml = ""
$returnCount = 0
# generate HTML for each return value
foreach ( $returnValue in $returnXml.returnValues.returnValue )
{
if ( $returnHtml -ne "" )
{
$returnHtml += " <br /><br />`n"
}
if ( $returnValue.type.name.get_InnerText().Trim() -ne "" -or
$returnValue.type.description.get_InnerText().Trim() -ne "" )
{
$returnHtml += " $( $returnValue.type.name.get_InnerText().Trim() )`n"
$returnHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $returnValue.type.description.get_InnerXml().Trim() )
</div>
"@
$returnCount++
}
}
$returnHtml.Trim()
$returnCount
}
function Get-ExampleHtml( [xml] $exampleXml )
{
$exampleHtml = ""
$exampleTotalCount = 0
$exampleCount = 0
foreach ( $example in $exampleXml.examples.example )
{
$exampleTotalCount++
}
# generate HTML for each example
foreach ( $example in $exampleXml.examples.example )
{
if ( $example.code -and $example.code.get_InnerText().Trim() -ne "" )
{
if ( $exampleHtml -ne "" )
{
$exampleHtml += " <br />`n"
}
if ( $exampleTotalCount -gt 1 )
{
$exampleHtml +=
" <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n"
}
$exampleCodeHtml = "$( Html-Encode $example.introduction.get_InnerText().Trim() )" +
"$( Html-Encode $example.code.get_InnerText().Trim() )"
$exampleHtml += " <div class=`"syntaxregion`">$exampleCodeHtml</div>`n"
$foundFirstPara = $false
foreach ( $para in $example.remarks.para )
{
if ( $para.get_InnerText().Trim() -ne "" )
{
# the first para is generally the description of the example.
# other para tags usually contain sample output
if ( !$foundFirstPara )
{
$exampleHtml += @"
<div id="contenttext">
<p>
$( Html-Encode $para.get_InnerText().Trim() )
</p>
</div>
"@
$foundFirstPara = $true
}
else
{
$exampleHtml += @"
<pre class="syntaxregion">$( $( ( Html-Encode $para.get_InnerText().Trim() ) -replace "<br />", "`n" ) )</pre>
"@
}
}
}
$exampleCount++
}
}
$exampleHtml.Trim()
$exampleCount
}
function Get-TaskExampleHtml( [xml] $exampleXml )
{
$exampleHtml = ""
$exampleCount = 0
$exampleTotalCount = 0
foreach ( $example in $exampleXml.examples.example )
{
$exampleTotalCount++
}
# generate HTML for each example
foreach ( $example in $exampleXml.examples.example )
{
if ( $exampleHtml -ne "" )
{
$exampleHtml += " <br />`n"
}
if ( $exampleTotalCount -gt 1 )
{
$exampleHtml += " <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n"
}
$exampleHtml += " <div>$( Get-ParagraphedHtml $example.introduction.get_InnerXml().Trim() )</div>`n"
$exampleCodeHtml = ( Html-Encode $example.code.Trim() ) -replace "<br />", "`n"
$exampleHtml += " <pre class=`"syntaxregion`">$exampleCodeHtml</pre>"
$exampleHtml += " <div>$( Get-ParagraphedHtml $example.remarks.get_InnerXml().Trim() )</div>`n"
$exampleCount++
}
$exampleHtml.Trim()
}
function Get-LinkHtml( [xml] $linkXml )
{
$linkHtml = ""
$linkCount = 0
# generate HTML for each related link
foreach ( $navigationLink in $linkXml.relatedLinks.navigationLink )
{
if ( $navigationLink.linkText -and `
( $helpHash.Keys | Foreach-Object { $_.ToUpper() } ) -contains $navigationLink.linkText.Trim().ToUpper() )
{
$linkHtml += " $( $navigationLink.linkText.Trim() )<br />`n"
$linkCount++
}
}
$linkHtml.Trim()
$linkCount
}
function Get-TaskHtml( [xml] $taskXml )
{
$taskHtml = ""
$taskCount = 0
foreach ( $task in $taskXml.tasks.task )
{
if ( $taskHtml -ne "" )
{
$taskHtml += " <br />`n"
}
$taskHtml += " <nobr><span class=`"boldtext`">Task:</span> $( $task.title.Trim() )</nobr>`n"
$taskDescriptionHtml = ( Get-ParagraphedHtml $task.description.get_InnerXml().Trim() )
$taskHtml += " <div id=`"contenttext`">$taskDescriptionHtml</div>`n"
# add the example sections
if ( $task.examples )
{
$taskHtml += @"
<div id="contenttext">
<p>
$( Get-TaskExampleHtml ( [xml]$task.examples.get_OuterXml() ) )
</p>
</div>
"@
}
$taskCount++
}
$taskHtml.Trim()
$taskCount
}
function Get-DynamicParameterHtml( [xml] $dynamicParameterXml )
{
$dynamicParameterHtml = ""
# generate HTML for each dynamic parameter
foreach ( $dynamicParameter in $dynamicParameterXml.dynamicparameters.dynamicparameter )
{
$dynamicParameterHtml += " <nobr><span class=`"boldtext`">-$( $dynamicParameter.name.Trim() )"
if ( $dynamicParameter.type )
{
$dynamicParameterHtml += " <$( $dynamicParameter.type.name.Trim() )>"
}
$dynamicParameterHtml += "</span></nobr>`n"
$dynamicParameterHtml += @"
<br />
<div id="contenttext">
<p>
$( Html-Encode $dynamicParameter.description.Trim() )
</p>
"@
if ( $dynamicParameter.possiblevalues )
{
foreach ( $possibleValue in $dynamicParameter.possiblevalues.possiblevalue )
{
$dynamicParameterHtml += @"
<div id="contenttext">
<span class=`"boldtext`">$( $possibleValue.value )</span>
<div id="contenttext">
$( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() )
</div>
</div>
"@
}
}
$dynamicParameterHtml += @"
<br />
<span class=`"boldtext`">Cmdlets Supported</span>
<div id="contenttext">
<p>
$( Html-Encode $dynamicParameter.cmdletsupported.Trim() )
</p>
</div>
</div>
<br />
"@
}
$dynamicParameterHtml.Trim()
}
function Write-AboutTopic( [string] $topicName, [string] $topicPath )
{
# just dump the contents of the about topic exactly as it is. the only changes needed
# are to encode the special HTML characters and add topic links
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() )</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() )
</div>
<pre>
$( ( Html-Encode ( [string]::Join( [Environment]::NewLine, ( Get-Content -Path $topicPath ) ) ) ) -replace "<br />" )
</pre>
</body>
</html>
"@
$topicHtml = Add-Links $topicName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$topicName.html" -Encoding Ascii -Input $topicHtml
}
function Write-ProviderTopic( [string] $providerFullName, [xml] $providerXml )
{
$providerName = $providerXml.providerhelp.Name.Trim()
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>$providerName Help</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
$providerName Provider
<div style="text-align: right; padding-right: 3px;">
$( $providerFullName -replace "^\\w+\\." )
</div>
</div>
<div class="categorytitle">Drives</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.drives.get_InnerXml().Trim() )
</div>
<div class="categorytitle">Synopsis</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.synopsis.Trim() )</p>
</div>
"@
$topicHtml += @"
<div class="categorytitle">Description</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.detaileddescription.get_InnerXml().Trim() )
</div>
"@
if ( $providerXml.providerhelp.capabilities.get_InnerText().Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Capabilities</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.capabilities.get_InnerXml().Trim() )
</div>
"@
}
$taskHtml, $taskCount = Get-TaskHtml( $providerXml.providerhelp.tasks.get_OuterXml() )
if ( $taskCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Task$( if ( $taskCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$taskHtml
</div>
"@
}
if ( $providerXml.providerhelp.dynamicparameters )
{
$topicHtml += @"
<div class="categorytitle">Dynamic Parameters</div>
<div id="contenttext">
$( Get-DynamicParameterHtml( $providerXml.providerhelp.dynamicparameters.get_OuterXml() ) )
</div>
"@
}
if ( $providerXml.providerhelp.notes.Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Notes</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.notes.Trim() )</p>
</div>
"@
}
$topicHtml += @"
<div class="categorytitle">Related Links</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.relatedlinks.Trim() )</p>
</div>
<br />
</body>
</html>
"@
$topicHtml = Add-Links $providerName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$providerFullName.html" -Encoding Ascii -Input $topicHtml
}
function Write-CmdletTopic( [string] $cmdletFullName, [xml] $cmdletXml )
{
$cmdletName = $cmdletXml.command.details.name.Trim()
# add the heading, syntax section, and description
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>$cmdletName Help</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
$cmdletName Cmdlet
<div style="text-align: right; padding-right: 3px;">
$( $cmdletFullName -replace "^\\w+-\\w+\\." )
</div>
</div>
<div class="categorytitle">Synopsis</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.details.description.get_InnerXml().Trim() )
</div>
<div class="categorytitle">Syntax</div>
<div id="contenttext">
<div class="syntaxregion">$( Get-SyntaxHtml ( [xml]$cmdletXml.command.syntax.get_OuterXml() ) )</div>
</div>
<div class="categorytitle">Description</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.description.get_InnerXml().Trim() )
</div>
"@
# add the parameters section
if ( $cmdletXml.command.parameters )
{
$topicHtml += @"
<div class="categorytitle">Parameters</div>
<div id="contenttext">
<p>
$( Get-ParameterHtml ( [xml]$cmdletXml.command.parameters.get_OuterXml() ) )
</p>
</div>
"@
}
else
{
$topicHtml += @"
<div class="categorytitle">Parameters</div>
<div id="contenttext">
<p>
<nobr><span class="boldtext"><CommonParameters></span></nobr><br />
<div id="contenttext">
<p>
For more information about common parameters, type "Get-Help about_commonparameters".
</p>
</div>
</p>
</div>
"@
}
# add the input types section
if ( $cmdletXml.command.inputTypes )
{
$inputHtml, $inputCount = Get-InputHtml ( [xml]$cmdletXml.command.inputTypes.get_OuterXml() )
if ( $inputCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Input Type$( if ( $inputCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$inputHtml
</div>
"@
}
}
# add the return values section
if ( $cmdletXml.command.returnValue )
{
$returnHtml, $returnCount = Get-ReturnHtml ( [xml]$cmdletXml.command.returnValues.get_OuterXml() )
if ( $returnCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Return Value$( if ( $returnCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$returnHtml
</div>
"@
}
}
# add the notes section
if ( $cmdletXml.command.alertSet )
{
if ( $cmdletXml.command.alertSet.get_InnerText().Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Notes</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.alertSet.get_InnerXml().Trim() )
</div>
"@
}
}
# add the example section
if ( $cmdletXml.command.examples )
{
$exampleHtml, $exampleCount = Get-ExampleHtml ( [xml]$cmdletXml.command.examples.get_OuterXml() )
if ( $exampleCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Example$( if ( $exampleCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
<p>
$exampleHtml
</p>
</div>
"@
}
}
# add the related links section
if ( $cmdletXml.command.relatedLinks )
{
$linkHtml, $linkCount = Get-LinkHtml ( [xml]$cmdletXml.command.relatedLinks.get_OuterXml() )
if ( $linkCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Related Link$( if ( $linkCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
<p>
$linkHtml
</p>
</div>
<br />
"@
}
else
{
$topicHtml += " <br />`n"
}
}
else
{
$topicHtml += " <br />`n"
}
$topicHtml += @"
</body>
</html>
"@
$topicHtml = Add-Links $cmdletName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$cmdletFullName.html" -Encoding Ascii -Input $topicHtml
}
function Add-Links( [string] $topicName, [string] $topicHtml )
{
# we only want to add links for Cmdlets and about topics
$helpHash.Keys | Where-Object { $_ -match "(^\\w+-\\w+|^about_)" } | Foreach-Object {
$searchText = $_
# keys representing Cmdlets are formatted like this:
# <Cmdlet Name>.<PSProvider name>
if ( $_ -match "^\\w+-\\w+" )
{
# we only want to search for the Cmdlet name
$searchText = $matches[ 0 ]
}
# if the search text isn't the topic being processed
if ( $searchText -ne $topicName )
{
$topicHtml = $topicHtml -replace "\\b($searchText)\\b", "<a href=`"Topics\\$_.html`"><nobr>`$1</nobr></a>"
}
}
$topicHtml
}
# file dumping functions
function Write-Hhp
{
# write the contents of the Html Help Project file
Out-File -FilePath "$outDirectory\\powershell.hhp" -Encoding Ascii -Input @"
[OPTIONS]
Binary TOC=Yes
Compatibility=1.1 or later
Compiled file=PowerShell.chm
Contents file=powershell.hhc
Default topic=Topics/default.html
Full-text search=Yes
Language=0x409 English (United States)
Title=PowerShell Help
[INFOTYPES]
"@
}
function Write-DefaultPage
{
$defaultHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>PowerShell Help</title>
</head>
<body style="margin: 5px 5px 5px 5px; color: #FFFFFF; background-color: #C86400;">
<h2>Windows PowerShell Help</h2>
<br />
This complied help manual contains the help for all of the built-in PowerShell Cmdlets
and PSProviders, as well as the help for any Cmdlets or PSProviders added through
Add-PSSnapin, if help for them is available. Also included are all of the "about" topics.
<br /><br />
To use this manual from the PowerShell command line, add the following function and
alias to your PowerShell profile:
<div id="contenttext">
<pre class="syntaxregion">function Get-CompiledHelp( [string] `$topic )
{
if ( `$topic )
{
# Get-Command will fail if the topic is a PSProvider or an "about" topic.
`$ErrorActionPreference = "SilentlyContinue"
# we don't want Get-Command to resolve to an application or a function
`$command = Get-Command `$topic | Where-Object { `$_.CommandType -match "Alias|Cmdlet" }
# if the topic is an alias or a Cmdlet, combine its name with
# its PSProvider to get the full name of the help file
if ( `$command -and `$command.CommandType -eq "Alias" )
{
`$topic = "`$( `$command.Definition ).`$( `$command.ReferencedCommand.PSSnapIn.Name )"
}
elseif ( `$command -and `$command.CommandType -eq "Cmdlet" )
{
`$topic = "`$( `$command.Name ).`$( `$command.PSSnapIn.Name )"
}
else
{
# check to see if we have a PSProvider
`$psProvider = Get-PSProvider `$topic
if ( `$psProvider )
{
`$topic = "`$( `$psProvider.Name ).`$( `$psProvider.PSSnapIn.Name )"
}
}
hh.exe "mk:@MSITStore:$( Resolve-Path "$outDirectory" )\\PowerShell.chm::/Topics/`$topic.html"
}
else
{
hh.exe "$( Resolve-Path "$outDirectory" )\\PowerShell.chm"
}
}
Set-Alias chelp Get-CompiledHelp</pre>
</div>
<br />
The path in the Get-CompliedHelp function corresponds to the location where this compiled
help manual was originally created. If this file is moved to another location, the path
in the function will need to be updated.
<br />
<br />
To view the help topic for Get-ChildItem, type the following:
<div id="contenttext">
<div class="syntaxregion">PS$ Get-CompiledHelp Get-ChildItem</div>
</div>
<br />
Because "ls" is an alias for Get-ChildItem, and "chelp" is an alias for Get-CompliedHelp, the following also works:
<div id="contenttext">
<div class="syntaxregion">PS$ chelp ls</div>
</div>
</body>
</html>
"@
$defaultHtml = Add-Links "" $defaultHtml
Out-File -FilePath "$outDirectory\\Topics\\default.html" -Encoding Ascii -Input $defaultHtml
}
function Write-Css
{
Out-File -FilePath "$outDirectory\\powershell.css" -Encoding Ascii -Input @"
body
{
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 70%;
width: 100%;
}
div#topicheading
{
position: relative;
left: 0px;
padding: 5px 0px 5px 10px;
border-bottom: 1px solid #999999;
color: #FFFFFF;
background-color: #C86400;
font-size: 110%;
font-weight: bold;
text-align: left;
}
div#topictitle
{
padding: 5px 5px 5px 5px;
color: #FFFFFF
font-size: 90%;
font-weight: normal;
}
div#contenttext
{
top: 0px;
padding: 0px 25px 0px 25px;
}
p { margin: 5px 0px 5px 0px; }
a:link { color: #0000FF; }
a:visited { color: #0000FF; }
a:hover { color: #3366FF; }
table.parametertable
{
margin-left: 25px;
font-size: 100%;
border-collapse:collapse
}
table.parametertable td
{
font-size: 100%;
border: solid #999999 1px;
padding: 0in 5.4pt 0in 5.4pt
}
pre.syntaxregion, div.syntaxregion
{
background: #DDDDDD;
padding: 4px 8px;
cursor: text;
margin-top: 1em;
margin-bottom: 1em;
margin-left: .6em;
color: #000000;
border-width: 1px;
border-style: solid;
border-color: #999999;
}
.categorytitle
{
padding-top: .8em;
font-size: 110%;
font-weight: bold;
text-align: left;
margin-left: 5px;
}
.boldtext { font-weight: bold; }
"@
}
### main ###
# create the topics directory
New-Item -Type Directory -Path "$outDirectory" -Force | Out-Null
New-Item -Type Directory -Path "$outDirectory\\Topics" -Force | Out-Null
"`nRetrieving help content...`n"
# initialize variables for HHC file
$hhcContentsHtml = ""
$cmdletCategoryHtml = ""
$cmdletCategoryHash = @{}
# help content hash
$helpHash = @{}
# get the Cmdlet help
Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object {
$psSnapInName = $_.Name
$helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile
# the culture needs to be added to the path on Vista
if ( !( Test-Path $helpFilePath ) )
{
$helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )"
}
if ( Test-Path $helpFilePath )
{
$helpXml = [xml]( Get-Content $helpFilePath )
$cmdletCategoryContents = ""
Get-Command -PSSnapIn $_ | Foreach-Object {
$commandName = $_.Name
$helpXml.helpitems.command | Where-Object {
$_.details.name -and $_.details.name.Trim() -imatch "\\b$commandName\\b"
} | Foreach-Object {
# add the Xml Help of the Cmdlet to the help hashtable
$helpHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $_.get_OuterXml()
$cmdletTopicItem = @"
<li><object type="text/sitemap">
<param name="Name" value="$commandName">
<param name="Local" value="Topics\\$( "{0}.{1}" -f $commandName, $psSnapInName ).html">
</object>
"@
if ( $GroupByPSSnapIn )
{
$cmdletCategoryContents += $cmdletTopicItem
}
else
{
# save the topics so they can be sorted properly and added to the HHC later
$cmdletCategoryHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $cmdletTopicItem
}
}
}
if ( $GroupByPSSnapIn )
{
# add a category in the HHC for this PSSnapIn and its Cmdlets
$cmdletCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$psSnapInName">
</object>
<ul>
$( $cmdletCategoryContents.Trim() )
</ul>
"@
}
}
}
# sort the Cmdlets so they are added to the HHC in a logical order
if ( !$GroupByPSSnapIn )
{
$cmdletCategoryHash.Keys | Sort-Object | Foreach-Object {
$cmdletCategoryHtml += $cmdletCategoryHash[ $_ ]
}
}
# add the Cmdlet category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="Cmdlet Help">
</object>
<ul>
$( $cmdletCategoryHtml.Trim() )
</ul>
"@
$providerCategoryHtml = ""
$providerCategoryHash = @{}
# get the PSProvider help
Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object {
$psSnapInName = $_.Name
$helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile
# the culture needs to be added to the path on Vista
if ( !( Test-Path $helpFilePath ) )
{
$helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )"
}
if ( Test-Path $helpFilePath )
{
$helpXml = [xml]( Get-Content $helpFilePath )
$providerCategoryContents = ""
Get-PSProvider | Where-Object { $_.PSSnapin.Name -eq $psSnapInName } | Foreach-Object {
$psProviderName = $_.Name
$helpXml.helpitems.providerhelp |
Where-Object { $_.name.Trim() -imatch "\\b$psProviderName\\b" } |
Foreach-Object {
$helpHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $_.get_OuterXml()
# add a category in the HHC for this PSProvider
$providerTopicItem = @"
<li><object type="text/sitemap">
<param name="Name" value="$psProviderName">
<param name="Local" value="Topics\\$( "{0}.{1}" -f $psProviderName, $psSnapInName ).html">
</object>
"@
if ( $GroupByPSSnapIn )
{
$providerCategoryContents += $providerTopicItem
}
else
{
# save the topics so they can be sorted properly and added to the HHC later
$providerCategoryHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $providerTopicItem
}
}
}
if ( $GroupByPSSnapIn -and $providerCategoryContents -ne "" )
{
# add a category in the HHC for this PSSnapIn and its Cmdlets
$providerCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$psSnapInName">
</object>
<ul>
$( $providerCategoryContents.Trim() )
</ul>
"@
}
}
}
# sort the PSProviders so they are added to the HHC in a logical order
if ( !$GroupByPSSnapIn )
{
$providerCategoryHash.Keys | Sort-Object | Foreach-Object {
$providerCategoryHtml += $providerCategoryHash[ $_ ]
}
}
# add the PSProvider category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="Provider Help">
</object>
<ul>
$( $providerCategoryHtml.Trim() )
</ul>
"@
# get the about topics
$about_TopicPaths = @()
$helpPath = ""
if ( Resolve-Path "$pshome\\about_*.txt" )
{
$helpPath = "$pshome"
}
elseif ( Resolve-Path "$pshome\\$( $Host.CurrentUICulture.Name )\\about_*.txt" )
{
$helpPath = "$pshome\\$( $Host.CurrentUICulture.Name )"
}
if ( Test-Path $helpPath )
{
$about_TopicPaths += Get-ChildItem "$helpPath\\about_*.txt"
}
# we SilentlyContinue with Get-ChildItem errors because the ModuleName
# for the built-in PSSnapins doesn't resolve to anything, since the assemblies
# are only in the GAC.
$about_TopicPaths += Get-PSSnapin | Foreach-Object {
( Get-ChildItem $_.ModuleName -ErrorAction "SilentlyContinue" ).DirectoryName
} | Foreach-Object {
Get-ChildItem "$_\\about_*.txt"
}
if ( $about_TopicPaths.Count -gt 0 )
{
$aboutCategoryHtml = ""
$about_TopicPaths | Sort-Object -Unique -Property @{ Expression = { $_.Name.ToUpper() } }| Foreach-Object {
# pull the topic name out of the file name
$name = ( $_.Name -replace "(.xml)?.help.txt", "`$1" )
# add the path of the topic to the help hashtable
$helpHash[ $name ] = $_.FullName
$topicName = Capitalize-Words ( $name -replace "(about)?_", " " ).Trim()
# add a category in the HHC for this about topic
$aboutCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$topicName">
<param name="Local" value="Topics\\$name.html">
</object>
"@
}
# add the About Topics category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="About Topics">
</object>
<ul>
$( $aboutCategoryHtml.Trim() )
</ul>
"@
}
# write the contents file
Out-File -FilePath "$outDirectory\\powershell.hhc" -Encoding Ascii -Input @"
<!doctype html public "-//ietf//dtd html//en">
<html>
<head>
<meta name="Generator" content="Microsoft® HTML Help Workshop 4.1">
<!-- Sitemap 1.0 -->
</head>
<body>
<object type="text/site properties">
<param name="Window Styles" value="0x800025">
</object>
<ul>
<li><object type="text/sitemap">
<param name="Name" value="PowerShell Help">
<param name="Local" value="Topics\\default.html">
</object>
$( $hhcContentsHtml.Trim() )
</ul>
</body>
</html>
"@
$helpHash.Keys | Sort-Object | Foreach-Object {
switch -regex ( $_ )
{
# about topic
"about_"
{
"Creating help for the $_ about topic..."
Write-AboutTopic $_ $helpHash[ $_ ]
}
# Verb-Noun: Cmdlet
"\\w+-\\w+"
{
"Creating help for the $( $_ -replace '(^\\w+-\\w+).*', '$1' ) Cmdlet..."
Write-CmdletTopic $_ $helpHash[ $_ ]
}
# PSProvider
default
{
"Creating help for the $( $_ -replace '(^\\w+).*', '$1' ) PSProvider..."
Write-ProviderTopic $_ $helpHash[ $_ ]
}
}
}
Write-DefaultPage
Write-Css
Write-Hhp
if ( Test-Path "C:\\Program Files\\HTML Help Workshop\\hhc.exe" )
{
# compile the help
"`nCompiling the help manual...`n"
Push-Location
Set-Location $outDirectory
& "C:\\Program Files\\HTML Help Workshop\\hhc.exe" powershell.hhp
Pop-Location
# open the help file
& "$outDirectory\\PowerShell.chm"
}
else
{
Write-Host -ForegroundColor Red @"
HTML Help Workshop is not installed, or it was not installed in its default
location of "C:\\Program Files\\HTML Help Workshop".
HTML Help Workshop is required to compile the help manual. It can be downloaded
free of charge from Microsoft:
http://www.microsoft.com/downloads/details.aspx?familyid=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en
If you do not want to install HTML Help Workshop on this machine, all of the
files necessary to compile the manual have been created here:
$( Resolve-Path $outDirectory )
Copy these files to a machine with HTML Help Workshop, and you can compile the
manual there, with the following command:
<HTML Help Workshop location>\\hhc.exe powershell.hhp
"@
}
|
PowerShellCorpus/PoshCode/Get-RemoteRegistryChildI.ps1
|
Get-RemoteRegistryChildI.ps1
|
##############################################################################\n##\n## Get-RemoteRegistryChildItem\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\nGet the list of subkeys below a given key on a remote computer.\n\n.EXAMPLE\n\nGet-RemoteRegistryChildItem LEE-DESK HKLM:\\Software\n\n#>\n\nparam(\n ## The computer that you wish to connect to\n [Parameter(Mandatory = $true)]\n $ComputerName,\n\n ## The path to the registry items to retrieve\n [Parameter(Mandatory = $true)]\n $Path\n)\n\nSet-StrictMode -Version Latest\n\n## Validate and extract out the registry key\nif($path -match "^HKLM:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "LocalMachine", $computername)\n}\nelseif($path -match "^HKCU:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "CurrentUser", $computername)\n}\nelse\n{\n Write-Error ("Please specify a fully-qualified registry path " +\n "(i.e.: HKLM:\\Software) of the registry key to open.")\n return\n}\n\n## Open the key\n$key = $baseKey.OpenSubKey($matches[1])\n\n## Retrieve all of its children\nforeach($subkeyName in $key.GetSubKeyNames())\n{\n ## Open the subkey\n $subkey = $key.OpenSubKey($subkeyName)\n\n ## Add information so that PowerShell displays this key like regular\n ## registry key\n $returnObject = [PsObject] $subKey\n $returnObject | Add-Member NoteProperty PsChildName $subkeyName\n $returnObject | Add-Member NoteProperty Property $subkey.GetValueNames()\n\n ## Output the key\n $returnObject\n\n ## Close the child key\n $subkey.Close()\n}\n\n## Close the key and base keys\n$key.Close()\n$baseKey.Close()
|
PowerShellCorpus/PoshCode/Watch-Expression.ps1
|
Watch-Expression.ps1
|
#############################################################################\n##\n## Watch-Expression\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\nUpdates your prompt to display the values of information you want to track.\n\n\n.EXAMPLE\n\nPS >Watch-Expression { (Get-History).Count }\n\nExpression Value\n---------- -----\n(Get-History).Count 3\n\nPS >Watch-Expression { $count }\n\nExpression Value\n---------- -----\n(Get-History).Count 4\n$count\n\nPS >$count = 100\n\nExpression Value\n---------- -----\n(Get-History).Count 5\n$count 100\n\nPS >Watch-Expression -Reset\nPS >\n\n#>\n\nparam(\n ## The expression to track\n [ScriptBlock] $ScriptBlock,\n\n ## Switch to no longer watch an expression\n [Switch] $Reset\n)\n\nSet-StrictMode -Version Latest\n\nif($Reset)\n{\n Set-Item function:\\prompt ([ScriptBlock]::Create($oldPrompt))\n\n Remove-Item variable:\\expressionWatch\n Remove-Item variable:\\oldPrompt\n\n return\n}\n\n## Create the variableWatch variable if it doesn't yet exist\nif(-not (Test-Path variable:\\expressionWatch))\n{\n $GLOBAL:expressionWatch = @()\n}\n\n## Add the current variable name to the watch list\n$GLOBAL:expressionWatch += $scriptBlock\n\n## Update the prompt to display the expression values,\n## if needed.\n$GLOBAL:oldPrompt = Get-Content function:\\prompt\nif($oldPrompt -notlike '*$expressionWatch*')\n{\n $newPrompt = @'\n $results = foreach($expression in $expressionWatch)\n {\n New-Object PSObject -Property @{\n Expression = $expression.ToString().Trim();\n Value = & $expression\n } | Select Expression,Value\n }\n Write-Host "`n"\n Write-Host ($results | Format-Table -Auto | Out-String).Trim()\n Write-Host "`n"\n\n'@\n\n $newPrompt += $oldPrompt\n\n Set-Item function:\\prompt ([ScriptBlock]::Create($newPrompt))\n}
|
PowerShellCorpus/PoshCode/VMware datastore graph.ps1
|
VMware datastore graph.ps1
|
if ((Test-Path REGISTRY::HKEY_CLASSES_ROOT\\OWC11.ChartSpace.11) -eq $False)
{
Write-Host "This script requires Office Web Components to run correctly, please install these from the following website: http://www.microsoft.com/downloads/details.aspx?FamilyId=7287252C-402E-4F72-97A5-E0FD290D4B76&displaylang=en"
exit
}
connect-VIServer yourserver
$Caption = "Datastore Usage %"
$categories = @()
$values = @()
$chart = new-object -com OWC11.ChartSpace.11
$chart.Clear()
$c = $chart.charts.Add(0)
$c.Type = 4
$c.HasTitle = "True"
$series = ([array] $chart.charts)[0].SeriesCollection.Add(0)
Get-datastore |Sort-Object FreeSpaceMB -Descending | foreach-object {
$capacitymb = $_.CapacityMB
$FreeSpaceMB = $_.FreeSpaceMB
$UsedSpace = $capacitymb - $freespacemb
$perc = $UsedSpace / $capacitymb * 100
$categories += $_.Name
$values += $perc * 1
}
$series.Caption = $Caption
$series.SetData(1, -1, $categories)
$series.SetData(2, -1, $values)
$filename = (resolve-path .).Path + "\\Chart.jpg"
$chart.ExportPicture($filename, "jpg", 800, 500)
invoke-item $filename
|
PowerShellCorpus/PoshCode/Import-VCBImage.ps1
|
Import-VCBImage.ps1
|
#
# import-VCBImage.ps1 : use the Converter to import a VCB created disk image into a datacenter
#
# Author: LucD
#
# History:
#
# v1.0 20/09/09 first version
#
$I2VImageDir = <directory where the VCB images are stored>
$I2VShare = <Sharename of the $I2VImageDir directory>
$tgtDatacenter = <Target-datacenter>
$I2Vuser = <account with access to the image directory and to the datacenter>
$I2Vpassword = <password of the $I2Vuser account>
$I2Vhost = <hostname where the images are stored>
$ConvProgDir = "$env:ProgramFiles (x86)\\VMware\\Infrastructure\\Converter Enterprise"
$ConvService = "vmware-converter"
$I2Vprog = "converter-tool.exe"
# Template XML file for Convertor job
$p2v = [xml]@"
<p2v version="2.2" xmlns="http://www.vmware.com/v2/sysimage/p2v" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vmware.com/v2/sysimage/p2v p2vJob.xsd" xsi:type="P2VJob">
<source>
<hostedSpec networkPassword="" networkUsername="" path=""/>
</source>
<dest>
<managedSpec datastore="" folder="" host="" resourcePool="" vmName="">
<creds host="" port="0" type="sessionId" username="" password="" />
</managedSpec>
</dest>
<importParams diskType="VMFS" preserveHWInfo="true" removeSystemRestore="false" targetProductVersion="PRODUCT_MANAGED">
<nicMappings/>
<diskLocations/>
</importParams>
<postProcessingParams/>
</p2v>
"@
# Function will start a DOS commmand and wait for it to finish
#
function Invoke-Cmd{
param($cmd, $arguments)
$global:StdOut = ""
$global:StdErr = ""
$pStart = new-object System.Diagnostics.ProcessStartInfo
$pStart.Filename = $cmd
$pStart.Arguments = $arguments
$pStart.UseShellExecute = $false
$pStart.ErrorDialog = $false
$pStart.CreateNoWindow = $True
$pStart.RedirectStandardOutput = $true
$pStart.RedirectStandardError = $true
$myProcess = [System.Diagnostics.Process]::Start($pStart)
$myOutput = $myProcess.StandardOutput
$myErrOutput = $myProcess.StandardError
$global:StdOut = $myOutput.ReadToEnd()
$global:StdErr = $myErrOutput.ReadToEnd()
$myProcess.WaitForExit()
$myProcess.ExitCode
}
# Function that builds the Converter XML file and launches the job
#
function Import-VCBImage{
param($vmName, $portgroup)
# Check if directory exists
if((Get-Item -path ($I2VImageDir + "\\*") | Where-Object {$_.Name -eq $vmName} | Measure-Object).Count -ne 1){
Write-Host "Snapshot directory not found for " $vmName
return
}
# Determine target VmHost and target Datastore based on largest free space on datastore
$selectESX = ""
$selectDS = ""
$selectFree = 0
Get-Datacenter $tgtDatacenter | Get-VMHost | % {
$tmpESX = $_.Name
$_ | Get-Datastore | % {
if($_.FreeSpaceMb -gt $selectFree){
$selectESX = $tmpESX
$selectDS = $_.Name
$selectFree = $_.FreeSpaceMb
}
}
}
# Check if sufficient free space on ESXi server
if(((Get-Item -path ($I2VImageDir + "\\" + $vmName + "\\*") | Measure-Object -property Length -sum).Sum / 1mb) -gt $selectFree){
Write-Host "Not enough free disk space on" $selectFree
return
}
# Find VMX file
$vmxName = (Get-Item -path ($I2VImageDir + "\\" + $vmName + "\\*") | Where-Object {$_.Name -like "*.vmx"}).Name
# Update fields in XML tree
$p2v.p2v.source.hostedSpec.path = "\\\\" + $I2Vhost + "\\" + $I2VShare + "\\" + $vmName + "\\" + $vmxName
$p2v.p2v.source.hostedSpec.networkUsername = $I2Vuser
$p2v.p2v.source.hostedSpec.networkPassword = $I2Vpassword
$p2v.p2v.dest.managedSpec.creds.username = $I2Vuser
$p2v.p2v.dest.managedSpec.creds.password = $I2Vpassword
$p2v.p2v.dest.managedSpec.datastore = $selectDS
$p2v.p2v.dest.managedSpec.host = $selectESX
$p2v.p2v.dest.managedSpec.folder = ""
$p2v.p2v.dest.managedSpec.resourcePool = ""
$V2VvmName = $vmName + "-" + $tgtDatacenter + "-" + (Get-Date -format yyyyMMdd-HHmmss)
$p2v.p2v.dest.managedSpec.vmName = $V2VvmName
$p2v.p2v.dest.managedSpec.creds.host = $I2Vhost
$p2v.p2v.dest.managedSpec.creds.username = $I2Vuser
$p2v.p2v.dest.managedSpec.creds.password = $I2Vpassword
# As a security measure the RDM machines are connected to the isolated network
$NIC = $p2v.CreateElement("nicMapping")
$network = $p2v.CreateAttribute("network")
$network.psbase.Value = $portgroup
$dummy = $NIC.SetAttributeNode($network)
$p2v.p2v.importParams["nicMappings"].AppendChild($NIC)
# Save the XML file
$XMLfile = $I2VImageDir + "\\" + "I2V-" + $vmName + ".xml"
$p2v.Save($XMLfile)
# Start Convertor service if it is not running.
if((Get-Service -name $ConvService).Status -eq "Stopped"){
Start-Service -name $ConvService
}
# Start the import
# ! parameters are case-sensitive ! (--vchost is not accepted, must be --vcHost) !
$myarg = "--vcHost " + $I2Vhost + " --jobExec " + $XMLfile + " --vcCred " + $I2Vuser + ":" + $I2Vpassword
$mycmd = $ConvProgDir + "\\" + $I2Vprog
$rc = Invoke-Cmd $mycmd $myarg
# Remove older DRM guest(s) (if present AND if V2V completed successfully)
if($rc -eq 0){
foreach($vm in (Get-Datacenter $tgtDatacenter | Get-VM ($vmName + "-" + $tgtDatacenter + "*") | where {$_.Name -ne $V2VvmName})){
$vm | Remove-VM - DeleteFromDisk:$true - Confirm:$false
}
}
}
# Sample call
# Import-VCBImage "PC1" "isolated"
|
PowerShellCorpus/PoshCode/345ba1e2-f03d-4a3c-b553-da7d433d2436.ps1
|
345ba1e2-f03d-4a3c-b553-da7d433d2436.ps1
|
Get-PSDrive -PSProvider FileSystem | foreach { $_.Root } | `
Get-ChildItem -Recurse -Include '*.ps1', '*.psm1', '*.ps1xml' | `
where { Select-String -Path $_ -SimpleMatch -Pattern `
'VMware.VimAutomation.Types.', `
'VMware.VimAutomation.Client20.', `
'[Datastore]' }
|
PowerShellCorpus/PoshCode/5566cee5-63c0-4a96-8ed6-c53a1f2237b2.ps1
|
5566cee5-63c0-4a96-8ed6-c53a1f2237b2.ps1
|
function KillDBConnections([string]$serverName, [string]$DBName)
{
$ConnectionString = "Data Source=$serverName;Initial Catalog=master;Integrated Security=SSPI"
$connection = New-Object System.Data.SqlClient.SqlConnection($ConnectionString);
$command = New-Object System.Data.SqlClient.SqlCommand;
$command.Connection = $connection;
$command.CommandType = [System.Data.CommandType]::Text;
$command.CommandText = "SELECT spid FROM master..sysprocesses WHERE dbid=db_id('$DBName')";
$connection.open();
$reader = $command.ExecuteReader();
$stringBuilder = New-Object System.Text.StringBuilder
while ($reader.Read())
{
$stringBuilder.AppendFormat("kill {0};", $reader.GetValue(0));
}
$reader.Close();
$command.CommandText = $stringBuilder.ToString();
if($command.CommandText)
{
$command.ExecuteNonQuery();
}
$connection.Dispose();
}
|
PowerShellCorpus/PoshCode/Get-Excuse.ps1
|
Get-Excuse.ps1
|
Function Get-Excuse {
<#
.Synopsis
Retrieves a BOFH excuse from Jeff Ballard's website (http://jeffballard.us/).
.Description
Uses System.Net.WebRequest to retrieve page content as a string from the predefined URL. By default,
Get-Excuse uses the system defined Proxy Server. Alternate proxy settings can be defined using the
optional parameters.
.Parameter ProxyServer
A proxy server for this connection, in the format http://proxyserver:port.
.Parameter Credential
Alternate credentials to use for the proxy server.
.Example
Get-Excuse -Proxy "http://1.2.3.4:8080"
Request an excuse using the specified proxy server.
#>
[CmdLetBinding()]
Param(
[ValidatePattern("https?://.+")]
[Uri]$ProxyServer,
[Management.Automation.PsCredential]$Credential
)
$WebRequest = [Net.WebRequest]::Create("http://pages.cs.wisc.edu/~ballard/bofh/bofhserver.pl")
# If a proxy is defined, overwrite the system defined proxy server
If ($ProxyServer) {
$WebProxy = New-Object Net.WebProxy
$WebProxy.Address = $ProxyServer
# If credentials are specified
If ($Credential) {
$WebProxy.Credentials = $Credential.GetNetworkCredential()
}
}
$Response = $WebRequest.GetResponse()
If ($Response.StatusCode -eq "OK") {
$ResponseStream = New-Object IO.StreamReader($Response.GetResponseStream(), "UTF8")
$Page = $ResponseStream.ReadToEnd()
$Page -Match '(?<=(<br><font size = "\\+2">)).+' | Out-Null
Return $Matches[0]
}
$Response.Close()
Return ""
}
$Excuse = Get-Excuse
If ($Excuse) {
$Predicate = Get-TransportRulePredicate FromMemberOf
$Predicate.Addresses = Get-DistributionGroup "address@domain.com"
$Action = Get-TransportRuleAction SetHeader
$Action.MessageHeader = "X-BOFH-Excuse"
$Action.HeaderValue = $Excuse
New-TransportRule -Name "BOFH Excuse" -Actions $Action -Comments "Includes the excuse of the day in an email header" `
-Conditions $Predicate -Enabled $True -WhatIf
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.