full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Function Run-Script_4.ps1
Function Run-Script_4.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. # The source directory of any script must always be the current '$pwd'. # V2.0 Use Try/Catch to trap (child) script errors & change Hotkey to F2. # v3.1 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" #Now grab any parameters entered from the command line... $parms = $psISE.CurrentPowerShellTab.CommandPane.Text $tag = "$startTime [$script] start. --> PSE $($myInvocation.Line) $pwd\\$script $parms" 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." 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) $pwd\\$script $parms" 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/New-Struct.ps1
New-Struct.ps1
## New-Struct ## Creates a Struct class and emits it into memory ## The Struct includes a constructor which takes the parameters in order... ## ## Usage: ## # Assuming you have a csv file with no header and columns: artist,name,length ## New-Struct Song @{ ## Artist=[string]; ## Name=[string]; ## Length=[TimeSpan]; ## } ## $songs = gc C:\\Scripts\\songlist.csv | % { new-object Song @($_ -split ",") } ## function New-Struct { param([string]$Name,[HashTable]$Properties) switch($Properties.Keys){{$_ -isnot [String]}{throw "Invalid Syntax"}} switch($Properties.Values){{$_ -isnot [type]}{throw "Invalid Syntax"}} # CODE GENERATION MAGIKS! $code = @" using System; public struct $Name { $($Properties.Keys | % { " public {0} {1};`n" -f $Properties[$_],($_.ToUpper()[0] + $_.SubString(1)) }) public $Name ($( ($Properties.Keys | % { "{0} {1}" -f $Properties[$_],($_.ToLower()) }) -join ", " )) { $($Properties.Keys | % { " {0} = {1};`n" -f ($_.ToUpper()[0] + $_.SubString(1)),($_.ToLower()) }) } } "@ ## Obtains an ICodeCompiler from a CodeDomProvider class. $provider = New-Object Microsoft.CSharp.CSharpCodeProvider ## Get the location for System.Management.Automation DLL $dllName = [PsObject].Assembly.Location ## Configure the compiler parameters $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters $assemblies = @("System.dll", $dllName) $compilerParameters.ReferencedAssemblies.AddRange($assemblies) $compilerParameters.IncludeDebugInformation = $true $compilerParameters.GenerateInMemory = $true $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code) if($compilerResults.Errors.Count -gt 0) { $compilerResults.Errors | % { Write-Error $_.Line + ":`t" + $_.ErrorText } } }
PowerShellCorpus/PoshCode/UIAutomation Simple.ps1
UIAutomation Simple.ps1
[Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") [Reflection.Assembly]::Load("UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35") function Select-Window { PARAM( [string]$Text="*", [switch]$Recurse, [System.Windows.Automation.AutomationElement]$Parent = [System.Windows.Automation.AutomationElement]::RootElement ) PROCESS { if($Recurse) { $Parent.FindAll( "Descendants", [System.Windows.Automation.Condition]::TrueCondition ) | Where-Object { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElementIdentifiers]::NameProperty) -like $Text } | Add-Member -Name Window -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.WindowPattern]::Pattern )} -Passthru } else { $Parent.FindAll( "Children", [System.Windows.Automation.Condition]::TrueCondition ) | Where-Object { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElementIdentifiers]::NameProperty) -like $Text }| Add-Member -Name Window -Type ScriptProperty -Value {$this.GetCurrentPattern( [System.Windows.Automation.WindowPattern]::Pattern )} -Passthru } }} ### To minimize notepad, for example # $notepad = select-window *notepad # $notepad | ForEach { $_.Window.SetWindowVisualState("Minimized") }
PowerShellCorpus/PoshCode/Get-BracketContent.ps1
Get-BracketContent.ps1
function global:Get-BracketContent { PARAM ( [string[]] $txtInput = $(Throw "Please provide input string(s)!") , [string] $patternString = '<.*>' , [switch] $caseSensitive = $false ) # Store the pattern in a variable we can change depending on caseSensitive option. Leave original pattern there to use in Select-String Later. $regexPattern = $patternString # By default, we're searching case-insensitive, so modify the regexpattern to indicate such & create the actual regex object if ($caseSensitive -eq $false) { $regexPattern = "(?i)$regexPattern" } $regex = New-Object System.Text.RegularExpressions.Regex $regexPattern # Function to find a regex match & output only the match. All other text on the line is discarded. function Select-PatternMatch ([string]$inputText) { $index = 0 # Start at the beginning of the line while ($index -lt $inputText.Length) { # Keep looking for matches as long as we're not at the end of the line $match = $regex.Match($inputText, $index) # Beginning where we're at on the line, check to see if a match exists. if ($match.Success -and $match.Length -gt 0) { # If there's a match, output it to the pipeline Write-Output $match.Value.ToString() $index = $match.Index + $match.Length # Update our current location on the line } else { $index = $inputText.Length } # If no match was found at all, then just say we're at the end so the while loop will stop. } } $txtInput | Select-String -pattern:$patternString | ForEach-Object { Select-PatternMatch $_.Line } | ForEach-Object { $_.SubString(1,($_.Length -2 )) } } Get-BracketContent "Alert from monitor: <alert@email.com>."
PowerShellCorpus/PoshCode/Out-HTMLTable.ps1
Out-HTMLTable.ps1
<# .SYNOPSIS Takes input objects, and outputs a sortable HTML table .DESCRIPTION The function requires at least 2 parameters, an input object and a path where the result is to be output to. The function will output 3 files, a css file that determines the way the result is formatted, a javascript file that handles the sorting, and a HTML file that contains the data. .PARAMETER $InputObject Contains the objects that should go into the table. (required) .PARAMETER $OutputFolder The folder where the resulting files should be put, if the folder does not exist it will be created. (required) .PARAMETER $BrowserTitle The name that will show up in the browser title line .PARAMETER $ReportTitle The name of the report on the HTML page .EXAMPLE PS C:\\> Out-HTMLTable -$InputObject (Get-process | select Name,Handles) -$OutputFolder c:\\Reports .EXAMPLE PS C:\\> (Get-process | select Name,Handles) | Out-HTMLTable -$OutputFolder c:\\Reports -$BrowserTitle "Very Important Report" .INPUTS Powershell objects .OUTPUTS HTMLTable .NOTES Additional information about the function go here. .LINK about_functions_advanced .LINK about_comment_based_help #> Function Out-HTMLTable { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] $InputObject, [Parameter(Mandatory=$true,Position=1)] $OutPutFolder, [Parameter(Mandatory=$false)] $BrowserTitle = "Table Report", [Parameter(Mandatory=$false)] $ReportTitle = "Data" ) begin { [Object[]]$Objects = @() If (!($OutPutFolder.EndsWith("\\"))) {$OutPutFolder = $OutPutFolder +"\\"} if (!(Test-Path -path $OutputFolder)) { New-Item $OutputFolder -type directory } } process { $Objects += $InputObject } end { $Note = "Number of objects: " + [String](($Objects).Count) $Objects | ConvertTo-Html –body "<a name='Data'></a><H4>$Title</H4>" -Head "<title>$($BrowserTitle)</title><link rel='stylesheet' href='style.css'><script src='sortable.js'></script>" | ForEach-Object {$_.replace("&lt;","<").replace("&gt;",">").replace("</html>","<footer>$($Note)</footer></html>").replace("<tr><th>","<table class='sortable' id='anyid'><thead><tr><th>").replace("</th></tr>","</th></tr></thead><tbody>").replace("</table>","</tbody></table>")} | Out-File -Encoding ASCII -FilePath ($OutPutFolder + "\\table.html") -Force #*############################# #* Output Style Sheet to file # #*############################# $css = @' /* Copyright 2006 Joost de Valk */ a img { border: 0; } table.sortable { border-spacing: 0; border: 1px solid #000; border-collapse: collapse; } table.sortable th, table.sortable td { text-align: left; padding: 2px 4px 2px 4px; width: 125px; border-style: solid; border-color: #444; } table.sortable th { border-width: 0px 1px 1px 1px; background-color: #ccc; } table.sortable td { border-width: 0px 1px 0px 1px; } table.sortable tr.odd td { background-color: #ddd; } table.sortable tr.even td { background-color: #fff; } table.sortable tr.sortbottom td { border-top: 1px solid #444; background-color: #ccc; font-weight: bold; } '@ $css | Out-File -encoding ASCII -FilePath ($OutPutFolder + "Style.css") -Force #*############################# #* Output Style Sheet to file # #*############################# $sorttable= @' /* Table sorting script by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/. Based on a script from http://www.kryogenix.org/code/browser/sorttable/. Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html . Copyright (c) 1997-2007 Stuart Langridge, Joost de Valk. Version 1.5.7 */ /* You can change these values */ var image_path = "http://www.joostdevalk.nl/code/sortable-table/"; var image_up = "arrowup.gif"; var image_down = "arrowdown.gif"; var image_none = "arrownone.gif"; var europeandate = true; var alternate_row_colors = true; /* Don't change anything below this unless you know what you're doing */ addEvent(window, "load", sortables_init); var SORT_COLUMN_INDEX; var thead = false; function sortables_init() { // Find all tables with class sortable and make them sortable if (!document.getElementsByTagName) return; tbls = document.getElementsByTagName("table"); for (ti=0;ti<tbls.length;ti++) { thisTbl = tbls[ti]; if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) { ts_makeSortable(thisTbl); } } } function ts_makeSortable(t) { if (t.rows && t.rows.length > 0) { if (t.tHead && t.tHead.rows.length > 0) { var firstRow = t.tHead.rows[t.tHead.rows.length-1]; thead = true; } else { var firstRow = t.rows[0]; } } if (!firstRow) return; // We have a first row: assume it's the header, and make its contents clickable links for (var i=0;i<firstRow.cells.length;i++) { var cell = firstRow.cells[i]; var txt = ts_getInnerText(cell); if (cell.className != "unsortable" && cell.className.indexOf("unsortable") == -1) { cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this, '+i+');return false;">'+txt+'<span class="sortarrow">&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/></span></a>'; } } if (alternate_row_colors) { alternate(t); } } function ts_getInnerText(el) { if (typeof el == "string") return el; if (typeof el == "undefined") { return el }; if (el.innerText) return el.innerText; //Not needed but it is faster var str = ""; var cs = el.childNodes; var l = cs.length; for (var i = 0; i < l; i++) { switch (cs[i].nodeType) { case 1: //ELEMENT_NODE str += ts_getInnerText(cs[i]); break; case 3: //TEXT_NODE str += cs[i].nodeValue; break; } } return str; } function ts_resortTable(lnk, clid) { var span; for (var ci=0;ci<lnk.childNodes.length;ci++) { if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci]; } var spantext = ts_getInnerText(span); var td = lnk.parentNode; var column = clid || td.cellIndex; var t = getParent(td,'TABLE'); // Work out a type for the column if (t.rows.length <= 1) return; var itm = ""; var i = 0; while (itm == "" && i < t.tBodies[0].rows.length) { var itm = ts_getInnerText(t.tBodies[0].rows[i].cells[column]); itm = trim(itm); if (itm.substr(0,4) == "<!--" || itm.length == 0) { itm = ""; } i++; } if (itm == "") return; sortfn = ts_sort_caseinsensitive; if (itm.match(/^\\d\\d[\\/\\.-][a-zA-z][a-zA-Z][a-zA-Z][\\/\\.-]\\d\\d\\d\\d$/)) sortfn = ts_sort_date; if (itm.match(/^\\d\\d[\\/\\.-]\\d\\d[\\/\\.-]\\d\\d\\d{2}?$/)) sortfn = ts_sort_date; if (itm.match(/^-?[Ł$€Ű˘´]\\d/)) sortfn = ts_sort_numeric; if (itm.match(/^-?(\\d+[,\\.]?)+(E[-+][\\d]+)?%?$/)) sortfn = ts_sort_numeric; SORT_COLUMN_INDEX = column; var firstRow = new Array(); var newRows = new Array(); for (k=0;k<t.tBodies.length;k++) { for (i=0;i<t.tBodies[k].rows[0].length;i++) { firstRow[i] = t.tBodies[k].rows[0][i]; } } for (k=0;k<t.tBodies.length;k++) { if (!thead) { // Skip the first row for (j=1;j<t.tBodies[k].rows.length;j++) { newRows[j-1] = t.tBodies[k].rows[j]; } } else { // Do NOT skip the first row for (j=0;j<t.tBodies[k].rows.length;j++) { newRows[j] = t.tBodies[k].rows[j]; } } } newRows.sort(sortfn); if (span.getAttribute("sortdir") == 'down') { ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_down + '" alt="&darr;"/>'; newRows.reverse(); span.setAttribute('sortdir','up'); } else { ARROW = '&nbsp;&nbsp;<img src="'+ image_path + image_up + '" alt="&uarr;"/>'; span.setAttribute('sortdir','down'); } // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones // don't do sortbottom rows for (i=0; i<newRows.length; i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) { t.tBodies[0].appendChild(newRows[i]); } } // do sortbottom rows only for (i=0; i<newRows.length; i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) t.tBodies[0].appendChild(newRows[i]); } // Delete any other arrows there may be showing var allspans = document.getElementsByTagName("span"); for (var ci=0;ci<allspans.length;ci++) { if (allspans[ci].className == 'sortarrow') { if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us? allspans[ci].innerHTML = '&nbsp;&nbsp;<img src="'+ image_path + image_none + '" alt="&darr;"/>'; } } } span.innerHTML = ARROW; alternate(t); } function getParent(el, pTagName) { if (el == null) { return null; } else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) { return el; } else { return getParent(el.parentNode, pTagName); } } function sort_date(date) { // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX dt = "00000000"; if (date.length == 11) { mtstr = date.substr(3,3); mtstr = mtstr.toLowerCase(); switch(mtstr) { case "jan": var mt = "01"; break; case "feb": var mt = "02"; break; case "mar": var mt = "03"; break; case "apr": var mt = "04"; break; case "may": var mt = "05"; break; case "jun": var mt = "06"; break; case "jul": var mt = "07"; break; case "aug": var mt = "08"; break; case "sep": var mt = "09"; break; case "oct": var mt = "10"; break; case "nov": var mt = "11"; break; case "dec": var mt = "12"; break; // default: var mt = "00"; } dt = date.substr(7,4)+mt+date.substr(0,2); return dt; } else if (date.length == 10) { if (europeandate == false) { dt = date.substr(6,4)+date.substr(0,2)+date.substr(3,2); return dt; } else { dt = date.substr(6,4)+date.substr(3,2)+date.substr(0,2); return dt; } } else if (date.length == 8) { yr = date.substr(6,2); if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; } if (europeandate == true) { dt = yr+date.substr(3,2)+date.substr(0,2); return dt; } else { dt = yr+date.substr(0,2)+date.substr(3,2); return dt; } } return dt; } function ts_sort_date(a,b) { dt1 = sort_date(ts_getInnerText(a.cells[SORT_COLUMN_INDEX])); dt2 = sort_date(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); if (dt1==dt2) { return 0; } if (dt1<dt2) { return -1; } return 1; } function ts_sort_numeric(a,b) { var aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); aa = clean_num(aa); var bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]); bb = clean_num(bb); return compare_numeric(aa,bb); } function compare_numeric(a,b) { var a = parseFloat(a); a = (isNaN(a) ? 0 : a); var b = parseFloat(b); b = (isNaN(b) ? 0 : b); return a - b; } function ts_sort_caseinsensitive(a,b) { aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase(); bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase(); if (aa==bb) { return 0; } if (aa<bb) { return -1; } return 1; } function ts_sort_default(a,b) { aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]); bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]); if (aa==bb) { return 0; } if (aa<bb) { return -1; } return 1; } function addEvent(elm, evType, fn, useCapture) // addEvent and removeEvent // cross-browser event handling for IE5+, NS6 and Mozilla // By Scott Andrew { if (elm.addEventListener){ elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent){ var r = elm.attachEvent("on"+evType, fn); return r; } else { alert("Handler could not be removed"); } } function clean_num(str) { str = str.replace(new RegExp(/[^-?0-9.]/g),""); return str; } function trim(s) { return s.replace(/^\\s+|\\s+$/g, ""); } function alternate(table) { // Take object table and get all it's tbodies. var tableBodies = table.getElementsByTagName("tbody"); // Loop through these tbodies for (var i = 0; i < tableBodies.length; i++) { // Take the tbody, and get all it's rows var tableRows = tableBodies[i].getElementsByTagName("tr"); // Loop through these rows // Start at 1 because we want to leave the heading row untouched for (var j = 0; j < tableRows.length; j++) { // Check if j is even, and apply classes for both possible results if ( (j % 2) == 0 ) { if ( !(tableRows[j].className.indexOf('odd') == -1) ) { tableRows[j].className = tableRows[j].className.replace('odd', 'even'); } else { if ( tableRows[j].className.indexOf('even') == -1 ) { tableRows[j].className += " even"; } } } else { if ( !(tableRows[j].className.indexOf('even') == -1) ) { tableRows[j].className = tableRows[j].className.replace('even', 'odd'); } else { if ( tableRows[j].className.indexOf('odd') == -1 ) { tableRows[j].className += " odd"; } } } } } } '@ $sorttable | Out-File -Encoding Unicode -FilePath ($OutPutFolder + 'sortable.js') -Force } } #Examples #Out-HTMLTable -InputObj (Get-process | select name,workingset,vm,pm -First 20) -OutPutFolder "C:\\AP VMs\\" -BrowserTitle "Hej med dig" #(Get-process | select name,workingset,vm,pm -First 25) | Out-HTMLTable -OutPutFolder "C:\\AP VMs\\estt" -BrowserTitle "Hej med dig"
PowerShellCorpus/PoshCode/Watch-SG2011LeaderBoard.ps1
Watch-SG2011LeaderBoard.ps1
#requires -Version 2.0 <# .Synopsis Script that will produce table of leaders in a give category. .Description Just some fun with regex/ xml. :) It will grab SG 2011 Leader Board for a given category. Than parse the string, convert it into XML, create custom objects and in the end - produce nice table. Not really best practices, but well... it's all about display this time. Goes in loop, so it should keep leaderboard. And if you miss you name in topX - add it using -Name parameter. :) .Example Watch-SG2011LeaderBoard Starts using defaults: Advanced category, Top 10 users, 5 seconds delay, and 2011 SG url. .Example Watch-SG2011LeaderBoard -Categeroy Beg -Name ScriptingWife Show Beginner category, and include ScriptingWife regardless her current position. :) #> [CmdletBinding()] param ( # Leader Board category that you want to look up. [ValidateSet('Adv','Advanced','Beg','Beginner')] [string]$Category = 'Adv', # Name of the person that you want to be included no matter what position it holds. [string]$Name, # Total number of TOP you would like to include (mind you window size...) [int]$Top = 10, # Delay between list will be refreshed for you. [int]$Delay = 5, # URL to main site, may be handy for next year... ;) [string]$URL = 'https://2011sg.poshcode.org/Reports/TopUsers' ) $WebClient = New-Object Net.WebClient switch -regex ($Category) { "^A.*" { $URL = $URL + '?filter=Advanced' } "^B.*" { $URL = $URL + '?filter=Beginner' } default { Write-Verbose "Why would I handle alien's/ divine intervention? Isn't parameter validation enough? ;)" } } $Title = "$Category Scripting Games Leaderboard" if ($Name) { $Filter = { ($TopDisplayed++ -lt $Top) -or ($_.Name -match $Name) } } else { $Filter = { $TopDisplayed++ -lt $Top } } while ($True) { $WebClient.DownloadString($URL) | Select-String -Pattern '(<table>[\\s\\S]*?</table>)' | Select -ExpandProperty Matches | ForEach-Object { # Probably should have some replacement table for &specials; -> not know them well enough so just remove them for now... # XML will try to abuse those, so we need to 'strip' them... :( # Also remove <a ... > </a> to take names 'up' in XML schema. # And last but not least - remove all whitespaces except for those between words... :) $Table = $_.Groups[0].Value -replace '&\\w+?;' -replace '</?a.*?>' -replace '\\s*(?!\\w)' -replace '(?<!\\w)\\s*' } try { $XML = [xml]$Table } catch { Write-Host "Sorry, could not change to XML. Take a look at error below for more details..." Write-Error $_ exit } # Got here so we should have $XML with nice struct. Let's parse it and show some results... :) # Parsing first to create object. Than sort/ where to show all top + named if not in top... $TopDisplayed = 0 Clear-Host Write-Host $Title "=" * $Title.Length | Out-Default "Last update: $(Get-Date -DisplayHint Time)" $XML.table.tr | Select-Object -Skip 1 | ForEach-Object { New-Object PSObject -Property @{ Name = $_.td[0] Total = [double]($_.td[1]) Rated = [int]($_.td[2]) Notes = [int]($_.td[3]) } } | Sort-Object -Property Total -Descending | Where-Object $Filter | Format-Table Name, Total, Rated, Notes -AutoSize Start-Sleep -Seconds $Delay }
PowerShellCorpus/PoshCode/RunAsAdmin Tool.ps1
RunAsAdmin Tool.ps1
<# DOWNLOAD THE DEPLOY PACKAGE FROM http://techjeeper.com/?page_id=112 for all the pieces to make this work. Author: Cody Dean (aka TechJeeper) Date: 3-16-2013 RunAsAdmin uses (and includes) the following tools: PowerShell Community Extensions SysInternals PsExec PSTerminalServices Make-ps1exewrapper.ps1 PowerShellPack To implement a new RunAsAdmin program, extract the RunAsAdmin.zip to the C:\\Tools\\ directory. From an Administrator PowerShell prompt do the following: PS> cd C:\\Tools\\ PS C:\\Tools\\> .\\Deploy-RunAsAdmin.ps1 The Deploy RunAsAdmin window will appear. GUI Description: Application Path: The path to the application you want to run with elevated privileges. Task Name: The name given to the application (will be the name of the exe the user will run) Project Short-Name: A “name” for the project, allows for multiple programs to utilize a single group for user access. Service Account Name: The name of the Service Account that will be an Administrator and will run the program. If the SA doesn’t exist, it will be created. Service Account Password: The password for the SA. If the SA exists, password must match existing password. Cleanup Checkbox: If checked, the source files will be deleted, leaving only the files for the process in C:\\Tools. #> #Checks Powershell Version $winVersion = (Get-WmiObject Win32_OperatingSystem).Caption $psVersion = $Host.Version $psVersion = $psVersion.Major If ($psVersion -eq "3") { Function Get-Script { If ($myInvocation.ScriptName) { $myInvocation.ScriptName } else { $myInvocation.MyCommand.Definition } } $script = Get-Script Write-Host "PowerShell Version 3 Detected... Starting Powershell Version 2 Window" $powershell = "powershell.exe -version 2 -file $script" invoke-expression $powershell exit } <# Make-PS1ExeWrapper.ps1 Fuction Author: Keith Hill Date: Aug 7, 2010 http://rkeithhill.wordpress.com #> function make-exe { [CmdletBinding(DefaultParameterSetName="Path")] param( [Parameter(Mandatory=$true, Position=0, ParameterSetName="Path", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Path to bitmap file")] [ValidateNotNullOrEmpty()] [string[]] $Path, [Alias("PSPath")] [Parameter(Mandatory=$true, Position=0, ParameterSetName="LiteralPath", ValueFromPipelineByPropertyName=$true, HelpMessage="Path to bitmap file")] [ValidateNotNullOrEmpty()] [string[]] $LiteralPath, [Parameter(Mandatory = $true, Position = 1)] [string] $OutputAssembly, [Parameter(Position = 2)] [string] $IconPath, [Parameter()] [switch] $STA ) Begin { Set-StrictMode -Version latest $MainAttribute = '' $ApartmentState = 'System.Threading.ApartmentState.MTA' if ($Sta) { $MainAttribute = '[STAThread]' $ApartmentState = 'System.Threading.ApartmentState.STA' } $src = @' using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.IO.Compression; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Runspaces; using System.Reflection; using System.Security; using System.Text; using System.Threading; namespace PS1ToExeTemplate { class Program { private static object _powerShellLock = new object(); private static readonly Host _host = new Host(); private static PowerShell _powerShellEngine; '@ + @" $MainAttribute "@ + @' static void Main(string[] args) { Console.CancelKeyPress += Console_CancelKeyPress; Console.TreatControlCAsInput = false; string script = GetScript(); RunScript(script, args, null); } private static string GetScript() { string script = String.Empty; Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream("Resources.Script.ps1.gz")) { var gZipStream = new GZipStream(stream, CompressionMode.Decompress, true); var streamReader = new StreamReader(gZipStream); script = streamReader.ReadToEnd(); } return script; } private static void RunScript(string script, string[] args, object input) { lock (_powerShellLock) { _powerShellEngine = PowerShell.Create(); } try { _powerShellEngine.Runspace = RunspaceFactory.CreateRunspace(_host); _powerShellEngine.Runspace.ApartmentState = '@ + @" $ApartmentState; "@ + @' _powerShellEngine.Runspace.Open(); _powerShellEngine.AddScript(script); _powerShellEngine.AddCommand("Out-Default"); _powerShellEngine.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); if (input != null) { _powerShellEngine.Invoke(new[] { input }); } else { _powerShellEngine.Invoke(); } } finally { lock (_powerShellLock) { _powerShellEngine.Dispose(); _powerShellEngine = null; } } } private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { try { lock (_powerShellLock) { if (_powerShellEngine != null && _powerShellEngine.InvocationStateInfo.State == PSInvocationState.Running) { _powerShellEngine.Stop(); } } e.Cancel = true; } catch (Exception ex) { _host.UI.WriteErrorLine(ex.ToString()); } } } class Host : PSHost { private PSHostUserInterface _psHostUserInterface = new HostUserInterface(); public override void SetShouldExit(int exitCode) { Environment.Exit(exitCode); } public override void EnterNestedPrompt() { throw new NotImplementedException(); } public override void ExitNestedPrompt() { throw new NotImplementedException(); } public override void NotifyBeginApplication() { } public override void NotifyEndApplication() { } public override string Name { get { return "PSCX-PS1ToExeHost"; } } public override Version Version { get { return new Version(1, 0); } } public override Guid InstanceId { get { return new Guid("E4673B42-84B6-4C43-9589-95FAB8E00EB2"); } } public override PSHostUserInterface UI { get { return _psHostUserInterface; } } public override CultureInfo CurrentCulture { get { return Thread.CurrentThread.CurrentCulture; } } public override CultureInfo CurrentUICulture { get { return Thread.CurrentThread.CurrentUICulture; } } } class HostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection { private PSHostRawUserInterface _psRawUserInterface = new HostRawUserInterface(); public override PSHostRawUserInterface RawUI { get { return _psRawUserInterface; } } public override string ReadLine() { return Console.ReadLine(); } public override SecureString ReadLineAsSecureString() { throw new NotImplementedException(); } public override void Write(string value) { string output = value ?? "null"; Console.Write(output); } public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { string output = value ?? "null"; var origFgColor = Console.ForegroundColor; var origBgColor = Console.BackgroundColor; Console.ForegroundColor = foregroundColor; Console.BackgroundColor = backgroundColor; Console.Write(output); Console.ForegroundColor = origFgColor; Console.BackgroundColor = origBgColor; } public override void WriteLine(string value) { string output = value ?? "null"; Console.WriteLine(output); } public override void WriteErrorLine(string value) { string output = value ?? "null"; var origFgColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(output); Console.ForegroundColor = origFgColor; } public override void WriteDebugLine(string message) { WriteYellowAnnotatedLine(message, "DEBUG"); } public override void WriteVerboseLine(string message) { WriteYellowAnnotatedLine(message, "VERBOSE"); } public override void WriteWarningLine(string message) { WriteYellowAnnotatedLine(message, "WARNING"); } private void WriteYellowAnnotatedLine(string message, string annotation) { string output = message ?? "null"; var origFgColor = Console.ForegroundColor; var origBgColor = Console.BackgroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.BackgroundColor = ConsoleColor.Black; WriteLine(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", annotation, output)); Console.ForegroundColor = origFgColor; Console.BackgroundColor = origBgColor; } public override void WriteProgress(long sourceId, ProgressRecord record) { throw new NotImplementedException(); } public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions) { if (String.IsNullOrEmpty(caption) && String.IsNullOrEmpty(message) && descriptions.Count > 0) { Console.Write(descriptions[0].Name + ": "); } else { this.Write(ConsoleColor.DarkCyan, ConsoleColor.Black, caption + "\\n" + message + " "); } var results = new Dictionary<string, PSObject>(); foreach (FieldDescription fd in descriptions) { string[] label = GetHotkeyAndLabel(fd.Label); this.WriteLine(label[1]); string userData = Console.ReadLine(); if (userData == null) { return null; } results[fd.Name] = PSObject.AsPSObject(userData); } return results; } public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName) { throw new NotImplementedException(); } public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) { throw new NotImplementedException(); } public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice) { // Write the caption and message strings in Blue. this.WriteLine(ConsoleColor.Blue, ConsoleColor.Black, caption + "\\n" + message + "\\n"); // Convert the choice collection into something that is // easier to work with. See the BuildHotkeysAndPlainLabels // method for details. string[,] promptData = BuildHotkeysAndPlainLabels(choices); // Format the overall choice prompt string to display. var sb = new StringBuilder(); for (int element = 0; element < choices.Count; element++) { sb.Append(String.Format(CultureInfo.CurrentCulture, "|{0}> {1} ", promptData[0, element], promptData[1, element])); } sb.Append(String.Format(CultureInfo.CurrentCulture, "[Default is ({0}]", promptData[0, defaultChoice])); // Read prompts until a match is made, the default is // chosen, or the loop is interrupted with ctrl-C. while (true) { this.WriteLine(sb.ToString()); string data = Console.ReadLine().Trim().ToUpper(CultureInfo.CurrentCulture); // If the choice string was empty, use the default selection. if (data.Length == 0) { return defaultChoice; } // See if the selection matched and return the // corresponding index if it did. for (int i = 0; i < choices.Count; i++) { if (promptData[0, i] == data) { return i; } } this.WriteErrorLine("Invalid choice: " + data); } } #region IHostUISupportsMultipleChoiceSelection Members public Collection<int> PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, IEnumerable<int> defaultChoices) { this.WriteLine(ConsoleColor.Blue, ConsoleColor.Black, caption + "\\n" + message + "\\n"); string[,] promptData = BuildHotkeysAndPlainLabels(choices); var sb = new StringBuilder(); for (int element = 0; element < choices.Count; element++) { sb.Append(String.Format(CultureInfo.CurrentCulture, "|{0}> {1} ", promptData[0, element], promptData[1, element])); } var defaultResults = new Collection<int>(); if (defaultChoices != null) { int countDefaults = 0; foreach (int defaultChoice in defaultChoices) { ++countDefaults; defaultResults.Add(defaultChoice); } if (countDefaults != 0) { sb.Append(countDefaults == 1 ? "[Default choice is " : "[Default choices are "); foreach (int defaultChoice in defaultChoices) { sb.AppendFormat(CultureInfo.CurrentCulture, "\\"{0}\\",", promptData[0, defaultChoice]); } sb.Remove(sb.Length - 1, 1); sb.Append("]"); } } this.WriteLine(ConsoleColor.Cyan, ConsoleColor.Black, sb.ToString()); var results = new Collection<int>(); while (true) { ReadNext: string prompt = string.Format(CultureInfo.CurrentCulture, "Choice[{0}]:", results.Count); this.Write(ConsoleColor.Cyan, ConsoleColor.Black, prompt); string data = Console.ReadLine().Trim().ToUpper(CultureInfo.CurrentCulture); if (data.Length == 0) { return (results.Count == 0) ? defaultResults : results; } for (int i = 0; i < choices.Count; i++) { if (promptData[0, i] == data) { results.Add(i); goto ReadNext; } } this.WriteErrorLine("Invalid choice: " + data); } } #endregion private static string[,] BuildHotkeysAndPlainLabels(Collection<ChoiceDescription> choices) { // Allocate the result array string[,] hotkeysAndPlainLabels = new string[2, choices.Count]; for (int i = 0; i < choices.Count; ++i) { string[] hotkeyAndLabel = GetHotkeyAndLabel(choices[i].Label); hotkeysAndPlainLabels[0, i] = hotkeyAndLabel[0]; hotkeysAndPlainLabels[1, i] = hotkeyAndLabel[1]; } return hotkeysAndPlainLabels; } private static string[] GetHotkeyAndLabel(string input) { string[] result = new string[] { String.Empty, String.Empty }; string[] fragments = input.Split('&'); if (fragments.Length == 2) { if (fragments[1].Length > 0) { result[0] = fragments[1][0].ToString(). ToUpper(CultureInfo.CurrentCulture); } result[1] = (fragments[0] + fragments[1]).Trim(); } else { result[1] = input; } return result; } } class HostRawUserInterface : PSHostRawUserInterface { public override KeyInfo ReadKey(ReadKeyOptions options) { throw new NotImplementedException(); } public override void FlushInputBuffer() { } public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { throw new NotImplementedException(); } public override void SetBufferContents(Rectangle rectangle, BufferCell fill) { throw new NotImplementedException(); } public override BufferCell[,] GetBufferContents(Rectangle rectangle) { throw new NotImplementedException(); } public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill) { throw new NotImplementedException(); } public override ConsoleColor ForegroundColor { get { return Console.ForegroundColor; } set { Console.ForegroundColor = value; } } public override ConsoleColor BackgroundColor { get { return Console.BackgroundColor; } set { Console.BackgroundColor = value; } } public override Coordinates CursorPosition { get { return new Coordinates(Console.CursorLeft, Console.CursorTop); } set { Console.SetCursorPosition(value.X, value.Y); } } public override Coordinates WindowPosition { get { return new Coordinates(Console.WindowLeft, Console.WindowTop); } set { Console.SetWindowPosition(value.X, value.Y); } } public override int CursorSize { get { return Console.CursorSize; } set { Console.CursorSize = value; } } public override Size BufferSize { get { return new Size(Console.BufferWidth, Console.BufferHeight); } set { Console.SetBufferSize(value.Width, value.Height); } } public override Size WindowSize { get { return new Size(Console.WindowWidth, Console.WindowHeight); } set { Console.SetWindowSize(value.Width, value.Height); } } public override Size MaxWindowSize { get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); } } public override Size MaxPhysicalWindowSize { get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); } } public override bool KeyAvailable { get { return Console.KeyAvailable; } } public override string WindowTitle { get { return Console.Title; } set { Console.Title = value; } } } } '@ } Process { if ($psCmdlet.ParameterSetName -eq "Path") { # In the -Path (non-literal) case we may need to resolve a wildcarded path $resolvedPaths = @($Path | Resolve-Path | Convert-Path) } else { # Must be -LiteralPath $resolvedPaths = @($LiteralPath | Convert-Path) } foreach ($rpath in $resolvedPaths) { Write-Verbose "Processing $rpath" $gzItem = Get-ChildItem $rpath | Write-GZip -Quiet $resourcePath = "$($gzItem.Directory)\\Resources.Script.ps1.gz" if (Test-Path $resourcePath) { Remove-Item $resourcePath } Rename-Item $gzItem $resourcePath # Configure the compiler parameters $referenceAssemblies = 'System.dll',([psobject].Assembly.Location) $outputPath = $OutputAssembly if (![IO.Path]::IsPathRooted($outputPath)) { $outputPath = [io.path]::GetFullPath((Join-Path $pwd $outputPath)) } if ($rpath -eq $outputPath) { throw 'Oops, you don''t really want to overwrite your script with an EXE.' } $cp = new-object System.CodeDom.Compiler.CompilerParameters $referenceAssemblies,$outputPath,$true $cp.TempFiles = new-object System.CodeDom.Compiler.TempFileCollection ([IO.Path]::GetTempPath()) $cp.GenerateExecutable = $true $cp.GenerateInMemory = $false $cp.IncludeDebugInformation = $true if ($IconPath) { $rIconPath = Resolve-Path $IconPath $cp.CompilerOptions = " /win32icon:$rIconPath" } [void]$cp.EmbeddedResources.Add($resourcePath) # Create the C# codedom compiler $dict = new-object 'System.Collections.Generic.Dictionary[string,string]' $dict.Add('CompilerVersion','v3.5') $provider = new-object Microsoft.CSharp.CSharpCodeProvider $dict # Compile the source and report errors $results = $provider.CompileAssemblyFromSource($cp, $src) if ($results.Errors.Count) { $errorLines = "" foreach ($error in $results.Errors) { $errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText } Write-Error $errorLines } } }} function Reload-Profile { @( $Profile.AllUsersAllHosts, $Profile.AllUsersCurrentHost, $Profile.CurrentUserAllHosts, $Profile.CurrentUserCurrentHost ) | % { if(Test-Path $_){ Write-Verbose "Running $_" . $_ } } } $pspCheck = $NULL $pspCheck = Get-Module -ListAvailable | Where-Object {$_.Name -eq "PowerShellPack"} if (!$pspCheck) { Write-Host "Installing PowerShellPack... Please Wait..." $install = "C:\\Tools\\PowerShellPack.msi /quiet" invoke-expression $install Start-Sleep -Seconds 30 Reload-Profile } $pscxCheck = $NULL $pscxCheck = Get-Module -ListAvailable | Where-Object {$_.Name -eq "Pscx"} $psVer = ($host.version).Major if (!$pscxCheck) { Write-Host "Installing PSCX..." Copy-Item C:\\Tools\\Pscx C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules -Recurse Start-Sleep -Seconds 30 Reload-Profile } Import-Module PowerShellPack Import-Module Pscx $xApp = "" $xTask = "" $xProj = "" $xSA = "" #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 # Generated On: 3/14/2013 9:51 AM # Generated By: deanc4 ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $form = New-Object System.Windows.Forms.Form $exitBtn = New-Object System.Windows.Forms.Button $okBtn = New-Object System.Windows.Forms.Button $fileBtn = New-Object System.Windows.Forms.Button $cleanupCkbx = New-Object System.Windows.Forms.CheckBox $passTxt = New-Object System.Windows.Forms.TextBox $passLbl = New-Object System.Windows.Forms.Label $svcAcctTxt = New-Object System.Windows.Forms.ComboBox $svcAcctLbl = New-Object System.Windows.Forms.Label $projShortTxt = New-Object System.Windows.Forms.TextBox $projShortLbl = New-Object System.Windows.Forms.Label $taskNameTxt = New-Object System.Windows.Forms.TextBox $taskNameLbl = New-Object System.Windows.Forms.Label $appPathTxt = New-Object System.Windows.Forms.TextBox $appPathLbl = New-Object System.Windows.Forms.Label $progressBar = New-Object System.Windows.Forms.ProgressBar $timer1 = New-Object System.Windows.Forms.Timer $timer2 = New-Object System.Windows.Forms.Timer $openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. function stepBar { if ($progressBar.Value -lt 100) { $progressBar.Increment(1) } else { $progressBar.Value = 1 } } $okBtn_OnClick= { $timer1.Interval = 1000 $timer1.add_Tick({stepBar}) $timer1.start() $xApp=$appPathTxt.Text $xTask=$taskNameTxt.Text $xProj=$projShortTxt.Text $xSA=$svcAcctTxt.Text $xPass=$passTxt.Text # Creates the Script Files and Folder Directory (Under C:\\Tools) $newDir = "C:\\Tools\\"+$xTask New-Item $newDir -type directory $scriptRun = $newDir+"\\"+$xTask + ".ps1" $scriptTask = $newDir+"\\"+$xTask + "_Task.ps1" $scriptTaskExe = $newDir+"\\"+$xTask + "_Task.exe" $scriptExe = $newDir+"\\"+$xTask + ".exe" New-Item $scriptRun -type file -force New-Item $scriptTask -type file -force if ($winVersion -like "*2003*") { $taskDir = "C:\\WINDOWS\\Tasks\\"+$xProj } else { # Creates the Tasks sub-directory $taskDir = "C:\\Windows\\System32\\Tasks\\"+$xProj } New-Item $taskDir -type directory -force #$netuser = $xSA+" "+$password+" /add" Write-Host "Creating Local User" net user $xSA $xPass /add net localgroup administrators /add $xSA $localGroup = $xProj+"_TaskRunners" Write-Host "Creating Local Group" net localgroup $localGroup /add Write-Host "Setting Permissions" $cacls = "cacls.exe "+$taskDir+" /T /E /G "+$localGroup+":R" Invoke-Expression $cacls # Copy PSTerminalServices Module Write-Host "Copying Module" New-Item C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules\\PSTerminalServices -type directory -Force Copy-Item C:\\Tools\\PSTerminalServices\\* C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules\\PSTerminalServices\\ -Recurse -ErrorAction SilentlyContinue if ($winVersion -like "*2003*") { $Task = $xTask $newTask = $scriptTaskExe } else { $Task = $xProj+"\\"+$xTask $newTask = $scriptTaskExe } if ($winVersion -like "*2003*") { SCHTASKS /CREATE /RU $xSA /RP $xPass /TN $Task /TR $newTask /SC ONCE /ST 00:01 /F } else { New-Task | Add-TaskAction -Path $newTask -WorkingDirectory "" | Register-ScheduledTask $Task SCHTASKS /Change /RU $xSA /RP $xPass /TN $Task /RL HIGHEST } $tempPath = "C:\\Tools\\"+$xTask+"\\Temp" New-Item -Type Directory -Path $tempPath $scriptRunContents = @" Import-Module PSTerminalServices `$tempFile`="C:\\Tools\\$xTask\\Temp\\session.tmp" `$logFile`="C:\\Tools\\$xTask\\Temp\\log.txt" `$task` = "$Task" `$user`=whoami `$user`=`$user`.Split("\\")[1] `$getSessions`=Get-TSSession `$getSessions`=`$getSessions`|Select "SessionID", "UserName" `$userSession`=`$getSessions`|Where-Object {`$_.UserName` -eq `$user`} `$sessionId`=`$userSession.SessionId` `$sessionId`|Out-File `$tempFile` schtasks /run /TN $task "@ Out-File -InputObject $scriptRunContents -FilePath $scriptRun $cacls = "cacls.exe "+$scriptRun+" /T /E /G "+$localGroup+":R" Invoke-Expression $cacls $cacls = "cacls.exe "+$tempPath+" /T /E /G "+$localGroup+":C" Invoke-Expression $cacls Write-Host "Copying PsExec to System32" Copy-Item -Path C:\\Tools\\PsExec.exe C:\\Windows\\System32\\ $scriptTaskContents = @" Import-Module PSTerminalServices `$logFile`="C:\\Tools\\$xTask\\Temp\\log.txt" `$tempFile`="C:\\Tools\\$xTask\\Temp\\session.tmp" `$psexec`="PsExec.exe /accepteula" `$command`=`"cmd /C ```"$xApp```"`" `$session`=get-content `$tempFile` `$cmd`=`$psexec`+" -s -d -i "+`$session`+" "+`$command` Get-Date|Out-File `$logFile` -Append `$event` = Get-TSSession -SessionID `$session`|Select "SessionID", "IPAddress", "UserName"|Format-Table -autosize Invoke-Expression `$cmd` Remove-Item `$tempFile` "@ Out-File -InputObject $scriptTaskContents -FilePath $scriptTask make-exe $scriptRun $scriptExe C:\\Tools\\Run.ico make-exe $scriptTask $scriptTaskExe C:\\Tools\\Run.ico $pdbFile = $newDir+"\\*.pdb" $gzFile = $newDir+"\\*.gz" Remove-Item $pdbFile Remove-Item $gzFile Remove-Item $scriptRun Remove-Item $scriptTask $chkbox = $cleanupCkbx.Checked if ($chkbox -eq $TRUE) { $PscxFiles = "C:\\Tools\\Pscx" Remove-Item $PscxFiles -Recurse -Force $PSTSFiles = "C:\\Tools\\PSTerminalServices" Remove-Item $PSTSFiles -Recurse -Force Remove-Item C:\\Tools\\PowerShellPack.msi -Force Remove-Item C:\\Tools\\Run.ico Remove-Item C:\\Tools\\PsExec.exe } $xPass = $NULL $timer1.Stop() $form.Close() } $handler_form_Load= { $progressBar.Value = 0 $timer1.Stop() } $exitBtn_OnClick= { $timer1.Stop() $form.Close() } $fileBtn_OnClick= { $openFileDialog1.ShowDialog() $appPathTxt.Text = $openFileDialog1.FileName } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $form.WindowState = $InitialFormWindowState } $users = get-wmiobject -class "Win32_UserAccount" -Filter "LocalAccount = True" foreach ($user in $users) { $svcAcctTxt.Items.Add($user.Name) } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 268 $System_Drawing_Size.Width = 229 $form.ClientSize = $System_Drawing_Size $form.DataBindings.DefaultDataSourceUpdateMode = 0 $form.Name = "form" $form.Text = "Deploy RunAsAdmin" $form.add_Load($handler_form_Load) $exitBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 119 $System_Drawing_Point.Y = 223 $exitBtn.Location = $System_Drawing_Point $exitBtn.Name = "exitBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 98 $exitBtn.Size = $System_Drawing_Size $exitBtn.TabIndex = 14 $exitBtn.Text = "EXIT" $exitBtn.UseVisualStyleBackColor = $True $exitBtn.add_Click($exitBtn_OnClick) $form.Controls.Add($exitBtn) $okBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 223 $okBtn.Location = $System_Drawing_Point $okBtn.Name = "okBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 98 $okBtn.Size = $System_Drawing_Size $okBtn.TabIndex = 13 $okBtn.Text = "OK" $okBtn.UseVisualStyleBackColor = $True $okBtn.add_Click($okBtn_OnClick) $form.Controls.Add($okBtn) $fileBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 191 $System_Drawing_Point.Y = 19 $fileBtn.Location = $System_Drawing_Point $fileBtn.Name = "fileBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 26 $fileBtn.Size = $System_Drawing_Size $fileBtn.TabIndex = 12 $fileBtn.Text = "..." $fileBtn.UseVisualStyleBackColor = $True $fileBtn.add_Click($fileBtn_OnClick) $form.Controls.Add($fileBtn) $cleanupCkbx.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 200 $cleanupCkbx.Location = $System_Drawing_Point $cleanupCkbx.Name = "cleanupCkbx" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 16 $System_Drawing_Size.Width = 300 $cleanupCkbx.Size = $System_Drawing_Size $cleanupCkbx.TabIndex = 11 $cleanupCkbx.Text = "Cleanup source files after completion " $cleanupCkbx.UseVisualStyleBackColor = $True $cleanupCkbx.add_CheckedChanged($handler_cleanupCkbx_CheckedChanged) $form.Controls.Add($cleanupCkbx) $passTxt.DataBindings.DefaultDataSourceUpdateMode = 0 $passTxt.HideSelection = $False $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 176 $passTxt.Location = $System_Drawing_Point $passTxt.Name = "passTxt" $passTxt.PasswordChar = '*' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 205 $passTxt.Size = $System_Drawing_Size $passTxt.TabIndex = 10 $form.Controls.Add($passTxt) $passLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 160 $passLbl.Location = $System_Drawing_Point $passLbl.Name = "passLbl" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 12 $System_Drawing_Size.Width = 205 $passLbl.Size = $System_Drawing_Size $passLbl.TabIndex = 9 $passLbl.Text = "Service Account Password:" $form.Controls.Add($passLbl) $svcAcctTxt.DataBindings.DefaultDataSourceUpdateMode = 0 $svcAcctTxt.FormattingEnabled = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 136 $svcAcctTxt.Location = $System_Drawing_Point $svcAcctTxt.Name = "svcAcctTxt" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 21 $System_Drawing_Size.Width = 205 $svcAcctTxt.Size = $System_Drawing_Size $svcAcctTxt.TabIndex = 8 $form.Controls.Add($svcAcctTxt) $svcAcctLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 120 $svcAcctLbl.Location = $System_Drawing_Point $svcAcctLbl.Name = "svcAcctLbl" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 12 $System_Drawing_Size.Width = 205 $svcAcctLbl.Size = $System_Drawing_Size $svcAcctLbl.TabIndex = 7 $svcAcctLbl.Text = "Service Account Name:" $form.Controls.Add($svcAcctLbl) $projShortTxt.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 97 $projShortTxt.Location = $System_Drawing_Point $projShortTxt.Name = "projShortTxt" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 204 $projShortTxt.Size = $System_Drawing_Size $projShortTxt.TabIndex = 6 $form.Controls.Add($projShortTxt) $projShortLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 81 $projShortLbl.Location = $System_Drawing_Point $projShortLbl.Name = "projShortLbl" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 12 $System_Drawing_Size.Width = 204 $projShortLbl.Size = $System_Drawing_Size $projShortLbl.TabIndex = 5 $projShortLbl.Text = "Project Short-Name:" $form.Controls.Add($projShortLbl) $taskNameTxt.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 58 $taskNameTxt.Location = $System_Drawing_Point $taskNameTxt.Name = "taskNameTxt" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 204 $taskNameTxt.Size = $System_Drawing_Size $taskNameTxt.TabIndex = 4 $form.Controls.Add($taskNameTxt) $taskNameLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 42 $taskNameLbl.Location = $System_Drawing_Point $taskNameLbl.Name = "taskNameLbl" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 12 $System_Drawing_Size.Width = 204 $taskNameLbl.Size = $System_Drawing_Size $taskNameLbl.TabIndex = 3 $taskNameLbl.Text = "Task Name:" $form.Controls.Add($taskNameLbl) $appPathTxt.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 19 $appPathTxt.Location = $System_Drawing_Point $appPathTxt.Name = "appPathTxt" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 172 $appPathTxt.Size = $System_Drawing_Size $appPathTxt.TabIndex = 2 $form.Controls.Add($appPathTxt) $appPathLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 3 $appPathLbl.Location = $System_Drawing_Point $appPathLbl.Name = "appPathLbl" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 12 $System_Drawing_Size.Width = 205 $appPathLbl.Size = $System_Drawing_Size $appPathLbl.TabIndex = 1 $appPathLbl.Text = "Application Path:" $form.Controls.Add($appPathLbl) $progressBar.DataBindings.DefaultDataSourceUpdateMode = 0 $progressBar.ForeColor = [System.Drawing.Color]::FromArgb(255,160,160,160) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 252 $progressBar.Location = $System_Drawing_Point $progressBar.Name = "progressBar" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 10 $System_Drawing_Size.Width = 205 $progressBar.Size = $System_Drawing_Size $progressBar.TabIndex = 0 $form.Controls.Add($progressBar) $openFileDialog1.FileName = "openFileDialog1" $openFileDialog1.ShowHelp = $True #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $form.WindowState #Init the OnLoad event to correct the initial state of the form $form.add_Load($OnLoadForm_StateCorrection) #Show the Form $form.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/Send-Growl _2.0.ps1
Send-Growl _2.0.ps1
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0) ## v 1.0 supports a very simple notice, and no callbacks ## v 2.0 supports registering multiple message types ## supports callbacks ## v 2.1 redesigned to be a module used from apps, rather than it's own "PowerGrowler" app ## ## TODO: ## * Test sending notices to other PCs directly Set-StrictMode -Version 2 ## this is just a default now, you'll have opportunities to override it... $script:appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Global:PowerGrowlerNotices)) { $global:PowerGrowlerNotices = @{} } ## We can safely recreate this, it doesn't store much $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" function Register-GrowlType { #.Synopsis # Register a new Type name for growl notices from PowerGrowl #.Description # Creates a new type name that can be used for sending growl notices #.Parameter AppName # The name of the application you want to register as #.Parameter Name # The type name to be used sending growls #.Parameter DisplayName # The test to use for display (defaults to use the same value as the type name) #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter MachineName # The name of a remote machine to register remotely instead of locally. #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Register-GrowlType "PoshTwitter" "Command Completed" # # Registers the type "Command Completed," using the default icon, for sending notifications to the local PC # PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$AppName , [Parameter(Mandatory=$true,Position=1)] [ValidateScript( {!$global:PowerGrowlerNotices.Contains($AppName) -OR !$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [String]$Name , [Parameter(Mandatory=$false,Position=5)] [String]$Icon = "$PSScriptRoot\\default.ico" , [Parameter(Mandatory=$false,Position=6)] [String]$DisplayName = $Name , [Parameter(Mandatory=$false,Position=7)] [String]$MachineName , [Parameter(Mandatory=$false)] [String]$AppIcon ) [Growl.Connector.NotificationType]$Notice = $Name $Notice.DisplayName = $DisplayName $Notice.Icon = Convert-Path (Resolve-Path $Icon) if($MachineName) { $Notice.MachineName = $MachineName } if(!$global:PowerGrowlerNotices.Contains($AppName)) { $global:PowerGrowlerNotices.Add( $AppName, ([Growl.Connector.Application]$AppName) ) $global:PowerGrowlerNotices.$AppName = Add-Member -input $global:PowerGrowlerNotices.$AppName -Name Notices -Type NoteProperty -Value (New-Object hashtable) -Passthru $global:PowerGrowlerNotices.$AppName.Icon = Convert-Path (Resolve-Path $AppIcon) } $global:PowerGrowlerNotices.$AppName.Notices.Add( $Name, $Notice ) $script:PowerGrowler.Register( $global:PowerGrowlerNotices.$AppName , [Growl.Connector.NotificationType[]]@($global:PowerGrowlerNotices.$AppName.Notices.Values) ) } function Set-GrowlPassword { #.Synopsis # Set the Growl password #.Description # Set the password and optionally, the encryption algorithm, for communicating with Growl #.Parameter Password # The password for Growl #.Parameter Encryption # The algorithm to be used for encryption (defaults to AES) #.Parameter KeyHash # The algorithm to be used for key hashing (defaults to SHA1) PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$Password , [Parameter(Mandatory=$false,Position=1)] [ValidateSet( "AES", "DES", "RC2", "TripleDES", "PlainText" )] [String]$Encryption = "AES" , [Parameter(Mandatory=$false,Position=2)] [ValidateSet( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" )] [String]$KeyHash = "SHA1" ) $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$Encryption" $script:PowerGrowler.KeyHashAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$KeyHash" $script:PowerGrowler.Password = $Password } ## Register the "PowerGrowler" "Default" notice so everything works out of the box Register-GrowlType $script:AppName "Default" -appIcon "$PsScriptRoot\\default.ico" function Register-GrowlCallback { #.Synopsis # Register a script to be called when each notice is finished. #.Description # Registers a scriptblock as a handler for the NotificationCallback event. You should accept two parameters, a Growl.Connector.Response and a Growl.Connector.CallbackData object. # # The NotificationCallback only happens when a callback is requested, which in this Growl library only happens if you pass both CallbackData and CallbackType to the Send-Growl function. #.Example # Register-GrowlCallback { PARAM( $response, $context ) # Write-Host "Response $($response|out-string)" -fore Cyan # Write-Host "Context $($context|fl|out-string)" -fore Green # Write-Host $("Response Type: {0}`nNotification ID: {1}`nCallback Data: {2}`nCallback Data Type: {3}`n" -f $context.Result, $context.NotificationID, $context.Data, $context.Type) -fore Yellow # } # # Registers an informational debugging-style handler. # PARAM( [Parameter(Mandatory=$true)] [Scriptblock]$Handler ) Register-ObjectEvent $script:PowerGrowler NotificationCallback -Action $Handler } function Send-Growl { [CmdletBinding(DefaultParameterSetName="DataCallback")] #.Synopsis # Send a growl notice #.Description # Send a growl notice with the scpecified values #.Parameter Caption # The short caption to display #.Parameter Message # The message to send (most displays will resize to accomodate) #.Parameter NoticeType # The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur. # For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities. #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Send-Growl "Greetings" "Hello World!" # # The Hello World of Growl. #.Example # Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png # # Displays a message with a couple of movie quotes and a mail icon. # PARAM ( [Parameter(Mandatory=$true, Position=0)] [ValidateScript( {$global:PowerGrowlerNotices.Contains($AppName)} )] [string]$AppName , [Parameter(Mandatory=$true, Position=1)][Alias("Type")] [ValidateScript( {$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [string]$NoticeType , [Parameter(Mandatory=$true, Position=2)] [string]$Caption , [Parameter(Mandatory=$true, Position=3)] [string]$Message , [Parameter(Mandatory=$true, Position=4, ParameterSetName="UrlCallback")] [Uri]$Url , [Parameter(Mandatory=$true, Position=4, ParameterSetName="DataCallback")] [string]$CallbackData , [Parameter(Mandatory=$true, Position=5, ParameterSetName="DataCallback")] [string]$CallbackType , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } if( Test-Path Variable:Local:Url ) { $context = new-object Growl.Connector.CallbackContext ## These two things aren't used? Probably shouldn't so all this work :) $context.Data = $(if(Test-Path Variable:Local:CallbackData){$CallbackData}else{$Url.ToString()}) $context.Type = $(if(Test-Path Variable:Local:CallbackType){$CallbackType}else{"$NoticeType+Url"}) $urlCb = new-object Growl.Connector.UrlCallbackTarget Write-Host $Url -Fore Cyan $urlCb.Url = $Url $context.SetUrlCallbackTarget($urlcb) $script:PowerGrowler.Notify($notice, $context) } elseif( (Test-Path Variable:Local:CallbackData) -and (Test-Path Variable:Local:CallbackType) ) { $context = new-object Growl.Connector.CallbackContext $context.Data = $CallbackData $context.Type = $CallbackType Write-Host $context.GetUrlCallbackTarget() -Fore Magenta $script:PowerGrowler.Notify($notice, $context) } else { $script:PowerGrowler.Notify($notice) } } Export-ModuleMember -Function Send-Growl, Set-GrowlPassword, Register-GrowlCallback, Register-GrowlType
PowerShellCorpus/PoshCode/callias.ps1
callias.ps1
function prompt { $mapped_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=4" | foreach {echo $_.deviceid} $local_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" | foreach {echo $_.deviceid} $removable_drives = Get-WmiObject Win32_LogicalDisk -Filter "drivetype=2" | foreach {echo $_.deviceid} $t = $(get-date -format "HH:mm:ss") $a = (get-location).path $d = (get-location).path.substring(0,$a.indexof(":")+1) $a = $a.substring($a.LastIndexOf("`\\")+1) if ((get-location).path.substring(0,(get-location).path.indexof(":")) -eq "Microsoft.PowerShell.Core\\FileSystem") { $a = (get-location).path $a = $a.substring($a.indexof(":")+2) write-host -fore white -back blue "$t - $a ";"`$`> "} else { if ($a -eq "") {$a = "`\\"} if ($d.length -gt 2) { write-host -ForegroundColor black -backgroundcolor red "[$t] - [$d] $a ";"`$`> "} elseif ($local_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor green "[$t] - [$d] $a ";"`$`> "} elseif ($removable_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor yellow "[$t] - [$d] $a ";"`$`> "} elseif ($mapped_drives -contains "$d") { write-host -ForegroundColor black -backgroundcolor magenta "[$t] - [$d] $a ";"`$`> "} } }
PowerShellCorpus/PoshCode/chkhash_11.ps1
chkhash_11.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 $fm = 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 -u -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++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { 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 { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} $xfiles=@(import-clixml $hashespath) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es) 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) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing $($f.fullname) ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} # Update and continue is specified. $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "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." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Get-VMware-Guest-Invento.ps1
Get-VMware-Guest-Invento.ps1
#Requires -Version 2.0 #Requires –PsSnapIn Quest.ActiveRoles.ADManagement #Requires –PsSnapIn VMware.VimAutomation.Core <#> ========================================================================== This script was created and tested on the following: Name Version ----------------- ----------------- PowerShell :2.0 VMWare PowerCLi :4.1.1.0 Quest AcitveRoles for AD :1.4.0.2139 ============================== NAME: |Get-VMware-Guest-Inventory.ps1 ============================== AUTHOR: |Omarr Miller EMAIL: |omarr.miller@delta.com ============================== COMMENT: This script will create an inventory of all Guests within the requested Virtual Center and save it as a .csv file. If you need to inventory only a specific cluster, edit lines 54, 55 & 58 You have a royalty-free right to use, modify, reproduce, and distribute this script file in any way you find useful, provided that you agree that the creator, owner above has no warranty, obligations, or liability for such use. REQUIREMENTS OF THIS SCRIPT: Name Version ----------------- ----------------- PowerShell :2.0 VMWare PowerCLi :4.1.1.0 Quest AcitveRoles for AD :1.4.0.2139 VERSION HISTORY: 1.0 3/22/2011 - Initial release 1.5 7/21/2011 - Updated Get-View syntax ========================================================================== </#> $VirtualCenter = Read-Host "Please enter the name of the Virtual Center Server" #$ResourcePool = Read-Host "Please enter the complete name of the target Resource Pool" $FileLocation = Read-Host "Please Enter Complete Path and file name to save the output. Must end in .csv or .txt" Connect-VIServer $VirtualCenter $stats = @() #Uncomment the next two lines if you would like to inventory just a cluster instead of all VMs in vCenter #$VMCluster = Read-Host "Please enter the name of the HA Cluster" #$ServerList = Get-VM -Location $VMCluster #If the two lines abover are uncommented, then comment the next line #$ServerList = Get-ResourcePool $ResourcePool | Get-VM #$ServerList = Get-VM | Where {$_.PowerState -match "on"} | Sort Name $ServerList = Get-VM | Sort Name Clear Foreach ($Guests in $ServerList) { $Guest = $Guests.Name.ToUpper() Write-Progress -Activity "Creating VMware Guest Inventory" -Status "Processing VM Guest $Guest"# Display progress bar $VM = Get-VM $Guest #$VMGuest = Get-VMGuest $Guest $ESXHost = $VM.Host.Name.ToUpper() $VMHost = Get-VMHost $ESXHost $row = New-Object System.Object $row | Add-Member -Type NoteProperty -Name "Guest" -Value $Guest $row | Add-Member -Type NoteProperty -Name "DNS Name" -Value $VM.ExtensionData.Guest.HostName.ToUpper() $row | Add-Member -Type NoteProperty -Name "Power State" -Value $VM.PowerState $row | Add-Member -Type NoteProperty -Name "Guest OS Full Name" -Value $VM.Guest.OSFullName $row | Add-Member -Type NoteProperty -Name "Guest RAM (MB)" -Value $VM.MemoryMB $row | Add-Member -Type NoteProperty -Name "Guest vCPU Count" -Value $VM.NumCPU $row | Add-Member -Type NoteProperty -Name "Guest Hardware Ver" -Value $VM.Version $row | Add-Member -Type NoteProperty -Name "Guest VMTools Status" -Value $VM.ExtensionData.Guest.ToolsStatus $row | Add-Member -Type NoteProperty -Name "Guest VMTools Version" -Value $VM.ExtensionData.Guest.ToolsVersion $row | Add-Member -Type NoteProperty -Name "Guest VMTools Version Status" -Value $VM.ExtensionData.Guest.ToolsVersionStatus $row | Add-Member -Type NoteProperty -Name "Guest VMTools Running Status" -Value $VM.ExtensionData.Guest.ToolsRunningStatus $row | Add-Member -Type NoteProperty -Name "Guest IP" -Value $VM.ExtensionData.Summary.Guest.IpAddress $row | Add-Member -Type NoteProperty -Name "Guest Provisioned Space (GB)" -Value $VM.ProvisionedSpaceGB $DiskCount = 0 $DT = @() ForEach ($vDisk in $VM.Guest.Disks) { $DriveLoc = "Guest Drive " + $DiskCount + " Location" $DriveLetter = "Guest Drive " + $DiskCount + "" $DriveSize = "Guest Drive " + $DiskCount + " Size" $DriveFree = "Guest Drive " + $DiskCount + " Free Space" $vDiskCap = [math]::Round(($vDisk.Capacity) / 1GB) $vDiskFree = [math]::Round(($vDisk.FreeSpace) / 1GB) $vDiskLoc = $VM.HardDisks[$DiskCount] $row | Add-Member -Type NoteProperty -Name $DriveLetter -Value $vDisk.Path $row | Add-Member -Type NoteProperty -Name $DriveSize -Value $vDiskCap $row | Add-Member -Type NoteProperty -Name $DriveFree -Value $vDiskFree $row | Add-Member -Type NoteProperty -Name $DriveLoc -Value $vDiskLoc.Filename $DiskCount++ $DriveTotals = "" + $row.$DriveLetter + " " + $row.$DriveSize + ";" $DT += $DriveTotals } $row | Add-Member -Type NoteProperty -Name "Host Name" -Value $VMHost.ExtensionData.Summary.Config.Name.ToUpper() $row | Add-Member -Type NoteProperty -Name "# of Sessions on Host" -Value $VMHost.ExtensionData.VM.Count $ESXCluster = Get-Cluster -VMHost $ESXHost -ErrorAction SilentlyContinue IF (!$ESXCluster) { $row | Add-Member -Type NoteProperty -Name "Host is Member of Cluster" -Value "Stand Alone Host" } ELSE { $row | Add-Member -Type NoteProperty -Name "Host is Member of Cluster" -Value $ESXCluster.Name.ToUpper() } $row | Add-Member -Type NoteProperty -Name "Host Vendor" -Value $VMHost.ExtensionData.Hardware.SystemInfo.Vendor $row | Add-Member -Type NoteProperty -Name "Host Model" -Value $VMHost.ExtensionData.Hardware.SystemInfo.Model $HostRam = [math]::Round(($VMHost.ExtensionData.Summary.Hardware.MemorySize) / 1GB) $row | Add-Member -Type NoteProperty -Name "Host RAM" -Value $HostRam $row | Add-Member -Type NoteProperty -Name "Host CPU Model" -Value $VMHost.ExtensionData.Summary.Hardware.CpuModel $row | Add-Member -Type NoteProperty -Name "Host CPU Count" -Value $VMHost.ExtensionData.Summary.Hardware.NumCpuThreads $row | Add-Member -Type NoteProperty -Name "Host CPU Speed" -Value $VMHost.ExtensionData.Summary.Hardware.CpuMhz $row | Add-Member -Type NoteProperty -Name "Host Product Name" -Value $VMHost.ExtensionData.Summary.Config.Product.Name $row | Add-Member -Type NoteProperty -Name "Host Product Version" -Value $VMHost.ExtensionData.Summary.Config.Product.Version $row | Add-Member -Type NoteProperty -Name "Host Product Build" -Value $VMHost.ExtensionData.Summary.Config.Product.Build $row | Add-Member -Type NoteProperty -Name "Host Service Console" -Value $VMHost.ExtensionData.Config.Network.vNic[0].Spec.IP.IPAddress $row | Add-Member -Type NoteProperty -Name "Host Service Console Subnet Mask" -Value $VMHost.ExtensionData.Config.Network.vNic[0].Spec.IP.SubnetMask $row | Add-Member -Type NoteProperty -Name "Host Service Console 1" -Value $VMHost.ExtensionData.Config.Network.vNic[1].Spec.IP.IPAddress $row | Add-Member -Type NoteProperty -Name "Host Service Console 1 Subnet Mask" -Value $VMHost.ExtensionData.Config.Network.vNic[1].Spec.IP.SubnetMask $row | Add-Member -Type NoteProperty -Name "Host vMotion IP Address" -Value $VMHost.ExtensionData.Config.vMotion.IPConfig.IpAddress $row | Add-Member -Type NoteProperty -Name "Host vMotion Subnet Mask" -Value $VMHost.ExtensionData.Config.vMotion.IPConfig.SubnetMask $row $stats += $row } $stats | Export-Csv -Force .\\$FileLocation -NoTypeInformation Invoke-Item .\\$FileLocation
PowerShellCorpus/PoshCode/_1.ps1
_1.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 Identity,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}} # Set the ActiveSyncAllowedDeviceIDs attribute of all Mailboxes $EASMailboxes | foreach {Set-CASMailbox $_.Identity -ActiveSyncAllowedDeviceIDs $_.DeviceID}
PowerShellCorpus/PoshCode/TabExpansion_5.ps1
TabExpansion_5.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. ## Some features(relate to '$_' expansion) require the latest Get-Pipeline.ps1 in a same diretory. (from http://poshcode.org/author/foobar) ## ## 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 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> ## >>> $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 -exp <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 ## [ 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 ### 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 Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Get-Content -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 Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Get-Content -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 Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Get-Content -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 Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_WMIClasses = Get-Content -Path $PSHOME\\WMIClasses.txt;' } $global:_snapin = $null # Load Get-PipeLineObject function for $_ and property name expansion. $_scriptpath = gi $MyInvocation.MyCommand.Path iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1")) 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] + '*' foreach ( $_exp in $_TypeNames_System -like $_opt ) { '[' + $_exp } foreach ( $_exp in $_TypeNames -like $_opt ) { '[' + $_exp } 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 ) { $_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 ( "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 ( $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 ) { $_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 ( "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 ( $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 ( "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; } } 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 + "*" gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/WhoAmI.ps1
WhoAmI.ps1
function whoami { [System.Security.Principal.WindowsIdentity]::GetCurrent().Name }
PowerShellCorpus/PoshCode/List AD Attributes_3.ps1
List AD Attributes_3.ps1
$forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $Schema = $forest.schema $Properties = $Schema.FindAllProperties() foreach($property in $Properties) { "#################################" "Name: {0}" -f $property.Name "Link: {0}" -f $property.link "LinkID: {0}" -f $property.linkid if(!$?) { "Error: {0}" -f $error[0].message } "#################################" }
PowerShellCorpus/PoshCode/Get-NetView.ps1
Get-NetView.ps1
function Get-NetView { switch -regex (NET.EXE VIEW) { "^\\\\\\\\(?<Name>\\S+)\\s+" {$matches.Name}} }
PowerShellCorpus/PoshCode/Set-IPAddress_6.ps1
Set-IPAddress_6.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), @@[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} @@$NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) } Fourth line from the bottom should read $NetInterface.EnableStatic($ip, $mask) You had the variables wrong - you had 1st variable as "$mask" ([string]$mask) and the next usage as "$subnetmask" - both should match. Either have both as "$mask" or both as "$subnetmask."
PowerShellCorpus/PoshCode/TabExpansion_10.ps1
TabExpansion_10.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 (this also support default help and man function) ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion (this also support default help and man function) ## 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> ### 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\\") $_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 ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames.txt $_TypeNames = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } 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 ) { $_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 { $_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 = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref", "Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml" 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 = 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) '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 '.') { $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') } } } # 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 { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } # 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 'All' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'All' $_cmdlet.Definition)[0] } if ( $_cmdlet.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 ( $_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 ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$') { $_pat = $Matches[2] + '*' "regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1' break; } elseif ( $_cmdlet -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; } # 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 { $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 -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 -or "man" -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,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 -or "man" -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 -or "help" -eq $_cmdlet.Name -or "man" -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/check-disabledstatus.ps1
check-disabledstatus.ps1
# check-disabledstatus.ps1 # by Ken Hoover <ken.hoover@yale.edu> - Yale University ITS Windows Systems Team - Spring 2009 # # reads a text file of usernames and outputs CSV showing the status of that user - OK, DISABLED or NOTFOUND if (!($args[0])) { Write-Host "`nPlease specify a file containing usernames to check on the command line.`n" -ForegroundColor yellow exit } # the bit pattern for a disabled user $isdisabled = 0x02 $searcher = new-object DirectoryServices.DirectorySearcher([ADSI]"") $userlist = Get-Content $args[0] | sort $i = 0 foreach ($user in $userlist) { $status = "NOSUCHUSER" $i++ $pc = [int](($i / $userlist.count) * 100) Write-Progress -Activity "Checking users" -Status "$user..." -percentcomplete $pc $searcher.filter = "(&(objectClass=user)(sAMAccountName= $user))" $founduser = $searcher.findOne() # $uac = ($founduser.psbase.properties.useraccountcontrol[0]) if ($founduser.psbase.properties.useraccountcontrol) { if ($founduser.psbase.properties.useraccountcontrol[0] -band $isdisabled) { # Logical AND test $status = "DISABLED" } else { $status = "OK" } } Write-Host "$user, $status" }
PowerShellCorpus/PoshCode/ConvertFrom-SDDL_1.ps1
ConvertFrom-SDDL_1.ps1
filter ConvertFrom-SDDL { <# .SYNOPSIS Convert a raw security descriptor from SDDL form to a parsed security descriptor. Author: Matthew Graeber (@mattifestation) .DESCRIPTION ConvertFrom-SDDL generates a parsed security descriptor based upon any string in raw security descriptor definition language (SDDL) form. ConvertFrom-SDDL will parse the SDDL regardless of the type of object the security descriptor represents. .PARAMETER RawSDDL Specifies the security descriptor in raw SDDL form. .EXAMPLE ConvertFrom-SDDL -RawSDDL 'D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)' .EXAMPLE 'O:BAG:SYD:(D;;0xf0007;;;AN)(D;;0xf0007;;;BG)(A;;0xf0005;;;SY)(A;;0x5;;;BA)', 'O:BAG:SYD:PAI(D;OICI;FA;;;BG)(A;OICI;FA;;;BA)(A;OICIIO;FA;;;CO)(A;OICI;FA;;;SY)' | ConvertFrom-SDDL .INPUTS System.String ConvertFrom-SDDL accepts SDDL strings from the pipeline .OUTPUTS System.Management.Automation.PSObject .LINK http://www.exploit-monday.com #> Param ( [Parameter( Position = 0, Mandatory = $True, ValueFromPipeline = $True )] [ValidateNotNullOrEmpty()] [String[]] $RawSDDL ) Set-StrictMode -Version 2 # Get reference to sealed RawSecurityDescriptor class $RawSecurityDescriptor = [Int].Assembly.GetTypes() | ? { $_.FullName -eq 'System.Security.AccessControl.RawSecurityDescriptor' } # Create an instance of the RawSecurityDescriptor class based upon the provided raw SDDL try { $Sddl = [Activator]::CreateInstance($RawSecurityDescriptor, [Object[]] @($RawSDDL)) } catch [Management.Automation.MethodInvocationException] { throw $Error[0] } if ($Sddl.Group -eq $null) { $Group = $null } else { $SID = $Sddl.Group $Group = $SID.Translate([Security.Principal.NTAccount]).Value } if ($Sddl.Owner -eq $null) { $Owner = $null } else { $SID = $Sddl.Owner $Owner = $SID.Translate([Security.Principal.NTAccount]).Value } $ObjectProperties = @{ Group = $Group Owner = $Owner } if ($Sddl.DiscretionaryAcl -eq $null) { $Dacl = $null } else { $DaclArray = New-Object PSObject[](0) $ValueTable = @{} $EnumValueStrings = [Enum]::GetNames([System.Security.AccessControl.CryptoKeyRights]) $CryptoEnumValues = $EnumValueStrings | % { $EnumValue = [Security.AccessControl.CryptoKeyRights] $_ if (-not $ValueTable.ContainsKey($EnumValue.value__)) { $EnumValue } $ValueTable[$EnumValue.value__] = 1 } $EnumValueStrings = [Enum]::GetNames([System.Security.AccessControl.FileSystemRights]) $FileEnumValues = $EnumValueStrings | % { $EnumValue = [Security.AccessControl.FileSystemRights] $_ if (-not $ValueTable.ContainsKey($EnumValue.value__)) { $EnumValue } $ValueTable[$EnumValue.value__] = 1 } $EnumValues = $CryptoEnumValues + $FileEnumValues foreach ($DaclEntry in $Sddl.DiscretionaryAcl) { $SID = $DaclEntry.SecurityIdentifier $Account = $SID.Translate([Security.Principal.NTAccount]).Value $Values = New-Object String[](0) # Resolve access mask foreach ($Value in $EnumValues) { if (($DaclEntry.Accessmask -band $Value) -eq $Value) { $Values += $Value.ToString() } } $Access = "$($Values -join ',')" $DaclTable = @{ Rights = $Access IdentityReference = $Account IsInherited = $DaclEntry.IsInherited InheritanceFlags = $DaclEntry.InheritanceFlags PropagationFlags = $DaclEntry.PropagationFlags } if ($DaclEntry.AceType.ToString().Contains('Allowed')) { $DaclTable['AccessControlType'] = [Security.AccessControl.AccessControlType]::Allow } else { $DaclTable['AccessControlType'] = [Security.AccessControl.AccessControlType]::Deny } $DaclArray += New-Object PSObject -Property $DaclTable } $Dacl = $DaclArray } $ObjectProperties['Access'] = $Dacl $SecurityDescriptor = New-Object PSObject -Property $ObjectProperties Write-Output $SecurityDescriptor }
PowerShellCorpus/PoshCode/SNTP.ps1
SNTP.ps1
\n<#\n.SYNOPSIS\nGets the SNTP servers a machine is configured to use\n \n.DESCRIPTION\nGets the SNTP servers a machine is configured to use\n \n.PARAMETER Server\nThe machine to get the SNTP Servers for\n \n.EXAMPLE\nPS C:\\> Get-SNTPServer -Server MachineName\nThis is return the SNTP servers for MachienName\n \n.EXAMPLE\nPS C:\\> Get-SNTPServer -server Machine1 | Set-SNTPServer -server Machine2\nThis will get the sntp server for Machine1 and set Machine2 to the same\n\n.EXAMPLE\nPS C:\\> Get-Content servers.txt | Get-SNTPServer \n \n.NOTES\n NAME : Get-SNTPServer\n VERSION : 1.0\n LAST UPDATED: 04/04/2011\n AUTHOR : a Monkey\n \n.LINK\nhttp://amonkeysden.tumblr.com/post/4393059808/sntp-module\n \n#>\nfunction Get-SNTPServer\n{\n [cmdletbinding()]\n Param(\n [Parameter(\n Mandatory = $True,\n Position = 0,\n ParameterSetName = '',\n ValueFromPipeline = $True)]\n [string]$Server\n )\n [string] $z = net time \\\\$server /QUERYSNTP\n if (($z.contains("The current SNTP value is:"))) {\n #$out = "{0}: {1}" -f $Server,$z.split(" ")[5]\n #Write-Output $out\n Write-Output $z.split(" ")[5]\n } else {\n Write-Error "$z"\n }\n}\n \n<#\n.SYNOPSIS\nSets the SNTP servers a machine is configured to use\n \n.DESCRIPTION\nSets the SNTP servers a machine is configured to use\n \n.PARAMETER Servers\nThe machines to set the SNTP Servers for\n \n.PARAMETER $SNTPServerList\nThe machine to get the SNTP Servers for\n \n.EXAMPLE\nPS C:\\> Set-SNTPServer -Server MachineName -SNTPServerList "dc1,dc2"\nThis will set the SNTP servers to DC1 and DC2 for MachienName\n \n.EXAMPLE\nPS C:\\> Get-SNTPServer -server Machine1 | Set-SNTPServer -server Machine2\nThis will get the sntp server for Machine1 and set Machine2 to the same\n\n.EXAMPLE\nPS C:\\> Get-Content servers.txt | Set-SNTPServer -SNTPServerList "dc1,dc2"\n\n.NOTES\n NAME : Set-SNTPServer\n VERSION : 1.0\n LAST UPDATED: 04/04/2011\n AUTHOR : a Monkey\n \n.LINK\nhttp://amonkeysden.tumblr.com/post/4393059808/sntp-module\n\n#>\nfunction Set-SNTPServer\n{\n [cmdletbinding()]\n Param(\n [Parameter(\n Mandatory = $True,\n Position = 0,\n ParameterSetName = '',\n ValueFromPipeline = $True)]\n [string]$Server,\n [Parameter(\n Mandatory = $True,\n Position = 1,\n ParameterSetName = '',\n ValueFromPipeline = $True)]\n [string]$SNTPServerList\n )\n foreach ($s in $Server.Split(",")) \n {\n [string] $z = net time \\\\$s /SETSNTP:$SNTPServerList\n if (($z.contains("The command completed successfully."))) {\n Write-Output $z\n } else {\n Write-Error $z\n }\n }\n}\n \n \n# export the functions to be used\nExport-ModuleMember Set-SNTPServer\nExport-ModuleMember Get-SNTPServer\n \n
PowerShellCorpus/PoshCode/Update-AdminPassword.ps1
Update-AdminPassword.ps1
<# .SYNOPSIS Local administrator password update .DESCRIPTION This script changes the local administrator password. .PARAMETER ADSPath The ActiveDirectory namespace to search for computers .PARAMETER AdminAccount The username of the administrator account .PARAMETER NewPassword The new password .EXAMPLE .\\Update-AdminPassword.ps1 -ADSPath "LDAP://DC=company,DC=com" -AdminAccount "administrator" ` -NewPassword "N3wp@ssw0rd" |Export-Csv .\\sample.csv -NoTypeInformation Description ----------- This example shows all parameters being used with the output being piped to a spreadsheet. .EXAMPLE .\\Update-AdminPassword.ps1 -ADSPath "LDAP://OU=TestOU,DC=company,Dc=com" -AdminAccount Administrator ` -NewPassword Pass12345 ComputerName UserName Status ------------ -------- ------ L1132C-VM01 Administrator The network path was not found. l1132c-pc17 Administrator The user name could not be found. l1132c-pc05 Administrator Access is denied. L1132C-PC01 Administrator Password updated Description ----------- This shows an example of the output .NOTES ScriptName is used to register events for this script LogName is used to determine which classic log to write to This script assumes that the includes folder contains the libraries needed for this script to work. I've not added credentials for this, so it will need to be run from an account that has the ability to change passwords on your computers. .LINK http://scripts.patton-tech.com/wiki/PowerShell/Production/UpdateAdminPassword .LINK http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet .LINK http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement #> Param ( [Parameter(Mandatory=$true)] [string]$ADSPath, [Parameter(Mandatory=$true)] [string]$AdminAccount, [Parameter(Mandatory=$true)] [string]$NewPassword ) Begin { $ScriptName = $MyInvocation.MyCommand.ToString() $LogName = "Application" $ScriptPath = $MyInvocation.MyCommand.Path $Username = $env:USERDOMAIN + "\\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message . .\\includes\\ActiveDirectoryManagement.ps1 . .\\includes\\ComputerManagement.ps1 } Process { $Workstations = Get-ADObjects -ADSPath $ADSPath $Jobs = @() foreach ($Workstation in $Workstations) { [string]$ThisWorkstation = $Workstation.Properties.name $ThisJob = New-Object PSobject [string]$Retval = Set-Pass -ComputerName $ThisWorkstation -UserName $AdminAccount -Password $NewPassword Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "ComputerName" -Value $ThisWorkstation Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "UserName" -Value $AdminAccount Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "Status" -Value $RetVal.Trim() $Jobs += $ThisJob $ThisJob } $Message = [system.string]::Join("`n",($Jobs)) Write-EventLog -LogName $LogName -Source $ScriptName -EventId "101" -EntryType "Information" -Message $Message } End { $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message }
PowerShellCorpus/PoshCode/chkhash_24.ps1
chkhash_24.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length $spaces = "" if ($global:lastlen -gt $writestr.length) { $spaces = " " * ($global:lastlen-$writestr.length) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:oldctop=[console]::cursortop if ([console]::cursorleft -ne 0) {$global:oldctop+=1} write-host "$spaces" -nonewline $global:lastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=0 } function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other { # and before printing something else if ($global:oldctop -eq $null) {return} [console]::cursortop=$global:oldctop [console]::cursorleft=0 } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false "ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, " "in order to detect corrupt or hacked files." "" ".\\chkhash.ps1 -h for usage." "" for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]" " [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml" " or create it and store hashes there if not present]" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" " [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude " " c:\\users\\eve\\hashes directory and subdirs]" " PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u" " [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to" " existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]" " PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml" " [Load hashes.xml and check hashes of all files contained within.]" "" "Note: files in subdirectories of any specified directory are automatically processed." " if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") { $i++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { while (($i+1) -lt $args2.count) { $i++ if ($args2[$i] -like "-*") {break} $exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories. } continue } $args3+=@($args2[$i]) # Add files/dirs } if ($args3.count -ne 0) { # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files, minus directories and minus files in excluded paths if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} WriteFileNameEnd $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es)." $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {WriteFileNameEnd; "Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..." $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches WriteFileNameEnd if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } WriteFileNameEnd # restore cursor position after last write string if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Search-SPN.ps1
Search-SPN.ps1
<# .SYNOPSIS This function is used for finding all AD objects with a given SPN. .DESCRIPTION Finds all AD objects that have a given SPN. Wildcard search patterns are acceptable. .PARAMETER SearchRoot The root path at which to search. Should be in the form of "LDAP://xyz". .PARAMETER SPNName The name of the SPN to search for. Can include the "*" wildcard character. .PARAMETER Credential The alternate credentials to use when searching the domain. Can be either a string (user name) or a PSCredential object. .EXAMPLE Search-SPN -SearchRoot "LDAP://mydomain.com" -SPNName "MSSQLSvc*" -Credential josh@mydomain.com Will find all objects with a SPN starting with "MSSQLSvc" (used for SQL Server services) within the "mydomain.com" AD domain. Will prompt the user for the password of the "josh@mydomain.com" account and use that to authenticate against the domain. .NOTES Author - Josh Feierman Date - 5/22/2012 #> function Search-SPN { [Cmdletbinding()] param ( [parameter(mandatory=$true)] [string]$SearchRoot, [parameter(mandatory=$true)] [string]$SPNName, [parameter(mandatory=$false)] $Credential ) try { if ($Credential) { switch ($Credential.GetType().FullName) { "System.Management.Automation.Credential" {} "System.String" { $Credential = Get-Credential -Credential $Credential } default { throw "Invalid type given for parameter Credential." } } $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($Credential.Password) $Password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr) $de = New-Object system.DirectoryServices.DirectoryEntry $SearchRoot,$Credential.UserName,$Password } else { $de = New-Object system.DirectoryServices.DirectoryEntry $SearchRoot } $ds = New-Object System.DirectoryServices.DirectorySearcher $de $ds.Filter = "(servicePrincipalName=$SPNName)" $ds.FindAll() } catch { if ($_.Exception.Message -like "*The server is not operational*") { Write-Warning "Server for search root '$SearchRoot' could not be contacted. Exiting." } else { Write-Warning "Error occurred while executing." Write-Warning $_.Exception.Message } Write-Verbose $_.Exception } }
PowerShellCorpus/PoshCode/Deploy VM with Static IP.ps1
Deploy VM with Static IP.ps1
# 1. Create a simple customizations spec: $custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows -OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” –DomainAdminUsername “user” –DomainAdminPassword “password” # 2. Modify the default network customization settings: $custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress 192.168.121.228 -SubnetMask 255.255.248.0 -Dns 192.168.108.1 -DefaultGateway 192.168.108.1 # 3. Deploy a VM from a template using the newly created customization: New-VM -Name “MyNewVM” -Template $template -VMHost $vmHost -OSCustomizationSpec $custSpec
PowerShellCorpus/PoshCode/Import-UniqueModule.ps1
Import-UniqueModule.ps1
## WARNING: I take no responsibility for how weird this is. function Import-UniqueModule { param([Parameter(Mandatory=$true)][String]$ModuleName) $unique = [guid]::NewGuid().Guid -replace "-" Import-Module $ModuleName -Prefix $unique Get-Command -Module $ModuleName | New-Alias -Name {$_.Name -replace $unique} -Value { "{0}/{1}" -f $_.ModuleName, $_.name } }
PowerShellCorpus/PoshCode/Start-Encryption.ps1
Start-Encryption.ps1
## Start-Encryption ################################################################################################## ## Rijndael symmetric key encryption ... with no passes on the key. Very lazy. ## USAGE: ## $encrypted = Encrypt-String "Oisin Grehan is a genius" "P@ssw0rd" ## Decrypt-String $encrypted "P@ssw0rd" ## ## You can choose to return an array by passing -arrayOutput to Encrypt-String ## I chose to use Base64 encoded strings because they're easier to save ... [Reflection.Assembly]::LoadWithPartialName("System.Security") function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key", [switch]$arrayOutput) { $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $c = $r.CreateEncryptor() $ms = new-Object IO.MemoryStream $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write" $sw = new-Object IO.StreamWriter $cs $sw.Write($String) $sw.Close() $cs.Close() $ms.Close() $r.Clear() [byte[]]$result = $ms.ToArray() if($arrayOutput) { return $result } else { return [Convert]::ToBase64String($result) } } function Decrypt-String($Encrypted, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key") { if($Encrypted -is [string]){ $Encrypted = [Convert]::FromBase64String($Encrypted) } $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [System.Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $d = $r.CreateDecryptor() $ms = new-Object IO.MemoryStream @(,$Encrypted) $cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read" $sr = new-Object IO.StreamReader $cs Write-Output $sr.ReadToEnd() $sr.Close() $cs.Close() $ms.Close() $r.Clear() }
PowerShellCorpus/PoshCode/Ayth.ps1
Ayth.ps1
# ======================================================================== # # Microsoft PowerShell Source File -- Created with PowerShell Plus Professional # # NAME: Disable-MassMailPF.ps1 # # AUTHOR: Darrin Henshaw , Ignition IT Canada Ltd. # DATE : 8/13/2008 # # COMMENT: Used to disable mail on an imported list of public folders. # # ======================================================================== # param($csv = $Args[0]) # # # Import the list of the public folders to the variable $pflist # $pflist = Import-Csv -path $csv # # # Loop through allt he public folder names in the variable we created above. # foreach ($pf in $pflist) # # # For all of them, we get their properties and examine as to whether they are mail enabled already. If they are we disable the mail on them. # {Get-PublicFolder -identity $pf.Identity |Where-Object {$_.MailEnabled -eq "True"}|Disable-MailPublicFolder -confirm:$false -Server hfxignvmexpf1} # # # Line of code used for testing just outs to the commandline the value of our imported property. # # {Out-Host -inputObject $pf.Identity -paging} param($csv = $Args[0]) $Preference = $ConfirmPreference $ConfirmPreference = 'none' # Import the list of the public folders to the variable $pflist $pflist = Import-Csv -path $csv # Loop through allt he public folder names in the variable we created above. foreach ($pf in $pflist) # For all of them, we get their properties and examine as to whether they are mail enabled already. If they are we disable the mail on them. {Get-PublicFolder -identity $pf.Identity |Where-Object {$_.MailEnabled -eq $true}|Disable-MailPublicFolder -Server hfxignvmexpf1} $ConfirmPreference = $Preference
PowerShellCorpus/PoshCode/Get_Set Signature _3.0.ps1
Get_Set Signature _3.0.ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping) #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## Get all the signatures ## ## ls | Select-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 2.1 - Added some extra exports and aliases, and included my Start-AutoSign script... ## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support ## 1.7 - Modified the reading of certs to better support people who only have one :) ## 1.6 - Converted to work with CTP 3, and added function help comments ## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file ## Note: If you get this off PoshCode, you'll have to create it yourself, see below: ## 1.4 - Moved the default certificate setting into an external psd1 file. ## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-AuthenticodeSigned ## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned ## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files ## It's important to remember that the signatures are NOT checked by PowerShell yet... ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## #################################################################################################### ## README! README! README! README! ################################################################# ## README! README! README! README! ################################################################# ## ## You should set the location to your default signing certificate. The permanent way to do that is ## to modify (or create) the .psd1 file to set the PrivateData member variable. Otherwise you'll be ## prompted to provide a cert path whenever you try to sign a script without passing a certificate. ## ## The PrivateData variable should point at your code-signing certificate either with a full path ## or with the THUMBPRINT of a certificate you have available in your Cert:\\CurrentUser\\My\\ provider ## ## EG: ## 4F8842037D878C1FCDC6FD1313B200449716C353 ## OR: ## "Cert:\\CurrentUser\\My\\4F8842037D878C1FCDC6FD1313B200449716C353" ## OR a file name: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## ## The simplest thing is to just update the PSD1 ## ## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 ` ## -Author "" -COmpany "" -Copy "" -Desc "" ` ## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() ` ## -PrivateData 4F8842037D878C1FCDC6FD1313B200449716C353 ## #################################################################################################### #################################################################################################### function Get-UserCertificate { <#.SYNOPSIS Gets the user's default signing certificate so we don't have to ask them over and over... .DESCRIPTION The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can be reused without re-querying for the location and/or password ... .RETURNVALUE An X509Certificate2 suitable for code-signing #> [CmdletBinding()] Param() Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)" $UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData $ExecutionContext.SessionState.Module.PrivateData = $UserCertificate.Thumbprint return $UserCertificate } function Get-AuthenticodeCertificate { [CmdletBinding()] PARAM ( $Name = $ExecutionContext.SessionState.Module.PrivateData ) BEGIN { if(!$ExecutionContext.SessionState.Module.PrivateData -and $Name) { $ExecutionContext.SessionState.Module.PrivateData = $Name } } PROCESS { trap { Write-Host "The authenticode script module requires configuration to function fully!" Write-Host Write-Host "You must put the path to your default signing certificate in the module metadata"` "file before you can use the module's Set-Authenticode cmdlet or to the 'mine'"` "feature of the Select-AuthenticodeSigned or Test-AuthenticodeSignature. To set it up, you can do this:" Write-Host Write-Host "PrivateData = 'C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\PoshCerts\\Code-Signing.pfx'" Write-Host Write-Host "If you load your certificate into your 'CurrentUser\\My' store, or put the .pfx file"` "into the folder with the Authenthenticode module script, you can just specify it's"` "thumprint or filename, respectively. Otherwise, it should be a full path." Write-Error $_ return } # Import-LocalizedData -bindingVariable CertificatePath -EA "STOP" if(!$Name) { $certs = ls Cert:\\CurrentUser\\My if($certs.Count) { Write-Host "You have $($certs.Count) certs in your local cert storage which you can specify by Thumbprint:" -fore cyan $certs | Out-Host } $Name = $(Read-Host "Please specify a user certificate") } if($Name -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { Write-Debug "CertificatePath: $Name" $ResolvedPath = $Null $ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue" if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { Write-Debug "Not a full path: $ResolvedPath" $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { Write-Debug "Not a file Path: $ResolvedPath" $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $("$Name".ToUpper()) -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" Write-Debug "ResolvedPath: $ResolvedPath" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } Write-Verbose "Certificate: $($Certificate | Out-String)" $Name = $Certificate } return $Name } } #################################################################################################### function Test-AuthenticodeSignature { <#.SYNOPSIS Tests a script signature to see if it is valid, or at least unaltered. .DESCRIPTION The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it is Valid, OR **unaltered** and signed by the user's certificate .NOTES Test-AuthenticodeSignature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate. .EXAMPLE ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_} To get the signature reports for all the scripts that we consider safely signed. .EXAMPLE ls | ? { gas $_ | Test-AuthenticodeSignature } List all the valid signed scripts (or scripts signed by our cert) .INPUTTYPE System.Management.Automation.Signature .PARAMETER Signature Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature. .PARAMETER ForceValid Switch parameter, forces the signature to be valid -- otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate). Aliases Valid .RETURNVALUE Boolean value representing whether the script's signature is valid, or YOUR certificate ################################################################################################## #> [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] # The signature to test. $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint) ) ) } #################################################################################################### function Set-AuthenticodeSignature { <#.SYNOPSIS Adds an Authenticode signature to a Windows PowerShell script or other file. .DESCRIPTION The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed. .NOTES After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script. When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate To sign all of the files with the specified certificate .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate. .INPUTTYPE String. You can pipe a file path to Set-AuthenticodeSignature. .PARAMETER FilePath Specifies the path to a file that is being signed. Aliases Path, FullName .PARAMETER Certificate Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails. .PARAMETER Force Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions. .Parameter HashAlgorithm Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm. Files that are signed with a different hashing algorithm might not be recognized on other systems. .PARAMETER IncludeChain Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default. Valid values are: -- Signer: Includes only the signer's certificate. -- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority. --All: Includes all the certificates in the certificate chain. .PARAMETER TimestampServer Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string. Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing. .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) , [Switch]$Force , [ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")] [String]$HashAlgorithm #="SHA1" , [ValidateSet("Signer","NotRoot","All")] [String]$IncludeChain #="NotRoot" , [String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll" ) BEGIN { if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $Certificate = Get-AuthenticodeCertificate $Certificate } $PSBoundParameters["Certificate"] = $Certificate } PROCESS { Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)" $PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath) if(Test-Path $FilePath -Type Leaf) { Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters } else { Write-Warning "Cannot sign folders: '$FilePath'" } } } #################################################################################################### function Get-AuthenticodeSignature { <#.SYNOPSIS Gets information about the Authenticode signature in a file. .DESCRIPTION The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE Get-AuthenticodeSignature script.ps1 To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string[]] $FilePath ) PROCESS { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath } } #################################################################################################### function Select-AuthenticodeSigned { <#.SYNOPSIS Select files based on the status of their Authenticode Signature. .DESCRIPTION The Select-AuthenticodeSigned function filters files on the pipeline based on the state of their authenticode signature. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1,*.ps[dm]1 | Select-AuthenticodeSigned To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter()] # Return only files that are signed with the users' certificate (as returned by Get-UserCertificate). [switch]$MineOnly , [Parameter()] # Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate). [switch]$NotMineOnly , [Parameter()] [Alias("HashMismatch")] # Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match). [switch]$BrokenOnly , [Parameter()] # Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate). # # That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly) [switch]$TrustedOnly , [Parameter()] # Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate. [switch]$ValidOnly , [Parameter()] # Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate). [switch]$InvalidOnly , [Parameter()] # Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed. [switch]$UnsignedOnly ) PROCESS { if(!(Test-Path -PathType Leaf $FilePath)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$FilePath'" # } } else { foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) { # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $FilePath" return } # Trusted only returns ONLY things which are Valid if($ValidOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $FilePath" return } # AllValid returns only things that are SIGNED and not HashMismatch if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $FilePath" return } # InvalidOnly returns things that are Either NotSigned OR HashMismatch ... if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $FilePath" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $FilePath" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint)))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" return } # NotMine returns only things that were NOT signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint)))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Signed: $FilePath" return } get-childItem $sig.Path }} } } function Start-AutoSign { # .Synopsis # Start a FileSystemWatcher to automatically sign scripts when you save them # .Description # Create a FileSystemWatcher with a scriptblock that uses the Authenticode script Module to sign anything that changes # .Parameter Path # The path to the folder you want to monitor # .Parameter Filter # A filter to select only certain files: by default, *.ps* (because we can only sign .ps1, .psm1, .psd1, and .ps1xml # .Parameter Recurse # Whether we should also watch autosign files in subdirectories # .Parameter CertPath # The path or name of a certain certificate, to override the defaults from the Authenticode Module # .Parameter NoNotify # Whether wo should avoid using Growl to notify the user each time we sign something. # .NOTE # Don't run this on a location where you're going to be generating dozens or hundreds of files ;) PARAM($Path=".", $Filter= "*.ps*", [Switch]$Recurse, $CertPath, [Switch]$NoNotify) if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) { Import-Module Growl Register-GrowlType AutoSign "Signing File" -ErrorAction 0 } else { $NoNotify = $false } $realItem = Get-Item $Path -ErrorAction Stop if (-not $realItem) { return } $Action = { ## Files that can't be signed show up as "UnknownError" with this message: $InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider" ## Files that are signed with a cert we don't trust also show up as UnknownError, but with different messages: # $UntrustedCert = "A certificate chain could not be built to a trusted root authority" # $InvalidCert = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider" # $ExpiredCert = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file" ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature | Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } | Select-Object -ExpandProperty Path ) { if(!$NoNotify) { Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file" } if($CertPath) { Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath } else { Set-AuthenticodeSignature -FilePath $file } } } $watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse } Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null } Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias" Set-Alias slas Select-AuthenticodeSigned -Description "Authenticode Module Alias" Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias" Export-ModuleMember -Alias gas,sas,slas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate, Start-AutoSign # SIG # Begin signature block # MIIIPAYJKoZIhvcNAQcCoIIILTCCCCkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUbRDcSlj31gB3Dj0E/HWIHY/w # 5IKgggVaMIIFVjCCBD6gAwIBAgIQSX2g7+3+PL1oSJra3tEBIzANBgkqhkiG9w0B # AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0 # IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD # VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS # Rmlyc3QtT2JqZWN0MB4XDTA5MTAxNjAwMDAwMFoXDTEwMTAxNjIzNTk1OVowgcQx # CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUxNDYyMzERMA8GA1UECAwITmV3IFlvcmsx # EjAQBgNVBAcMCVJvY2hlc3RlcjEUMBIGA1UECQwLTVMgMDgwMS0xN0ExGjAYBgNV # BAkMETEzNTAgSmVmZmVyc29uIFJkMRowGAYDVQQKDBFYZXJveCBDb3Jwb3JhdGlv # bjEUMBIGA1UECwwLU0VFRFUgVG9vbHMxGjAYBgNVBAMMEVhlcm94IENvcnBvcmF0 # aW9uMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+BtkDUSRsr9qshYW # 6mBLwe62RdoKaBiCZh1whKQbAqN58lmbN3fP2Qf6eheR03EyqPXq5gGQO8SpeeOn # tDmlgR47dKFfawWKLEM4H189FJ6VHKD8Hmk1+/OAv/6F45HvbXOrGmisUgKplmzl # tmot9uv04nyFlRXMPbHwKxNlWOdSSs1N9Y+q7y3kuSBm4bCqquqEFnm7gAzHt/A1 # 1CkT8f/0UP0ODKj0Cs/hc+b/xOCCL06SALYOYtMdBFwluBs85p2Bv1WcdUIELprz # jnOjgoF4vk29UIUNkDZ5j2d0W0FCNd61ukm9faJMuU2/yw348sxclSoT18yOeC+Z # vKc4lQIDAQABo4IBbzCCAWswHwYDVR0jBBgwFoAU2u1kdBScFDyr3ZmpvVsoTYs8 # ydgwHQYDVR0OBBYEFAu07ifjpHK32XeSDsdjIK4/R25LMA4GA1UdDwEB/wQEAwIH # gDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMBEGCWCGSAGG+EIB # AQQEAwIEEDBGBgNVHSAEPzA9MDsGDCsGAQQBsjEBAgEDAjArMCkGCCsGAQUFBwIB # Fh1odHRwczovL3NlY3VyZS5jb21vZG8ubmV0L0NQUzBCBgNVHR8EOzA5MDegNaAz # hjFodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLVVTRVJGaXJzdC1PYmplY3Qu # Y3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuY29t # b2RvY2EuY29tMCEGA1UdEQQaMBiBFkpvZWwuQmVubmV0dEBYZXJveC5jb20wDQYJ # KoZIhvcNAQEFBQADggEBAG5+It5AFsnqx1GDTuHxuExJGtpRYH6OatSs3eV507zz # 5tyKbtCros6j92rvJOUfefk38saqbk81o5vMvEyQ/lQ7tp06NV0QBdt5WtoOnUZk # u2lG4NcxiSz5vxQRF4+3mUZ77K3kRu6zY+zrauTTONmRPOdhYMMbKfZ67kePVNNv # gnueXBxhd+xj5FJUVTW0qlks6+uYMKNM+MLvRxV83WUYwpnfcQyyvVILsVdw56qp # OzOxIsQDc2flhqYVktPjL80fOXAPWzs88VXxoEkO3fvqHXi3VlWxMVV/861RORzk # 5aleuMEp/2Ue1dJG279ATD1QDCHiG11Vz34Pdptf3FYxggJMMIICSAIBATCBqjCB # lTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug # Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho # dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3Qt # T2JqZWN0AhBJfaDv7f48vWhImtre0QEjMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3 # AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBSLcWVsGmEs # y3aqToxGv4N7GtZKaTANBgkqhkiG9w0BAQEFAASCAQBKs1LvUwZC+0Bs9/3D03/L # xp9NYjTfnXfeKI73KOnw4RMKY4rnnbEi0eLxsKOyFTDLbvEkO0dPeRa8LVANktgx # H2zHECjyud949UaU1CnAhJhbx0EHQQatumsBEcaQqO/vJGTTE3F1faxIbQoyxkZC # bax1ISAF1JeR8avSDgLEEDj1kqTP7a5lNTO0k9CX0kvmF7GXGBwEJJ0XZh1ipCFW # PEF9xdE3wP3iXs2rVk8LZIKx6Iz14PPhp/004hKKPUolAg9PPJM+fiN6vsluTpoH # tDe5OXi71/Hpl51E9XNpRz/kUyB5MSxvsl9bf0DTHwWTa4hOrvWUBpkPU10FT7y6 # SIG # End signature block
PowerShellCorpus/PoshCode/vSphere Resultant Privs.ps1
vSphere Resultant Privs.ps1
# Need the Quest ActiveRoles cmdlets for this one. Add-PSSnapin Quest.ActiveRoles* -ea SilentlyContinue function Get-Groups { param($principal) # Start with this principal's base set of groups. Write-Verbose "Checking principal $principal" $groups = Get-QADUser $principal | Get-QADMemberOf # Groups can be members of groups, so iterate until the list size remains fixed. do { $startLength = $groups.length Write-Verbose ("Start length " + $startLength) $groups += $groups | Get-QADMemberOf $groups = $groups | Sort -Unique $endLength = $groups.length Write-Verbose ("End length " + $endLength) } while ($endLength -ne $startLength) Write-Output $groups } # Get the resultant privileges that a user has for a given object. function Get-ResultantPrivileges { param($principal, $viobject) # Get the groups for this user. $groups = Get-Groups -principal $principal $groupNames = $groups | Foreach { $_.Name } # Get the full permission set for this object. $perms = $viobject | Get-VIPermission # Determine the list of roles that apply to this principal. $relevantPerms = $perms | Where { (($_.IsGroup -eq $true) -and ($groupNames -contains $_.Principal)) -or ($_.Principal -eq $principal) } # Retrieve all these roles. $roleNames = $relevantPerms | Foreach { $_.Role } | Sort -Unique Write-Verbose "Rolenames are $roleNames" $roleObjects = Get-VIRole $roleNames $roleCount = ($roleObjects | Measure-Object).Count # The resultant set is the intersection of the privileges within the role. $roleObjects | Foreach { $_.PrivilegeList } | Group | Where { $_.Count -eq $roleCount } | Select Name } # Example: # Get-ResultantPrivileges -principal "VMWORLD\\cshanklin" -viobject (Get-VM OpenFiler)
PowerShellCorpus/PoshCode/Get-PipeLineObject_2.ps1
Get-PipeLineObject_2.ps1
# For TabExpansion.ps1 # this requires latest TabExpansion.ps1 in a same directory 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] } } }
PowerShellCorpus/PoshCode/VM Last Poweron Time.ps1
VM Last Poweron Time.ps1
# Get a VM's last power on date based on the VM's events. # Requires PowerCLI 4.0 and PowerShell v2. function Get-LastPowerOn { param( [Parameter( Mandatory=$true, ValueFromPipeline=$true, HelpMessage="VM" )] [VMware.VimAutomation.Types.VirtualMachine] $VM ) Process { # Patterns that indicate an attempt to power a VM on. This differ # across versions and likely across language. Please add your own # if you find one missing. $patterns = @( "*Power On virtual machine*", # vCenter 4 English "*is starting*" # ESX 4/3.5 English ) $events = $VM | Get-VIEvent $qualifiedEvents = @() foreach ($pattern in $patterns) { $qualifiedEvents += $events | Where { $_.FullFormattedMessage -like $pattern } } $qualifiedEvents = $qualifiedEvents | Where { $_ -ne $null } $sortedEvents = Sort-Object -InputObject $qualifiedEvents -Property CreatedTime -Descending $event = $sortedEvents | select -First 1 $obj = New-Object PSObject $obj | Add-Member -MemberType NoteProperty -Name VM -Value $_ $obj | Add-Member -MemberType NoteProperty -Name PowerState -Value $_.PowerState $obj | Add-Member -MemberType NoteProperty -Name LastPoweron -Value $null if ($event) { $obj.LastPoweron = $event.CreatedTime } Write-Output $obj } }
PowerShellCorpus/PoshCode/Poczta.ps1
Poczta.ps1
param( [switch]$Help , [string] $User , [string] $Password , [string[]] $ComputerNames = @() ) $usage = @' Get-OUComputerNames usage : [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...] returns : Sets local account passwords on one or more computers author : Nathan Hartley '@ if ($help) {Write-Host $usage;break} $ComputerNames += @($input) if (! $ComputerNames) { $ComputerNames = $env:computername } function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) { "*** Setting password for $ChangeComputer/$ChangeUser" & { $ErrorActionPreference="silentlycontinue" ([ADSI] "WinNT://$computer/$user").SetPassword($password) if ($?) { " Success" } else { " Failed: $($error[0])" } } } ForEach ($computer in $ComputerNames) { ChangePassword $computer $user $password }
PowerShellCorpus/PoshCode/Select-FilteredObject.ps.ps1
Select-FilteredObject.ps.ps1
##############################################################################\n##\n## Select-FilteredObject\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\nProvides an inteactive window to help you select complex sets of objects.\nTo do this, it takes all the input from the pipeline, and presents it in a\nnotepad window. Keep any lines that represent objects you want to retain,\ndelete the rest, then save the file and exit notepad.\n\nThe script then passes the original objects that you kept along the\npipeline.\n\n.EXAMPLE\n\nGet-Process | Select-FilteredObject | Stop-Process -WhatIf\nGets all of the processes running on the system, and displays them to you.\nAfter you've selected the ones you want to stop, it pipes those into the\nStop-Process cmdlet.\n\n#>\n\n## PowerShell runs your "begin" script block before it passes you any of the\n## items in the pipeline.\nbegin\n{\n Set-StrictMode -Version Latest\n\n ## Create a temporary file\n $filename = [System.IO.Path]::GetTempFileName()\n\n ## Define a header in a "here-string" that explains how to interact with\n ## the file\n $header = @"\n############################################################\n## Keep any lines that represent obects you want to retain,\n## and delete the rest.\n##\n## Once you finish selecting objects, save this file and\n## exit.\n############################################################\n\n"@\n\n ## Place the instructions into the file\n $header > $filename\n\n ## Initialize the variables that will hold our list of objects, and\n ## a counter to help us keep track of the objects coming down the\n ## pipeline\n $objectList = @()\n $counter = 0\n}\n\n## PowerShell runs your "process" script block for each item it passes down\n## the pipeline. In this block, the "$_" variable represents the current\n## pipeline object\nprocess\n{\n ## Add a line to the file, using PowerShell's format (-f) operator.\n ## When provided the ouput of Get-Process, for example, these lines look\n ## like:\n ## 30: System.Diagnostics.Process (powershell)\n "{0}: {1}" -f $counter,$_.ToString() >> $filename\n\n ## Add the object to the list of objects, and increment our counter.\n $objectList += $_\n $counter++\n}\n\n## PowerShell runs your "end" script block once it completes passing all\n## objects down the pipeline.\nend\n{\n ## Start notepad, then call the process's WaitForExit() method to\n ## pause the script until the user exits notepad.\n $process = Start-Process Notepad -Args $filename -PassThru\n $process.WaitForExit()\n\n ## Go over each line of the file\n foreach($line in (Get-Content $filename))\n {\n ## Check if the line is of the special format: numbers, followed by\n ## a colon, followed by extra text.\n if($line -match "^(\\d+?):.*")\n {\n ## If it did match the format, then $matches[1] represents the\n ## number -- a counter into the list of objects we saved during\n ## the "process" section.\n ## So, we output that object from our list of saved objects.\n $objectList[$matches[1]]\n }\n }\n\n ## Finally, clean up the temporary file.\n Remove-Item $filename\n}
PowerShellCorpus/PoshCode/Decode Psi IM passwords.ps1
Decode Psi IM passwords.ps1
function decrypt-psi ($jid, $pw) { $OFS = ""; $u = 0; for($p=0;$p -lt $pw.Length;$p+=4) { [char]([int]"0x$($pw[$p..$($p+3)])" -bxor [int]$jid[$u++]) } } $accounts = ([xml](cat ~\\psidata\\profiles\\default\\accounts.xml))["accounts"]["accounts"] foreach($account in ($accounts | gm a[0-9]*)) { $a = $accounts.$($account.Name) "$($a.jid.'#text'):$( decrypt-psi $a.jid.'#text' $a.password.'#text' )" }
PowerShellCorpus/PoshCode/New-SelfRestartingTask.ps1
New-SelfRestartingTask.ps1
function New-SelfRestartingTask { #.Notes # For production use you should consider investigating more specific matching in the Query clause. # # There are many possibilities here: you could watch for instances of a process with specific command-line parameters, or a certain caption, etc. Or, you could match against one process, but fire off a different one when it crashes. # # Have a look at the Win32_Process class to see all the properties available for matching. #.Link # Win32_Process Class http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx #.Link # __InstanceDeletionEvent http://msdn.microsoft.com/en-us/library/aa394652%28VS.85%29.aspx #.Link # ScriptCenter article on Events http://www.microsoft.com/technet/scriptcenter/topics/winpsh/events.mspx #.Synopsis # Restarts an application when it exits or crashes #.Description # Create a WMIEvent handler to watch for the termination of a specific executable and restart it. # #.Parameter Application # The path to an application you want to restart when it crashes # #.Parameter Parameters # Parameters to be passed to the application when we (re)start it # #.Parameter Start # Automatically start the process (even if it's already running) # #.Parameter Interval # Polling interval to check whether the application has exited or not # #.Example # New-SelfRestartingTask notepad -Start # # Description # ----------- # Starts notepad right away and monitors for crash or exit and restarts it. # #.Example # New-SelfRestartingTask C:\\Program` Files\\Internet` Explorer\\IExplore.exe http://HuddledMasses.org # # Description # ----------- # Monitors for the termination of Internet Explorer and restarts it pointed at my blog. # Note that this does NOT start IE, so it could already be running, or you should start it by hand later... # param( [Parameter(Mandatory=$true, Position=0)] [string]$Application , [Parameter(Mandatory=$false)] [double]$Interval = 5.0 , [Parameter(Mandatory=$false)] [switch]$Start , [Parameter(ValueFromRemainingArguments=$true)] [string[]]$Parameters ) $ExecutablePath = gcm $Application -type application | select -expand definition -first 1 | %{ $_ -replace '\\\\','\\\\' } if($Parameters) { $Parameters = "-ArgumentList `"$($Parameters -join '", "')`"" } $sb = Invoke-Expression "{ Start-Process `"$ExecutablePath`" $Parameters }" Register-WMIEvent -Action $sb -Query "Select * From __InstanceDeletionEvent Within $Interval Where TargetInstance ISA 'Win32_Process' And TargetInstance.ExecutablePath='$ExecutablePath'" | Out-Null if($Start){ sleep -milli 500 &$sb } }
PowerShellCorpus/PoshCode/TheMathFunction.ps1
TheMathFunction.ps1
Add-Type -Path (Join-Path (Split-Path $Profile) Libraries\\LoreSoft.MathExpressions.dll) ## You can dot-source this in 1.0 after uncommenting the following line, and deleting the first and last lines. # [Reflection.Assembly]::LoadFrom((Join-Path (Split-Path $Profile) Libraries\\LoreSoft.MathExpressions.dll)) | Out-Null $MathEvaluator = New-Object LoreSoft.MathExpressions.MathEvaluator Function Use-Math { $MathEvaluator.Evaluate( ($args -join " ") ) } Set-Alias Math Use-Math Export-ModuleMember -Function * -Alias *
PowerShellCorpus/PoshCode/Home Directory Perms.ps1
Home Directory Perms.ps1
$FolderPath = "\\\\site filer\\userdata$\\" $rootfolder = Get-ChildItem -Path $FolderPath -recurse foreach ($file in $rootfolder) { $file.FullName Get-Acl $file.FullName | Format-List $acl = Get-Acl $file.FullName $acl.Access | %{$acl.RemoveAccessRule($_)} #Values ($False, $True) place Administrators,Domain Admins and System. $acl.SetAccessRuleProtection($False, $True) $Rights = [System.Security.AccessControl.FileSystemRights]::FullControl $inherit = [System.Security.AccessControl.FileSystemAccessRule]::ContainerInherit -bor [System.Security.AccessControl.FileSystemAccessRule]::ObjectInherit $Propagation = [System.Security.AccessControl.PropagationFlags]::None $Access = [System.Security.AccessControl.AccessControlType]::Allow $acct=New-Object System.Security.Principal.NTAccount("Builtin\\Administrators") $acl.SetOwner($acct) Set-Acl $file.FullName $acl Get-Acl $file.FullName | Format-List } Write-Host "##########################################" -ForegroundColor Green Write-Host "# #" -ForegroundColor Green Write-Host "#Adding user specific Permissions now #" -ForegroundColor Green Write-Host "# #" -ForegroundColor Green Write-Host "##########################################" -ForegroundColor Green $rootfolder = Get-ChildItem -Path $FolderPath -recurse foreach ($userfolder in $rootfolder) { $userfolder.FullName If (get-user "DomainName\\$userfolder") { Get-Acl $userfolder.FullName | Format-List $acl = Get-Acl $userfolder.FullName $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userfolder.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.AddAccessRule($rule) Set-Acl $userfolder.FullName $acl Get-Acl $userfolder.FullName | Format-List } }
PowerShellCorpus/PoshCode/Publish Friendfeed Entry.ps1
Publish Friendfeed Entry.ps1
#Publish FF Entry using PowerShell script #Description: PowerShell script to publish an entry to Friendfeed. #Change the FF Username and Remotekey in the script. #More info on the FF Api: http://friendfeed.com/api/ #Change the FF Username and Remotekey in the script. #Author: Stefan Stranger #Website: http://tinyurl.com/sstranger #Date: 12/05/2010 #Version: 0.1 [System.Reflection.Assembly]::LoadWithPartialName(”System.Web") | Out-Null Function Publish-FFEntry([string] $FFEntryText) { [System.Net.ServicePointManager]::Expect100Continue = $false $request = [System.Net.WebRequest]::Create("http://friendfeed-api.com/v2/entry") $Username = "username" $Remotekey = "remotekey" $request.Credentials = new-object System.Net.NetworkCredential($Username, $Remotekey) $request.Method = "POST" $request.ContentType = "application/x-www-form-urlencoded" write-progress "Publishing FF Entry" "Posting Entry" -cu $FFEntryText $formdata = [System.Text.Encoding]::UTF8.GetBytes( "body=" + $FFEntryText ) $requestStream = $request.GetRequestStream() $requestStream.Write($formdata, 0, $formdata.Length) $requestStream.Close() $response = $request.GetResponse() write-host $response.statuscode $reader = new-object System.IO.StreamReader($response.GetResponseStream()) $reader.ReadToEnd() $reader.Close() } #Author: Stefan Stranger #Website: http://tinyurl.com/sstranger #Date: 12/05/2010 #Version: 0.1 [System.Reflection.Assembly]::LoadWithPartialName(”System.Web") | Out-Null Function Publish-FFEntry([string] $FFEntryText) { [System.Net.ServicePointManager]::Expect100Continue = $false $request = [System.Net.WebRequest]::Create("http://friendfeed-api.com/v2/entry") $Username = "username" $Remotekey = "remotekey" $request.Credentials = new-object System.Net.NetworkCredential($Username, $Remotekey) $request.Method = "POST" $request.ContentType = "application/x-www-form-urlencoded" write-progress "Publishing FF Entry" "Posting Entry" -cu $FFEntryText $formdata = [System.Text.Encoding]::UTF8.GetBytes( "body=" + $FFEntryText ) $requestStream = $request.GetRequestStream() $requestStream.Write($formdata, 0, $formdata.Length) $requestStream.Close() $response = $request.GetResponse() write-host $response.statuscode $reader = new-object System.IO.StreamReader($response.GetResponseStream()) $reader.ReadToEnd() $reader.Close() } Publish-FFentry "This entry is being published using a PowerShell script. Yabbadabadoo!!"
PowerShellCorpus/PoshCode/Shift Operators_1.ps1
Shift Operators_1.ps1
#requires -version 2.0 Add-Type @" public class Shift { public static int Left(int x, int count) { return x >> count; } public static uint Left(uint x, int count) { return x >> count; } public static long Left(long x, int count) { return x >> count; } public static ulong Left(ulong x, int count) { return x >> count; } public static int Right(int x, int count) { return x << count; } public static uint Right(uint x, int count) { return x << count; } public static long Right(long x, int count) { return x << count; } public static ulong Right(ulong x, int count) { return x << count; } } "@ #.Example # Shift-Left 16 1 ## returns 8 #.Example # 8,16 |Shift-Left ## returns 4,8 function Shift-Left { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Left( $x, $y ) } } PROCESS { if($_){ [Shift]::Left($_, $x) } } } #.Example # Shift-Right 8 1 ## returns 16 #.Example # 2,4,8 |Shift-Right 2 ## returns 8,16,32 function Shift-Right { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Right( $x, $y ) } } PROCESS { if($_){ [Shift]::Right($_, $x) } } }
PowerShellCorpus/PoshCode/LibraryMSCS.ps1
LibraryMSCS.ps1
# ------------------------------------------------------------------------ ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Defines functions for working with Microsoft Cluster Service (MSCS) ### </Description> ### <Usage> ### . ./LibraryMSCS.ps1 ### </Usage> ### </Script> # ------------------------------------------------------------------------ ####################### function Get-ClusterList { $cmd = `cluster.exe /LIST` for ( $i=3; $i -le ($cmd.length - 1); $i++) { if ( $cmd[$i] -match '\\w+' ) { $cmd[$i].TrimEnd() } } } #Get-ClusterList ####################### function Get-ClusterToNode { foreach ($cluster in $input) { trap {Write-Error "Cannot connect to $i.";continue} Get-WmiObject -class MSCluster_Node -namespace "root\\mscluster" -computername $cluster | add-member noteproperty Cluster $cluster -pass | select Cluster, Name } } #Get-ClusterToNode ####################### function Get-ClusterToVirtual { foreach ($cluster in $input) { $pv = '.*VirtualServerName\\s+(?<virtual>\\w+$)' $pi = '.*InstanceName\\s+(?<instance>\\w+$)' $seen = @() $cmd = cluster.exe $cluster res /Priv | select-string "VirtualServerName|InstanceName" for ( $i=0; $i -le ($cmd.length - 1); $i++) { if ( $cmd[$i] -match $pv ) { $virtual = $matches.virtual $cmd[$i+1] -match $pi > $null $instance = $matches.instance if (!($seen -contains $virtual)) { $seen += $virtual new-object psobject | add-member -pass NoteProperty Cluster $cluster | add-member -pass NoteProperty Virtual $virtual | add-member -pass NoteProperty Instance $instance } } } } } #Get-ClusterToVirtual ####################### function Get-ClusterPreferredNode { param($cluster) # $prfHash = @{} # Get-ClusterPreferredNode "." | where {$_.order -eq 1} | foreach { $prfHash[$_.groupname] = $_.node } # $prfHash.keys | foreach { cluster . group "$_" /online:$prfHash."$_" /wait } #cluster . group /status #get-content ./clusters.txt | foreach {Get-ClusterPreferredNode $_} #get-content ./clusters.txt | foreach {Get-ClusterPreferredNode $_} | where {$_.order -eq 1} $pg = 'MSCluster_ResourceGroup.Name="(?<group>[^"]+)' $pn = 'MSCluster_Node.Name="(?<node>[^"]+)' get-wmiobject -class MSCluster_ResourceGroupToPreferredNode -namespace "root\\mscluster" -computername $cluster | select groupcomponent, partcomponent | foreach { if ($_.GroupComponent -match $pg) { add-member -in $_ -membertype noteproperty clustername $cluster add-member -in $_ -membertype noteproperty groupname $matches.group if ($grp -ne $matches.group) { $i = 1; $grp = $matches.group} else { $i++ } add-member -in $_ -membertype noteproperty order $i } if ($_.PartComponent -match $pn) {add-member -in $_ -membertype noteproperty node $matches.node -passthru} } | select clustername, order, groupname, node } #Get-ClusterPreferredNode ####################### function Get-ClusterGroup { param($cluster) #$grpArray = @() #get-clustergroup . | where {$_.groupname -notlike "Cluster*"} | foreach {$grpArray += $_.groupname} #$grpArray | foreach { cluster . group "$_" /offline /wait} #cluster . group /status $p = '(?<group>^\\w+\\s?\\w*)\\s+(?<node>\\w+)\\s+(?<status>\\w+$)' $cmd = `cluster $cluster group` for ( $i=8; $i -le ($cmd.length - 1); $i++) { if ( $cmd[$i] -match $p ) { new-object psobject | add-member -pass NoteProperty groupname $matches.group.TrimEnd() | add-member -pass NoteProperty node $matches.node | add-member -pass NoteProperty status $matches.status } } } #Get-ClusterGroup
PowerShellCorpus/PoshCode/Get-Software Function.ps1
Get-Software Function.ps1
Function Get-Software{ <# .SYNOPSIS Gets the software applications on a remote computer. .DESCRIPTION This function interrogates the remote registry for installed software products. It then returns an array of powershell objects that can be sorted and parsed. Optionally, you can provide a product name that will filter applications based on displayname before they are returned, thus reducing the typing needed to get specific results. .PARAMETER computer The name of the computer to retrieve a software list from. .PARAMETER product The partial name of a software application to search for. .INPUTS .OUTPUTS .NOTES Name: Get-Software Author: Geoffrey Guynn DateCreated 9 Aug 2011 .EXAMPLE Get-Software -computer "computer" -name "Adobe" Returns all instances of Adobe software on the computer. #> [cmdletbinding( SupportsShouldProcess = $True, DefaultParameterSetName = "process", ConfirmImpact = "low" )] param( [ValidateNotNullOrEmpty()] [string]$Computer , [string]$Product ) #Get Architechture Type of the system $OSArch = (Gwmi -computer $Computer win32_operatingSystem).OSArchitecture if ($OSArch -like "*64*") {$Architectures = @("32bit","64bit")} else {$Architectures = @("32bit")} #Create an array to capture program objects. $arApplications = @() foreach ($Architecture in $Architectures){ #We have a 64bit machine, get the 32 bit software. if ($Architecture -like "*64*"){ #Define the entry point to the registry. $strSubKey = "SOFTWARE\\\\WOW6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall" $SoftArchitecture = "32bit" $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry64 } #We have a 32bit machine, use the 32bit registry provider. elseif ($Architectures -notcontains "64bit"){ #Define the entry point to the registry. $strSubKey = "SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall" $SoftArchitecture = "32bit" $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry32 } #We have "64bit" in our array, capture the 64bit software. else{ #Define the entry point to the registry. $strSubKey = "SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall" $SoftArchitecture = "64bit" $RegViewEnum = [Microsoft.Win32.RegistryView]::Registry64 } #The standard routine to get software. #************************************************************************ #Create a remote registry connection to the server. $remRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer, $RegViewEnum) #Open the entry point. $remKey = $remRegistry.OpenSubKey($strSubKey) #Get all subkeys that exist in the entry point. $remSoftware = $remKey.GetSubKeyNames() #Loop through the applications and capture data. foreach ($remApplication in $RemSoftware){ $remProgram = $remRegistry.OpenSubKey("$strSubKey\\\\$remApplication") $strDisplayName = $remProgram.GetValue("DisplayName") if ($strDisplayName){ #Get a list of all available properties for the program. $arProperties = $remProgram.GetValueNames() #Create a custom object for this program. $objApplication = New-Object System.Object #Write-Host "`n" foreach ($strProperty in $arProperties){ #Get the value associated with the current property. $strValue = [string]($remProgram.GetValue($strProperty)) if ($strValue){ #If the property has a value but no name, then it is the default property. if (!$strProperty){ $objApplication | Add-Member -type NoteProperty -Name "(Default)" -Value $strValue } #The property has a value and a name, assign them both as a new property on the object. else{ $objApplication | Add-Member -type NoteProperty -Name ([string]$strProperty) -Value $strValue } } #Write-Host $strValue ": " $remProgram.GetValue($strValue) } #Add a final property to denote the software architecture type. $objApplication | Add-Member -type NoteProperty -Name "Architecture" -Value $SoftArchitecture #Add the last application to the array of programs. $arApplications += $objApplication } } } if ($Product){ $objApplication = $arApplications | ? {$_.DisplayName -Like "*$Product*"} | Sort-Object -property Architecture,DisplayName return $objApplication } #Sort the array by each object's Architecture and DisplayName. $arApplications = $arApplications | Sort-Object -property Architecture,DisplayName return $arApplications }
PowerShellCorpus/PoshCode/Measure-File.ps1
Measure-File.ps1
#.Synopsis # Calculate statistics about files #.Description # A lightweight simulation of unix's "wc" word count application #.Parameter $file # Accepts PIPELINE input # The file name(s) or wildcard patterns for the file(s) you want to count #.Example # wc *.ps1 # # Calculates line, word, and character counts for powershell script files in the current directory. #.Example # wc *.ps1, *.psm1, *.psd1 # # Calculates line, word, and character counts for powershell script and module files # function Measure-File { Param([string[]]$file) PROCESS{ if(!$file -and $_) {$file = $_} # wrap it with get-childitem so we do each file... foreach($f in ls $file){ gc $f -delim [char]0| measure -line -word -char | select Lines, Words, Characters, @{n="Name";e={$f.Name}} } }} new-alias wc measure-file
PowerShellCorpus/PoshCode/Get-Desktop.ps1
Get-Desktop.ps1
Add-Type @' #region License // Desktop 1.1 // * // Copyright (C) 2004 http://www.onyeyiri.co.uk // Coded by: Nnamdi Onyeyiri // // This code may be used in any way you desire except for commercial use. // The code can be freely redistributed unmodified as long as all of the authors // copyright notices remain intact, as long as it is not being sold for profit. // Although I have tried to ensure the stability of the code, I will not take // responsibility for any loss, damages, or death it may cause. // // This software is provided "as is" without any expressed or implied warranty. // // ------------------------- // Change Log // // Version 1.0: -First Release // // Version 1.1: -Added Window and WindowCollection classes // 6/6/2004 -Added another GetWindows overload, that used WindowCollection // -Added GetInputProcesses method to retrieve processes on Input desktop // -Changed GetWindows and GetDesktops to return arrays, instead of them being passed by ref // // Version 1.2 -Implemented IDisposable // 8/7/2004 -Implemented ICloneable // -Overrided ToString to return desktop name // // Version 2.0 -Switched to Generic Collections // 7/19/2010 -Added enumeration of process from alternate desktops // Joel Bennett -Renamed a lot of methods to remove duplication #endregion using System; using System.Threading; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Encapsulates the Desktop API. /// </summary> public class Desktop : IDisposable, ICloneable { #region Imports [DllImport("kernel32.dll")] private static extern int GetThreadId(IntPtr thread); [DllImport("kernel32.dll")] private static extern int GetProcessId(IntPtr process); // // Imported winAPI functions. // [DllImport("user32.dll")] private static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags, long dwDesiredAccess, IntPtr lpsa); [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr hDesktop); [DllImport("user32.dll")] private static extern IntPtr OpenDesktop(string lpszDesktop, int dwFlags, bool fInherit, long dwDesiredAccess); [DllImport("user32.dll")] private static extern IntPtr OpenInputDesktop(int dwFlags, bool fInherit, long dwDesiredAccess); [DllImport("user32.dll")] private static extern bool SwitchDesktop(IntPtr hDesktop); [DllImport("user32.dll")] private static extern bool EnumDesktops(IntPtr hwinsta, EnumDesktopProc lpEnumFunc, IntPtr lParam); [DllImport("user32.dll")] private static extern IntPtr GetProcessWindowStation(); [DllImport("user32.dll")] private static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsProc lpfn, IntPtr lParam); [DllImport("user32.dll")] private static extern bool SetThreadDesktop(IntPtr hDesktop); [DllImport("user32.dll")] public static extern IntPtr GetThreadDesktop(int dwThreadId); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex, IntPtr pvInfo, int nLength, ref int lpnLengthNeeded); [DllImport("user32.dll")] private static extern int GetWindowText(IntPtr hWnd, IntPtr lpString, int nMaxCount); private delegate bool EnumDesktopProc(string lpszDesktop, IntPtr lParam); private delegate bool EnumDesktopWindowsProc(IntPtr desktopHandle, IntPtr lParam); // The Unicode version of this function, CreateProcessW, can modify the contents of the lpCommandLine string. // Therefore, you can't just pass a string (because it's a constant, so it becomes a pointer to read-only memory). [return: MarshalAs(UnmanagedType.Bool)][DllImport("kernel32.dll")] private static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, [Out]out PROCESS_INFORMATION lpProcessInformation); [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } #endregion #region Constants /// <summary> /// Size of buffer used when retrieving window names. /// </summary> public const int MaxWindowNameLength = 100; // // winAPI constants. // private const short SW_HIDE = 0; private const short SW_NORMAL = 1; private const int STARTF_USESTDHANDLES = 0x00000100; private const int STARTF_USESHOWWINDOW = 0x00000001; private const int UOI_NAME = 2; private const int STARTF_USEPOSITION = 0x00000004; private const int NORMAL_PRIORITY_CLASS = 0x00000020; private const long DESKTOP_CREATEWINDOW = 0x0002L; private const long DESKTOP_ENUMERATE = 0x0040L; private const long DESKTOP_WRITEOBJECTS = 0x0080L; private const long DESKTOP_SWITCHDESKTOP = 0x0100L; private const long DESKTOP_CREATEMENU = 0x0004L; private const long DESKTOP_HOOKCONTROL = 0x0008L; private const long DESKTOP_READOBJECTS = 0x0001L; private const long DESKTOP_JOURNALRECORD = 0x0010L; private const long DESKTOP_JOURNALPLAYBACK = 0x0020L; private const long AccessRights = DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_READOBJECTS; #endregion #region Structures /// <summary> /// Stores window handles and titles. /// </summary> public struct Window { #region Private Variables private IntPtr m_handle; private string m_text; #endregion #region Public Properties /// <summary> /// Gets the window handle. /// </summary> public IntPtr Handle { get { return m_handle; } } /// <summary> /// Gets teh window title. /// </summary> public string Text { get { return m_text; } } #endregion #region Construction /// <summary> /// Creates a new window object. /// </summary> /// <param name="handle">Window handle.</param> /// <param name="text">Window title.</param> public Window(IntPtr handle, string text) { m_handle = handle; m_text = text; } #endregion } #endregion #region Private Variables private IntPtr m_desktop; private string m_desktopName; private static List<String> m_sc; private List<IntPtr> m_windows; private bool m_disposed; #endregion #region Public Properties /// <summary> /// Gets if a desktop is open. /// </summary> public bool IsOpen { get { return (m_desktop != IntPtr.Zero); } } /// <summary> /// Gets the name of the desktop, returns null if no desktop is open. /// </summary> public string DesktopName { get { return m_desktopName; } } /// <summary> /// Gets a handle to the desktop, IntPtr.Zero if no desktop open. /// </summary> public IntPtr DesktopHandle { get { return m_desktop; } } /// <summary> /// Opens the default desktop. /// </summary> public static readonly Desktop Default = Desktop.OpenDefault(); /// <summary> /// Opens the desktop the user if viewing. /// </summary> public static readonly Desktop Input = Desktop.OpenInput(); #endregion #region Construction/Destruction /// <summary> /// Creates a new Desktop object. /// </summary> public Desktop() { // init variables. m_desktop = IntPtr.Zero; m_desktopName = String.Empty; m_windows = new List<IntPtr>(); m_disposed = false; } /// <summary> /// Creates a new Desktop object. /// </summary> public Desktop(string name) { // init variables. m_desktop = IntPtr.Zero; m_desktopName = name; m_windows = new List<IntPtr>(); m_disposed = false; } // constructor is private to prevent invalid handles being passed to it. private Desktop(IntPtr desktop) { // init variables. m_desktop = desktop; m_desktopName = Desktop.GetName(desktop); m_windows = new List<IntPtr>(); m_disposed = false; } ~Desktop() { // clean up, close the desktop. Close(); } #endregion #region Methods /// <summary> /// Closes the handle to a desktop. /// </summary> /// <returns>True if an open handle was successfully closed.</returns> public bool Close() { // make sure object isnt disposed. CheckDisposed(); // check there is a desktop open. if (m_desktop != IntPtr.Zero) { // close the desktop. bool result = CloseDesktop(m_desktop); if (result) { m_desktop = IntPtr.Zero; m_desktopName = String.Empty; } return result; } // no desktop was open, so desktop is closed. return true; } /// <summary> /// Opens a desktop. /// </summary> /// <param name="name">The name of the desktop to open.</param> /// <returns>True if the desktop was successfully opened.</returns> public bool Open() { // make sure object isnt disposed. CheckDisposed(); // close the open desktop. if (m_desktop != IntPtr.Zero) { // attempt to close the desktop. if (!Close()) return false; } // open the desktop. m_desktop = OpenDesktop(m_desktopName, 0, true, AccessRights); // something went wrong. if (m_desktop == IntPtr.Zero) return false; return true; } /// <summary> /// Switches input to the currently opened desktop. /// </summary> /// <returns>True if desktops were successfully switched.</returns> public bool Show() { // make sure object isnt disposed. CheckDisposed(); // make sure there is a desktop to open. if (m_desktop == IntPtr.Zero) return false; // attempt to switch desktops. bool result = SwitchDesktop(m_desktop); return result; } /// <summary> /// Enumerates the windows on a desktop. /// </summary> /// <param name="windows">Array of Desktop.Window objects to recieve windows.</param> /// <returns>A window colleciton if successful, otherwise null.</returns> public List<Window> GetWindows() { // make sure object isnt disposed. CheckDisposed(); // make sure a desktop is open. if (!IsOpen) return null; // init the List. m_windows.Clear(); List<Window> windows = new List<Window>(); // get windows. bool result = EnumDesktopWindows(m_desktop, new EnumDesktopWindowsProc(DesktopWindowsProc), IntPtr.Zero); // check for error. if (!result) return null; // get window names. IntPtr ptr = Marshal.AllocHGlobal(MaxWindowNameLength); foreach(IntPtr wnd in m_windows) { GetWindowText(wnd, ptr, MaxWindowNameLength); windows.Add(new Window(wnd, Marshal.PtrToStringAnsi(ptr))); } Marshal.FreeHGlobal(ptr); return windows; } private bool DesktopWindowsProc(IntPtr wndHandle, IntPtr lParam) { // add window handle to colleciton. m_windows.Add(wndHandle); return true; } /// <summary> /// Creates a new process in a desktop. /// </summary> /// <param name="path">Path to application.</param> /// <returns>The process object for the newly created process.</returns> public Process CreateProcess(string path) { return CreateProcess(path, null); } /// <summary> /// Creates a new process in a desktop. /// </summary> /// <param name="path">Path to application.</param> /// <param name="commandLineParameters">Arguments for the application.</param> /// <returns>The process object for the newly created process.</returns> public Process CreateProcess(string path, string commandLineParameters) { // make sure object isnt disposed. CheckDisposed(); return Desktop.CreateProcess(path,commandLineParameters,m_desktopName); } /// <summary> /// Prepares a desktop for use by launching the Explorer Shell. For use only on newly created desktops, call straight after CreateDesktop. /// </summary> public void Prepare() { // make sure object isnt disposed. CheckDisposed(); // make sure a desktop is open. if (IsOpen) { // load explorer. CreateProcess("explorer.exe"); } } /// <summary> /// Gets an array of all the processes running on this desktop. /// </summary> /// <returns>An array of the processes.</returns> public Process[] GetProcesses() { return GetProcesses( m_desktopName, StringComparison.InvariantCulture); } #endregion #region Static Methods /// <summary> /// Enumerates all of the desktops. /// </summary> /// <param name="desktops">String array to recieve desktop names.</param> /// <returns>True if desktop names were successfully enumerated.</returns> public static string[] GetDesktops() { // attempt to enum desktops. IntPtr windowStation = GetProcessWindowStation(); // check we got a valid handle. if (windowStation == IntPtr.Zero) return new string[0]; string[] desktops; // lock the object. thread safety and all. lock(m_sc = new List<String>()) { bool result = EnumDesktops(windowStation, new EnumDesktopProc(DesktopProc), IntPtr.Zero); // something went wrong. if (!result) return new string[0]; // // turn the collection into an array. desktops = new string[m_sc.Count]; for(int i = 0; i < desktops.Length; i++) desktops[i] = m_sc[i]; } return desktops; } private static bool DesktopProc(string lpszDesktop, IntPtr lParam) { // add the desktop to the collection. m_sc.Add(lpszDesktop); return true; } /// <summary> /// Switches to the specified desktop. /// </summary> /// <param name="name">Name of desktop to switch input to.</param> /// <returns>True if desktops were successfully switched.</returns> public static bool Show(string name) { // attmempt to open desktop. bool result = false; using (Desktop d = new Desktop(name)) { result = d.Open(); // something went wrong. if (!result) return false; // attempt to switch desktops. result = d.Show(); } return result; } /// <summary> /// Gets the desktop of the calling thread. /// </summary> /// <returns>Returns a Desktop object for the valling thread.</returns> public static Desktop GetCurrent() { // get the desktop. return new Desktop(GetThreadDesktop(System.Threading.Thread.CurrentThread.ManagedThreadId)); } /// <summary> /// Sets the desktop of the calling thread. /// NOTE: Function will fail if thread has hooks or windows in the current desktop. /// </summary> /// <param name="desktop">Desktop to put the thread in.</param> /// <returns>True if the threads desktop was successfully changed.</returns> public static bool SetCurrent(Desktop desktop) { // set threads desktop. if (!desktop.IsOpen) return false; return SetThreadDesktop(desktop.DesktopHandle); } /// <summary> /// Opens a desktop. /// </summary> /// <param name="name">The name of the desktop to open.</param> /// <returns>If successful, a Desktop object, otherwise, null.</returns> public static Desktop Open(string name) { // open the desktop. Desktop desktop = new Desktop(name); bool result = desktop.Open(); // something went wrong. if (!result) return null; return desktop; } /// <summary> /// Opens the current input desktop. /// </summary> /// <returns>If successful, a Desktop object, otherwise, null.</returns> public static Desktop OpenInput() { // open the desktop. IntPtr deskptr = OpenInputDesktop(0, true, AccessRights); if (deskptr == IntPtr.Zero) return null; return new Desktop(deskptr); } /// <summary> /// Opens the default desktop. /// </summary> /// <returns>If successful, a Desktop object, otherwise, null.</returns> public static Desktop OpenDefault() { // opens the default desktop. return Desktop.Open("Default"); } /// <summary> /// Creates a new desktop. /// </summary> /// <param name="name">The name of the desktop to create. Names are case sensitive.</param> /// <returns>If successful, a Desktop object, otherwise, null.</returns> public static Desktop Create(string name) { // make sure desktop doesnt already exist. if (Desktop.Exists(name)) { // it exists, so open it. return Open(name); } // attempt to create desktop. IntPtr deskptr = CreateDesktop(name, IntPtr.Zero, IntPtr.Zero, 0, AccessRights, IntPtr.Zero); if (deskptr == IntPtr.Zero) return null; // open the desktop. return Open(name); } /// <summary> /// Gets the name of a given desktop. /// </summary> /// <param name="desktop">Desktop object whos name is to be found.</param> /// <returns>If successful, the desktop name, otherwise, null.</returns> public static string GetName(Desktop desktop) { // get name. if (desktop.IsOpen) return null; return GetName(desktop.DesktopHandle); } public static Win32Exception LastError; /// <summary> /// Gets the name of a desktop from a desktop handle. /// </summary> /// <param name="desktopHandle"></param> /// <returns>If successful, the desktop name, otherwise, null.</returns> public static string GetName(IntPtr desktopHandle) { // check its not a null pointer. // null pointers wont work. if (desktopHandle == IntPtr.Zero) return null; // get the length of the name. int needed = 0; string name = null; // always returns false, because we pass 0 for available size GetUserObjectInformation(desktopHandle, UOI_NAME, IntPtr.Zero, 0, ref needed); // get the name. IntPtr ptr = Marshal.AllocHGlobal(needed); if(!GetUserObjectInformation(desktopHandle, UOI_NAME, ptr, needed, ref needed)) { Marshal.FreeHGlobal(ptr); LastError = new Win32Exception(); } else { name = Marshal.PtrToStringAnsi(ptr); Marshal.FreeHGlobal(ptr); } return name; } /// <summary> /// Checks if the specified desktop exists (using a case sensitive search). /// </summary> /// <param name="name">The name of the desktop.</param> /// <returns>True if the desktop exists, otherwise false.</returns> public static bool Exists(string name) { return Desktop.Exists(name, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Checks if the specified desktop exists. /// </summary> /// <param name="name">The name of the desktop.</param> /// <param name="comparisonType">The type of string comparison to do.</param> /// <returns>True if the desktop exists, otherwise false.</returns> public static bool Exists(string name, StringComparison comparisonType) { // enumerate desktops. string[] desktops = Desktop.GetDesktops(); // return true if desktop exists. foreach(string desktop in desktops) { if(desktop.Equals( name, comparisonType )) return true; } return false; } /// <summary> /// Creates a new process on the specified desktop. /// </summary> /// <param name="path">Path to application.</param> /// <param name="commandLineParameters">Arguments for the application.</param> /// <param name="desktop">Desktop name.</param> /// <returns>A Process object for the newly created process, otherwise, null.</returns> public static Process CreateProcess(string path, string commandLineParameters, string desktop) { if (!Desktop.Exists(desktop)) return null; // set startup parameters. STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = desktop; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); //StringBuilder lpPath = new StringBuilder(path); StringBuilder lpCommandLine = new StringBuilder(); lpCommandLine.Append("\\""); lpCommandLine.Append(path); lpCommandLine.Append("\\" "); lpCommandLine.Append(commandLineParameters); // lpPath.EnsureCapacity(256); // create the process. if(!CreateProcess(null, lpCommandLine.ToString(), IntPtr.Zero, IntPtr.Zero, true, NORMAL_PRIORITY_CLASS, IntPtr.Zero, null, ref si, out pi) ) { throw new Win32Exception(); } // Get the process. return Process.GetProcessById(pi.dwProcessId); } /// <summary> /// Gets an array of all the processes running on the Input desktop. /// </summary> /// <returns>An array of the processes.</returns> public static Process[] GetInputProcesses() { return GetProcesses( GetName(Desktop.Input.DesktopHandle), StringComparison.InvariantCulture); } /// <summary> /// Gets an array of all the processes running on the specified desktop. /// </summary> /// <param name="desktop">The name of the desktop for which to return processes</param> /// <returns>An array of the processes.</returns> public static Process[] GetProcesses(string desktop) { return GetProcesses( desktop, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Gets an array of all the processes running on the specified desktop (using the speficied string comparison) /// </summary> /// <param name="desktop">The name of the desktop for which to return processes</param> /// <param name="comparisonType">The type of string comparison to do</param> /// <returns>An array of the processes.</returns> public static Process[] GetProcesses(string desktop, StringComparison comparisonType) { // get all processes. Process[] processes = Process.GetProcesses(); List<Process> procs = new List<Process>(); // cycle through the processes. foreach(Process process in processes) { // check the threads of the process - are they in this one? foreach(ProcessThread pt in process.Threads) { string deskname = GetName(GetThreadDesktop(pt.Id)); if(deskname == null) continue; // check for a desktop name match. if (deskname.Equals(desktop,comparisonType)) { // found a match, add to list, and bail. procs.Add(process); break; } else { Console.WriteLine("Wow, Really? The '" + deskname + "' desktop showed up!"); } } } return procs.ToArray(); } #endregion #region IDisposable /// <summary> /// Dispose Object. /// </summary> public void Dispose() { // dispose Dispose(true); // suppress finalisation GC.SuppressFinalize(this); } /// <summary> /// Dispose Object. /// </summary> /// <param name="disposing">True to dispose managed resources.</param> public virtual void Dispose(bool disposing) { if (!m_disposed) { // dispose of managed resources, // close handles Close(); } m_disposed = true; } private void CheckDisposed() { // check if disposed if (m_disposed) { // object disposed, throw exception throw new ObjectDisposedException(""); } } #endregion #region ICloneable /// <summary> /// Creates a new Desktop object with the same desktop open. /// </summary> /// <returns>Cloned desktop object.</returns> public object Clone() { // make sure object isnt disposed. CheckDisposed(); Desktop desktop = new Desktop(m_desktopName); // if a desktop is open, make the clone open it. if (IsOpen) desktop.Open(); return desktop; } #endregion #region Overrides /// <summary> /// Gets the desktop name. /// </summary> /// <returns>The desktop name, or a blank string if no desktop open.</returns> public override string ToString() { // return the desktop name. return m_desktopName; } #endregion } '@ if( !([Desktop]::GetDesktops() -eq "Alternate") ) { [Desktop]::Create("Alternate") | Out-Null ## Don't use PowerShell.exe (Try it, you'll see why) [Desktop]::CreateProcess("PowerShell_ISE.exe", $MyInvocation.MyCommand.Definition, "Alternate") } Write-Host "Now try: [Desktop]::Show('Alternate') and when you get there, to come back you can: [Desktop]::Show('Default') "
PowerShellCorpus/PoshCode/Get-Payment.ps1
Get-Payment.ps1
function Get-Payment { param ( $LoanAmount, [double]$InterestRatePerPeriod, $NumberPayments ) $a = $LoanAmount $b = $InterestRatePerPeriod*[math]::Pow(($InterestRatePerPeriod + 1),$NumberPayments) $c = [math]::Pow((1+$InterestRatePerPeriod),$NumberPayments) - 1 $payment = $a*($b/$c) "{0:C}" -f $payment } #
PowerShellCorpus/PoshCode/ConvertHelpTo-Html.ps1
ConvertHelpTo-Html.ps1
## ConvertTo-DekiContent (aka Convert Help to Html) #################################################################################################### ## Converts the -Full help output to HTML markup for insertion into web pages. #################################################################################################### ## Usage: ## ## foreach($cmd in (gcm -type cmdlet | ? { $_.PsSnapin -like "Microsoft.PowerShell*" })) { ## ## Get-Help $cmd.Name -full | ConvertTo-DekiContent Cmdlet_Help | ## %{ Set-DekiContent "Cmdlet_Help/$($cmd.PSSnapin)/$($cmd.Name)" $_ } ## } ## #################################################################################################### ## History: ## v2.0 - Refactoring of markup and code by Joel "Jaykul" Bennett to avoid line-wrapping, and 'pre' ## blocks in the code and to format the parameters and examples more like the originals. ## v1.0 - Original version by http://blogs.vmware.com/vipowershell/2007/09/new-htmlhelp.html #################################################################################################### #Import System.Web in order to use HtmlEncode functionality [System.Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null ## Get-HtmlHelp - A Helper function for generating help: ## Usage: Get-HtmlHelp Get-* function Get-HtmlHelp { param([string[]]$commands, [string]$baseUrl) $commands | Get-Command -type Cmdlet -EA "SilentlyContinue" | get-help -Full | ConvertTo-DekiContent $baseUrl } function ConvertTo-DekiContent { param($baseUrl) PROCESS { if($_ -and ($_.PSObject.TypeNames -contains "MamlCommandHelpInfo#FullView")) { $help = $_ # Name isn't needed, since this is going as the body, but ... # $data = "<html><head><title>$(encode($help.Name))</title></head><body>"; # $data += "<h1>$(encode($help.Name))</h1>" # Synopsis $data += "<h2>Synopsis</h2>$($help.Synopsis | Out-HtmlPara)" # Syntax $data += "<h2>Syntax</h2>$($help.Syntax | Out-HtmlPara)" # Related Commands $data += "<h2>Related Commands</h2>" foreach ($relatedLink in $help.relatedLinks.navigationLink) { if($relatedLink.linkText -ne $null -and $relatedLink.linkText.StartsWith("about") -eq $false) { $uri = "" if( $relatedLink.uri -ne "" ) { $uri = $relatedLink.uri } else{ $uri = "$baseUrl/$((get-command $relatedLink.linkText -EA "SilentlyContinue").PSSnapin.Name)/$($relatedLink.linkText)" } $data += "<a href='$(encode($uri)).html'>$(encode($relatedLink.linkText))</a><br>" } } # Detailed Description $data += "<h2>Detailed Description</h2>$(encode(&{$help.Description | out-string -width 200000}))" # Parameters $data += "<h2>Parameters</h2>" $help.parameters.parameter | %{ $param = $_ $data += "<h4>-$(encode($param.Name)) [&lt;$(encode($param.type.name))&gt;]</h4>" $data += $param.Description | Out-HtmlPara $data += "<table>" $data += "<tr><th>Required? &nbsp;</th><td> $(encode($param.Required))</td></tr>" $data += "<tr><th>Position? &nbsp;</th><td> $(encode($param.Position))</td></tr>" $data += "<tr><th>Default value? &nbsp;</th><td> $(encode($param.defaultValue))</td></tr>" $data += "<tr><th>Accept pipeline input? &nbsp;</th><td> $(encode($param.pipelineInput))</td></tr>" $data += "<tr><th>Accept wildcard characters? &nbsp;</th><td> $(encode($param.globbing))</td></tr></table>" } if($help.inputTypes) { # Input Type $data += "<h3>Input Type</h3>$($help.inputTypes | Out-HtmlPara)" } if($help.returnValues) { # Return Type $data += "<h3>Return Type</h3>$($help.returnValues | Out-HtmlPara)" } # Notes $data += "<h2>Notes</h2>$($help.alertSet | Out-HtmlPara)" # Examples $data += "<h2>Examples</h2>" $help.Examples.example | %{ $example = $_ $data += "<h4>$(encode($example.title.trim(' -')))</h4>" $data += "<code><strong>PS&gt;</strong>&nbsp;$(encode($example.code))</code>" $data += "<p>$($example.remarks | out-string -width ([int]::MaxValue) | Out-HtmlPara)</p>" } # $data += "</body>" write-output $data } else { Write-Error "Can only process -Full view help output" } }} function encode($str) { begin{ if($str){ $str.split("`n") | encode } } process{ if($_){ [System.Web.HttpUtility]::HtmlEncode($_).Trim() } } } function trim($str) { begin{ if($str){ $str.Trim() } } process{ if($_){ $_.Trim() } } } function split($Separator="`n",$inputObject) { begin{ if($inputObject){ $inputObject | split $Separator } } process{ if($_){ [regex]::Split($_,$Separator) | ? {$_.Length} } } } function join($Separator=$ofs,$inputObject) { begin{ if($inputObject){ [string]::Join($Separator,$inputObject) } else { $array =@() }} process{ if($_){ $array += $_ } } end{ if($array.Length) { [string]::Join($Separator,$array) } } } function Out-HtmlPara { process{if($_){"<p>$($_ | out-string -width ([int]::MaxValue) | split "\\s*`n" | encode | trim | join "</p>`n<p>")</p>"}} }
PowerShellCorpus/PoshCode/Find Local Group Members_5.ps1
Find Local Group Members_5.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/Compare-DataSources_1.ps1
Compare-DataSources_1.ps1
#Define DPMHosts [CmdletBinding()] param([string]$PrimaryDPMHost, [string]$SecondaryDPMHost); Write-Verbose "Compare-DataSources.ps1 written by Shai Perednik shaiss@gmail.com" Write-Verbose "Primary DPM Host: $PrimaryDPMHost" Write-Verbose "Secondary DPM Host: $SecondaryDPMHost" #Load DPM Snaping Write-Verbose "Loading DPM PowerShell snapin" Add-PSSnapin -name Microsoft.DataProtectionManager.PowerShell -ErrorAction SilentlyContinue Write-Verbose "Finished loading DPM PowerShell snapin" #*============================================================================= #* FUNCTION GetDataSourcesFromDPMHost #*============================================================================= # Function: GetDataSourcesFromDPMHost # Created: [05/03/2012] # Author: Shai Perednik shaiss@gmail.com http://shaiperednik.com # Arguments:DPMHost # Version: 0.0.1 # ============================================================================= # Purpose: Gets the DPM Hosts DataSources in a sorted array # # # ============================================================================= Function GetDataSourcesFromDPMHost ($DPMHost){ Write-Verbose "===========================================================================" Write-Verbose "Starting GetDataSourcesFromDPMHost Function on DPM Host: $DPMHost" Write-Verbose "===========================================================================" #Get the ProtectionGroups on the Primary Write-Verbose "Getting Protection Groups from $DPMHost" $PG = Get-Protectiongroup -DPMServerName $DPMHost | Sort-Object FriendlyName #Initialize the variable $DataSourceDetails $DataSourceDetails = @() #Loop through the Protection Groups and Get the DataSources foreach ($pgitem in $PG) { Write-Verbose "Getting DataSources from $DPMHost" $DS = Get-Datasource -ProtectionGroup $pgitem | Sort-Object FriendlyName Write-Verbose "Checking individual datasource items and adding them to the array" #Check what kind of DataSource it is foreach ($dsitem in $DS) { #Write-Host $dsitem.Type.DatasourceType switch ($dsitem.Type.DatasourceType) { "Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.SQL.SQLObjectType" { Write-Verbose "SQL DataSource: $dsitem.DisplayPath" $DataSourceDetails += $dsitem.DisplayPath break } "Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.SystemProtection.SystemProtectionObjectType" { Write-Verbose "System State DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName" $DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName break } "Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.FileSystem.FsObjectType" { Write-Verbose "Volume DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName" $DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName break } "Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.FileSystem.FsDataSource" { Write-Verbose "Volume DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName" $DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName break } default { Write-Verbose "Other/Unknown DataSource: $dsitem" break } } } } #disconnect from DPMhost Write-Verbose "Disconnecting form $DPMHost" Disconnect-DPMServer -DPMServerName $DPMHost #Sort the Array Write-Verbose "Sorting the Array" [Array]::Sort([array]$DataSourceDetails) #Return a value return $DataSourceDetails } #*============================================================================= #* End of Function #*============================================================================= #*============================================================================= #* SCRIPT BODY #*============================================================================= #Get the DataSources of the Primary and Secondary DPM hosts Write-Verbose "Geting the datasources from the primary host $PrimaryDPMHost using GetDataSourcesFromDPMHost function" $arPrimaryHost = GetDataSourcesFromDPMHost $PrimaryDPMHost Write-Verbose "Geting the datasources from the Secondary host $SecondaryDPMHost using GetDataSourcesFromDPMHost function" $arSecondaryHost = GetDataSourcesFromDPMHost $SecondaryDPMHost #Now compare the two arrays #Define container arrays $PrimaryDataSourcesInSecondaryHost = @() $PrimaryDataSourcesNotInSecondaryHost = @() #do the work Write-Verbose "Comparing the DataSources of the primary DPM host $PrimaryDPMHost againsnt the secodary $SecondaryDPMHost" Foreach ($PrimaryHostItem in $arPrimaryHost) { If ($arSecondaryHost -contains $PrimaryHostItem){ $PrimaryDataSourcesInSecondaryHost += $PrimaryHostItem } Else{ $PrimaryDataSourcesNotInSecondaryHost += $PrimaryHostItem } } Write-Verbose "===============================================================================================" Write-Verbose "Primary, $PrimaryDPMHost, DataSources in secondary host $SecondaryDPMHost" Write-Verbose "===============================================================================================" $strOutString = Out-String -InputObject $PrimaryDataSourcesInSecondaryHost Write-Verbose $strOutString Write-Verbose "===============================================================================================" Write-Verbose "===============================================================================================" Write-Verbose "Primary, $PrimaryDPMHost, DataSources ***NOT*** in secondary host $SecondaryDPMHost" Write-Verbose "===============================================================================================" $strOutString = Out-String -InputObject $PrimaryDataSourcesNotInSecondaryHost Write-Verbose $strOutString Write-Verbose "===============================================================================================" #Write the Results to a file on c:\\temp\\logs Write-Host "Writing the comparisons to log files under c:\\temp\\logs" New-Item -Path c:\\temp\\logs -ItemType directory -ErrorAction SilentlyContinue $inpath = "c:\\temp\\logs\\" + $PrimaryDPMHost + "_DataSources_In_" + $SecondaryDPMHost + ".log" $notinpath = "c:\\temp\\logs\\" + $PrimaryDPMHost + "_DataSources_Not_In_" + $SecondaryDPMHost + ".log" Out-File -FilePath $inpath -InputObject $PrimaryDataSourcesInSecondaryHost Write-Host "Wrote $inpath" -ForegroundColor Green -BackgroundColor Black Out-File -FilePath $notinpath -InputObject $PrimaryDataSourcesNotInSecondaryHost Write-Host "Wrote $notinpath" -ForegroundColor Green -BackgroundColor Black Write-Verbose "Script finished" #*============================================================================= #* END OF SCRIPT: #*=============================================================================
PowerShellCorpus/PoshCode/ConvertTo-CliXml_3.ps1
ConvertTo-CliXml_3.ps1
#requires -version 2.0 function ConvertTo-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [PSObject[]]$InputObject ) begin { $type = [PSObject].Assembly.GetType('System.Management.Automation.Serializer') $ctor = $type.GetConstructor('instance,nonpublic', $null, @([System.Xml.XmlWriter]), $null) $sw = New-Object System.IO.StringWriter $xw = New-Object System.Xml.XmlTextWriter $sw $serializer = $ctor.Invoke($xw) $method = $type.GetMethod('Serialize', 'nonpublic,instance', $null, [type[]]@([object]), $null) $done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance') } process { try { [void]$method.Invoke($serializer, $InputObject) } catch { Write-Warning "Could not serialize $($InputObject.GetType()): $_" } } end { [void]$done.Invoke($serializer, @()) $sw.ToString() $xw.Close() $sw.Dispose() } }
PowerShellCorpus/PoshCode/Ellipsis.ps1
Ellipsis.ps1
## Usage: ls | ... FullName ################################################ ${function:...} = { process { $_.$($args[0]) } }
PowerShellCorpus/PoshCode/Get-Parameter_9.ps1
Get-Parameter_9.ps1
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) { $command = Get-Command $Cmdlet -ea silentlycontinue # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = Get-Command ($command.definition) } if (-not $command) { return } foreach ($paramset in $command.ParameterSets){ $Output = @() foreach ($param in $paramset.Parameters) { if ( !$ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue } } $process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory, Pipeline, PipelineByPropertyName $process.Name = $param.Name $process.Type = $param.ParameterType.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 $process.Pipeline = $param.ValueFromPipeline $process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName $output += $process } if ( !$Full ) { $Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline } else { Write-Output $Output } } }
PowerShellCorpus/PoshCode/VM Performance Report_2.ps1
VM Performance Report_2.ps1
<# .SYNOPSIS The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address. .DESCRIPTION The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3491) or run interactively. .NOTES File Name : Get-VMPeformanceReport.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://poshcode.org/3485 .EXAMPLE Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt> #> #Change These Values $VC = "vm-trb-vc02.th.local" #VirtualCenter $SMTPServer = "10.247.50.25" #SMTP Server $SendersAddress = "noreply@tribalgroup.com" #The report comes from this address $SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3491 $CompanyLogo = "http://placehold.it/150x50" function Out-LogFile { #Log File Function http://poshcode.org/3232 [CmdletBinding(DefaultParameterSetName='Message')] param( [Parameter(ParameterSetName='Message', Position=0, ValueFromPipeline=$true)] [object[]]$Message, [Parameter(ParameterSetName='Message')] [string]$LogFile = $global:DefaultLogPath, [Parameter(ParameterSetName='Message')] [int]$BlankLine = 0, [switch]$WriteHost = $global:WriteHostPreference, [string]$Severity = "I", [Parameter(ParameterSetName='Message')] [switch]$DontFormat, [Parameter(ParameterSetName='Message')] [string]$DateFormat = "dd-MM-yyyy HH:mm:ss", #[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)] [string]$Title, [System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor, [System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor, [ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')] [string]$Encoding = 'Unicode', [switch]$Force ) begin { Write-Verbose "Log File: $LogFile" if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break} if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null } if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break} if ( $Title ) { $text = $Title $Title = $null Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding } } process { if ( $Message ) { $text = $Message foreach ( $text in $Message ) { if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" } if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor} $text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append } } if ( $BlankLine -gt 0 ){ for ($i = 0; $i -lt $BlankLine; $i++ ) { "" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor } } } } end { } } #end of logfile function #New Line Variable $nl = [Environment]::NewLine #INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential) #NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3491), and retrive as below $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3491) $VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3491 $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) #Get Datafile, this wil contain VM's to report on, and an email address to send the report to #Datafile format: first line is email address, subsequent lines are VM's, one per line) if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error! { Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)" #$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file } else { $Datafile = $args[0] } #From Datafile, get a log file, and a $LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log" $Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm" $global:WriteHostPreference = $true $global:DefaultLogPath = $LogFile Out-LogFile -Message "Starting script with $datafile" #Load PowerCLI if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin VMware.VimAutomation.Core } If (!(Get-PSSnapin -Name VMware.VimAutomation.Core)) {Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E" Exit(1) } #Static HTML $HTMLPreString=@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css"> <style type="text/css"> body { padding: 20px; } h2 { color: #3A87AD; } .mytable { width: 776px; margin: 12px; } .alert-info { color: #3A87AD; background-color: #D9EDF7; border-color: #BCE8F1; padding: 8px 8px 8px 14px; margin-top: 12px; margin-left: 12px; margin-right: 12px; margin-bottom: 12px; border: 1px solid; border-radius: 4px; } .chart_wrap { width: 800px; border-style:solid; border-width:1px; border-color: #DDDDDD; margin: 0px 0px 10px 0px; } .chart { text-align: center; width: 800px; height: 400px; } </style> <title> Virtual Machine Performance statistics </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['corechart']}); </script> "@ $HTMLPreString += "$nl" $HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl" $HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl" $HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl" $HTMLPostString=@" <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script> </body> </html> "@ #Functions for dynamic HTML Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title) { #https://developers.google.com/chart/interactive/docs/examples#custom_table_example $mystring = "<script type=`"text/javascript`">$nl" $mystring += "function drawVisualization$UID() {$nl" $mystring += "// Create and populate the data table. $nl" $mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl" $mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl" $VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"} $mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl" $ColumnCount = 0 $RowCount = 0 $Statistics | % { $ColumnCount = 0 $formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null) $JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0) $formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm") $formatteddate = "new Date($formatteddate)" $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl" $_.Group | % { $ColumnCount = 0 foreach ($VM in $VMs) { $ColumnCount += 1 If ($_.Entity.Name -eq $VM ) { if ($Summation -eq $true) { $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181 $strPercent = [system.math]::round($strPercent,2) $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl" } else { $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" } } } } $RowCount += 1 } $mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl" $VisParam = "` { ` legend: {position: 'in',alignment:`"center`"}, ` lineWidth:`"2`", ` curveType: `"none`",` chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},` focusTarget:`"category`", ` hAxis: {slantedText:`"true`", format:`"E, d MMM`"},` vAxis: {textPosition:`"out`"},` width: 800, ` height: 400, ` title:`"$Title`"}" $mystring += "draw(" + "$UID" + "data, $VisParam);$nl" $mystring +="}$nl" $mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl" return $mystring } function Get-DivHTML ($UID, $Notes) { $tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl" $tempHTML += " <div class=`"chart_wrap`">$nl" $tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl" $tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl" $tempHTML += " </div>$nl" $tempHTML += "</div>$nl" return $tempHTML } #Main Code #Process datafile, get VM's to report on, and an email address to send the report to $DataTable = @(Get-Content $Datafile) $email = $DataTable[0] $VMs = @($DataTable[1..($DataTable.Count)]) #Connect to VC Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails. { Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost Exit (1) } else {Out-LogFile -Message "Connected to vCenter ($VC)"} #Validate VM's exist $VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue) $VMs | % { $tmpvm = $_ $Exists = $false $VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}} If ($Exists){ Out-LogFile -Message "$_ found in vCenter inventory" } Else { Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W" $VMs = $VMs |? {$_ -ne $tmpvm} } } #To add new Stat #1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics) #2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #3. Invent a new UID - MyUID ? #4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title") #5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li> #6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart") #Start and Finish times $todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1) $metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average" $start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart $finish = $todayMidnight $startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm") $finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm") Out-LogFile -Message "Getting stats from vCenter" #Variable for all stats combined $Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average Out-LogFile -Message "Got stats from vCenter" Out-LogFile -Message "Sorting and filtering stats" #Split stats out by each indivial metric into individual variable $CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #Creates HTML inside of <head> for javascript for the charts Out-LogFile -Message "Creating HTML" $HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)") $HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)") $HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)") $HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)") $HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)") $HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)") $HTMLOut += "</head>$nl" $HTMLOut += $HTMLBodyBegin + $nl #Navigation Tabs... #Edit below to add a tab, when adding a new metric $HTMLOut += @" <div id="content"> <ul class="nav nav-tabs"> <li class="active"><a href="#Info" data-toggle="tab">Information</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#CPU" data-toggle="tab">CPU Usage</a></li> <li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#Memory" data-toggle="tab">Memory Usage</a></li> <li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li> </ul> <li> <li><a href="#Disk" data-toggle="tab">Disk</a></li> <li><a href="#Net" data-toggle="tab">Network</a></li> </ul> <div id="my-tab-content" class="tab-content"> <div class="tab-pane fade in active" id="Info"> <div class="chart_wrap"> <div class="alert alert-info"> <strong>Information: </strong> "@ #Info for fist tab $HTMLOut += "Each datapoint represents resource consumption since the last datapoint ` and its value is either an average, maximum, or summation of all usage in that interval. ` Any values that are zero may actually be zero, or may indicate statistics were not ` collected over that period (for example, if a virtual machine was powered off). $nl ` The statistics displayed are from $startstring to $finishstring</div>$nl" #Table that contains VM resource config & limits. $HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl" $VCVMs | % { $tmpname =$_.Name $tmpNumCpu = $_.NumCpu $TmpMemoryMB = $_.MemoryMB $tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None") $tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None") $HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl" } $HTMLOut += "</tbody></table>$nl" $HTMLOut +=@" </div> </div> "@ #Div elements that contain each chart $HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval") $HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory") $HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps") $HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval") $HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal") $HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0") $HTMLOut += @" </div> </div> </div> "@ $datenow = Get-Date -Format "F" $HTMLOut += "<h6>Report generated at $datenow<h6>$nl" $HTMLOut += $HTMLPostString #Finished HTML Out-LogFile -Message "Finished building HTML, writing to $Outfile" $HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8" #Build Email $body =@" <P>Performance statistics for the Virtual Machines listed below are attached</p> "@ $body += "<p>Statistics are from $startstring to $finishstring<p>" $VMs | % {$body+= "<li>$_</li>" } Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer" #Send email Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer Disconnect-VIServer -Confirm:$false Out-LogFile -Message "Disconnected from vCenter" Out-LogFile -Message "Finished"
PowerShellCorpus/PoshCode/Add-RelativePathCapture..ps1
Add-RelativePathCapture..ps1
##############################################################################\n##\n## Add-RelativePathCapture\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 that captures relative path\nnavigation without having to explicitly call 'Set-Location'\n\n.EXAMPLE\n\nPS C:\\Users\\Lee\\Documents>..\nPS C:\\Users\\Lee>...\nPS C:\\>\n\n.NOTES\n\nThis commands builds on New-CommandWrapper, also included in the Windows\nPowerShell Cookbook.\n\n#>\n\nSet-StrictMode -Version Latest\n\nNew-CommandWrapper Out-Default `\n -Process {\n if(($_ -is [System.Management.Automation.ErrorRecord]) -and\n ($_.FullyQualifiedErrorId -eq "CommandNotFoundException"))\n {\n ## Intercept all CommandNotFound exceptions, where the actual\n ## command consisted solely of dots.\n $command = $_.TargetObject\n if($command -match '^(\\.)+$')\n {\n ## Count the number of dots, and go that many levels (minus\n ## one) up the directory hierarchy.\n $newLocation = "..\\" * ($command.Length - 1)\n if($newLocation) { Set-Location $newLocation }\n\n ## Handle the error\n $error.RemoveAt(0)\n $_ = $null\n }\n }\n }
PowerShellCorpus/PoshCode/Test-Hash 2.ps1
Test-Hash 2.ps1
function Test-Hash { #.Synopsis # Test the HMAC hash(es) of a file #.Description # Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash #.Example # Get-ChildItem -File | Test-Hash -BasePath . | Format-Table -Auto # # This example shows how to list the files in the current directory (PS3) and also shows how to use the BasePath parameter to avoid outputing the full path, so that you can (hopefully) see the full output without elipsis. #.Example # Get-ChildItem .\\Bin\\Release -recurse | Test-Hash -BasePath .\\Bin\\Release -Type SHA256 | Export-CSV ~\\Hashes.csv # C:\\PS> Set-Location "C:\\Program Files\\MyProduct" # C:\\Program Files\\MyProduct>Import-CSV ~\\Hashes.csv | Test-Hash # # This example shows how to take the hash of a collection of files and store them in a csv file, and then later verify that the files in a secondary location match the originals exactly. # #.Example # Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5 # # Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name # and take the hash of the file (using the extension of the HashFile as the Type of Hash). # #.Example # Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5 # # Takes the MD5 hash and compares it to the provided hash # #.Example # Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517 # # Tests all of the hashes against the provided (Sha1) hash #.Notes # Version History: # 1.0 Initial Version # 1.1 Fixed missing 'm' # 2.0 Change hashing to use stream instead of reading all bytes (wow!) [CmdletBinding(DefaultParameterSetName="NoExpectation")] PARAM( # The path to the file to hash [Parameter(Position=0,Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [string]$Path, # When hashing many files in folders, use this to convert to relative paths (so you can compare again in a different location) [Parameter(Position=2,Mandatory=$false,ParameterSetName="NoExpectation")] [string]$BasePath, # Supports hashing against a .md5 or .sha1 file such as frequently found on open source servers or torrent sites [Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")] [string]$HashFileName, # Supports passing in the expected hash (particularly useful when piping input from a previous run) [Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)] [Parameter(Position=2,Mandatory=$false,ParameterSetName="FromHashFile")] [ALias("Hash")] [string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $Path)[0].split(" ")[0] }), # The algorithm to use when hashing [Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)] [Parameter(Position=1,Mandatory=$false,ParameterSetName="NoExpectation")] [ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160")] [string[]]$Algorithm = $(if($HashFileName){ [IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1) } else { "SHA256" }) ) begin { $ofs="" if($BasePath) { Push-Location $BasePath } } process { if($BasePath) { $Path = Resolve-Path $Path -Relative } else { $Path = Convert-Path $Path } if(Test-Path $Path -Type Container) { # I'd like to support recursing all the files, but for now, just skip Write-Warning "Cannot calculate hash for directories: '$Path'" return } $Hashes = @( foreach($Type in $Algorithm) { # Take the Hash without storing the bytes try { $stream = [IO.File]::OpenRead( (Convert-Path $Path) ) [string]$hash = [Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( $stream ) | ForEach { "{0:x2}" -f $_ } } catch {} finally { $stream.Dispose() } # Output an object with the hash, algorithm and path New-Object PSObject -Property @{ Path = $Path; Algorithm = $Type; Hash = $Hash } } ) if($ExpectedHash) { # Check all the hashes to see if any of them match if( $Match = $Hashes | Where { $_.Hash -eq $ExpectedHash } ) { Write-Verbose "Matched hash:`n$($Match | Out-String)" # Output an object with the hash, algorithm and path New-Object PSObject -Property @{ Path = $Match.Path; Algorithm = $Match.Algorithm; Hash = $Match.Hash; Matches = $True } } else { Write-Verbose "Failed to match hash:`n$($PSBoundParameters | Out-String)" # Output an object with the first hash, algorithm and path New-Object PSObject -Property @{ Path = $Hashes[0].Path; Algorithm = $Hashes[0].Algorithm; Hash = $Hashes[0].Hash; Matches = $False } } } else { Write-Output $Hashes } } end { if($BasePath) { Pop-Location } } }
PowerShellCorpus/PoshCode/Get-ObservedIPRange_1.ps1
Get-ObservedIPRange_1.ps1
function Get-ObservedIPRange { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Physical NIC from Get-VMHostNetworkAdapter")] [VMware.VimAutomation.Client20.Host.NIC.PhysicalNicImpl] $Nic ) process { $hostView = Get-VMHost -Id $Nic.VMHostId | Get-View -Property ConfigManager $ns = Get-View $hostView.ConfigManager.NetworkSystem $hints = $ns.QueryNetworkHint($Nic.Name) foreach ($hint in $hints) { foreach ($subnet in $hint.subnet) { $observed = New-Object -TypeName PSObject $observed | Add-Member -MemberType NoteProperty -Name Device -Value $Nic.Name $observed | Add-Member -MemberType NoteProperty -Name VMHostId -Value $Nic.VMHostId $observed | Add-Member -MemberType NoteProperty -Name IPSubnet -Value $subnet.IPSubnet $observed | Add-Member -MemberType NoteProperty -Name VlanId -Value $subnet.VlanId Write-Output $observed } } } } # Example use: # Get-VMHost esx01a.vmworld.com | Get-VMHostNetworkAdapter | Where { $_.Name -eq "vmnic1" } | Get-ObservedIPRange # Example output: #Device VMHostId IPSubnet VlanId #------ -------- -------- ------ #vmnic1 HostSystem-host-102 10.91.245.128-10.91... 2907 #vmnic1 HostSystem-host-102 10.91.244.133-10.91... 2905 #vmnic1 HostSystem-host-102 10.91.243.253-10.91... 2903 #vmnic1 HostSystem-host-102 10.91.246.11-10.91.... 2908 #vmnic1 HostSystem-host-102 10.91.246.129-10.91... 2909
PowerShellCorpus/PoshCode/Get-LockoutInfo.ps1
Get-LockoutInfo.ps1
<###################################################### # Find Lockout Events # # # # Pre-Requisites: Domain Admin Rights, Writeable # # C:\\temp directory on both the local machine and # # the domain controllers. # # # # Summary: Script will prompt for AD username, # # the name of the domain controller, and the name # # of the domain. A WMI call will initiate a backup # # of the security event log on the domain controller. # # That backup copy will be moved to the local machine # # where it is parsed for specific events filtered by # # user and/or event. Output is written to a text file# # in the local c:\\temp directory. Lastly, the local # # copy of the security log is deleted if possible as # # a cleanup measure. # # # # Note: Run on every domain controller and review # # output after each run. # # # # # # # # # # -Alex Stone 8/1/2011 # #######################################################> $error.clear() $user = Read-Host "Please enter the userid of the account in question." $dc = Read-Host "Please enter the name of the server to be searched." $domain = Read-Host "Please enter the name of the domain." Set-Location c:\\temp\\ $mymachine = $env:COMPUTERNAME #Use WMI to attach to the remote WMI instance for the event log $dclog = Get-WmiObject -ComputerName $dc Win32_NTEventlogFile #Select security as its own object $seclog = $dclog |where-object { $_.LogfileName -match "Security"} #Strings for paths to be used as temp space. $logstr = "c:\\temp\\"+$dc+"seclog.evt" $mvstr = "\\\\"+$dc+"\\c$\\temp\\"+$dc+"seclog.evt" #Backup the security log locally to the server. $seclog.BackupEventlog($logstr) #Move the newly created backup to our local machine for processing. move $mvstr $logstr -force #Convert user name into SID $objUser = New-Object System.Security.Principal.NTAccount($domain, $user) $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]) #Search local copy of log for events for that user $userevents = Get-WinEvent -oldest -FilterHashtable @{Path=$logstr; UserID=$strSID.value} #Write header into output file. $outpath = "C:\\temp\\"+$user+"rpt.txt" "Report for lockouts on user " +$user > $outpath #Loop to find certain eventid that relate to account invalid logins. if ($userevents -ne $null) { foreach ($event in $userevents) { #Events to find relating to login failures. if (($event.id -eq 529) -or ($event.id -eq 530) -or ($event.id -eq 531) -or ($event.id -eq 533) -or ($event.id -eq 534) -or ($event.id -eq 535) -or ($event.id -eq 536) -or ($event.id -eq 537) -or ($event.id -eq 539) -or ($event.id -eq 549) -or ($event.id -eq 644) -or ($event.id -eq 675) -or ($event.id -eq 676) -or ($event.id -eq 681) -or ($event.id -eq 12294)) { $outstring = $event.id.tostring()+" "+$event.timecreated+" "+$event.message.tostring() $outstring >> $outpath } } } else {"No events detected for "+$user} #Attempt to find specific lockout event type (Event 644). $lockevents = Get-WinEvent -oldest -FilterHashtable @{Path=$logstr; ID=644} #Loop to find lockout events that relate to specifc target user. if ($lockevents -ne $null) { foreach ($lockevent in $lockevents) { $properties = $lockevent.properties foreach ($prop in $properties) { if ($prop.value -match $user) { $outstring = $lockevent.id.tostring()+" "+$lockevent.timecreated+" "+$lockevent.message.tostring() $outstring >> $outpath } } } } else {"No lock events detected."} #Section to delete local copy of the security log. #First clear the error stack. $error.Clear() #Attempt to delete the local copy of the log. remove-item $logstr #If delete was a filure, wait 25 seconds and try again. if ($error.count -ne 0) { "Error deleting local copy of log file. Waiting 25 seconds and trying again." Start-sleep 25 #Second attempt at delete. $error.clear() remove-item $logstr #If the error counter still indicates a problem, notify the user to delete it manually. if ($error.count -ne 0) {"Unable to delete "+$logstr+", you will have to delete it manually."} else {"Deleting local copy of security log complete."} } else {"Deleting local copy of security log complete."} #Final message indicating location of output. "See "+$outpath+" for results information."
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object_4.ps1
h20 -Hashtables 2 object_4.ps1
uCMzpE this is delisious! xfather123
PowerShellCorpus/PoshCode/get-netstat 1.2.ps1
get-netstat 1.2.ps1
$netstat = netstat -a -n -o | where-object { $_ -match "(UDP|TCP)" } [regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)' foreach ($net in $netstat) { [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName switch -regex ($net.Trim()) { $regexTCP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = [int]$matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } $regexUDP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = [int]$matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } } $process }
PowerShellCorpus/PoshCode/IPv4 Helpers.ps1
IPv4 Helpers.ps1
Function ConvertTo-BinaryIP { #.Synopsis # Convert an IP address to binary #.Example # ConvertTo-BinaryIP -IP 192.168.1.1 Param ( [string] $IP ) Process { $out = @() Foreach ($octet in $IP.split('.')) { $strout = $null 0..7|% { IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { $octet = $octet - [math]::pow(2,(7-$_)) [string]$strout = $strout + "1" } else { [string]$strout = $strout + "0" } } $out += $strout } return [string]::join('.',$out) } } Function ConvertFrom-BinaryIP { #.Synopsis # Convert from Binary to an IP address #.Example # Convertfrom-BinaryIP -IP 11000000.10101000.00000001.00000001 Param ( [string] $IP ) Process { $out = @() Foreach ($octet in $IP.split('.')) { $strout = 0 0..7|% { $bit = $octet.Substring(($_),1) IF ($bit -eq 1) { $strout = $strout + [math]::pow(2,(7-$_)) } } $out += $strout } return [string]::join('.',$out) } } Function ConvertTo-MaskLength { #.Synopsis # Convert from a netmask to the masklength #.Example # ConvertTo-MaskLength -Mask 255.255.255.0 Param ( [string] $mask ) Process { $out = 0 Foreach ($octet in $Mask.split('.')) { $strout = 0 0..7|% { IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { $octet = $octet - [math]::pow(2,(7-$_)) $out++ } } } return $out } } Function ConvertFrom-MaskLength { #.Synopsis # Convert from masklength to a netmask #.Example # ConvertFrom-MaskLength -Mask /24 #.Example # ConvertFrom-MaskLength -Mask 24 Param ( [int] $mask ) Process { $out = @() [int]$wholeOctet = ($mask - ($mask % 8))/8 if ($wholeOctet -gt 0) { 1..$($wholeOctet) |%{ $out += "255" } } $subnet = ($mask - ($wholeOctet * 8)) if ($subnet -gt 0) { $octet = 0 0..($subnet - 1) | %{ $octet = $octet + [math]::pow(2,(7-$_)) } $out += $octet } for ($i=$out.count;$i -lt 4; $I++) { $out += 0 } return [string]::join('.',$out) } } Function Get-NetworkAddress { #.Synopsis # Get the network address of a given lan segment #.Example # Get-NetworkAddress -IP 192.168.1.36 -mask 255.255.255.0 Param ( [string] $IP, [string] $Mask, [switch] $Binary ) Process { $BinaryIP = ConvertTo-BinaryIP $IP $BinaryMask = ConvertTo-BinaryIP $Mask 0..34 | %{ $IPBit = $BinaryIP.Substring($_,1) $MaskBit = $BinaryMask.Substring($_,1) IF ($IPBit -eq '1' -and $MaskBit -eq '1') { $NetAdd = $NetAdd + "1" } elseif ($IPBit -eq ".") { $NetAdd = $NetAdd +'.' } else { $NetAdd = $NetAdd + "0" } } if ($Binary) { return $NetAdd } else { return ConvertFrom-BinaryIP $NetAdd } } } Function Get-BroadcastAddress { #.Synopsis # Get the Broadcast address of a given Lan segment #.Example # Get-BroadcastAddress -IP 192.168.1.36 -Mask 255.255.255.0 Param ( [string] $IP, [string] $Mask, [switch] $Binary ) Process { $BinaryIP = ConvertTo-BinaryIP $IP $BinaryMask = ConvertTo-BinaryIP $Mask 0..34 | %{ $IPBit = $BinaryIP.Substring($_,1) $MaskBit = $BinaryMask.Substring($_,1) IF ($IPBit -eq '1' -or $MaskBit -eq '0') { $Broadcast = $Broadcast + "1" } elseif ($IPBit -eq ".") { $Broadcast = $Broadcast +'.' } else { $Broadcast = $Broadcast + "0" } } if ($Binary) { return $Broadcast } else { return ConvertFrom-BinaryIP $Broadcast } } } Function Get-IPRange { #.Synopsis # Given an Ip and subnet, return every IP in that lan segment #.Example # Get-IPRange -IP 192.168.1.36 -Mask 255.255.255.0 #.Example # Get-IPRange -IP 192.168.5.55 -Mask /23 Param ( [string] $IP, [string] $netmask ) Process { iF ($netMask.length -le 3) { $masklength = $netmask.replace('/','') $Subnet = ConvertFrom-MaskLength $masklength } else { $masklength = ConvertTo-MaskLength $netmask } $network = Get-NetworkAddress $IP $Subnet [int]$FirstOctet,[int]$SecondOctet,[int]$ThirdOctet,[int]$FourthOctet = $network.split('.') $TotalIPs = ([math]::pow(2,(32-$masklength)) -2) $blocks = ($TotalIPs - ($TotalIPs % 256))/256 if ($Blocks -gt 0) { 1..$blocks | %{ 0..255 |%{ if ($FourthOctet -eq 255) { If ($ThirdOctet -eq 255) { If ($SecondOctet -eq 255) { $FirstOctet++ $secondOctet = 0 } else { $SecondOctet++ $ThirdOctet = 0 } } else { $FourthOctet = 0 $ThirdOctet++ } } else { $FourthOctet++ } Write-Output ("{0}.{1}.{2}.{3}" -f ` $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) } } } $sBlock = $TotalIPs - ($blocks * 256) if ($sBlock -gt 0) { 1..$SBlock | %{ if ($FourthOctet -eq 255) { If ($ThirdOctet -eq 255) { If ($SecondOctet -eq 255) { $FirstOctet++ $secondOctet = 0 } else { $SecondOctet++ $ThirdOctet = 0 } } else { $FourthOctet = 0 $ThirdOctet++ } } else { $FourthOctet++ } Write-Output ("{0}.{1}.{2}.{3}" -f ` $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) } } } }
PowerShellCorpus/PoshCode/Compress-Bitmap.ps1
Compress-Bitmap.ps1
function Compress-Bitmap { PARAM( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [IO.FileInfo]$SourceFile , [Parameter(Mandatory=$true, Position=1)] [String]$DestinationFile , [Parameter(Mandatory=$false)] [Int]$Width , [Parameter(Mandatory=$false)] [Int]$Height , [Parameter(Mandatory=$false)] [Int]$MaxFilesize , [Parameter(Mandatory=$false)] [Int]$Quality = 100 ) BEGIN { if($SourceFile) { $SourceFile = Get-ChildItem $SourceFile } } PROCESS { # Work our way down until we get a small enough file (this might be slow) [string]$intermediate = [IO.path]::GetRandomFileName() + ".jpeg" $bitmap = Import-Bitmap $SourceFile if($Width -and $Height) { $bitmap = Resize-Bitmap -Bitmap $bitmap -Width $Width -Height $Height } else { # work around another bug in Export-Bitmap $bitmap = Resize-Bitmap -Bitmap $bitmap -Percent 100 } do { Export-Bitmap -Bitmap $bitmap -Path $intermediate -Quality ($Quality--) } while( $MaxFilesize -and ((Get-ChildItem $intermediate).Length -gt $MaxFilesize)) Write-Host "Output Quality: $($Quality + 1)%" -Foreground Yellow Move-Item $intermediate $DestinationFile -Force -Passthru } }
PowerShellCorpus/PoshCode/Easy Snapshot Tool.ps1
Easy Snapshot Tool.ps1
#Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: Richard Yaw # Generated On: 19/04/2012 # # Easy Snapshot Tool for VMware # - GUI based tool # - Centralised view of all snapshots in a vCenter server # - Create and delete snapshots of multiple VMs at the SAME time ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $EasySnapForm = New-Object System.Windows.Forms.Form $FormHeader = new-object System.Windows.Forms.Label $vCenterLabel = New-Object System.Windows.Forms.Label $VCComboBox = New-Object System.Windows.Forms.ComboBox $LoginBtn = New-Object System.Windows.Forms.Button $RefreshBtn = New-Object System.Windows.Forms.Button $ListSnapBtn = New-Object System.Windows.Forms.Button $CreateSnapBtn = New-Object System.Windows.Forms.Button $SnapshotlistView = New-Object System.Windows.Forms.ListView $DeleteSnapBtn = New-Object System.Windows.Forms.Button $VM = New-Object System.Windows.Forms.ColumnHeader $SnapName = New-Object System.Windows.Forms.ColumnHeader $Description = New-Object System.Windows.Forms.ColumnHeader $Created = New-Object System.Windows.Forms.ColumnHeader $ResetBtn = New-Object System.Windows.Forms.Button $ExitBtn = New-Object System.Windows.Forms.Button $InitialFormWindowState1 = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $LoginBtn_Click= { If ($VCComboBox.SelectedItem -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show("Please choose a vCenter Server from the drop-down list.") } Else { #TODO: Place custom script here If ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "VMware.VimAutomation.Core" } #Connect to vCenter $vCenterName = $VCComboBox.SelectedItem.ToString() Connect-VIServer $vCenterName -ErrorAction SilentlyContinue $VCComboBox.Enabled = $false $LoginBtn.Enabled = $false $DeleteSnapBtn.Enabled = $true $Refreshbtn.Enabled = $true $Resetbtn.Enabled = $true $ListSnapBtn.Enabled = $true $CreateSnapBtn.Enabled = $true [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show("You are now connected to $vCenterName.") $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $EasySnapForm.WindowState = $InitialFormWindowState1 } } } $DeleteSnapBtn_OnClick= { #TODO: Place custom script here $CheckedSnapshots = $SnapshotlistView.CheckedItems If($CheckedSnapshots.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No Snapshot Selected.') } Else { foreach($CheckedSnapshot in $CheckedSnapshots){ $VMName = $CheckedSnapshot.SubItems[0].Text $SnapshotName = $CheckedSnapshot.SubItems[1].Text Get-VM -Name $VMName | Get-Snapshot | Where{$_.Name -eq $SnapshotName} | remove-snapshot -Confirm:$false -RunAsync $SnapshotlistView.Items.RemoveAt($SnapshotlistView.Items.IndexOf($CheckedSnapshot)) $SnapshotlistView.refresh() } } } $RefreshBtn_OnClick= { #TODO: Place custom script here $SnapshotlistView.Items.Clear() Get-View -ViewType VirtualMachine -Property Name,Snapshot -SearchRoot(Get-Datacenter | get-view).MoRef ` -Filter @{"Snapshot"="VMware.Vim.VirtualMachineSnapshotInfo"} | foreach-object { $vmname = $_.Name (Get-View -Id $_.MoRef -Property Snapshot).Snapshot.RootSnapshotList | foreach-object { $Item_VM = New-Object System.Windows.Forms.ListViewItem($vmname) $Item_Snapshot = $Item_VM.SubItems.Add($_.Name) $Item_Created = $Item_VM.SubItems.Add($_.CreateTime.ToString("yyyy/MM/dd")) $Item_ArrDesc = ($_.Description).split("_") If ($Item_ArrDesc[0] -ne $null) { $Item_CreatorID = $Item_VM.SubItems.Add($Item_ArrDesc[0]) } Else { $Item_CreatorID = $Item_VM.SubItems.Add("") } If ($Item_ArrDesc[1] -ne $null) { $Item_ChangeNo = $Item_VM.SubItems.Add($Item_ArrDesc[1]) } Else { $Item_ChangeNo = $Item_VM.SubItems.Add("") } If ($Item_ArrDesc[2] -ne $null) { $Item_DeletionDate = $Item_VM.SubItems.Add($Item_ArrDesc[2]) } Else { $Item_DeletionDate = $Item_VM.SubItems.Add("") } $SnapDaysOld = (new-timespan -start (Get-Date $_.CreateTime.ToString("yyyy/MM/dd"))).Days If($SnapDaysOld -lt 10) { $Item_DaysOld = $Item_VM.SubItems.Add("0" + $SnapDaysOld) } Else{ $Item_DaysOld = $Item_VM.SubItems.Add($SnapDaysOld) If($SnapDaysOld -ge 15) { $Item_VM.UseItemStyleForSubItems = $False $Item_VM.BackColor = "Red" $Item_Snapshot.BackColor = "Red" $Item_Created.BackColor = "Red" $Item_CreatorID.BackColor = "Red" $Item_ChangeNo.BackColor = "Red" $Item_DeletionDate.BackColor = "Red" $Item_DaysOld.BackColor = "Red" } } $SnapshotlistView.Items.Add($Item_VM) } } } $ListSnapBtn_OnClick= { #TODO: Place custom script here If (!$?) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show($($error[0])) } Else { $SnapshotlistView.Items.Clear() Get-View -ViewType VirtualMachine -Property Name,Snapshot -SearchRoot(Get-Datacenter | get-view).MoRef ` -Filter @{"Snapshot"="VMware.Vim.VirtualMachineSnapshotInfo"} | foreach-object { $vmname = $_.Name (Get-View -Id $_.MoRef -Property Snapshot).Snapshot.RootSnapshotList | foreach-object { $Item_VM = New-Object System.Windows.Forms.ListViewItem($vmname) $Item_Snapshot = $Item_VM.SubItems.Add($_.Name) $Item_Created = $Item_VM.SubItems.Add($_.CreateTime.ToString("yyyy/MM/dd")) $Item_ArrDesc = ($_.Description).split("_") If ($Item_ArrDesc[0] -ne $null) { $Item_CreatorID = $Item_VM.SubItems.Add($Item_ArrDesc[0]) } Else { $Item_CreatorID = $Item_VM.SubItems.Add("") } If ($Item_ArrDesc[1] -ne $null) { $Item_ChangeNo = $Item_VM.SubItems.Add($Item_ArrDesc[1]) } Else { $Item_ChangeNo = $Item_VM.SubItems.Add("") } If ($Item_ArrDesc[2] -ne $null) { $Item_DeletionDate = $Item_VM.SubItems.Add($Item_ArrDesc[2]) } Else { $Item_DeletionDate = $Item_VM.SubItems.Add("") } $SnapDaysOld = (new-timespan -start (Get-Date $_.CreateTime.ToString("yyyy/MM/dd"))).Days If($SnapDaysOld -lt 10) { $Item_DaysOld = $Item_VM.SubItems.Add("0" + $SnapDaysOld) } Else{ $Item_DaysOld = $Item_VM.SubItems.Add($SnapDaysOld) If($SnapDaysOld -ge 15) { $Item_VM.UseItemStyleForSubItems = $False $Item_VM.BackColor = "Red" $Item_Snapshot.BackColor = "Red" $Item_Created.BackColor = "Red" $Item_CreatorID.BackColor = "Red" $Item_ChangeNo.BackColor = "Red" $Item_DeletionDate.BackColor = "Red" $Item_DaysOld.BackColor = "Red" } } $SnapshotlistView.Items.Add($Item_VM) } } } } $CreateSnapBtn_OnClick= { #TODO: Place custom script here GenerateSnapForm } $ResetBtn_OnClick= { #TODO: Place custom script here #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false $SnapshotlistView.Items.Clear() $VCComboBox.Enabled = $true $VCComboBox.Text = "" $LoginBtn.Enabled = $true $DeleteSnapBtn.Enabled = $false $Refreshbtn.Enabled = $false $Resetbtn.Enabled = $false $ListSnapBtn.Enabled = $false $CreateSnapBtn.Enabled = $false } $comparerClassString = @" using System; using System.Windows.Forms; using System.Drawing; using System.Collections; public class ListViewItemComparer : IComparer { private int col; public ListViewItemComparer() { col = 0; } public ListViewItemComparer(int column) { col = column; } public int Compare(object x, object y) { return String.Compare( ((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text); } } "@ # Add the comparer class Add-Type -TypeDefinition $comparerClassString ` -ReferencedAssemblies (` 'System.Windows.Forms', 'System.Drawing') # Add the event to the ListView ColumnClick event $columnClick = { $SnapshotlistView.ListViewItemSorter = ` New-Object ListViewItemComparer($_.Column) } $ExitBtn_OnClick= { #TODO: Place custom script here If ($VCComboBox.Text -ne "") { #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false } #Close Form $EasySnapForm.close() } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 462 $System_Drawing_Size.Width = 734 $EasySnapForm.ClientSize = $System_Drawing_Size $EasySnapForm.DataBindings.DefaultDataSourceUpdateMode = 0 $EasySnapForm.Name = "EasySnapForm" $EasySnapForm.Text = "Easy Snapshot Tool" $EasySnapForm.StartPosition = "CenterScreen" $EasySnapForm.FormBorderStyle = "FixedDialog" $EasySnapForm.MaximizeBox = $false $EasySnapForm.MinimizeBox = $false #Start Form Header $FormHeader.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold) $FormHeader.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft $FormHeader.Text = 'Easy Snapshot Tool' $FormHeader.Location = new-object System.Drawing.Point(15,15) $FormHeader.Size = new-object System.Drawing.Size(300, 20) $EasySnapForm.Controls.Add($FormHeader) #End Form Header # Start vCenter Server Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 20 $vCenterLabel.Size = $System_Drawing_Size $vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",10,[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' $EasySnapForm.Controls.Add($vCenterLabel) # End vCenter Server Label # Start vCenter ComboBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 20 $VCComboBox.Size = $System_Drawing_Size $VCComboBox.Font = new-object System.Drawing.Font("Tahoma",8) $VCComboBox.DataBindings.DefaultDataSourceUpdateMode = 0 $VCComboBox.Name = 'VCComboBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 135 $System_Drawing_Point.Y = 50 $VCComboBox.Location = $System_Drawing_Point $VCComboBox.TabIndex = 0 $VCNames = @('VCServer01','VCServer02','VCServer03') foreach($VCName in $VCNames) { $VCComboBox.Items.add($VCName) } $EasySnapForm.Controls.Add($VCComboBox) # End vCenter ComboBox # Start Login Button $LoginBtn.TabIndex = 1 $LoginBtn.Name = 'LoginBtn' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 22 $LoginBtn.Size = $System_Drawing_Size $LoginBtn.UseVisualStyleBackColor = $True $LoginBtn.Font = new-object System.Drawing.Font("Tahoma",8) $LoginBtn.Text = 'Login' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 260 $System_Drawing_Point.Y = 50 $LoginBtn.Location = $System_Drawing_Point $LoginBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $LoginBtn.add_Click($LoginBtn_Click) $EasySnapForm.Controls.Add($LoginBtn) # End Login Button #Start Create Snapshot Button $CreateSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 622 $System_Drawing_Point.Y = 50 $CreateSnapBtn.Location = $System_Drawing_Point $CreateSnapBtn.Name = "CreateSnapBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $CreateSnapBtn.Size = $System_Drawing_Size $CreateSnapBtn.TabIndex = 6 $CreateSnapBtn.Text = "Create Snapshots" $CreateSnapBtn.Font = new-object System.Drawing.Font("Tahoma",8) $CreateSnapBtn.UseVisualStyleBackColor = $True $CreateSnapBtn.Enabled = $false $CreateSnapBtn.add_Click($CreateSnapBtn_OnClick) $EasySnapForm.Controls.Add($CreateSnapBtn) #End Create Snapshot Button #Start List Snapshot Button $ListSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 515 $System_Drawing_Point.Y = 50 $ListSnapBtn.Location = $System_Drawing_Point $ListSnapBtn.Name = "ListSnapBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $ListSnapBtn.Size = $System_Drawing_Size $ListSnapBtn.TabIndex = 6 $ListSnapBtn.Text = "List Snapshots" $ListSnapBtn.Font = new-object System.Drawing.Font("Tahoma",8) $ListSnapBtn.UseVisualStyleBackColor = $True $ListSnapBtn.Enabled = $false $ListSnapBtn.add_Click($ListSnapBtn_OnClick) $EasySnapForm.Controls.Add($ListSnapBtn) #End List Snapshot Button #Start Snapshot List $SnapshotlistView.AllowColumnReorder = $True $SnapshotlistView.CheckBoxes = $True $System_Windows_Forms_ColumnHeader_45 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_45.Name = "VM" $System_Windows_Forms_ColumnHeader_45.Text = "VM Name" $System_Windows_Forms_ColumnHeader_45.Width = 100 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_45)|Out-Null $System_Windows_Forms_ColumnHeader_46 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_46.Name = "SnapName" $System_Windows_Forms_ColumnHeader_46.Text = "Snapshot Name" $System_Windows_Forms_ColumnHeader_46.Width = 200 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_46)|Out-Null $System_Windows_Forms_ColumnHeader_47 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_47.Name = "CreationDate" $System_Windows_Forms_ColumnHeader_47.Text = "Created On" $System_Windows_Forms_ColumnHeader_47.Width = 80 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_47)|Out-Null $System_Windows_Forms_ColumnHeader_48 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_48.Name = "CreatorID" $System_Windows_Forms_ColumnHeader_48.Text = "Created By" $System_Windows_Forms_ColumnHeader_48.Width = 80 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_48)|Out-Null $System_Windows_Forms_ColumnHeader_49 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_49.Name = "ChangeNo" $System_Windows_Forms_ColumnHeader_49.Text = "Change No" $System_Windows_Forms_ColumnHeader_49.Width = 80 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_49)|Out-Null $System_Windows_Forms_ColumnHeader_50 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_50.Name = "DeletionDate" $System_Windows_Forms_ColumnHeader_50.Text = "Deletion Date" $System_Windows_Forms_ColumnHeader_50.Width = 80 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_50)|Out-Null $System_Windows_Forms_ColumnHeader_51 = New-Object System.Windows.Forms.ColumnHeader $System_Windows_Forms_ColumnHeader_51.Name = "DaysOld" $System_Windows_Forms_ColumnHeader_51.Text = "Days Old" $System_Windows_Forms_ColumnHeader_51.Width = 60 $SnapshotlistView.Columns.Add($System_Windows_Forms_ColumnHeader_51)|Out-Null $SnapshotlistView.DataBindings.DefaultDataSourceUpdateMode = 0 $SnapshotlistView.FullRowSelect = $True $SnapshotlistView.GridLines = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 90 $SnapshotlistView.Location = $System_Drawing_Point $SnapshotlistView.Name = "SnapshotlistView" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 330 $System_Drawing_Size.Width = 709 $SnapshotlistView.Size = $System_Drawing_Size $SnapshotlistView.TabIndex = 7 $SnapshotlistView.UseCompatibleStateImageBehavior = $False $SnapshotlistView.View = 'Details' $SnapshotlistView.Sorting = 'Ascending' $SnapshotlistView.add_ColumnClick($ColumnClick) $EasySnapForm.Controls.Add($SnapshotlistView) #End Snapshot List #Start Delete Button $DeleteSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 427 $DeleteSnapBtn.Location = $System_Drawing_Point $DeleteSnapBtn.Name = "DeleteSnapBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $DeleteSnapBtn.Size = $System_Drawing_Size $DeleteSnapBtn.TabIndex = 6 $DeleteSnapBtn.Text = "Delete" $DeleteSnapBtn.Font = new-object System.Drawing.Font("Tahoma",8) $DeleteSnapBtn.UseVisualStyleBackColor = $True $DeleteSnapBtn.Enabled = $false $DeleteSnapBtn.add_Click($DeleteSnapBtn_OnClick) $EasySnapForm.Controls.Add($DeleteSnapBtn) #End Delete Button #Start Refresh Button $RefreshBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 120 $System_Drawing_Point.Y = 427 $RefreshBtn.Location = $System_Drawing_Point $RefreshBtn.Name = "RefreshBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $RefreshBtn.Size = $System_Drawing_Size $RefreshBtn.TabIndex = 6 $RefreshBtn.Text = "Refresh" $RefreshBtn.Font = new-object System.Drawing.Font("Tahoma",8) $RefreshBtn.UseVisualStyleBackColor = $True $RefreshBtn.Enabled = $false $RefreshBtn.add_Click($RefreshBtn_OnClick) $EasySnapForm.Controls.Add($RefreshBtn) #End Refresh Button #Start Reset Button $ResetBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 515 $System_Drawing_Point.Y = 427 $ResetBtn.Location = $System_Drawing_Point $ResetBtn.Name = "ResetBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $ResetBtn.Size = $System_Drawing_Size $ResetBtn.TabIndex = 6 $ResetBtn.Text = "Reset" $ResetBtn.Font = new-object System.Drawing.Font("Tahoma",8) $ResetBtn.UseVisualStyleBackColor = $True $ResetBtn.Enabled = $false $ResetBtn.add_Click($ResetBtn_OnClick) $EasySnapForm.Controls.Add($ResetBtn) #End Reset Button #Start Exit Button $ExitBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 622 $System_Drawing_Point.Y = 427 $ExitBtn.Location = $System_Drawing_Point $ExitBtn.Name = "ExitBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $ExitBtn.Size = $System_Drawing_Size $ExitBtn.TabIndex = 6 $ExitBtn.Text = "Exit" $ExitBtn.Font = new-object System.Drawing.Font("Tahoma",8) $ExitBtn.UseVisualStyleBackColor = $True $ExitBtn.add_Click($ExitBtn_OnClick) $EasySnapForm.Controls.Add($ExitBtn) #End Delete Button #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState1 = $EasySnapForm.WindowState #Init the OnLoad event to correct the initial state of the form $EasySnapForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $EasySnapForm.ShowDialog()| Out-Null } #End Function #Generated Snapshot Form Function function GenerateSnapForm { #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $TakeSnapForm = New-Object System.Windows.Forms.Form $FormHeader2 = new-object System.Windows.Forms.Label $InfoLabel = New-Object System.Windows.Forms.Label $VMListBox = New-Object System.Windows.Forms.CheckedListBox $SnapNameLbl = New-Object System.Windows.Forms.Label $SnapNameComboBox = New-Object System.Windows.Forms.ComboBox $CreatorLbl = New-Object System.Windows.Forms.Label $CreatorTxtBox = New-Object System.Windows.Forms.TextBox $RetentionLbl = New-Object System.Windows.Forms.Label $RetentionComboBox = New-Object System.Windows.Forms.ComboBox $ChangeNoLbl = New-Object System.Windows.Forms.Label $ChangeNoTxtBox = New-Object System.Windows.Forms.TextBox $FindTxtBox = New-Object System.Windows.Forms.TextBox $FindBtn = New-Object System.Windows.Forms.Button $ResetFindBtn = New-Object System.Windows.Forms.Button $FindLbl = New-Object System.Windows.Forms.Label $TakeSnapBtn = New-Object System.Windows.Forms.Button $ExitBtn2 = New-Object System.Windows.Forms.Button $InitialFormWindowState2 = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects $FindBtn_OnClick= { #TODO: Place custom script here If($FindTxtBox.Text -ne "") { If($VMListBox.CheckedItems.Count -eq 0) { $VMListBox.Items.Clear() } Else { $CheckedVMs = @() Foreach($VM in $VMListBox.CheckedItems) { $CheckedVMs += $VM } $VMListBox.Items.Clear() Foreach($CheckedVM in $CheckedVMs) { [void]$VMListBox.items.add($CheckedVM) $VMListBox.SetItemChecked($VMListBox.items.IndexOf($CheckedVM),$true) } } $BeforeCount = $VMListBox.Items.Count Get-VM -Name $FindTxtBox.Text -ErrorAction SilentlyContinue | % { [void]$VMListBox.items.add($_.Name) } $AfterCount = $VMListBox.Items.Count If($AfterCount -eq $BeforeCount) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No results found.') } } } $ResetFindBtn_OnClick= { #TODO: Place custom script here $VMListBox.Items.Clear() Get-VM | % { [void]$VMListBox.items.add($_.Name) } } $TakeSnapBtn_OnClick= { #TODO: Place custom script here $CheckedVMs = $VMListBox.CheckedItems If($CheckedVMs.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No VM Selected.') } Else { $SnapName = $SnapNameComboBox.Text $CreatorID = $CreatorTxtBox.Text $Retention = $RetentionCombobox.SelectedItem $DeletionDate = (Get-Date).AddDays($Retention).ToShortDateString() $ChangeNo = $ChangeNoTxtBox.Text $SnapDesc = $CreatorID + "_" + $ChangeNo + "_" + $DeletionDate If(($SnapName -eq "") -or ($ChangeNo -eq "")) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please make sure that you have entered a Snapshot Name, Change Number and a Retention Period.') } ElseIf(($Retention -lt 1) -or ($Retention -gt 14)) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Retention period must be between 1 and 14 days.') } Else { foreach($CheckedVM in $CheckedVMs){ New-Snapshot -VM(Get-VM -Name $CheckedVM) -Name $SnapName -Description $SnapDesc -Confirm:$false -RunAsync } $a = new-object -comobject wscript.shell $intAnswer = $a.popup("Task submitted successfully. Please check the task list in the vCenter console to view the progress. Do you want to create more snapshots?", 0,"Create Snapshots",4) If($intAnswer -eq 6) { $VMListBox.Items.Clear() Get-VM | % { [void]$VMListBox.items.add($_.Name) } $SnapNameComboBox.Text = "" $CreatorTxtBox.Text = "" $RetentionComboBox.Text = "" $ChangeNoTxtBox.Text = "" $FindTxtBox.Text = "" }Else { $TakeSnapForm.close() } } } } $ExitBtn2_OnClick= { #TODO: Place custom script here $TakeSnapForm.close() } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 462 $System_Drawing_Size.Width = 734 $TakeSnapForm.ClientSize = $System_Drawing_Size $TakeSnapForm.DataBindings.DefaultDataSourceUpdateMode = 0 $TakeSnapForm.Name = "TakeSnapForm" $TakeSnapForm.Text = "Snapshot Creation Form" $TakeSnapForm.StartPosition = "CenterScreen" $TakeSnapForm.FormBorderStyle = "FixedDialog" $TakeSnapForm.MaximizeBox = $false $TakeSnapForm.MinimizeBox = $false #Start Form Header $FormHeader2.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold) $FormHeader2.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft $FormHeader2.Text = 'Easy Snapshot Tool' $FormHeader2.Location = new-object System.Drawing.Point(15,15) $FormHeader2.Size = new-object System.Drawing.Size(230, 20) $TakeSnapForm.Controls.Add($FormHeader2) #End Form Header # Start Info Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 600 $System_Drawing_Size.Height = 20 $InfoLabel.Size = $System_Drawing_Size $InfoLabel.Font = new-object System.Drawing.Font("Tahoma",10) $InfoLabel.Text = 'Use this form to take a snapshot of multiple virtual machines at the same time.' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 50 $InfoLabel.Location = $System_Drawing_Point $InfoLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $InfoLabel.Name = 'InfoLabel' $TakeSnapForm.Controls.Add($InfoLabel) # End Info Label # Start VM List Box $VMListBox.TabIndex = 0 $VMListBox.FormattingEnabled = $True $VMListBox.CheckOnClick = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 330 $VMListBox.Size = $System_Drawing_Size $VMListBox.Font = new-object System.Drawing.Font("Tahoma",8) $VMListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $VMListBox.Name = 'VMListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 90 $VMListBox.Location = $System_Drawing_Point $VMListBox.MultiColumn = $False $VMListBox.Sorted = $True $VMListBox.HorizontalScrollbar = $True $TakeSnapForm.Controls.Add($VMListBox) #Get VMs in the selected vCenter Get-VM | % { [void]$VMListBox.items.add($_.Name) } # End VM List Box # Start Snap Name Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 400 $System_Drawing_Size.Height = 20 $SnapNameLbl.Size = $System_Drawing_Size $SnapNameLbl.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $SnapNameLbl.Text = 'Snapshot Name:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 90 $SnapNameLbl.Location = $System_Drawing_Point $SnapNameLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $SnapNameLbl.Name = 'SnapNameLbl' $TakeSnapForm.Controls.Add($SnapNameLbl) # End Snap Name Label # Start Snap Name Combobox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 20 $SnapNameComboBox.Size = $System_Drawing_Size $SnapNameComboBox.Font = new-object System.Drawing.Font("Tahoma",8) $SnapNameComboBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SnapNameComboBox.Name = 'SnapNameComboBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 110 $SnapNameComboBox.Location = $System_Drawing_Point $SnapNameComboBox.TabIndex = 1 $SnapshotNames = @("Patching","Hardening","Application Installation","Testing","Other") foreach($SnapshotName in $SnapshotNames) { $SnapNameComboBox.Items.add($SnapshotName) } $TakeSnapForm.Controls.Add($SnapNameComboBox) # End Snap Name Combobox # Start Creator Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 20 $CreatorLbl.Size = $System_Drawing_Size $CreatorLbl.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $CreatorLbl.Text = 'Created By:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 150 $CreatorLbl.Location = $System_Drawing_Point $CreatorLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $CreatorLbl.Name = 'CreatorLbl' $TakeSnapForm.Controls.Add($CreatorLbl) # End Creator Label # Start Creator Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 70 $System_Drawing_Size.Height = 20 $CreatorTxtBox.Size = $System_Drawing_Size $CreatorTxtBox.Font = new-object System.Drawing.Font("Tahoma",8) $CreatorTxtBox.DataBindings.DefaultDataSourceUpdateMode = 0 $CreatorTxtBox.Name = 'CreatorTxtBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 170 $CreatorTxtBox.Location = $System_Drawing_Point $TakeSnapForm.Controls.Add($CreatorTxtBox) $CreatorTxtBox.Text = [Environment]::UserName $CreatorTxtBox.Enabled = $false # End Creator Textbox # Start Retention Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 400 $System_Drawing_Size.Height = 20 $RetentionLbl.Size = $System_Drawing_Size $RetentionLbl.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $RetentionLbl.Text = 'Retention Period (Max 14 days):' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 210 $RetentionLbl.Location = $System_Drawing_Point $RetentionLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $RetentionLbl.Name = 'RetentionLbl' $TakeSnapForm.Controls.Add($RetentionLbl) # End Retention Label # Start Retention ComboBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 50 $System_Drawing_Size.Height = 20 $RetentionComboBox.Size = $System_Drawing_Size $RetentionComboBox.Font = new-object System.Drawing.Font("Tahoma",8) $RetentionComboBox.DataBindings.DefaultDataSourceUpdateMode = 0 $RetentionComboBox.Name = 'RetentionComboBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 230 $RetentionComboBox.Location = $System_Drawing_Point $RetentionComboBox.TabIndex = 1 $RetentionDays = @(1,2,3,4,5,6,7,8,9,10,11,12,13,14) foreach($RetentionDay in $RetentionDays) { $RetentionComboBox.Items.add($RetentionDay) } $TakeSnapForm.Controls.Add($RetentionComboBox) # End Retention ComboBox # Start Change No Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 300 $System_Drawing_Size.Height = 20 $ChangeNoLbl.Size = $System_Drawing_Size $ChangeNoLbl.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $ChangeNoLbl.Text = 'Change Number (e.g. C12345 or BAU):' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 270 $ChangeNoLbl.Location = $System_Drawing_Point $ChangeNoLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $ChangeNoLbl.Name = 'ChangeNoLbl' $TakeSnapForm.Controls.Add($ChangeNoLbl) # End Change No Label # Start Change No Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 70 $System_Drawing_Size.Height = 20 $ChangeNoTxtBox.Size = $System_Drawing_Size $ChangeNoTxtBox.Font = new-object System.Drawing.Font("Tahoma",8) $ChangeNoTxtBox.DataBindings.DefaultDataSourceUpdateMode = 0 $ChangeNoTxtBox.Name = 'ChangeNoTxtBox' $ChangeNoTxtBox.TabIndex = 2 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 290 $ChangeNoTxtBox.Location = $System_Drawing_Point $TakeSnapForm.Controls.Add($ChangeNoTxtBox) # End Change No Textbox # Start Find Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 20 $FindTxtBox.Size = $System_Drawing_Size $FindTxtBox.Font = new-object System.Drawing.Font("Tahoma",8) $FindTxtBox.DataBindings.DefaultDataSourceUpdateMode = 0 $FindTxtBox.Name = 'FindTxtBox' $FindTxtBox.TabIndex = 3 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 340 $FindTxtBox.Location = $System_Drawing_Point $TakeSnapForm.Controls.Add($FindTxtBox) # End Find Textbox #Start Find Button $TakeSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 355 $System_Drawing_Point.Y = 340 $FindBtn.Location = $System_Drawing_Point $FindBtn.Name = "FindBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 50 $FindBtn.Size = $System_Drawing_Size $FindBtn.TabIndex = 4 $FindBtn.Text = "Find" $FindBtn.Font = new-object System.Drawing.Font("Tahoma",8) $FindBtn.UseVisualStyleBackColor = $True $FindBtn.add_Click($FindBtn_OnClick) $TakeSnapForm.Controls.Add($FindBtn) #End Find Button #Start Reset Find Button $TakeSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 410 $System_Drawing_Point.Y = 340 $ResetFindBtn.Location = $System_Drawing_Point $ResetFindBtn.Name = "ResetFindBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 50 $ResetFindBtn.Size = $System_Drawing_Size $ResetFindBtn.TabIndex = 5 $ResetFindBtn.Font = new-object System.Drawing.Font("Tahoma",8) $ResetFindBtn.Text = "Reset" $ResetFindBtn.UseVisualStyleBackColor = $True $ResetFindBtn.add_Click($ResetFindBtn_OnClick) $TakeSnapForm.Controls.Add($ResetFindBtn) #End Reset Find Button # Start Find Label $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 300 $System_Drawing_Size.Height = 20 $FindLbl.Size = $System_Drawing_Size $FindLbl.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $FindLbl.Text = '(Note: Use * for Wildcards)' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 365 $FindLbl.Location = $System_Drawing_Point $FindLbl.DataBindings.DefaultDataSourceUpdateMode = 0 $FindLbl.Name = 'FindLbl' $TakeSnapForm.Controls.Add($FindLbl) # End Find Label #Start Take Snap Button $TakeSnapBtn.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 515 $System_Drawing_Point.Y = 427 $TakeSnapBtn.Location = $System_Drawing_Point $TakeSnapBtn.Name = "TakeSnapBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $TakeSnapBtn.Size = $System_Drawing_Size $TakeSnapBtn.TabIndex = 6 $TakeSnapBtn.Text = "Take Snapshot" $TakeSnapBtn.Font = new-object System.Drawing.Font("Tahoma",8) $TakeSnapBtn.UseVisualStyleBackColor = $True $TakeSnapBtn.add_Click($TakeSnapBtn_OnClick) $TakeSnapForm.Controls.Add($TakeSnapBtn) #End Take Snap Button #Start Exit Button $ExitBtn2.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 622 $System_Drawing_Point.Y = 427 $ExitBtn2.Location = $System_Drawing_Point $ExitBtn2.Name = "ExitBtn2" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 100 $ExitBtn2.Size = $System_Drawing_Size $ExitBtn2.TabIndex = 7 $ExitBtn2.Text = "Exit" $ExitBtn2.Font = new-object System.Drawing.Font("Tahoma",8) $ExitBtn2.UseVisualStyleBackColor = $True $ExitBtn2.add_Click($ExitBtn2_OnClick) $TakeSnapForm.Controls.Add($ExitBtn2) #End Exit Button #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState2 = $TakeSnapForm.WindowState #Init the OnLoad event to correct the initial state of the form $TakeSnapForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $TakeSnapForm.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/edit-file.ps1
edit-file.ps1
function edit-file2 ([string]$path=newfile.ps1) { $paths = @(resolve-path $path -ErrorAction SilentlyContinue); if ($paths.count -gt 1) {if ($psplus.Confirm(You are about to open the below files. Are you sure?, Open multiple files, $paths) -eq $FALSE) {break} } elseif ($paths.count -eq 0) { if ($psplus.Confirm(No files matched your request. Do you want to create a new file?, Create New File, $path) -eq $TRUE) {[En 11:01 vironment]::CurrentDirectory = (Get-Item (Get-Location)).FullName; trap { Write-Error $_.Exception.Message; continue} . {$path = [System.IO.Path]::GetFullPath($path); if (!($path.Contains(.))) {$path += .ps1}; > $path; $paths = @($path) }} else {break}}; foreach ($path in $paths) { $psplus.OpenFile((get-item $path).FullName) } }
PowerShellCorpus/PoshCode/POC csharp expressions_3.ps1
POC csharp expressions_3.ps1
$mytypes = @() function run-csharpexpression([string] $expression ) { $global:ccounter = [int]$ccounter + 1 $local:name = [system.guid]::NewGuid().tostring().replace('-','_').insert(0,"csharpexpr") $local:ns = "ShellTools.DynamicCSharpExpression.N${ccounter}" $local:template = @" using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace $ns { public static class Runner { public static object RunExpression() { return [[EXPRESSION]]; } } } "@ $local:source = $local:template.replace("[[EXPRESSION]]",$expression) #saving to a temporary file so that the error with anonymous types with the same signature doesn't happen $local:filename = [System.IO.Path]::GetTempFileName() $null = add-Type $local:source -Language CsharpVersion3 -outputassembly $local:filename $null = [System.Reflection.Assembly]::LoadFile($local:filename ) invoke-Expression ('[' + $local:ns + '.Runner]::RunExpression()') } set-alias c run-csharpexpression #test code c "new{a=1,b=2,c=3}" c "new{a=1,b=2,c=3}" (c DateTime.Now).adddays(5) (c "new{a=1,b=2,c=3}").b c 'from x in Directory.GetFiles(@"c:\\downloads") where x.Contains("win") select x'
PowerShellCorpus/PoshCode/PSISELibrary.ps1
PSISELibrary.ps1
Function Replace-TabsWithSpace { <# .SYNOPSIS Replaces a tab character with 4 spaces .DESCRIPTION This function examines the selected text in the PSIE SelectedText property and every tab character that is found is replaced with 4 spaces. .PARAMETER SelectedText The current contents of the SelectedText property .PARAMETER InstallMenu Specifies if you want to install this as a PSIE add-on menu .EXAMPLE Replace-TabsWithSpace -InstallMenu $true Description ----------- Installs the function as a menu item. .NOTES This was written specifically for me, I had some code originally created in Notepad++ that used actual tabs, later I changed that to spaces, but on occasion I come accross something that doesn't tab shift like it should. Since I've been doing some PowerShell ISE stuff lately I decided to write a little function that works as an Add-On menu. .LINK #> Param ( $SelectedText = $psISE.CurrentFile.Editor.SelectedText, $InstallMenu ) Begin { if ($InstallMenu) { Write-Verbose "Try to install the menu item, and error out if there's an issue." try { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Replace Tabs with Space",{Replace-TabsWithSpace},"Ctrl+Alt+R") | Out-Null } catch { Return $Error[0].Exception } } } Process { Write-Verbose "Try and find the tab character in the selected PSISE text, return an error if there's an issue." try { $psISE.CurrentFile.Editor.InsertText($SelectedText.Replace("`t"," ")) } catch { Return $Error[0].Exception } } End { } } Function New-CommentBlock { <# .SYNOPSIS Inserts a full comment block .DESCRIPTION This function inserts a full comment block that is formatted the way I format all my comment blocks. .PARAMETER InstallMenu Specifies if you want to install this as a PSIE add-on menu .EXAMPLE New-CommentBlock -InstallMenu $true Description ----------- Installs the function as a menu item. .NOTES FunctionName : New-CommentBlock Created by : Jeff Patton Date Coded : 09/13/2011 12:28:10 .LINK #> Param ( $InstallMenu ) Begin { $CommentBlock = @( " <#`n" " .SYNOPSIS`n" " .DESCRIPTION`n" " .PARAMETER`n" " .EXAMPLE`n" " .NOTES`n" " FunctionName : `n" " Created by : $($env:username)`n" " Date Coded : $(Get-Date)`n" " .LINK`n" " #>`n") if ($InstallMenu) { Write-Verbose "Try to install the menu item, and error out if there's an issue." try { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Insert comment block",{New-CommentBlock},"Ctrl+Alt+C") | Out-Null } catch { Return $Error[0].Exception } } } Process { if (!$InstallMenu) { Write-Verbose "Don't insert a comment if we're installing the menu" try { Write-Verbose "Create a new comment block, return an error if there's an issue." $psISE.CurrentFile.Editor.InsertText($CommentBlock) } catch { Return $Error[0].Exception } } } End { } } Function New-Script { <# .SYNOPSIS Create a new blank script .DESCRIPTION This function creates a new blank script based on my original template.ps1 .PARAMETER InstallMenu Specifies if you want to install this as a PSIE add-on menu .PARAMETER ScriptName This is the name of the new script. .EXAMPLE New-Script -ScriptName "New-ImprovedScript" Description ----------- This example shows calling the function with the ScriptName parameter .EXAMPLE New-Script -InstallMenu $true Description ----------- Installs the function as a menu item. .NOTES FunctionName : New-Script Created by : Jeff Patton Date Coded : 09/13/2011 13:37:24 .LINK #> Param ( $InstallMenu, $ScriptName ) Begin { $TemplateScript = @( "<#`n" " .SYNOPSIS`n" " Template script`n" " .DESCRIPTION`n" " This script sets up the basic framework that I use for all my scripts.`n" " .PARAMETER`n" " .EXAMPLE`n" " .NOTES`n" " ScriptName : $($ScriptName)`n" " Created By : $($env:Username)`n" " Date Coded : $(Get-Date)`n" " ScriptName is used to register events for this script`n" " LogName is used to determine which classic log to write to`n" "`n" " ErrorCodes`n" " 100 = Success`n" " 101 = Error`n" " 102 = Warning`n" " 104 = Information`n" " .LINK`n" "#>`n" "Param`n" " (`n" "`n" " )`n" "Begin`n" " {`n" " `$ScriptName = `$MyInvocation.MyCommand.ToString()`n" " `$LogName = `"Application`"`n" " `$ScriptPath = `$MyInvocation.MyCommand.Path`n" " `$Username = `$env:USERDOMAIN + `"\\`" + `$env:USERNAME`n" "`n" " New-EventLog -Source `$ScriptName -LogName `$LogName -ErrorAction SilentlyContinue`n" "`n" " `$Message = `"Script: `" + `$ScriptPath + `"``nScript User: `" + `$Username + `"``nStarted: `" + (Get-Date).toString()`n" " Write-EventLog -LogName `$LogName -Source `$ScriptName -EventID `"104`" -EntryType `"Information`" -Message `$Message`n" "`n" " # Dotsource in the functions you need.`n" " }`n" "Process`n" " {`n" " }`n" "End`n" " {`n" " `$Message = `"Script: `" + `$ScriptPath + `"``nScript User: `" + `$Username + `"``nFinished: `" + (Get-Date).toString()`n" " Write-EventLog -LogName `$LogName -Source `$ScriptName -EventID `"104`" -EntryType `"Information`" -Message `$Message `n" " }`n") if ($InstallMenu) { Write-Verbose "Try to install the menu item, and error out if there's an issue." try { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New blank script",{New-Script},"Ctrl+Alt+S") | Out-Null } catch { Return $Error[0].Exception } } } Process { if (!$InstallMenu) { Write-Verbose "Don't create a script if we're installing the menu" try { Write-Verbose "Create a new blank tab for the script" $NewScript = $psISE.CurrentPowerShellTab.Files.Add() Write-Verbose "Create a new empty script, return an error if there's an issue." $NewScript.Editor.InsertText($TemplateScript) $NewScript.Editor.InsertText(($NewScript.Editor.Select(22,1,22,2) -replace " ","")) $NewScript.Editor.InsertText(($NewScript.Editor.Select(26,1,26,2) -replace " ","")) $NewScript.Editor.InsertText(($NewScript.Editor.Select(40,1,40,2) -replace " ","")) $NewScript.Editor.InsertText(($NewScript.Editor.Select(43,1,43,2) -replace " ","")) $NewScript.Editor.Select(1,1,1,1) $NewScript.SaveAs("$((Get-Location).Path)\\$($ScriptName)") } catch { Return $Error[0].Exception } } } End { Return $NewScript } } Function New-Function { <# .SYNOPSIS Create a new function .DESCRIPTION This function creates a new function that wraps the selected text inside the Process section of the body of the function. .PARAMETER SelectedText Currently selected code that will become a function .PARAMETER InstallMenu Specifies if you want to install this as a PSIE add-on menu .PARAMETER FunctionName This is the name of the new function. .EXAMPLE New-Function -FunctionName "New-ImprovedFunction" Description ----------- This example shows calling the function with the FunctionName parameter .EXAMPLE New-Function -InstallMenu $true Description ----------- Installs the function as a menu item. .NOTES FunctionName : New-Function Created by : Jeff Patton Date Coded : 09/13/2011 13:37:24 .LINK #> Param ( $SelectedText = $psISE.CurrentFile.Editor.SelectedText, $InstallMenu, $FunctionName ) Begin { $TemplateFunction = @( "Function $FunctionName`n" " <#`n" " .SYNOPSIS`n" " .DESCRIPTION`n" " .PARAMETER`n" " .EXAMPLE`n" " .NOTES`n" " FunctionName : $FunctionName`n" " Created by : $($env:username)`n" " Date Coded : $(Get-Date)`n" " .LINK`n" " #>`n" "Param`n" " (`n" " )`n" "Begin`n" "{`n" " }`n" "Process`n" "{`n" "$($SelectedText)`n" " }`n" "End`n" "{`n" " }`n") if ($InstallMenu) { Write-Verbose "Try to install the menu item, and error out if there's an issue." try { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New function",{New-Function},"Ctrl+Alt+S") | Out-Null } catch { Return $Error[0].Exception } } } Process { if (!$InstallMenu) { Write-Verbose "Don't create a function if we're installing the menu" try { Write-Verbose "Create a new empty function, return an error if there's an issue." $psISE.CurrentFile.Editor.InsertText($TemplateFunction) } catch { Return $Error[0].Exception } } } End { } }
PowerShellCorpus/PoshCode/chkhash_10.ps1
chkhash_10.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 -u -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++ # Get hashes xml database path if ($i -ge $args2.count) { write-host "-X specified but no file path of .xml database specified. Exiting." exit } $hashespath=$args2[$i] continue } if ($args2[$i] -like "-e*") # Exclude files, dirs { 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 { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} $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) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing $($f.fullname) ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} # Update and continue is specified. $fc++ # increment files checked. if ($xfiles[$n].SHA512 -eq $f.SHA512) {continue} # Check SHA512 for mixmatch. $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/Export-SPListToSQL_1.ps1
Export-SPListToSQL_1.ps1
#Change these settings as needed #MS Access 2007 Data Components required $connString = 'Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes; DATABASE=http://sharepoint.acme.com/;LIST={96801432-2d03-42b8-82b0-ac96ca9fea8a};' #See http://chadwickmiller.spaces.live.com/blog/cns!EA42395138308430!275.entry for instructions on obtaining list GUID $qry = 'Select Title,Notes,CreateDate, Modified, Created from list' #Create a table in destination database with the with referenced columns and table name. $sqlserver = 'Z002\\SQL2K8' $dbname = 'SQLPSX' $tblname = 'splist_fill' ####################### function Get-SPList { param($connString, $qry='select * from list') $spConn = new-object System.Data.OleDb.OleDbConnection($connString) $spConn.open() $cmd = new-object System.Data.OleDb.OleDbCommand($qry,$spConn) $da = new-object System.Data.OleDb.OleDbDataAdapter($cmd) $dt = new-object System.Data.dataTable [void]$da.fill($dt) $dt } #Get-SPList ####################### function Write-DataTableToDatabase { param($dt,$destServer,$destDb,$destTbl) $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString $bulkCopy.DestinationTableName = "$destTbl" $bulkCopy.WriteToServer($dt) }# Write-DataTableToDatabase ####################### $dt = Get-SPList $connString $qry Write-DataTableToDatabase $dt $sqlserver $dbname $tblname
PowerShellCorpus/PoshCode/Test-UserCredential_6.ps1
Test-UserCredential_6.ps1
function Test-UserCredential { [CmdletBinding()] [OutputType([System.Boolean])] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] $Username, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] $Password, [Parameter()] [Switch] $Domain ) Begin { $assembly = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement') } Process { try { $system = Get-WmiObject -Class Win32_ComputerSystem if ($Domain) { if (0, 2 -contains $system.DomainRole) { throw 'This computer is not a member of a domain.' } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain } } else { $principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME } return $principalContext.ValidateCredentials($Username, $Password) } catch { throw 'Failed to test user credentials. The error was: "{0}".' -f $_ } } <# .SYNOPSIS Validates credentials for local or domain user. .PARAMETER Username The user's username. .PARAMETER Password The user's password. .EXAMPLE PS C:\\> Test-UserCredential -Username andy -password secret .EXAMPLE PS C:\\> Test-UserCredential -Username 'mydomain\\andy' -password secret -domain .EXAMPLE PS C:\\> Test-UserCredential -Username 'andy' -password secret -domain .INPUTS None. .OUTPUTS System.Boolean. .NOTES Revision History 2011-08-21: Andy Arismendi - Created. #> }
PowerShellCorpus/PoshCode/New Portgroups.ps1
New Portgroups.ps1
get-vc virtualCenterServerName get-vmhost | Get-VirtualSwitch -Name SwitchName | New-VirtualPortGroup -Name VLAN_12 -VLANID 12
PowerShellCorpus/PoshCode/datareader to dataset.ps1
datareader to dataset.ps1
@@This code was copied from the site http://www.ti4fun.com @@----------------------------------------------------------- Public Function ConvDataReaderToDataTable(Byval command As System.Data.SqlClient.SqlCommand) As System.Data.DataTable Dim datatable As New System.Data.DataTable Dim reader As System.Data.SqlClient.SqlDataReader = command.ExecuteReader() Try datatable.Load(reader) Finally reader.Close() command.Connection = Nothing End Try Return datatable End Function @@This code was copied from the site http://www.ti4fun.com @@-----------------------------------------------------------
PowerShellCorpus/PoshCode/TabExpansion_15.ps1
TabExpansion_15.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 (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 characters ## [<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 character after Ctrl+X until the character ## 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 ## #[ScriptBlock] member expansion for [ScriptBlock] literal ## { 1+1 }.inv<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> ## # Using Ctrl+K, characters insertion (bihind space or semi-coron or pipe operator) feature : it encloses tokens with parnthesis by default ## 1 - 1 - 1 - 1<Ctrl+K><tab> ## 1 - 1 - 1 - (1)<tab> ## 1 - 1 - 1 (- 1)<tab> ## 1 - 1 - (1 - 1)<tab><tab><tab>... ## with double Ctrl+K, it encloses tokens with $( ) ## for ( $i=0;$j=1<Ctrl+K><Ctrl+K><tab><tab> ## for ( $($i=0;$j=1) ## if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens ## 1+1 | {$_*2}<Ctrl+K>%<tab> ## 1+1 | %{$_*2} ## 1+1 +1+1<Ctrl+K>;<tab> ## 1+1 ;+1+1 ## if the character is ( or { or {, tokens are enclosed ( ) or { } or {} ## int<Ctrl+K>[<tab> ## [int] ## with double Ctrl+K, and if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens with '$' ## C:\\WINDOWS\\system32\\notepad.exe<Ctrl+K><Ctrl+K>{<tab> ## ${C:\\WINDOWS\\system32\\notepad.exe} ## % and ? are given special treatment with double Ctrl+K, these enclose tokens with % { } or ? { } behind '|' ## ls | $_.LastWriteTime -gt "2009/5"<Ctrl+K><Ctrl+K>?<tab> ## ls | ? {$_.LastWriteTime -gt "2009/5"} ## ls | $_.FullName<Ctrl+K><Ctrl+K>%<tab> ## ls | % {$_.FullName} ## # WMI Namespaces expansion for Get-WmiObject ## gwmi -Namespace <tab> ## Get-WmiObject -Namespace root\\asp<tab> ## # WMI Classes expansion which is corresponding to WMI Namespace (*) ## gwmi -Namespace ROOT\\CIMV2\\ms_409 -Class <tab>_<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 Namespaces list... if ( Test-Path $PSHOME\\WMINamespaces.txt ) { $_WMINamespaces = type $PSHOME\\WMINamespaces.txt -ReadCount 0 } else { $_WMINamespaces = & { $sb = { param ($ns) gwmi __NAMESPACE -Namespace $ns -com . | % { $ns = $_.__NAMESPACE + "\\" + $_.Name $ns & $sb $ns } } & $sb root } $_WMINamespaces = $_WMINamespaces + "ROOT" | sort '$_WMINamespaces was updated...' | Out-Host Set-Content -Value $_WMINamespaces -Path $PSHOME\\WMINamespaces.txt -Verbose } ### Get default WMI Namespace... $_WMIdftNS = $_WMINamespaces -eq (Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\WBEM\\Scripting)."Default Namespace" ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_WMIClasses = Import-Clixml $PSHOME\\WMIClasses.txt } else { $_new = '=(New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ));' $_WMIClasses = iex ('@{"' + [String]::Join( "`"$_new`"", $_WMINamespaces ) + "`"$_new}") foreach ( $_namespace in $_WMINamespaces ) { foreach ( $_class in gwmi -Namespace $_namespace -List ) { $_WMIClasses.$_namespace.Add($_class.Name) } $_WMIClasses.$_namespace.Sort() } '$_WMIClasses was updated...' | Out-Host Export-Clixml -InputObject $_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 = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref", "Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml" $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 -like "[_\\]" ) { $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 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 '.') { $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 ([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 TabExpansion; } # Ctrl+K put parentheses behind space or semi-coron or pipe operator 11 { if ( $line -ne $( "=" + [Char]11 ) ) { if ( $line[-2] -eq 11 ) { $left = '$' + "(" $line = $line.Substring(0,$line.length-2) } else { $left = "(" $line = $line.Substring(0,$line.length-1) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny(" ;|") $global:_ctrlk += $line.Insert($i+1, $left) + ")" $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") } else { $global:_ctrlk } break TabExpansion; } # Ctrl+L a part of history commands expansion 12 { Get-CommandLine $lastWord.SubString(0, $lastword.Length-1) break TabExpansion; } # Ctrl+P hand-operated pop from command buffer stack 16 { $_base = $lastword.SubString(0, $lastword.Length-1) $_buf = $global:_cmdstack.Pop() if ( $_buf.Contains("'") ) { $line = ($line.SubString(0, $line.Length-1) + $_buf) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") } else { $_base + $_buf } break TabExpansion; } # Ctrl+R $Host.UI.RawUI. 18 { '$Host.UI.RawUI.' '$Host.UI.RawUI' break TabExpansion; } # 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() $line = ($line.SubString(0, $line.Length-1) + $global:_clip.Text) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") break TabExpansion; } # 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 TabExpansion; } # 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 TabExpansion; } } switch ( [int]$line[-2] ) { # Ctrl+K put character behind space or semi-coron or pipe operator 11 { switch ( $line[-1] ) { '{' { $right = '}' } '(' { $right = ')' } '[' { $right = ']' } } $left = $line[-1] $delimiter = " ;|" if ( $line[-3] -eq 11 ) { if ( $line[-1] -eq '%' -or $line[-1] -eq '?' ) { $left = ' ' + $left + ' {'; $right = '}' $delimiter = '|' } else { $left = '$' + $left } $line = $line.Substring(0,$line.length-3) } else { $line = $line.Substring(0,$line.length-2) } $global:_ctrlk = @() $l = $line.Length while ( $l -ge 0 ) { $i = $line.Substring(0,$l).LastIndexOfAny($delimiter) $global:_ctrlk += $line.Insert($i+1, $left) + $right $l = $i } $global:_ctrlk += $line [Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}") break TabExpansion; } # Ctrl+X cut words with a character after Ctrl+X until the character 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 TabExpansion; } } 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 property and method expansion rooted at variables... # 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 item name expansion in variable notation... '(^.*\\${)(((\\w+):([\\\\/]?))[^\\\\/]+([\\\\/][^\\\\/]*)*)$' { $_prefix = $matches[1] $_driveName = $matches[3] $_itemName = $matches[2] + "*" Get-ChildItem $_itemName | % { if ( $matches[5] -and $_.PSProvider.Name -eq "FileSystem" ) { $output = $_prefix + $_.FullName } elseif ( $_.PSProvider.Name -eq "FileSystem" -and $matches[6] ) { $cd = (Get-Location -PSDrive $matches[4]).Path $output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1) } elseif ( $_.PSProvider.Name -eq "FileSystem" ) { $cd = (Get-Location -PSDrive $matches[4]).Path $output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1) } else { $output = $_prefix + $_driveName + $_.Name } if ( $_.PSIsContainer ) { $output } else { $output + "}" } } break; } # Handle PSDrive name expansion in variable notation... '(^.*\\${)(\\w+)$' { $_prefix = $matches[1] $_driveName = $matches[2] + "*" Get-PSDrive $_driveName | % { $_prefix + $_ + ':' } 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
PowerShellCorpus/PoshCode/Select-UserGroup.ps1
Select-UserGroup.ps1
New-Grid -ControlName SelectUserGroups -Columns Auto,* -Rows 4 { $GetGroups = { $user = Get-QADUuser $this.Text -SizeLimit 1 if($User.LogonName -eq $this.Text -or $User.Email -eq $this.Text) { $this.Foreground = "Black" $Group.ItemsSource = Get-QADGroup -ContainsMember $user $UserName.Text = $user.LogonName $EmailAddress.Text = $user.Email } else { $this.Foreground = "Red" $Group.ItemsSource = @() } } New-Label "Name" New-Textbox -name UserName -minwidth 100 -Column 1 -On_LostFocus $GetGroups New-Label "Email" -Row 1 New-Textbox -name EmailAddress -minwidth 100 -Column 1 -Row 1 -On_LostFocus $GetGroups New-Label "Group" -Row 2 New-Listbox -name Group -Column 1 -Row 2 New-Button "OK" -Row 3 -Column 1 -On_Click { Get-ParentControl | Set-UIValue -Passthru | Close-Control } } -Show
PowerShellCorpus/PoshCode/Email attachments_1.ps1
Email attachments_1.ps1
$file = "MYFILE.TXT" $smtpServer = "MYSMTPSERVER.EMAIL.CO.UK" $msg = new-object Net.Mail.MailMessage $att = new-object Net.Mail.Attachment($file) $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "FROMME@EMAIL.CO.UK" $msg.To.Add("TOME@EMAIL.CO.UK") $msg.Subject = "MY SUBJECT" $msg.Body = "MY TEXT FOR THE EMAIL" $msg.Attachments.Add($att) $smtp.Send($msg) $att.Dispose()
PowerShellCorpus/PoshCode/New-XVM_14.ps1
New-XVM_14.ps1
#EXAMPLES <# New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR01" -SwitchName "External(192.168.1.0/24)" -VhdType NoVHD New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR02" -SwitchName "External(192.168.1.0/24)" -VhdType ExistingVHD -VhdPath D:\\vhds\\WS2012-TESTSVR02.vhdx New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR03" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR04" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR05" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR06" -SwitchName "External(192.168.1.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -ComputerName HYPERVSVR02 -Name "WS2012-TESTSVR07" -SwitchName "External(192.168.1.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB} #> Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $vhdFilePath = $null } "ExistingVHD" { $vhdFilePath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -ComputerName $ComputerName -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -ComputerName $ComputerName -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } $vhdFilePath = $vhdFile.Path } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -ComputerName $ComputerName -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop $vhdFilePath = $vhdFile.Path } } if ($vhdFilePath -ne $null) { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$vhdFilePath'" } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Try { Invoke-Expression -Command $command } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } End {} }
PowerShellCorpus/PoshCode/_1.168.1.1.ps1
_1.168.1.1.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/SyntaxHighlighter Brush_2.ps1
SyntaxHighlighter Brush_2.ps1
/** * PowerShell 2.0 Brush for highlighter 2.0 * * SyntaxHighlighter http://alexgorbatchev.com/wiki/SyntaxHighlighter * * @version * 2.1.0 (April 07 2009) * * @copyright * Copyright (C) 2008-2009 Joel Bennett http://HuddledMasses.org/ * * @license * This file is for SyntaxHighlighter. * * SyntaxHighlighter is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SyntaxHighlighter is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SyntaxHighlighter. If not, see <http://www.gnu.org/licenses/>. */ SyntaxHighlighter.brushes.PowerShell = function() { var keywords ='while validateset validaterange validatepattern validatelength validatecount ' + 'until trap switch return ref process param parameter in if global: '+ 'function foreach for finally filter end elseif else dynamicparam do default ' + 'continue cmdletbinding break begin alias \\\\? % #script #private #local #global '+ 'mandatory parametersetname position valuefrompipeline ' + 'valuefrompipelinebypropertyname valuefromremainingarguments helpmessage '; var operators ='and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' + 'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' + 'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' + 'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' + 'lt match ne not notcontains notlike notmatch or regex replace wildcard'; var verbs = 'write where wait use update unregister undo trace test tee take suspend ' + 'stop start split sort skip show set send select scroll resume restore ' + 'restart resolve resize reset rename remove register receive read push ' + 'pop ping out new move measure limit join invoke import group get format ' + 'foreach export expand exit enter enable disconnect disable debug cxnew ' + 'copy convertto convertfrom convert connect complete compare clear ' + 'checkpoint aggregate add'; this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments { regex: new RegExp('@"\\\\n[\\\\s\\\\S]*?\\\\n"@', 'gm'), css: 'string' }, // double quoted here-strings { regex: new RegExp("@'\\\\n[\\\\s\\\\S]*?\\\\n'@", 'gm'), css: 'string' }, // single quoted here-strings { regex: new RegExp('"(?:\\\\$\\\\([^\\\\)]*\\\\)|[^"]|`"|"")*[^`]"','g'), css: 'string' }, // double quoted strings { regex: new RegExp("'(?:[^']|'')*'", 'g'), css: 'string' }, // single quoted strings { regex: new RegExp('[\\\\$|@|@@](?:(?:global|script|private|env):)?[A-Z0-9_]+', 'gi'), css: 'variable' }, // $variables { regex: new RegExp('(?:'+verbs.replace(/ /g, '\\\\b|\\\\b')+')-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'functions' }, // functions and cmdlets { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' }, // keywords { regex: new RegExp(this.getKeywords(operators.replace(/ /g,' -')), 'gmi'), css: 'value bold' }, // operators { regex: new RegExp('\\\\s+-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'color1' }, // parameters { regex: new RegExp('\\\\[[A-Z_\\\\[][A-Z0-9_. `,\\\\[\\\\]]*\\\\]', 'gi'), css: 'constants' } // .Net [Type]s ]; } SyntaxHighlighter.brushes.PowerShell.prototype = new SyntaxHighlighter.Highlighter(); SyntaxHighlighter.brushes.PowerShell.aliases = ['monad', 'msh', 'powershell', 'PowerShell', 'Powershell', 'posh'];
PowerShellCorpus/PoshCode/Invoke-ElevatedCommand.p.ps1
Invoke-ElevatedCommand.p.ps1
##############################################################################\n##\n## Invoke-ElevatedCommand\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\nRuns the provided script block under an elevated instance of PowerShell as\nthrough it were a member of a regular pipeline.\n\n.EXAMPLE\n\nPS >Get-Process | Invoke-ElevatedCommand.ps1 {\n $input | Where-Object { $_.Handles -gt 500 } } | Sort Handles\n\n#>\n\nparam(\n ## The script block to invoke elevated\n [Parameter(Mandatory = $true)]\n [ScriptBlock] $Scriptblock,\n\n ## Any input to give the elevated process\n [Parameter(ValueFromPipeline = $true)]\n $InputObject,\n\n ## Switch to enable the user profile\n [switch] $EnableProfile\n)\n\nbegin\n{\n Set-StrictMode -Version Latest\n $inputItems = New-Object System.Collections.ArrayList\n}\n\nprocess\n{\n $null = $inputItems.Add($inputObject)\n}\n\nend\n{\n ## Create some temporary files for streaming input and output\n $outputFile = [IO.Path]::GetTempFileName()\n $inputFile = [IO.Path]::GetTempFileName()\n\n ## Stream the input into the input file\n $inputItems.ToArray() | Export-CliXml -Depth 1 $inputFile\n\n ## Start creating the command line for the elevated PowerShell session\n $commandLine = ""\n if(-not $EnableProfile) { $commandLine += "-NoProfile " }\n\n ## Convert the command into an encoded command for PowerShell\n $commandString = "Set-Location '$($pwd.Path)'; " +\n "`$output = Import-CliXml '$inputFile' | " +\n "& {" + $scriptblock.ToString() + "} 2>&1; " +\n "Export-CliXml -Depth 1 -In `$output '$outputFile'"\n\n $commandBytes = [System.Text.Encoding]::Unicode.GetBytes($commandString)\n $encodedCommand = [Convert]::ToBase64String($commandBytes)\n $commandLine += "-EncodedCommand $encodedCommand"\n\n ## Start the new PowerShell process\n $process = Start-Process -FilePath (Get-Command powershell).Definition `\n -ArgumentList $commandLine -Verb RunAs `\n -WindowStyle Hidden `\n -Passthru\n $process.WaitForExit()\n\n ## Return the output to the user\n if((Get-Item $outputFile).Length -gt 0)\n {\n Import-CliXml $outputFile\n }\n\n ## Clean up\n Remove-Item $outputFile\n Remove-Item $inputFile\n}
PowerShellCorpus/PoshCode/Set-ADUserRandomPassword.ps1
Set-ADUserRandomPassword.ps1
###########################################################################" # # NAME: Set-ADUserRandomPassword.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: This script are used to set a random password for Active Directory users in a specified Organizational Unit. It stores the results in a csv-file. # The background for this script is a school domain needing to set random passwords for new users, and exporting the passwords to a csv-# # file to let the teachers disribute the first-time passwords. # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 22.08.2009 - Initial release # ###########################################################################" #Requires: Quest.ActiveRoles.ADManagement #Creating system.random object used to generate random numbers $random = New-Object System.Random #Creating an array to store user information in $CSV = @() #Get users Get-QADUser -SearchRoot "domain.local/MyUserOU" -SizeLimit 0 | ForEach-Object { #Generate a random password for each user $password = "pwd"+($random.Next(1000,9999)) #Set the password for each user Set-QADUser $_ -UserPassword $password #Select what user information we want to export to the csv-file and storing it in a variable $exportdata = Get-QADUser $_ | Select-Object name,samaccountname,company,department #Add the password as a member to $exportdata Add-Member -InputObject $exportdata -MemberType NoteProperty -Name Password -Value $password #Add the user information to the $CSV array $CSV += $exportdata } #Exporting all users to the csv-file $CSV | Export-Csv -Path "C:\\export\\passwordlist.csv" -Encoding unicode -NoTypeInformation
PowerShellCorpus/PoshCode/VHDFunctions_1.psm1.ps1
VHDFunctions_1.psm1.ps1
<# Name: VHDFunctions.psm1 Author: Rich Kusak (rkusak@cbcag.edu) Created: 2009-10-23 LastEdit: 2009-11-03 08:57 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 or Windows Server 2008 R2."} } 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 or Windows Server 2008 R2."} ## 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 or Windows Server 2008 R2."} } 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 and mounting (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 or Windows Server 2008 R2."} } } 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 { ## Use BCDEdit to set the VHD boot configuration entry ## $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 return the details of the VHD (VDisk). .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-11-03 08:55 #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 } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7 or Windows Server 2008 R2."} ## Validate the -Path parameter ## 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 function.ps1
Get-Parameter function.ps1
function Get-Parameters { param([string]$CommandName, [switch]$IncludeCommon) try { $command = get-command $commandname $parameters = (new-object System.Management.Automation.CommandMetaData $command, $includecommon).Parameters $parameters.getenumerator() # unroll dictionary } catch { write-warning "Could not find command or obtain parameters for $commandname" } }
PowerShellCorpus/PoshCode/LibraryChart_4.ps1
LibraryChart_4.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Defines functions for wokring with Microsoft Chart Control for .NET 3.5 Framework ### Pipe output of Powershell command to Out-Chart function and specify chart type ### Chart will display in form or save to image file ### Real-time charts are supported by passing in a script block ### My thanks to Richard MacDonald for his wonderful post on Charting with PowerShell ### http://blogs.technet.com/richard_macdonald/archive/2009/04/28/3231887.aspx ### Note: Requires NET Framework 3.5 and Microsoft Chart Controls for Microsoft .NET Framework 3.5 ### </Description> ### <Usage> ### . ./LibraryChart.ps1 ### -------------------------- EXAMPLE 1 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' ### ### This command will produce a default column chart ### ### -------------------------- EXAMPLE 2 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -filename 'c:\\users\\u00\\documents\\process.png' ### This command will output the chart to a file ### ### -------------------------- EXAMPLE 3 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -chartType 'Pie' ### ### This command will produce a pie chart ### ### -------------------------- EXAMPLE 4 -------------------------- ### out-chart -xField 'name' -yField 'WS' -scriptBlock {Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 1} -chartType 'line' ### ### This command will produce a real-time line chart ### ### </Usage> ### </Script> # -------------------------------------------------------------------------- [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") ####################### function New-Chart { param ([int]$width,[int]$height,[int]$left,[int]$top,$chartTitle) # create chart object $global:Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart $global:Chart.Width = $width $global:Chart.Height = $height $global:Chart.Left = $left $global:Chart.Top = $top # create a chartarea to draw on and add to chart $chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea $global:chart.ChartAreas.Add($chartArea) if ($chartTitle) { [void]$global:Chart.Title.Add($chartTitle) } # change chart area colour $global:Chart.BackColor = [System.Drawing.Color]::Transparent } #New-Chart ####################### function New-BarColumnChart { param ([hashtable]$ht, $chartType='Column', $chartTitle,$xTitle,$yTitle, [int]$width,[int]$height,[int]$left,[int]$top,[bool]$asc) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle $chart.ChartAreas[0].AxisX.Title = $xTitle $chart.ChartAreas[0].AxisY.Title = $yTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::$chartType if ($asc) { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Ascending, "Y") } else { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") } $global:Chart.Series["Data"]["DrawingStyle"] = "Cylinder" $global:chart.Series["Data"].IsValueShownAsLabel = $true $global:chart.Series["Data"]["LabelStyle"] = "Top" } #New-BarColumnChart ####################### function New-LineChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") # $global:Chart.Series["Data"].Points.AddXY($(get-date), $($ht.Values)) $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys,$ht.Values) #$global:Chart.Series["Data"].XValueType = [System.Windows.Forms.DataVisualization.Charting.ChartValueType]::Time #$global:Chart.chartAreas[0].AxisX.LabelStyle.Format = "hh:mm:ss" #$global:Chart.chartAreas[0].AxisX.LabelStyle.Interval = 1 #$global:Chart.chartAreas[0].AxisX.LabelStyle.IntervalType = [System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType]::Seconds $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line #$global:chart.Series["Data"].IsValueShownAsLabel = $false } #New-LineChart ####################### function New-PieChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie $global:Chart.Series["Data"]["PieLabelStyle"] = "Outside" $global:Chart.Series["Data"]["PieLineColor"] = "Black" #$global:chart.Series["Data"].IsValueShownAsLabel = $true #$global:chart.series["Data"].Label = "#PERCENT{P1}" #$legend = New-object System.Windows.Forms.DataVisualization.Charting.Legend #$global:Chart.Legends.Add($legend) #$Legend.Name = "Default" } #New-PieChart ####################### function Remove-Points { param($name='Data',[int]$maxPoints=200) while ( $global:chart.Series["$name"].Points.Count > $maxPoints ) { $global:chart.Series["$name"].Points.RemoveAT(0) } } #Add-Series ####################### function Out-Form { param($interval,$scriptBlock,$xField,$yField) # display the chart on a form $global:Chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = 'PowerCharts' $Form.Width = 600 $Form.Height = 600 $Form.controls.add($global:Chart) if ($scriptBlock -is [ScriptBlock]) { if (!($xField -or $yField)) { throw 'xField and yField required with scriptBlock parameter.' } $timer = New-Object System.Windows.Forms.Timer $timer.Interval = $interval $timer.add_Tick({ $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField if ($global:Chart.Series["Data"].ChartTypeName -eq 'Line') { Remove-Points $ht | foreach { $global:Chart.Series["Data"].Points.AddXY($($_.Keys), $($_.Values)) } } else { $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) } $global:chart.ResetAutoValues() $global:chart.Invalidate() }) $timer.Enabled = $true $timer.Start() } $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog() } #Out-Form ####################### function Out-ImageFile { param($fileName,$fileformat) $global:Chart.SaveImage($fileName,$fileformat) } ####################### ### ConvertTo-Hashtable function based on code by Jeffery Snover ### http://blogs.msdn.com/powershell/archive/2008/11/23/poshboard-and-convertto-hashtable.aspx ####################### function ConvertTo-Hashtable { param([string]$key, $value) Begin { $hash = @{} } Process { $thisKey = $_.$Key $hash.$thisKey = $_.$Value } End { Write-Output $hash } } #ConvertTo-Hashtable ####################### function Out-Chart { param( $xField=$(throw 'Out-Chart:xField is required'), $yField=$(throw 'Out-Chart:yField is required'), $chartType='Column',$chartTitle, [int]$width=500, [int]$height=400, [int]$left=40, [int]$top=30, $filename, $fileformat='png', [int]$interval=1000, $scriptBlock, [switch]$asc ) Begin { $ht = @{} } Process { if ($_) { $thisKey = $_.$xField $ht.$thisKey = $_.$yField } } End { if ($scriptBlock) { $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField } switch ($chartType) { 'Bar' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Column' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Pie' {New-PieChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } 'Line' {New-LineChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } } if ($filename) { Out-ImageFile $filename $fileformat } elseif ($scriptBlock ) { Out-Form $interval $scriptBlock $xField $yField } else { Out-Form } } } #Out-Chart
PowerShellCorpus/PoshCode/Function Run-Script.ps1
Function Run-Script.ps1
function Run-Script { if ($psISE.CurrentFile.DisplayName.StartsWith("Untitled")) { return } $script = $psISE.CurrentFile.DisplayName $psISE.CurrentFile.Save() $logfile = "$env:programfiles\\Sea Star Development\\" + "Script Monitor Service\\ScriptMon.txt" #Change to suit. if (!(Test-Path env:\\JobCount)) { $env:JobCount = 1 #This will work across multi Tab sessions. } $number = $env:JobCount.PadLeft(4,'0') $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$startTime [$script] start. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$startTime [$script] started." Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PSE$number) started." Invoke-Command -Scriptblock { & "$pwd\\$script" } $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$endTime [$script] ended. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$endTime [$script] ended." Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PSE$number) ended." $env:JobCount = [int]$env:JobCount+1 } $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Run Script",{Run-Script}, "Alt+R") | Out-Null
PowerShellCorpus/PoshCode/Get-NetworkStatistics_1.ps1
Get-NetworkStatistics_1.ps1
function Get-NetworkStatistics { [OutputType('System.Management.Automation.PSObject')] [CmdletBinding(DefaultParameterSetName='name')] param( [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='port')] [System.String]$Port='*', [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='name')] [System.String]$ProcessName='*', [Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName='address')] [System.String]$Address='*', [Parameter()] [ValidateSet('*','tcp','udp')] [System.String]$Protocol='*', [Parameter()] [ValidateSet('*','Closed','CloseWait','Closing','DeleteTcb','Established','FinWait1','FinWait2','LastAck','Listen','SynReceived','SynSent','TimeWait','Unknown')] [System.String]$State='*' ) begin { $properties = 'Protocol','LocalAddress','LocalPort' $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID' } process { netstat -ano | Select-String -Pattern '\\s+(TCP|UDP)' | ForEach-Object { $item = $_.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries) if($item[1] -notmatch '^\\[::') { if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6') { $localAddress = $la.IPAddressToString $localPort = $item[1].split('\\]:')[-1] } else { $localAddress = $item[1].split(':')[0] $localPort = $item[1].split(':')[-1] } if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6') { $remoteAddress = $ra.IPAddressToString $remotePort = $item[2].split('\\]:')[-1] } else { $remoteAddress = $item[2].split(':')[0] $remotePort = $item[2].split(':')[-1] } $procId = $item[-1] $procName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name $proto = $item[0] $status = if($item[0] -eq 'tcp') {$item[3]} else {$null} $pso = New-Object -TypeName PSObject -Property @{ PID = $procId ProcessName = $procName Protocol = $proto LocalAddress = $localAddress LocalPort = $localPort RemoteAddress =$remoteAddress RemotePort = $remotePort State = $status } | Select-Object -Property $properties if($PSCmdlet.ParameterSetName -eq 'port') { if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port) { if($pso.Protocol -like $Protocol -and $pso.State -like $State) { $pso } } } if($PSCmdlet.ParameterSetName -eq 'address') { if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address) { if($pso.Protocol -like $Protocol -and $pso.State -like $State) { $pso } } } if($PSCmdlet.ParameterSetName -eq 'name') { if($pso.ProcessName -like $ProcessName) { if($pso.Protocol -like $Protocol -and $pso.State -like $State) { $pso } } } } } } <# .SYNOPSIS Displays the current TCP/IP connections. .DESCRIPTION Displays active TCP connections and includes the process ID (PID) and Name for each connection. If the port is not yet established, the port number is shown as an asterisk (*). .PARAMETER ProcessName Gets connections by the name of the process. The default value is '*'. .PARAMETER Port The port number of the local computer or remote computer. The default value is '*'. .PARAMETER Address Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'. .PARAMETER Protocol The name of the protocol (TCP or UDP). The default value is '*' (all) .PARAMETER State Indicates the state of a TCP connection. The possible states are as follows: Closed - The TCP connection is closed. CloseWait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user. Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously. DeleteTcb - The transmission control buffer (TCB) for the TCP connection is being deleted. Established - The TCP handshake is complete. The connection has been established and data can be sent. FinWait1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously. FinWait2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint. LastAck - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously. Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint. SynReceived - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment. SynSent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request. TimeWait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request. Unknown - The TCP connection state is unknown. Values are based on the TcpState Enumeration: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx .EXAMPLE Get-NetworkStatistics .EXAMPLE Get-NetworkStatistics iexplore .EXAMPLE Get-NetworkStatistics -ProcessName md* -Protocol tcp .EXAMPLE Get-NetworkStatistics -Address 192* -State LISTENING .EXAMPLE Get-NetworkStatistics -State LISTENING -Protocol tcp .OUTPUTS System.Management.Automation.PSObject .NOTES Author: Shay Levy Blog : http://PowerShay.com #> } help Get-NetworkStatistics
PowerShellCorpus/PoshCode/Copy-History.ps1
Copy-History.ps1
##############################################################################\n##\n## Copy-History\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\nCopy selected commands from the history buffer into the clipboard as a script.\n\n.EXAMPLE\n\nCopy-History\nCopies the entire contents of the history buffer into the clipboard.\n\n.EXAMPLE\n\nCopy-History -5\nCopies the last five commands into the clipboard.\n\n.EXAMPLE\n\nCopy-History 2,5,8,4\nCopies commands 2,5,8, and 4.\n\n.EXAMPLE\n\nCopy-History (1..10+5+6)\nCopies commands 1 through 10, then 5, then 6, using PowerShell's array\nslicing syntax.\n\n#>\n\nparam(\n ## The range of history IDs to copy\n [int[]] $Range\n)\n\nSet-StrictMode -Version Latest\n\n$history = @()\n\n## If they haven't specified a range, assume it's everything\nif((-not $range) -or ($range.Count -eq 0))\n{\n $history = @(Get-History -Count ([Int16]::MaxValue))\n}\n## If it's a negative number, copy only that many\nelseif(($range.Count -eq 1) -and ($range[0] -lt 0))\n{\n $count = [Math]::Abs($range[0])\n $history = (Get-History -Count $count)\n}\n## Otherwise, go through each history ID in the given range\n## and add it to our history list.\nelse\n{\n foreach($commandId in $range)\n {\n if($commandId -eq -1) { $history += Get-History -Count 1 }\n else { $history += Get-History -Id $commandId }\n }\n}\n\n## Finally, export the history to the clipboard.\n$history | Foreach-Object { $_.CommandLine } | clip.exe
PowerShellCorpus/PoshCode/Send-MailMessage.ps1
Send-MailMessage.ps1
##############################################################################\n##\n## Send-MailMessage\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n## Illustrate the techniques used to send an email in PowerShell.\n## In version two, use the Send-MailMessage cmdlet.\n##\n## Example:\n##\n## PS >$body = @"\n## >> Hi from another satisfied customer of The PowerShell Cookbook!\n## >> "@\n## >>\n## PS >$to = "guide_feedback@leeholmes.com"\n## PS >$subject = "Thanks for all of the scripts."\n## PS >$mailHost = "mail.leeholmes.com"\n## PS >Send-MailMessage $to $subject $body $mailHost\n##\n##############################################################################\n\nparam(\n ## The recipient of the mail message\n [string[]] $To = $(throw "Please specify the destination mail address"),\n\n ## The subjecty of the message\n [string] $Subject = "<No Subject>",\n\n ## The body of the message\n [string] $Body = $(throw "Please specify the message content"),\n\n ## The SMTP host that will transmit the message\n [string] $SmtpHost = $(throw "Please specify a mail server."),\n\n ## The sender of the message\n [string] $From = "$($env:UserName)@example.com"\n)\n\n## Create the mail message\n$email = New-Object System.Net.Mail.MailMessage\n\n## Populate its fields\nforeach($mailTo in $to)\n{\n $email.To.Add($mailTo)\n}\n\n$email.From = $from\n$email.Subject = $subject\n$email.Body = $body\n\n## Send the mail\n$client = New-Object System.Net.Mail.SmtpClient $smtpHost\n$client.UseDefaultCredentials = $true\n$client.Send($email)
PowerShellCorpus/PoshCode/Solarized (Dark) Theme.ps1
Solarized (Dark) Theme.ps1
<?xml version="1.0" encoding="utf-16"?> <StorableColorTheme xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Keys> <string>ErrorForegroundColor</string> <string>ErrorBackgroundColor</string> <string>WarningForegroundColor</string> <string>WarningBackgroundColor</string> <string>VerboseForegroundColor</string> <string>VerboseBackgroundColor</string> <string>DebugForegroundColor</string> <string>DebugBackgroundColor</string> <string>OutputPaneBackgroundColor</string> <string>OutputPaneTextBackgroundColor</string> <string>OutputPaneForegroundColor</string> <string>CommandPaneBackgroundColor</string> <string>ScriptPaneBackgroundColor</string> <string>ScriptPaneForegroundColor</string> <string>TokenColors\\Attribute</string> <string>TokenColors\\Command</string> <string>TokenColors\\CommandArgument</string> <string>TokenColors\\CommandParameter</string> <string>TokenColors\\Comment</string> <string>TokenColors\\GroupEnd</string> <string>TokenColors\\GroupStart</string> <string>TokenColors\\Keyword</string> <string>TokenColors\\LineContinuation</string> <string>TokenColors\\LoopLabel</string> <string>TokenColors\\Member</string> <string>TokenColors\\NewLine</string> <string>TokenColors\\Number</string> <string>TokenColors\\Operator</string> <string>TokenColors\\Position</string> <string>TokenColors\\StatementSeparator</string> <string>TokenColors\\String</string> <string>TokenColors\\Type</string> <string>TokenColors\\Unknown</string> <string>TokenColors\\Variable</string> <string>ConsoleTokenColors\\Attribute</string> <string>ConsoleTokenColors\\Command</string> <string>ConsoleTokenColors\\CommandArgument</string> <string>ConsoleTokenColors\\CommandParameter</string> <string>ConsoleTokenColors\\Comment</string> <string>ConsoleTokenColors\\GroupEnd</string> <string>ConsoleTokenColors\\GroupStart</string> <string>ConsoleTokenColors\\Keyword</string> <string>ConsoleTokenColors\\LineContinuation</string> <string>ConsoleTokenColors\\LoopLabel</string> <string>ConsoleTokenColors\\Member</string> <string>ConsoleTokenColors\\NewLine</string> <string>ConsoleTokenColors\\Number</string> <string>ConsoleTokenColors\\Operator</string> <string>ConsoleTokenColors\\Position</string> <string>ConsoleTokenColors\\StatementSeparator</string> <string>ConsoleTokenColors\\String</string> <string>ConsoleTokenColors\\Type</string> <string>ConsoleTokenColors\\Unknown</string> <string>ConsoleTokenColors\\Variable</string> <string>XmlTokenColors\\Comment</string> <string>XmlTokenColors\\CommentDelimiter</string> <string>XmlTokenColors\\ElementName</string> <string>XmlTokenColors\\MarkupExtension</string> <string>XmlTokenColors\\Attribute</string> <string>XmlTokenColors\\Quote</string> <string>XmlTokenColors\\QuotedString</string> <string>XmlTokenColors\\Tag</string> <string>XmlTokenColors\\Text</string> <string>XmlTokenColors\\CharacterData</string> </Keys> <Values> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>203</R> <G>75</G> <B>22</B> <ScA>1</ScA> <ScR>0.5972018</ScR> <ScG>0.0703601</ScG> <ScB>0.008023193</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>38</R> <G>139</G> <B>210</B> <ScA>1</ScA> <ScR>0.0193823632</ScR> <ScG>0.258182883</ScG> <ScB>0.6444797</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>133</R> <G>153</G> <B>0</B> <ScA>1</ScA> <ScR>0.23455061</ScR> <ScG>0.3185468</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>43</G> <B>54</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.024157634</ScG> <ScB>0.0368894525</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>181</R> <G>137</G> <B>0</B> <ScA>1</ScA> <ScR>0.462077022</ScR> <ScG>0.2501583</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>108</R> <G>113</G> <B>196</B> <ScA>1</ScA> <ScR>0.149959788</ScR> <ScG>0.1651322</ScG> <ScB>0.55201143</ScB> </Color> <Color> <A>255</A> <R>133</R> <G>153</G> <B>0</B> <ScA>1</ScA> <ScR>0.23455061</ScR> <ScG>0.3185468</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>88</R> <G>110</G> <B>117</B> <ScA>1</ScA> <ScR>0.0975873545</ScR> <ScG>0.155926466</ScG> <ScB>0.177888423</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>211</R> <G>211</G> <B>211</B> <ScA>1</ScA> <ScR>0.651405632</ScR> <ScG>0.651405632</ScG> <ScB>0.651405632</ScB> </Color> <Color> <A>255</A> <R>220</R> <G>50</G> <B>47</B> <ScA>1</ScA> <ScR>0.715693533</ScR> <ScG>0.0318960324</ScG> <ScB>0.02842604</ScB> </Color> <Color> <A>255</A> <R>147</R> <G>161</G> <B>161</B> <ScA>1</ScA> <ScR>0.291770667</ScR> <ScG>0.356400162</ScG> <ScB>0.356400162</ScB> </Color> <Color> <A>255</A> <R>42</R> <G>161</G> <B>152</B> <ScA>1</ScA> <ScR>0.0231533684</ScR> <ScG>0.356400162</ScG> <ScB>0.313988745</ScB> </Color> <Color> <A>255</A> <R>203</R> <G>75</G> <B>22</B> <ScA>1</ScA> <ScR>0.5972018</ScR> <ScG>0.0703601</ScG> <ScB>0.008023193</ScB> </Color> <Color> <A>255</A> <R>131</R> <G>148</G> <B>150</B> <ScA>1</ScA> <ScR>0.2269659</ScR> <ScG>0.2961383</ScG> <ScB>0.304987341</ScB> </Color> <Color> <A>255</A> <R>38</R> <G>139</G> <B>210</B> <ScA>1</ScA> <ScR>0.0193823632</ScR> <ScG>0.258182883</ScG> <ScB>0.6444797</ScB> </Color> <Color> <A>255</A> <R>176</R> <G>196</G> <B>222</B> <ScA>1</ScA> <ScR>0.434153676</ScR> <ScG>0.55201143</ScG> <ScB>0.730460763</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>238</R> <G>130</G> <B>238</B> <ScA>1</ScA> <ScR>0.8549926</ScR> <ScG>0.223227978</ScG> <ScB>0.8549926</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>228</G> <B>181</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.7758222</ScG> <ScB>0.462077022</ScB> </Color> <Color> <A>255</A> <R>152</R> <G>251</G> <B>152</B> <ScA>1</ScA> <ScR>0.313988745</ScR> <ScG>0.9646863</ScG> <ScB>0.313988745</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>224</R> <G>255</G> <B>255</B> <ScA>1</ScA> <ScR>0.745404243</ScR> <ScG>1</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>228</G> <B>196</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.7758222</ScG> <ScB>0.55201143</ScB> </Color> <Color> <A>255</A> <R>211</R> <G>211</G> <B>211</B> <ScA>1</ScA> <ScR>0.651405632</ScR> <ScG>0.651405632</ScG> <ScB>0.651405632</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>219</R> <G>112</G> <B>147</B> <ScA>1</ScA> <ScR>0.7083758</ScR> <ScG>0.162029386</ScG> <ScB>0.291770667</ScB> </Color> <Color> <A>255</A> <R>143</R> <G>188</G> <B>143</B> <ScA>1</ScA> <ScR>0.274677336</ScR> <ScG>0.5028865</ScG> <ScB>0.274677336</ScB> </Color> <Color> <A>255</A> <R>245</R> <G>245</G> <B>245</B> <ScA>1</ScA> <ScR>0.913098633</ScR> <ScG>0.913098633</ScG> <ScB>0.913098633</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>69</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.0595112443</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>100</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.127437681</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>128</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0.215860531</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>139</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>0.258182883</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>140</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0.2622507</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>255</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>1</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>255</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>1</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>139</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0.258182883</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>139</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0.258182883</ScB> </Color> <Color> <A>255</A> <R>0</R> <G>0</G> <B>0</B> <ScA>1</ScA> <ScR>0</ScR> <ScG>0</ScG> <ScB>0</ScB> </Color> <Color> <A>255</A> <R>128</R> <G>128</G> <B>128</B> <ScA>1</ScA> <ScR>0.215860531</ScR> <ScG>0.215860531</ScG> <ScB>0.215860531</ScB> </Color> </Values> @@ <Name>Solarized (Dark)</Name> <FontFamily>Consolas</FontFamily> <FontSize>14</FontSize> </StorableColorTheme>
PowerShellCorpus/PoshCode/Split-Job.ps1
Split-Job.ps1
#requires -version 1.0 ################################################################################ ## Run commands in multiple concurrent pipelines ## by Arnoud Jansveld - www.jansveld.net/powershell ## ## Basic "drop in" usage examples: ## - Functions that accept pipelined input: ## Without Split-Job: ## Get-Content hosts.txt | MyFunction | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {MyFunction} | Export-Csv results.csv ## - Functions that do not accept pipelined input (use foreach): ## Without Split-Job: ## Get-Content hosts.txt |% { .\\MyScript.ps1 -ComputerName $_ } | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {%{ .\\MyScript.ps1 -ComputerName $_ }} | Export-Csv results.csv ## ## Example with an imported function: ## function Test-WebServer ($ComputerName) { ## $WebRequest = [System.Net.WebRequest]::Create("http://$ComputerName") ## $WebRequest.GetResponse() ## } ## Get-Content hosts.txt | Split-Job {%{Test-WebServer $_ }} -Function Test-WebServer | Export-Csv results.csv ## ## Version History ## 1.0 First version posted on poshcode.org ## Additional runspace error checking and cleanup ## 0.93 Improve error handling: errors originating in the Scriptblock now ## have more meaningful output ## Show additional info in the progress bar (thanks Stephen Mills) ## Add SnapIn parameter: imports (registered) PowerShell snapins ## Add Function parameter: imports functions ## Add SplitJobRunSpace variable; allows scripts to test if they are ## running in a runspace ## 0.92 Add UseProfile switch: imports the PS profile ## Add Variable parameter: imports variables ## Add Alias parameter: imports aliases ## Restart pipeline if it stops due to an error ## Set the current path in each runspace to that of the calling process ## 0.91 Revert to v 0.8 input syntax for the script block ## Add error handling for empty input queue ## 0.9 Add logic to distinguish between scriptblocks and cmdlets or scripts: ## if a ScriptBlock is specified, a foreach {} wrapper is added ## 0.8 Adds a progress bar ## 0.7 Stop adding runspaces if the queue is already empty ## 0.6 First version. Inspired by Gaurhoth's New-TaskPool script ################################################################################ function Split-Job { param ( $Scriptblock = $(throw 'You must specify a command or script block!'), [int]$MaxPipelines=10, [switch]$UseProfile, [string[]]$Variable, [string[]]$Function = @(), [string[]]$Alias = @(), [string[]]$SnapIn ) function Init ($InputQueue){ # Create the shared thread-safe queue and fill it with the input objects $Queue = [Collections.Queue]::Synchronized([Collections.Queue]@($InputQueue)) $QueueLength = $Queue.Count # Do not create more runspaces than input objects if ($MaxPipelines -gt $QueueLength) {$MaxPipelines = $QueueLength} # Create the script to be run by each runspace $Script = "Set-Location '$PWD'; " $Script += { $SplitJobQueue = $($Input) & { trap {continue} while ($SplitJobQueue.Count) {$SplitJobQueue.Dequeue()} } | }.ToString() + $Scriptblock # Create an array to keep track of the set of pipelines $Pipelines = New-Object System.Collections.ArrayList # Collect the functions and aliases to import $ImportItems = ($Function -replace '^','Function:') + ($Alias -replace '^','Alias:') | Get-Item | select PSPath, Definition $stopwatch = New-Object System.Diagnostics.Stopwatch $stopwatch.Start() } function Add-Pipeline { # This creates a new runspace and starts an asynchronous pipeline with our script. # It will automatically start processing objects from the shared queue. $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host) $Runspace.Open() if (!$?) {throw "Could not open runspace!"} $Runspace.SessionStateProxy.SetVariable('SplitJobRunSpace', $True) function CreatePipeline { param ($Data, $Scriptblock) $Pipeline = $Runspace.CreatePipeline($Scriptblock) if ($Data) { $Null = $Pipeline.Input.Write($Data, $True) $Pipeline.Input.Close() } $Null = $Pipeline.Invoke() $Pipeline.Dispose() } # Optionally import profile, variables, functions and aliases from the main runspace if ($UseProfile) { CreatePipeline -Script "`$PROFILE = '$PROFILE'; . `$PROFILE" } if ($Variable) { foreach ($var in (Get-Variable $Variable -Scope 2)) { trap {continue} $Runspace.SessionStateProxy.SetVariable($var.Name, $var.Value) } } if ($ImportItems) { CreatePipeline $ImportItems { foreach ($item in $Input) {New-Item -Path $item.PSPath -Value $item.Definition} } } if ($SnapIn) { CreatePipeline (Get-PSSnapin $Snapin -Registered) {$Input | Add-PSSnapin} } $Pipeline = $Runspace.CreatePipeline($Script) $Null = $Pipeline.Input.Write($Queue) $Pipeline.Input.Close() $Pipeline.InvokeAsync() $Null = $Pipelines.Add($Pipeline) } function Remove-Pipeline ($Pipeline) { # Remove a pipeline and runspace when it is done $Runspace = $Pipeline.RunSpace $Pipeline.Dispose() $Runspace.Close() $Runspace.Dispose() $Pipelines.Remove($Pipeline) } # Main # Initialize the queue from the pipeline . Init $Input # Start the pipelines while ($Pipelines.Count -lt $MaxPipelines -and $Queue.Count) {Add-Pipeline} # Loop through the runspaces and pass their output to the main pipeline while ($Pipelines.Count) { # Show progress if (($stopwatch.ElapsedMilliseconds - $LastUpdate) -gt 1000) { $Completed = $QueueLength - $Queue.Count - $Pipelines.count $LastUpdate = $stopwatch.ElapsedMilliseconds $SecondsRemaining = $(if ($Completed) { (($Queue.Count + $Pipelines.Count)*$LastUpdate/1000/$Completed) } else {-1}) Write-Progress 'Split-Job' ("Queues: $($Pipelines.Count) Total: $($QueueLength) " + "Completed: $Completed Pending: $($Queue.Count)") ` -PercentComplete ([Math]::Max((100 - [Int]($Queue.Count + $Pipelines.Count)/$QueueLength*100),0)) ` -CurrentOperation "Next item: $(trap {continue}; if ($Queue.Count) {$Queue.Peek()})" ` -SecondsRemaining $SecondsRemaining } foreach ($Pipeline in @($Pipelines)) { if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline ) { $Pipeline.Output.NonBlockingRead() $Pipeline.Error.NonBlockingRead() | Out-Default } else { # Pipeline has stopped; if there was an error show info and restart it if ($Pipeline.PipelineStateInfo.State -eq 'Failed') { $Pipeline.PipelineStateInfo.Reason.ErrorRecord | Add-Member NoteProperty writeErrorStream $True -PassThru | Out-Default # Restart the runspace if ($Queue.Count -lt $QueueLength) {Add-Pipeline} } Remove-Pipeline $Pipeline } } Start-Sleep -Milliseconds 100 } }
PowerShellCorpus/PoshCode/Queue Checker.ps1
Queue Checker.ps1
foreach ($ExchangServer in (Get-ExchangeServer | Where { $_.isHubTransportServer -eq $True})) {Get-queue -Server $ExchangeServer}
PowerShellCorpus/PoshCode/Script Listing.ps1
Script Listing.ps1
$pathToScripts = "C:\\Scripts\\*" foreach($itm in get-childitem $pathToScripts -include *.ps1 -recurse) {"{0,-25}{1,0}" -f ((" " + $itm.name) -replace ".ps1",""), ((get-content $itm | where {$_ -like "*Purpose:*"}) -replace "# Purpose: ","")}
PowerShellCorpus/PoshCode/Twitbrain cheat.ps1
Twitbrain cheat.ps1
#Twitbrain Cheat PowerShell script #Description: PowerShell script to beat everyone at the Twitter twitbrain game # For more info follow @twitbrain at www.twitter.com #Change the Twitter Username and Password in the script. #Author: Stefan Stranger #Website: http://tinyurl.com/sstranger #Date: 03/07/2009 #Version: 0.1 #Function Publish-Tweet from James O'Neills blog (http://blogs.technet.com/jamesone/archive/2009/02/16/how-to-drive-twitter-or-other-web-tools-with-powershell.aspx) [System.Reflection.Assembly]::LoadWithPartialName(”System.Web") | Out-Null Function Publish-Tweet([string] $TweetText) { [System.Net.ServicePointManager]::Expect100Continue = $false $request = [System.Net.WebRequest]::Create("http://twitter.com/statuses/update.xml") $Username = "username" $Password = "password" $request.Credentials = new-object System.Net.NetworkCredential($Username, $Password) $request.Method = "POST" $request.ContentType = "application/x-www-form-urlencoded" write-progress "Tweeting" "Posting status update" -cu $tweetText $formdata = [System.Text.Encoding]::UTF8.GetBytes( "status=" + $tweetText ) $requestStream = $request.GetRequestStream() $requestStream.Write($formdata, 0, $formdata.Length) $requestStream.Close() $response = $request.GetResponse() write-host $response.statuscode $reader = new-object System.IO.StreamReader($response.GetResponseStream()) $reader.ReadToEnd() $reader.Close() } Function Waiting() { #Change $a if you want to wait longer or shorter for ($a=15; $a -gt 1; $a--) { Write-Progress -Activity "Waiting for next poll" ` -SecondsRemaining $a -Status "Please wait." Start-Sleep 1 } } Write-Host "You are going to cheat;-)" $strResponse = Read-Host "Are you sure you want to continue? (Y/N)" if ($strResponse -eq 'N') { Write-host "Maybe a good choice. It has to be a fair competition ;-)" break } #infinite loop #Quit script by using Ctrl-C for (;;) { #Retrieve sum from Twitbrain website Write-host "Get calculation from Twitbrain website" $ws = New-Object net.WebClient #Download Twitbrain website $html = $ws.DownloadString("http://ajaxorized.com/twitbrain") #Save website content to temporarily file. $currentdir = [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath $html | Set-Content "$currentdir\\Twitbrain.html" $twitbrainpage = Get-Content "$currentdir\\Twitbrain.html" | out-string #Search for calculation string in web page $calc = [regex]::match($twitbrainpage,'(?<=\\<div class="challenge"\\>).+(?=\\</div> <p class="challenge-answer">)',"singleline").value.trim() #search/replace $calc = $calc -replace "\\*times\\*","*" $calc = $calc -replace "\\+plus\\+","+" $calc = $calc -replace "\\-minus\\-","-" #Do the math on the sum $result = invoke-expression $calc #Create tweet to post to twitter $tweet = "@twitbrain " + $result #Post to Twitter #Check if result has not been posted earlier. $oldresult = Get-Content "$currentdir\\oldresult.txt" if ($result -eq $oldresult) { write-host "No new Twitbrain question is published yet" } else { Write-host "What is the result of the next question?" Write-host $calc Publish-Tweet $tweet write-host "Tweet publised" #Write old result to text file $oldresult = $result Write-host "Save oldresult to text file" $oldresult > "$currentdir\\oldresult.txt" } #Wait 15 seconds #Call Waiting Function Waiting }
PowerShellCorpus/PoshCode/Get-Sequence.ps1
Get-Sequence.ps1
## Get-Sequence ## Optionless implementation of seq for PowerShell ############################################################################ ## Most of the options don't apply because they convert the numbers to text ## which isn't something a PowerShell Seq wants to do :) ############################################################################ ## Usage: ## seq $LAST ## seq $FIRST $LAST ## seq $FIRST $INTERVAL $LAST ############################################################################ function Get-Sequence{ switch($args.Count){ 1 {[int]$first=0; [int]$inc=1; [int]$last=$args[0]} 2 {[int]$first=$args[0]; [int]$inc=1; [int]$last=$args[1]} 3 {[int]$first=$args[0]; [int]$inc=$args[1]; [int]$last=$args[2]} } if($inc-gt0){ while($first-le$last){$first;$first+=$inc} } else { while($first-ge$last){$first;$first+=$inc} } } ## Set the default alias New-Alias seq Get-Sequence ############################################################################ ############################################################################ ## EXAMPLE SCRIPT: ## Original Bash Script using Gnome's Notify-Send for libnotify # s=.o0O0o.o0O0o.o0O0o.o0O0o.o0O0o.o0O0o.o0;n(){ for x in `seq $1 $2 $3`;do notify-send ${s:0:x}; done };while :;do n 1 2 39;n 39 -2 1;done ## PowerShell Script using Send-Notice for Growl ## BUT, if you don't have Growl and Send-Notice, just use this instead: New-Alias Send-Notice Write-Progress ## And then you can: (note that in the sample there's no end case, you have to CTRL+C) # $s=".o0O0o.o0O0o.o0O0o.o0O0o.o0O0o.o0O0o.o0";function n{$ofs="";foreach($x in $(seq @args)){Send-Notice "Working" "$($s[0..$x])"}}while(1){n 1 2 39;n 39 -2 1}
PowerShellCorpus/PoshCode/Read-HostWithPrompt.ps1
Read-HostWithPrompt.ps1
#############################################################################\n##\n## Read-HostWithPrompt\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\nRead user input, with choices restricted to the list of options you\nprovide.\n\n.EXAMPLE\n\nPS >$caption = "Please specify a task"\nPS >$message = "Specify a task to run"\nPS >$option = "&Clean Temporary Files","&Defragment Hard Drive"\nPS >$helptext = "Clean the temporary files from the computer",\n>> "Run the defragment task"\n>>\nPS >$default = 1\nPS >Read-HostWithPrompt $caption $message $option $helptext $default\n\nPlease specify a task\nSpecify a task to run\n[C] Clean Temporary Files [D] Defragment Hard Drive [?] Help\n(default is "D"):?\nC - Clean the temporary files from the computer\nD - Run the defragment task\n[C] Clean Temporary Files [D] Defragment Hard Drive [?] Help\n(default is "D"):C\n0\n\n#>\n\nparam(\n ## The caption for the prompt\n $Caption = $null,\n\n ## The message to display in the prompt\n $Message = $null,\n\n ## Options to provide in the prompt\n [Parameter(Mandatory = $true)]\n $Pption,\n\n ## Any help text to provide\n $HelpText = $null,\n\n ## The default choice\n $Default = 0\n)\n\nSet-StrictMode -Version Latest\n\n## Create the list of choices\n$choices = New-GenericObject `\n Collections.ObjectModel.Collection `\n Management.Automation.Host.ChoiceDescription\n\n## Go through each of the options, and add them to the choice collection\nfor($counter = 0; $counter -lt $option.Length; $counter++)\n{\n $choice = New-Object Management.Automation.Host.ChoiceDescription `\n $option[$counter]\n\n if($helpText -and $helpText[$counter])\n {\n $choice.HelpMessage = $helpText[$counter]\n }\n\n $choices.Add($choice)\n}\n\n## Prompt for the choice, returning the item the user selected\n$host.UI.PromptForChoice($caption, $message, $choices, $default)
PowerShellCorpus/PoshCode/Set-Computername_3.ps1
Set-Computername_3.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 -computername $originalPCName $computer.Rename($computerName) }
PowerShellCorpus/PoshCode/Get-NICSettings.ps1
Get-NICSettings.ps1
# Get-NICSettings by Hugo Peeters of www.peetersonline.nl ######################################################### $serverName = Read-Host "Enter server name" $NicConfig = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $serverName $myCol = @() ForEach ($Nic in $NicConfig) { If ($Nic.IPAddress -ne $null) { $myObj = "" | Select-Object Description, DHCPEnabled, IPAddress, IPSubnet, DefaultIPGateway, DNSServers, WINSServers, NICModel, SpeedDuplex $myObj.Description = $Nic.Description $myObj.DHCPEnabled = $Nic.DHCPEnabled $myObj.IPAddress = $Nic.IPAddress $myObj.IPSubnet = $Nic.IPSubnet $myObj.DefaultIPGateway = $Nic.DefaultIPGateway $myObj.DNSServers = $Nic.DNSServerSearchOrder $myObj.WINSServers = $Nic.WINSPrimaryServer,$Nic.WINSSecondaryServer $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $serverName) $baseKey = $registry.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}") $subKeyNames = $baseKey.GetSubKeyNames() ForEach ($subKeyName in $subKeyNames) { $subKey = $baseKey.OpenSubKey("$subKeyName") $ID = $subKey.GetValue("NetCfgInstanceId") If ($ID -eq $Nic.SettingId) { $componentID = $subKey.GetValue("ComponentID") If ($componentID -match "ven_14e4") { $myObj.NICModel = "Broadcom" $requestedMediaType = $subKey.GetValue("RequestedMediaType") $enum = $subKey.OpenSubKey("Ndi\\Params\\RequestedMediaType\\Enum") $myObj.SpeedDuplex = $enum.GetValue("$requestedMediaType") } ElseIf ($componentID -match "ven_8086") { $myObj.NICModel = "Intel" $SD = $subKey.GetValue("SpeedDuplex") $enum = $subKey.OpenSubKey("Ndi\\Params\\SpeedDuplex\\Enum") $myObj.SpeedDuplex = $enum.GetValue("$SD") } ElseIf ($componentID -match "b06bdrv") { $myObj.NICModel = "HP" $SD = $subKey.GetValue("req_medium") $enum = $subKey.OpenSubKey("Ndi\\Params\\req_medium\\Enum") $myObj.SpeedDuplex = $enum.GetValue("$SD") } Else { $myObj.NICModel = "unknown" $myObj.SpeedDuplex = "unknown" } } } $myCol += $myObj } } $myCol
PowerShellCorpus/PoshCode/play-note(s)_1.ps1
play-note(s)_1.ps1
function Play-Note([string]$note,[int] $duration = 5) { if (!($note -match '(\\d+)')) { $note+='4' };[void]($note -match '([A-G#]{1,2})(\\d+)') [console]::Beep((440 * [math]::Pow([math]::pow(2,(1/12)), (([int] $matches[2]) - 4)* 12 + $( switch($matches[1]) { 'A' { 0 } 'A#' { 1 } 'Bb' { 1 } 'B' { 2 } 'C' { 3 } 'C#' { 4 } 'Db' { 4 } 'D' { 5 } 'D#' { 6 } 'Eb' { 6 } 'E' { 7 } 'F' { 8 } 'F#' { 9 } 'Gb' { 9 } 'G' { 10 } 'G#' { 11 } 'Ab' { 11 } }))),$duration * 100 ) } function Speak-words ([string]$words,[bool]$pause = $true) { $flag = 1 if ($pause) {$flag = 2} $voice = new-Object -com SAPI.spvoice $voice.speak($words, [int] $flag) # 2 means wait until speaking is finished to continue } function Play-Notes { $defaultduration = 5;if($args[0] -is [int]) {$defaultduration = $args[0]} for($i = 0;$i -lt $args.length;$i++) { $duration = $defaultduration if ($i -lt $args.length-1) { if ($args[$i+1] -is [int]) {$duration = $args[$i+1] } } if ($args[$i] -is [string]) { if ($args[$i].startswith("!")) { speak-words $args[$i].replace('!','') } else { play-note $args[$i] $duration } } } } play-notes A B C 20 E 10 B 10 play-notes A B C 20 E 10 B 10 play-notes F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4 F5 2 E5 2 D5 2 C5 2 B5 2 A5 2 G 4 play-notes 2 F5 E5 D5 C5 B5 A5 G 4 F5 E5 D5 C5 B5 A5 G 4 play-notes 4 F5 E5 D5 C5 B5 A5 G F5 E5 D5 C5 B5 A5 G play-notes "!here we go now" Db5 Db Eb Gb Ab "C#" 6 !YEAH play-notes A "!$([datetime]::now)" C
PowerShellCorpus/PoshCode/Password Gen Form V2.ps1
Password Gen Form V2.ps1
$rs=[RunspaceFactory]::CreateRunspace() $rs.ApartmentState = "STA" $rs.ThreadOptions = "ReuseThread" $rs.Open() $ps = [PowerShell]::Create() $ps.Runspace = $rs $ps.Runspace.SessionStateProxy.SetVariable("pwd",$pwd) [void]$ps.AddScript({ #Load Required Assemblies Add-Type –assemblyName PresentationFramework Add-Type –assemblyName PresentationCore Add-Type –assemblyName WindowsBase Add-Type -AssemblyName System.Windows.Forms #Create Print Dialog object $printDialog = New-Object System.Windows.Controls.PrintDialog Function Create-Password { ##################################################################### ####################Password Specifications########################## ##################################################################### #How many characters in the password [int]$passwordlength = 14 #Minimum Upper Case characters in password [int]$min_upper = 3 #Minimum Lower Case characters in password [int]$min_lower = 3 #Minimum Numerical characters in password [int]$min_number = 3 #Minimum Symbol/Puncutation characters in password [int]$min_symbol = 3 #Misc password characters in password [int]$min_misc = ($passwordlength - ($min_upper + $min_lower + $min_number + $min_symbol)) If ($min_misc -lt 0) { [System.Windows.Forms.MessageBox]::Show("Password specification is not configured correctly, please make the proper edits and try again.","Warning") | Out-Null Break } #Characters for the password $upper = @("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z") $lower = @("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z") $number = @(1,2,3,4,5,6,7,8,9,0) $symbol = @("!","@","#","%","&","(",")","`"",".","<",">","+","=","-","_") $combine = $upper + $lower + $number + $symbol $password = @() #Start adding upper case into password 1..$min_upper | ForEach {$password += Get-Random $upper} #Add lower case into password 1..$min_lower | ForEach {$password += Get-Random $lower} #Add numbers into password 1..$min_number | ForEach {$password += Get-Random $number} #Add symbols into password 1..$min_symbol | ForEach {$password += Get-Random $symbol} #Fill out the rest of the password length 1..$min_misc | ForEach {$password += Get-Random $combine} $randompassword = $Null #Randomize password Get-Random $password -count $passwordlength | ForEach {[string]$randompassword += $_} Return $randompassword } [xml]$xaml = @" <Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Height = '500' Width = '750' ResizeMode = 'NoResize' WindowStartupLocation = 'CenterScreen' ShowInTaskbar = 'True' Title = 'Password Generator Version 5.0'> <Grid HorizontalAlignment="Stretch" ShowGridLines='false'> <Grid.ColumnDefinitions> <ColumnDefinition Width="25"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="25"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height = '*'/> <RowDefinition Height = 'Auto'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> <RowDefinition Height = '*'/> </Grid.RowDefinitions> <Label Grid.ColumnSpan = '4' Grid.Column = '0' Grid.Row = '0' HorizontalAlignment = 'Center' Foreground = 'Green' FontWeight="Bold" FontSize="24" VerticalAlignment = 'Center'> FOR OFFICIAL USE ONLY </Label> <TextBlock Grid.ColumnSpan = '2' Grid.Column = '1' Grid.Row = '1' HorizontalAlignment = 'Center' TextWrapping = 'wrap' FontWeight="Bold" FontSize="15"> Ensure your password contains at least 3 special characters, 3 numbers, 3 uppercase and 3 lowercase letters for a total of at least 14 characters long. </TextBlock> <Label Grid.Column = '1' Grid.Row = '2' HorizontalAlignment = 'Right' VerticalAlignment = 'Center' FontSize = '16' FontWeight="Bold"> Password: </Label> <TextBox x:Name = 'PassTextBlock' Grid.Column = '2' Grid.Row = '2' HorizontalAlignment = 'left' VerticalAlignment = 'Center' FontSize = '16' FontWeight="Bold" IsReadOnly = 'True' Width = 'Auto'> NOTVALID </TextBox> <CheckBox x:Name = 'PrintCheckBox' Grid.Column = '1' Grid.ColumnSpan = '2' Grid.Row = '3' HorizontalAlignment = 'Center' IsChecked = 'True' VerticalAlignment = 'Center'> Send to Printer </CheckBox> <Button x:Name = 'GenButton' Grid.Column = '1' Grid.ColumnSpan = '2' Grid.Row = '4' HorizontalAlignment = 'Center' Height = '30'> Generate Password </Button> <Label Grid.ColumnSpan = '4' Grid.Column = '0' Grid.Row = '5' HorizontalAlignment = 'Center' Foreground = 'Green' FontWeight="Bold" FontSize="24" VerticalAlignment = 'Center'> FOR OFFICIAL USE ONLY </Label> </Grid> </Window> "@ ##Load XAML $reader=(New-Object System.Xml.XmlNodeReader $xaml) $Window=[Windows.Markup.XamlReader]::Load( $reader ) ##Controls $GenButton = $window.FindName('GenButton') $PassTextBlock = $window.FindName('PassTextBlock') $PrintCheckBox = $window.FindName('PrintCheckBox') ##Events #Generate Random password button $GenButton.Add_Click({ $PassTextBlock.Text = Create-Password [Windows.Forms.Clipboard]::SetText($PassTextBlock.Text) $window.UpdateLayout() If ($PrintCheckBox.IsChecked) { Try { #Print out form to default printer $printDialog.PrintVisual($window,'Window Print') } Catch { If ($error[0] -match "printqueue") { [windows.messagebox]::Show('No Default Printer specified!','Warning','OK','Exclamation') } Else { [windows.messagebox]::Show('Unknown Error Occurred!','Error','OK','Exclamation') } } } }) #Clear password on close $Window.Add_Closed({ [Windows.Forms.Clipboard]::Clear() }) $window.ShowDialog() | Out-Null }).BeginInvoke()
PowerShellCorpus/PoshCode/VerifyCategoryRule.ps1
VerifyCategoryRule.ps1
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nSet-StrictMode -Version Latest\n\nif($message.Body -match "book")\n{\n [Console]::WriteLine("This is a message about the book.")\n}\nelse\n{\n [Console]::WriteLine("This is an unknown message.")\n}
PowerShellCorpus/PoshCode/Get-CrawlHealth (MOSS)_2.ps1
Get-CrawlHealth (MOSS)_2.ps1
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null @@#NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired @@# to something that more suits your reality. @@$crawlFreshnessDayThreshhold = 2 @@$crawlDurationHourThreshhold = 4 @@$successRatioThreshhold = 0.9 function Calculate-CrawlDuration( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) { return "Green - no current crawl" } $timespan = [datetime]::Now - $contentSource.CrawlStarted $timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days" + "($($timespan.TotalHours.ToString('0.0')) hours)" if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) { return "Green - $timespanFormatted" } elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-CrawlFreshness( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { $timespan = [datetime]::Now - $contentSource.CrawlCompleted $timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago" if ($timespan.Days -le 0) { return "Green - $timespanFormatted" } elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-IndexHealth( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource, $successCount, $warningCount, $errorCount) { $formatted = "($($successCount)/$($warningCount)/$($errorCount))" if ($errorCount -eq 1) { return "Red - exactly 1 error, usually indicates permissions/config error - $formatted" } $successRatio = ([double]$successCount)/([double]($warningCount + $errorCount)) $successRatioMidpointToPerfection = (1.0 + $successRatioThreshhold)/2.0 if ($successRatio -ge $successRatioMidpointToPerfection) { return "Green - $formatted" } elseif ($successRatio -ge $successRatioThreshhold) { return "Yellow - $formatted" } else { return "Red - $formatted" } } function Get-CrawlHealth { $serverContext = [Microsoft.Office.Server.ServerContext]::Default $searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext) $content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext $history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext $contentSources = $content.ContentSources | foreach { $_ } $contentSources | foreach { #unroll DataTable object into more useful DataRow object $crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ } add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value ( Calculate-CrawlDuration $_) add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value ( Calculate-CrawlFreshness $_) add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value ( Calculate-IndexHealth -contentSource $_ -successCount $crawlHistory.SuccessCount -warningCount ( $crawlHistory.WarningCount) -errorCount $crawlHistory.ErrorCount) } $contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth } @@#USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials @@# (specifically, with access to the SSP - usually the SharePoint farm account) @@# -Tweak the threshholds (they may be too ambitious for your environment) @@# -Paste this text into an open PowerShell window and type (without the # mark) @@# Get-CrawlHealth | Format-List
PowerShellCorpus/PoshCode/UIAutomation 1.9.ps1
UIAutomation 1.9.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 # v 1.9 - Fix bug with Select-UIElement by processName / processId # 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 } ) 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 * # SIG # Begin signature block # MIIfIAYJKoZIhvcNAQcCoIIfETCCHw0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUtL6Jm12dWBELoaH5g6kpaTxj # toagghpSMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV # UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu # dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q # WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC # i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4 # ezPkeQr78HWIQZz/xQNRmarXbJ+TaYdlKYOFwmAUxMjJOxTawIHwHw103pIiq8r3 # +3R8J+b3Sht/p8OeLa6K6qbmqicWfWH3mHERvOJQoUvlXfrlDqcsn6plINPYlujI # fKVOSET/GeJEB5IL12iEgF1qeGRFzWBGflTBE3zFefHJwXECAwEAAaOB+jCB9zAd # BgNVHQ4EFgQUX5r1blzMzHSa1N197z/b7EyALt0wMgYIKwYBBQUHAQEEJjAkMCIG # CCsGAQUFBzABhhZodHRwOi8vb2NzcC50aGF3dGUuY29tMBIGA1UdEwEB/wQIMAYB # Af8CAQAwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC50aGF3dGUuY29tL1Ro # YXd0ZVRpbWVzdGFtcGluZ0NBLmNybDATBgNVHSUEDDAKBggrBgEFBQcDCDAOBgNV # HQ8BAf8EBAMCAQYwKAYDVR0RBCEwH6QdMBsxGTAXBgNVBAMTEFRpbWVTdGFtcC0y # MDQ4LTEwDQYJKoZIhvcNAQEFBQADgYEAAwmbj3nvf1kwqu9otfrjCR27T4IGXTdf # plKfFo3qHJIJRG71betYfDDo+WmNI3MLEm9Hqa45EfgqsZuwGsOO61mWAK3ODE2y # 0DGmCFwqevzieh1XTKhlGOl5QGIllm7HxzdqgyEIjkHq3dlXPx13SYcqFgZepjhq # IhKjURmDfrYwggRPMIIDuKADAgECAgQHJ1g9MA0GCSqGSIb3DQEBBQUAMHUxCzAJ # BgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdU # RSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVy # VHJ1c3QgR2xvYmFsIFJvb3QwHhcNMTAwMTEzMTkyMDMyWhcNMTUwOTMwMTgxOTQ3 # WjBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL # ExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3Vy # YW5jZSBFViBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA # xszlc+b71LvlLS0ypt/lgT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZ # OtPclNY823Q4pErMTSWC90qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLj # BuUIkQzEKEFV+8taiRV+ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPr # UQqYQUEiTmVhh4FBUKZ5XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV # 215k4TeHMFYE5RG0KYAS8Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6H # XRpQCyASzEG7bgtROLhLywIDAQABo4IBbzCCAWswEgYDVR0TAQH/BAgwBgEB/wIB # ATBTBgNVHSAETDBKMEgGCSsGAQQBsT4BADA7MDkGCCsGAQUFBwIBFi1odHRwOi8v # Y3liZXJ0cnVzdC5vbW5pcm9vdC5jb20vcmVwb3NpdG9yeS5jZm0wDgYDVR0PAQH/ # BAQDAgEGMIGJBgNVHSMEgYEwf6F5pHcwdTELMAkGA1UEBhMCVVMxGDAWBgNVBAoT # D0dURSBDb3Jwb3JhdGlvbjEnMCUGA1UECxMeR1RFIEN5YmVyVHJ1c3QgU29sdXRp # b25zLCBJbmMuMSMwIQYDVQQDExpHVEUgQ3liZXJUcnVzdCBHbG9iYWwgUm9vdIIC # AaUwRQYDVR0fBD4wPDA6oDigNoY0aHR0cDovL3d3dy5wdWJsaWMtdHJ1c3QuY29t # L2NnaS1iaW4vQ1JMLzIwMTgvY2RwLmNybDAdBgNVHQ4EFgQUsT7DaQP4v0cB1Jgm # GggC72NkK8MwDQYJKoZIhvcNAQEFBQADgYEALnaF2TeWba+J8wZ4gjHERgcfZcmO # s8lUeObRQt91Lh5V6vf6mwTAdXvReTwF7HnEUt2mA9enUJk/BVnaxlX0hpwNZ6NJ # BJUyHceH7IWvZG7VxV8Jp0B9FrpJDaL99t9VMGzXeMa5z1gpZBZMoyCBR7FEkoQW # G29KvCHGCj3tM8owggSjMIIDi6ADAgECAhAOz/Q4yP6/NW4E2GqYGxpQMA0GCSqG # SIb3DQEBBQUAMF4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jw # b3JhdGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMgVGltZSBTdGFtcGluZyBTZXJ2aWNl # cyBDQSAtIEcyMB4XDTEyMTAxODAwMDAwMFoXDTIwMTIyOTIzNTk1OVowYjELMAkG # A1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMTQwMgYDVQQD # EytTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIFNpZ25lciAtIEc0MIIB # IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomMLOUS4uyOnREm7Dv+h8GEK # U5OwmNutLA9KxW7/hjxTVQ8VzgQ/K/2plpbZvmF5C1vJTIZ25eBDSyKV7sIrQ8Gf # 2Gi0jkBP7oU4uRHFI/JkWPAVMm9OV6GuiKQC1yoezUvh3WPVF4kyW7BemVqonShQ # DhfultthO0VRHc8SVguSR/yrrvZmPUescHLnkudfzRC5xINklBm9JYDh6NIipdC6 # Anqhd5NbZcPuF3S8QYYq3AhMjJKMkS2ed0QfaNaodHfbDlsyi1aLM73ZY8hJnTrF # xeozC9Lxoxv0i77Zs1eLO94Ep3oisiSuLsdwxb5OgyYI+wu9qU+ZCOEQKHKqzQID # AQABo4IBVzCCAVMwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcD # CDAOBgNVHQ8BAf8EBAMCB4AwcwYIKwYBBQUHAQEEZzBlMCoGCCsGAQUFBzABhh5o # dHRwOi8vdHMtb2NzcC53cy5zeW1hbnRlYy5jb20wNwYIKwYBBQUHMAKGK2h0dHA6 # Ly90cy1haWEud3Muc3ltYW50ZWMuY29tL3Rzcy1jYS1nMi5jZXIwPAYDVR0fBDUw # MzAxoC+gLYYraHR0cDovL3RzLWNybC53cy5zeW1hbnRlYy5jb20vdHNzLWNhLWcy # LmNybDAoBgNVHREEITAfpB0wGzEZMBcGA1UEAxMQVGltZVN0YW1wLTIwNDgtMjAd # BgNVHQ4EFgQURsZpow5KFB7VTNpSYxc/Xja8DeYwHwYDVR0jBBgwFoAUX5r1blzM # zHSa1N197z/b7EyALt0wDQYJKoZIhvcNAQEFBQADggEBAHg7tJEqAEzwj2IwN3ij # hCcHbxiy3iXcoNSUA6qGTiWfmkADHN3O43nLIWgG2rYytG2/9CwmYzPkSWRtDebD # Zw73BaQ1bHyJFsbpst+y6d0gxnEPzZV03LZc3r03H0N45ni1zSgEIKOq8UvEiCmR # DoDREfzdXHZuT14ORUZBbg2w6jiasTraCXEQ/Bx5tIB7rGn0/Zy2DBYr8X9bCT2b # W+IWyhOBbQAuOA2oKY8s4bL0WqkBrxWcLC9JG9siu8P+eJRRw4axgohd8D20UaF5 # Mysue7ncIAkTcetqGVvP6KUwVyyJST+5z3/Jvz4iaGNTmr1pdKzFHTx/kuDDvBzY # BHUwggafMIIFh6ADAgECAhAOaQaYwhTIerW2BLkWPNGQMA0GCSqGSIb3DQEBBQUA # MHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsT # EHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNzdXJh # bmNlIENvZGUgU2lnbmluZyBDQS0xMB4XDTEyMDMyMDAwMDAwMFoXDTEzMDMyMjEy # MDAwMFowbTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQH # Ew5XZXN0IEhlbnJpZXR0YTEYMBYGA1UEChMPSm9lbCBILiBCZW5uZXR0MRgwFgYD # VQQDEw9Kb2VsIEguIEJlbm5ldHQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK # AoIBAQDaiAYAbz13WMx9Em/Z3dTWUKxbyiTsaSOctgOfTMLUAurXWtY3k1XBVufX # feL4pXQ7yQzm93YzvETwKdUCDJuOSu9EPYioy2nhKvBC6IaJUaw1VY7e9IsdxaxL # 8js3RQilLk+FO4UHg9w7L8wdHgXaDoksysC2SlhbFq4AVl8XC4R+bq+pahsdMO3n # Ab7Oo5PExKLVS8vl8QwOh6MaqquIjHmYoPOu9Rv8As0pnWsY9aVPs7T9QetXlW45 # +CKPhdUoEB1yD0kvGTIAQgn5W9VDYmfeVU40IIdt+7khWF10yu7zVT+/lauPzRmv # CHZMfbmqVyVQqvp5dEu0/7EWbbcLAgMBAAGjggMzMIIDLzAfBgNVHSMEGDAWgBSX # SAPrFQhrubJYI8yULvHGZdJkjjAdBgNVHQ4EFgQUmJxEqr9ewFZG4rNTp5NQIEIJ # TrkwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMGkGA1UdHwRi # MGAwLqAsoCqGKGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j # cmwwLqAsoCqGKGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j # cmwwggHEBgNVHSAEggG7MIIBtzCCAbMGCWCGSAGG/WwDATCCAaQwOgYIKwYBBQUH # AgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVwb3NpdG9yeS5o # dG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0 # AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4AcwB0AGkAdAB1 # AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQAaABlACAARABp # AGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQAaABlACAAUgBl # AGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUAbgB0ACAAdwBo # AGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkAIABhAG4AZAAg # AGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUAcgBlAGkAbgAg # AGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wgYYGCCsGAQUFBwEBBHoweDAkBggr # BgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMFAGCCsGAQUFBzAChkRo # dHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNl # Q29kZVNpZ25pbmdDQS0xLmNydDAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBBQUA # A4IBAQAch95ik7Qm12L9Olwjp5ZAhhTYAs7zjtD3WMsTpaJTq7zA3q2QeqB46WzT # vRINQr4LWtWhcopnQl5zaTV1i6Qo+TJ/epRE/KH9oLeEnRbBuN7t8rv0u31kfAk5 # Gl6wmvBrxPreXeossuU9ohij9uqIyk1lF85yW6QqDaE7rvIxpCXwMQv8PlQ/VdlK # EXbNtq4frbvMQLkpcZljbJRuZYbY3SgfGv6rgbJ93Qw+1Tlq9Y4gsHRmw35uv5IJ # VUrqcrNq5cyTgdeYodpftzKyqmZCIVvv8nu09DTfspAocJj9n5+XRqtEKIeKH9D/ # mjC/nVZIo+JpSuQG90nSYpUr4xwfMIIGvzCCBaegAwIBAgIQCBxX7l1w65ugsVIM # cpwbCTANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln # aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJE # aWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTExMDIxMDEyMDAw # MFoXDTI2MDIxMDEyMDAwMFowczELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD # ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEyMDAGA1UEAxMpRGln # aUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBTaWduaW5nIENBLTEwggEiMA0GCSqG # SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDF+SPmlCfEgBSkgDJfQKONb3DA5TZxcTp1 # pKoakpSJXqwjcctOZ31BP6rjS7d7vp3BqDiPaS86JOl3WRLHZgRDwg0mgolAGfIs # 6udM53wFGrj/iAlPJjfvOqT6ImyIyUobYfKuEF5vvNF5m1kYYOXuKbUDKqTO8YMZ # T2kFcygJ+yIQkyKgkBkaTDHy0yvYhEOvPGP/mNsg0gkrVMHq/WqD5xCjEnH11tfh # EnrV4FZazuoBW2hlW8E/WFIzqTVhTiLLgco2oxLLBtbPG00YfrmSuRLPQCbYmjaF # sxWqR5OEawe7vNWz3iUAEYkAaMEpPOo+Le5Qq9ccMAZ4PKUQI2eRAgMBAAGjggNU # MIIDUDAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwggHDBgNV # HSAEggG6MIIBtjCCAbIGCGCGSAGG/WwDMIIBpDA6BggrBgEFBQcCARYuaHR0cDov # L3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsG # AQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABD # AGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABh # AGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQBy # AHQAIABFAFYAIABDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBn # ACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABs # AGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABp # AG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBl # AGYAZQByAGUAbgBjAGUALjAPBgNVHRMBAf8EBTADAQH/MH8GCCsGAQUFBwEBBHMw # cTAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEkGCCsGAQUF # BzAChj1odHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNz # dXJhbmNlRVZSb290Q0EuY3J0MIGPBgNVHR8EgYcwgYQwQKA+oDyGOmh0dHA6Ly9j # cmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hBc3N1cmFuY2VFVlJvb3RDQS5j # cmwwQKA+oDyGOmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hB # c3N1cmFuY2VFVlJvb3RDQS5jcmwwHQYDVR0OBBYEFJdIA+sVCGu5slgjzJQu8cZl # 0mSOMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEB # BQUAA4IBAQCCBemFr6dMv6/OPbLqYLFo3mfC0ssm4MMvm7VrDlOQhfab4DUC//pp # g6q0dDIUPC4QTCibCq0ICfnzhBGTj8tgQFbpdy9psoOZVatHJJbLf0uwELSXv8Sl # mQb+juwUUB5eV5fLR7k02fw6ov9QKcIKYgTu3pY6b6DChQ9v/AjkMnvThK5pYAlG # Jpzo8P//htnICTpmw6c2jxhP6LGWki5OvgunM5CuvG5P8X6NtEYOZPlZBiIhZABL # 4noIA+e8iZCeQk8BwLYWf3XqRrKlVC+Mk80RNjRqKFfMlD/pfMgYAwMEfkPa+Zeh # WUfaEqrgbTgAXTUrxSKGywbKvHpNPSZGMYIEODCCBDQCAQEwgYcwczELMAkGA1UE # BhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2lj # ZXJ0LmNvbTEyMDAGA1UEAxMpRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBT # aWduaW5nIENBLTECEA5pBpjCFMh6tbYEuRY80ZAwCQYFKw4DAhoFAKB4MBgGCisG # AQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQw # HAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFEpc # xm/enjt6WdToIKI5Zj4ZtUh/MA0GCSqGSIb3DQEBAQUABIIBADj8ZsvgtZablGVx # A6GfN3o9URqkugHDJToWZti2kX8cmCt9T+bghtkSKYwR0nDIc7L2uL5HovWaBscv # /L9QPy6PlHiD53RrTT9QXYQ43tjnyR6Jd9Q4r/9I83TPtPZvjChsVEq/V3HTCuRZ # V2iXB0OyWSH1EiiczqsjNOgM6fH1lpUibucuQYC6twkonqm1RL9vckkiClww7kSe # rchTHIXgJrEX79e2/20EEu1zCvDNkw9TB5Db55yV4xDodAeekF4UKUSpMqvYLhz5 # HHUs9PxUErKFLCSMaIai0at8iAr+6cND8STbApYRXBDNawm1PEKLBXXaXK4c/4xg # O76cT2OhggILMIICBwYJKoZIhvcNAQkGMYIB+DCCAfQCAQEwcjBeMQswCQYDVQQG # EwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5 # bWFudGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMgIQDs/0OMj+vzVu # BNhqmBsaUDAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAc # BgkqhkiG9w0BCQUxDxcNMTMwMjAyMjAwMDEzWjAjBgkqhkiG9w0BCQQxFgQUL30U # fC9V3lvWclZ+XK2MyEMQlZAwDQYJKoZIhvcNAQEBBQAEggEATKl0ITIxM+4GmUKR # Wt02io+YEWMNSGTyikiLhkHIfcLot+oiVhOH0pkkFGXrDtrJo1OdHkDTEM7w7TRN # We4mS4ApP8pbfi4t3kErrrJICwJ2P+VFm0OvDdVq2EdX2u2izNRs2wWufXmv9orf # lxzZQWQ5OHPWuga18zP4/kaBVbYfS2Mkc47MsPM37GmlbAGqFS4A25AP8JUPrk3L # bT9eqT72GVkmVY2W/MHl4TOcZZEdxPDaQzICNAlRhZVt06guqMlGi3n+62dmsS5E # yNw4MnWDSwM4L+jlI709bmiIHqtWa4rJvghV6SvuD6UvkgF6LeaX/J2fc1geQQz9 # 0YWbhw== # SIG # End signature block
PowerShellCorpus/PoshCode/Add-SqlTable.ps1
Add-SqlTable.ps1
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"} ####################### function Get-SqlType { param([string]$TypeName) switch ($TypeName) { 'Boolean' {[Data.SqlDbType]::Bit} 'Byte[]' {[Data.SqlDbType]::VarBinary} 'Byte' {[Data.SQLDbType]::VarBinary} 'Datetime' {[Data.SQLDbType]::DateTime} 'Decimal' {[Data.SqlDbType]::Decimal} 'Double' {[Data.SqlDbType]::Float} 'Guid' {[Data.SqlDbType]::UniqueIdentifier} 'Int16' {[Data.SQLDbType]::SmallInt} 'Int32' {[Data.SQLDbType]::Int} 'Int64' {[Data.SqlDbType]::BigInt} default {[Data.SqlDbType]::VarChar} } } #Get-SqlType ####################### <# .SYNOPSIS Creates a SQL Server from a DataTable .DESCRIPTION Creates a SQL Server from a DataTable using SMO. .EXAMPLE $dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt This example loads a variable dt of type DataTable from query and creates an empty SQL Server table .EXAMPLE $dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table. .NOTES Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available as separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52 Version History v1.0 - Chad Miller - Initial Release #> function Add-SqlTable { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [String]$TableName, [Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable, [Parameter(Position=4, Mandatory=$false)] [string]$Username, [Parameter(Position=5, Mandatory=$false)] [string]$Password, [ValidateRange(1,8000)] [Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000 ) if($Username) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance } $con.Connect() $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con $db = $server.Databases[$Database] $table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName foreach ($column in $DataTable.Columns) { $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)" if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar') { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength } else { $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType } $col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType $col.Nullable = $column.AllowDBNull $table.Columns.Add($col) } $table.Create() } #Add-SqlTable
PowerShellCorpus/PoshCode/Findup_12.ps1
Findup_12.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; namespace Findup { public class FileInfoExt { public FileInfoExt(FileInfo fi) { FI = fi; } public byte[] SHA512_1st1K; public byte[] SHA512_All; public FileInfo FI { get; private set; } public bool Matched { get; set; } } class Findup { const int HashLen = 512/8; // 64-byte hash for SHA512. public static System.Boolean noerr = false; public static void Main(string[] args) { Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile."); Console.WriteLine(" "); string[] paths = new string[0]; System.Boolean recurse = false; System.Boolean delete = false; System.Boolean noprompt = false; System.Boolean b4b = false; List<FileInfoExt> fs = new List<FileInfoExt>(); long bytesInDupes = 0; // bytes in all the duplicates long bytesRec = 0; // number of bytes recovered. int delFiles = 0; // number of files deleted. int numOfDupes = 0; // number of duplicate files found. int c = 0; int i = 0; string deleteConfirm; for (i = 0; i < args.Length; i++) { if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt] [-b4b]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help infomration."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -delete - deletes duplicates with confirmation prompt."); Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Slower in some cases, faster in others, and most secure."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt"); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -b4b"); Console.WriteLine(" "); return; } if (System.String.Compare(args[i], "-recurse", true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i], "-delete", true) == 0) { delete = true; continue; } if (System.String.Compare(args[i], "-noprompt", true) == 0) { noprompt = true; continue; } if (System.String.Compare(args[i], "-b4b", true) == 0) { b4b = true; continue; } if (System.String.Compare(args[i], "-noerr", true) == 0) { noerr = true; continue; } Array.Resize(ref paths, paths.Length + 1); paths[c] = args[i]; c++; } if (paths.Length == 0) { Console.WriteLine("No files specified, try findup.exe -help"); return; } Recursive(paths, "*.*", recurse, fs); if (fs.Count < 2) { Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(salt); // get 512-bit SHA-512 salt. for (i = 0; i < fs.Count; i++) { if (fs[i].Matched == true) // If file was already matched, then skip to next. continue; for (c = i + 1; c < fs.Count; c++) { if (fs[c].Matched == true) // skip already matched inner loop files. continue; if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash. continue; if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match. continue; if (fs[i].SHA512_1st1K == null) // check/hash first 1K first. if (Compute1KHash(fs[i]) == false) continue; if (fs[c].SHA512_1st1K == null) if (Compute1KHash(fs[c]) == false) continue; if (CompareBytes(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash.. continue; if (b4b == true) // byte for byte comparison specified? { if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function continue; } else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes. { if (fs[i].SHA512_All == null) // check/hash the rest of the files. if (ComputeFullHash(fs[i]) == false) continue; if (fs[c].SHA512_All == null) if (ComputeFullHash(fs[c]) == false) continue; if (CompareBytes(fs[i].SHA512_All, fs[c].SHA512_All) == false) continue; } Console.WriteLine("Match : " + fs[i].FI.FullName); Console.WriteLine("with : " + fs[c].FI.FullName); fs[c].Matched = true; // do not check or match against this file again. numOfDupes++; // increase count of matches. bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. continue; if (noprompt == false) { Console.Write("Delete the duplicate file <Y/n>?"); deleteConfirm = Console.ReadLine(); if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) // if user typed 'Y' then delete the file. continue; } try { File.Delete(fs[c].FI.FullName); Console.WriteLine("Deleted: " + fs[c].FI.FullName); bytesRec += fs[c].FI.Length; // record bytes recovered. delFiles++; } catch (Exception e) { WriteErr("File delete error: " + e.Message); } } } Console.WriteLine(" "); Console.WriteLine("Files checked : {0:N0}", fs.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes); Console.WriteLine("Duplicates deleted : {0:N0}", delFiles); Console.WriteLine("Recovered bytes : {0:N0}", bytesRec); return; // Exit after displaying statistics. } private static Boolean B4b(string path1, string path2) { try { using (var stream = File.OpenRead(path1)) { using (var stream2 = File.OpenRead(path2)) { while (stream.Position != stream.Length) { var length = stream.Read(largeBuf, 0, largeBuf.Length); var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length); if (length != length2) return false; if (CompareBytes(largeBuf, largeBuf2, length) == false) return false; } } } return true; } catch (Exception e) { WriteErr("Byte for Byte comparison failed: " + e.Message); return false; } } private static Boolean CompareBytes(byte[] byteArray1, byte[] byteArray2, int Len = HashLen) { int i = 0; while (i < Len) { if (byteArray1[i] != byteArray2[i]) return false; i++; } return true ; } private static readonly byte[] readBuf = new byte[1024]; private static readonly byte[] largeBuf = new byte[HashLen*200]; private static readonly byte[] largeBuf2 = new byte[HashLen*200]; private static readonly byte[] salt = new byte[HashLen]; private static void WriteErr(string Str) { if (noerr == false) Console.WriteLine(Str); } private static bool Compute1KHash(FileInfoExt path) { try { using (var stream = File.OpenRead(path.FI.FullName)) { var length = stream.Read(readBuf, 0, readBuf.Length); var _SHA512 = SHA512.Create(); _SHA512.TransformBlock(salt, 0, salt.Length, null, 0); _SHA512.TransformFinalBlock(readBuf, 0, length); path.SHA512_1st1K = _SHA512.Hash; return true; } } catch (Exception e) { WriteErr("Hash Error: " + e.Message); path.Matched = true; // since the file error'ed out, don't check against it again. return false; } } private static bool ComputeFullHash(FileInfoExt path) { try { var _SHA512 = SHA512.Create(); _SHA512.TransformBlock(salt, 0, salt.Length, null, 0); using (var stream = File.OpenRead(path.FI.FullName)) { while (true) { var length = stream.Read(largeBuf, 0, largeBuf.Length); if (stream.Position < stream.Length) // if not at end of file... _SHA512.TransformBlock(largeBuf, 0, length, null, 0); // hash the buffer, and loop. else { _SHA512.TransformFinalBlock(largeBuf, 0, length); // if at end of file, hash last time and end looping break; } } } path.SHA512_All = _SHA512.Hash; return true; } catch (Exception e) { WriteErr("Hash error: " + e.Message); path.Matched = true; return false; } } private static void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { Recursive(d, searchPattern, recursiveFlag, returnList); } return; } private static void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { returnList.Add(new FileInfoExt(new FileInfo(pathRec))); } 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))) { returnList.Add(new FileInfoExt(addf)); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { try { Recursive((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)) { Recursive(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }