full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Pause.ps1
|
Pause.ps1
|
## Pause (aka Pause-Script)
## Pause the script and wait for user action
###################################################################################################
## Parameters (are all OPTIONAL)
## Message - the message to use as the prompt to the user
## ReturnKey - when present, the script returns the key that was pressed as output
## LeaveMessage - if not present, the script erases the prompt when it's done
###################################################################################################
param([String]$Message="Press any key to continue...", [Switch]$ReturnKey, [Switch]$LeaveMessage)
## Get the cursor position before writing, we'll set it back here later.
$pos = $Host.UI.RawUI.CursorPosition;
## Flush the input buffer before pausing, just in case
$Host.UI.RawUI.FlushInputBuffer()
Write-Host -NoNewLine:$(!$LeaveMessage) $Message
## Save the key, in case they want it back
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
if(!$LeaveMessage) {
## Overwrite the Message with empty space
$Host.UI.RawUI.CursorPosition = $pos;
Write-Host -NoNewLine (" " *$Message.Length)
## Set the Cursor back where it started
$Host.UI.RawUI.CursorPosition = $pos;
}
## And return the key if they want it, otherwise we're done
if($ReturnKey) { return $Key }
|
PowerShellCorpus/PoshCode/ConvertTo-MultiArray_1.ps1
|
ConvertTo-MultiArray_1.ps1
|
function ConvertTo-MultiArray {
<#
.Notes
NAME: ConvertTo-MultiArray
AUTHOR: Tome Tanasovski
Website: http://powertoe.wordpress.com
Twitter: http://twitter.com/toenuff
Version: 1.1
CREATED: 11/5/2010
LASTEDIT:
11/5/2010 1.0
Initial Release
11/5/2010 1.1
Removed array parameter and passes a reference to the multi-dimensional array as output to the cmdlet
.Synopsis
Converts a collection of PowerShell objects into a multi-dimensional array
.Description
Converts a collection of PowerShell objects into a multi-dimensional array. The first row of the array contains the property names. Each additional row contains the values for each object.
This cmdlet was created to act as an intermediary to importing PowerShell objects into a range of cells in Exchange. By using a multi-dimensional array you can greatly speed up the process of adding data to Excel through the Excel COM objects.
.Parameter InputObject
Specifies the objects to export into the multi dimensional array. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to ConvertTo-MultiArray.
.Inputs
System.Management.Automation.PSObject
You can pipe any .NET Framework object to ConvertTo-MultiArray
.Outputs
[ref]
The cmdlet will return a reference to the multi-dimensional array. To access the array itself you will need to use the Value property of the reference
.Example
$arrayref = get-process |Convertto-MultiArray
.Example
$dir = Get-ChildItem c:\\
$arrayref = Convertto-MultiArray -InputObject $dir
.Example
$range.value2 = (ConvertTo-MultiArray (get-process)).value
.LINK
http://powertoe.wordpress.com
#>
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[PSObject[]]$InputObject
)
BEGIN {
$objects = @()
[ref]$array = [ref]$null
}
Process {
$objects += $InputObject
}
END {
$properties = $objects[0].psobject.properties |%{$_.name}
$array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count
# i = row and j = column
$j = 0
$properties |%{
$array.Value[0,$j] = $_
$j++
}
$i = 1
$objects |% {
$item = $_
$j = 0
$properties | % {
$array.value[$i,$j] = $item.($_)
$j++
}
$i++
}
$array
}
}
|
PowerShellCorpus/PoshCode/Save-Credentials_3.ps1
|
Save-Credentials_3.ps1
|
<#
.SYNOPSIS
The script saves a username and password, encrypted with a custom key to to a file.
.DESCRIPTION
The script saves a username and password, encrypted with a custom key to to a file. The key is coded into the script but should be changed before use. The key allows the password to be decrypted by any user who has the key, on any machine. if the key parameter is omitted from ConvertFrom-SecureString, only the user who generated the file on the computer that generated the file can decrypt the password.
see http://bsonposh.com/archives/254 for more info.
To retrieve the password:
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12
$VCCred = Import-Csv 'C:\\PATH\\FILE.TXT'
$VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key)
$VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password)
.NOTES
File Name : SaveCredentials.ps1
Author : Samuel Mulhearn
Version History:
Version 1.0
28 Jun 2012.
Release
.LINK
http://poshcode.org/3487
.EXAMPLE
Call the script with .\\Save-Credentials.ps1 no arguments or parameters are required
#>
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12
Write-Host "Key length is:" $key.length "The key length is acceptable if 16 or 32"
$ScriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition
$Outfile = "$ScriptPath\\Credentials.txt"
Write-Host "This script will a username and encrpyted password into $outfile"
$null | Out-File -FilePath $Outfile
$credential = Get-Credential
$obj = New-Object -typename System.Object
$obj | Add-Member -MemberType noteProperty -name Username -value $credential.UserName
$obj | Add-Member -MemberType noteProperty -name Password -value ($credential.Password | ConvertFrom-SecureString -key $key)
$obj | Export-Csv -Path $OutFile
write-host "Username and password have been saved to $outfile"
|
PowerShellCorpus/PoshCode/PowerBoots Gadgets.ps1
|
PowerBoots Gadgets.ps1
|
$gadgetWindow = @{
# Transparency, WindowStyle, and background work together
# to get rid of the standard window's chrome and make the window "irregular" shaped
# that is, the window will be the shape of it's content.
AllowsTransparency = $True
WindowStyle = "None"
Background = "Transparent"
# Async means the window will keep running but PowerShell will return to the prompt
Async = $True
# Assuming you put something on your window, this will make the window draggable
# It might get in the way of clicking on controls, so bear that in mind.
On_MouseDown = { $this.DragMove() }
# This makes a timer for you, based on the TITLE and TAG of the window
On_SourceInitialized = {
$this.Tag = DispatcherTimer -Interval $this.Tag[0] -On_Tick $this.Tag[1]
$this.Tag.Start()
}
# Stop that timer or it will just keep right on firing.
On_Closing = {
$this.Tag.Stop()
}
}
## Example uses:
# Create a little clock that's always topmost ...
boots { label -fontsize 24 | tee -var global:clock } @gadgetWindow -Title "Clock" -Topmost -Tag "00:00:00.2", { $global:clock.Content = "$(Get-Date -f 'hh:mm:ss')" }
# World's simplest weather report, updates every 5 minutes
$weatherUrl = "http`://weather.yahooapis.com/forecastrss?p={0}" -f 14586 # Must be a "woeid"
# To find your WOEID, browse or search for your city from the Weather home page.
# The WOEID is the LAST PART OF the URL for the forecast page for that city.
boots { Image -Stretch Uniform -Width 52.0 | tee -var global:weather } @gadgetWindow -Title "Weather" -Tag "00:05",
{ $h = ([int](Get-Date -f hh)); if($h -gt 8 -and $h -lt 7){$dayOrNight = 'd'}else{$dayOrNight = 'n'}
$code = ([xml](New-Object Net.WebClient).DownloadString($weatherUrl)).rss.channel.item.condition.code
$global:Weather.Source = "http`://l.yimg.com/a/i/us/nws/weather/gr/{0}{1}.png" -f $code, $dayOrNight
}
|
PowerShellCorpus/PoshCode/Get-PageUrls.ps1
|
Get-PageUrls.ps1
|
##############################################################################\n##\n## Get-PageUrls\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nParse all of the URLs out of a given file.\n\n.EXAMPLE\n\nGet-PageUrls microsoft.html http://www.microsoft.com\nGets all of the URLs from HTML stored in microsoft.html, and converts relative\nURLs to the domain of http://www.microsoft.com\n\n.EXAMPLE\n\nGet-PageUrls microsoft.html http://www.microsoft.com 'aspx$'\nGets all of the URLs from HTML stored in microsoft.html, converts relative\nURLs to the domain of http://www.microsoft.com, and returns only URLs that end\nin 'aspx'.\n\n#>\n\nparam(\n ## The filename to parse\n [Parameter(Mandatory = $true)]\n [string] $Path,\n\n ## The URL from which you downloaded the page.\n ## For example, http://www.microsoft.com\n [Parameter(Mandatory = $true)]\n [string] $BaseUrl,\n\n [switch] $Images,\n \n ## The Regular Expression pattern with which to filter\n ## the returned URLs\n [string] $Pattern = ".*"\n)\n\nSet-StrictMode -Version Latest\n\n## Load the System.Web DLL so that we can decode URLs\nAdd-Type -Assembly System.Web\n\n## Defines the regular expression that will parse an URL\n## out of an anchor tag.\n$regex = "<\\s*a\\s*[^>]*?href\\s*=\\s*[`"']*([^`"'>]+)[^>]*?>"\nif($Images)\n{\n $regex = "<\\s*img\\s*[^>]*?src\\s*=\\s*[`"']*([^`"'>]+)[^>]*?>"\n}\n\n## Parse the file for links\nfunction Main\n{\n ## Do some minimal source URL fixups, by switching backslashes to\n ## forward slashes\n $baseUrl = $baseUrl.Replace("\\", "/")\n\n if($baseUrl.IndexOf("://") -lt 0)\n {\n throw "Please specify a base URL in the form of " +\n "http://server/path_to_file/file.html"\n }\n\n ## Determine the server from which the file originated. This will\n ## help us resolve links such as "/somefile.zip"\n $baseUrl = $baseUrl.Substring(0, $baseUrl.LastIndexOf("/") + 1)\n $baseSlash = $baseUrl.IndexOf("/", $baseUrl.IndexOf("://") + 3)\n\n if($baseSlash -ge 0)\n {\n $domain = $baseUrl.Substring(0, $baseSlash)\n }\n else\n {\n $domain = $baseUrl\n }\n\n\n ## Put all of the file content into a big string, and\n ## get the regular expression matches\n $content = [String]::Join(' ', (Get-Content $path))\n $contentMatches = @(GetMatches $content $regex)\n\n foreach($contentMatch in $contentMatches)\n {\n if(-not ($contentMatch -match $pattern)) { continue }\n if($contentMatch -match "javascript:") { continue }\n\n $contentMatch = $contentMatch.Replace("\\", "/")\n\n ## Hrefs may look like:\n ## ./file\n ## file\n ## ../../../file\n ## /file\n ## url\n ## We'll keep all of the relative paths, as they will resolve.\n ## We only need to resolve the ones pointing to the root.\n if($contentMatch.IndexOf("://") -gt 0)\n {\n $url = $contentMatch\n }\n elseif($contentMatch[0] -eq "/")\n {\n $url = "$domain$contentMatch"\n }\n else\n {\n $url = "$baseUrl$contentMatch"\n $url = $url.Replace("/./", "/")\n }\n\n ## Return the URL, after first removing any HTML entities\n [System.Web.HttpUtility]::HtmlDecode($url)\n }\n}\n\nfunction GetMatches([string] $content, [string] $regex)\n{\n $returnMatches = new-object System.Collections.ArrayList\n\n ## Match the regular expression against the content, and\n ## add all trimmed matches to our return list\n $resultingMatches = [Regex]::Matches($content, $regex, "IgnoreCase")\n foreach($match in $resultingMatches)\n {\n $cleanedMatch = $match.Groups[1].Value.Trim()\n [void] $returnMatches.Add($cleanedMatch)\n }\n\n $returnMatches\n}\n\n. Main
|
PowerShellCorpus/PoshCode/out-form with sort colum_2.ps1
|
out-form with sort colum_2.ps1
|
# I think OUT-FORM is a very usefull function. I've added code to sort columns by clicking on headers.
# You nedd just add the columnTag parameters specifing if colunm value is text or numeric:
# out-form -data (get-process) -columnNames ("Name", "ID" ) -columnProperties ("Name", "ID") -columnTag ("Text", "Numeric")
# Hope can help
function Out-Form {
<#
.Synopsis
Output the results of a command in a Windows Form
.Description
Output the results of a command in a Windows Form with possibility to add buttons with actions
.Example
out-form -title "Services" -data (get-service) -columnNames ("Name", "Status") -columnProperties ("DisplayName", "Status") -actions @{"Start" = {$_.start()}; "Stop" = {$_.stop()};}
#>
param ($title = "", $data = $null, $columnNames = $null, $columnTag,
$columnProperties = $null, $actions = $null)
# a little data defaulting/validation
if ($columnNames -eq $null) {
$columnNames = $columnProperties
}
if ($columnProperties -eq $null -or
$columnNames.Count -lt 1 -or
$columnNames.Count -ne $columnNames.Count) {
throw "Data validation failed"
}
$numCols = $columnNames.Count
# figure out form width
$width = $numCols * 200
$actionWidth = $actions.Count * 100 + 40
if ($actionWidth -gt $width) {
$width = $actionWidth
}
# set up form
$form = new-object System.Windows.Forms.Form
$form.text = $title
$form.size = new-object System.Drawing.Size($width, 400)
$panel = new-object System.Windows.Forms.Panel
$panel.Dock = "Fill"
$form.Controls.Add($panel)
$lv = new-object windows.forms.ListView
$panel.Controls.Add($lv)
# add the buttons
$btnPanel = new-object System.Windows.Forms.Panel
$btnPanel.Height = 40
$btnPanel.Dock = "Bottom"
$panel.Controls.Add($btnPanel)
$btns = new-object System.Collections.ArrayList
if ($actions -ne $null) {
$btnOffset = 20
foreach ($action in $actions.GetEnumerator()) {
$btn = new-object windows.forms.Button
$btn.DialogResult = [System.Windows.Forms.DialogResult]"OK"
$btn.Text = $action.name
$btn.Left = $btnOffset
$btn.Width = 80
$btn.Top = 10
$exprString = '{$lv.SelectedItems | foreach-object { $_.Tag } | foreach-object {' + $action.value + '}}'
$scriptBlock = invoke-expression $exprString
$btn.add_Click($scriptBlock)
$btnPanel.Controls.Add($btn)
$btnOffset += 100
$btns += $btn
}
}
# create the columns
$lv.View = [System.Windows.Forms.View]"Details"
$lv.Size = new-object System.Drawing.Size($width, 350)
$lv.FullRowSelect = $true
$lv.GridLines = $true
$lv.Dock = "Fill"
foreach ($col in $columnNames) {
$lv.Columns.Add($col, 200) > $null
}
# populate the view
foreach ($d in $data) {
$item =
new-object System.Windows.Forms.ListViewItem(
(invoke-expression ('$d.' + $columnProperties[0])).tostring())
for ($i = 1; $i -lt $columnProperties.Count; $i++) {
$item.SubItems.Add(
(invoke-expression ('$d.' + $columnProperties[$i])).tostring()) > $null
}
$item.Tag = $d
$lv.Items.Add($item) > $null
}
# Added by Bar971.it
for ($i = 0; $i -lt $columnTag.Count; $i++) {
$lv.Columns[$i].Tag = $columnTag[$i]
}
$comparerClassString = @"
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
public class ListViewItemComparer : System.Collections.IComparer
{
public int col = 0;
public System.Windows.Forms.SortOrder Order; // = SortOrder.Ascending;
public ListViewItemComparer()
{
col = 0;
}
public ListViewItemComparer(int column, bool asc)
{
col = column;
if (asc)
{Order = SortOrder.Ascending;}
else
{Order = SortOrder.Descending;}
}
public int Compare(object x, object y) // IComparer Member
{
if (!(x is ListViewItem)) return (0);
if (!(y is ListViewItem)) return (0);
ListViewItem l1 = (ListViewItem)x;
ListViewItem l2 = (ListViewItem)y;
if (l1.ListView.Columns[col].Tag == null)
{
l1.ListView.Columns[col].Tag = "Text";
}
if (l1.ListView.Columns[col].Tag.ToString() == "Numeric")
{
float fl1 = float.Parse(l1.SubItems[col].Text);
float fl2 = float.Parse(l2.SubItems[col].Text);
if (Order == SortOrder.Ascending)
{
return fl1.CompareTo(fl2);
}
else
{
return fl2.CompareTo(fl1);
}
}
else
{
string str1 = l1.SubItems[col].Text;
string str2 = l2.SubItems[col].Text;
if (Order == SortOrder.Ascending)
{
return str1.CompareTo(str2);
}
else
{
return str2.CompareTo(str1);
}
}
}
}
"@
Add-Type -TypeDefinition $comparerClassString `
-ReferencedAssemblies (`
'System.Windows.Forms', 'System.Drawing')
$bool = $true
$columnClick =
{
$lv.ListViewItemSorter = New-Object ListViewItemComparer($_.Column, $bool)
$bool = !$bool
}
$lv.Add_ColumnClick($columnClick)
# End Add by Bar971.it
# display it
$form.Add_Shown( { $form.Activate() } )
if ($btns.Count -gt 0) {
$form.AcceptButton = $btns[0]
}
$form.showdialog()
}
|
PowerShellCorpus/PoshCode/New-CustomColumn (V1.0).ps1
|
New-CustomColumn (V1.0).ps1
|
# Function New-CustomColumn for PowerShell V1.0
#
# Helper function to create Custom Columns for select or format cmdlets
# for more info and examples see :
# http://thepowershellguy.com/blogs/posh/archive/2009/01/26/new-customcolumn-function-powershell-v1-0.aspx
#
# /\\/\\o\\/\\/ 2008
# http://thePowerShellGuy.com
Function New-CustomColumn {
PARAM (
$Expression,
$name,
$label,
$FormatString,
[int]$Width,
$Alignment
)
$column = @{}
if ($Expression){
$Column.Expression = $Expression
} else {
throw "Expression is mandatory"
}
if ($Name) {$Column.Name = $name}
if ($Label) {$Column.Label = $Label}
if ($FormatString) {$Column.FormatString = $FormatString}
if ($Width) {$Column.Width = $Width}
if ($Alignment) {$Column.Alignment = $Alignment}
$Column.psobject.baseobject
}
|
PowerShellCorpus/PoshCode/Start-Elevated.ps1
|
Start-Elevated.ps1
|
#function Start-Elevated {
param ($app)
$psi = new-object "System.Diagnostics.ProcessStartInfo"
$psi.FileName = $app;
$psi.Arguments = [string]$args;
$psi.Verb = "runas";
[System.Diagnostics.Process]::Start($psi)
#}
|
PowerShellCorpus/PoshCode/Snippet Compiler_3.ps1
|
Snippet Compiler_3.ps1
|
$def = $(if ((gi .).FullName -eq (gi .).Root) {
([string](gi .).Root).TrimEnd("\\")
}
else { (gi .).FullName }
)
##################################################################################################
function Get-CursorPoint {
$x = $rtbEdit.SelectionStart - $rtbEdit.GetFirstCharIndexOfCurrentLine()
$y = $rtbEdit.GetLineFromCharIndex($rtbEdit.SelectionStart) + 1
return (New-Object Drawing.Point($x, $y))
}
function Get-Image([string]$img) {
[Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = `
[Convert]::FromBase64String($img)), 0, $$.Length)))
}
function Invoke-Builder {
$lstBugs.Items.Clear()
if ($rtbEdit.Text -ne "") {
switch ($tsCom_1.SelectedIndex) {
"0" {$cscp = New-Object Microsoft.CSharp.CSharpCodeProvider; break}
"1" {$cscp = New-Object Microsoft.CSharp.CSharpCodeProvider($dict); break}
}
switch ($tsCom_2.SelectedIndex) {
"0" {$cdcp.GenerateExecutable = $true; break}
"1" {$cdcp.GenerateExecutable = $false; break}
"2" {
$cdcp.GenerateExecutable = $true
$cdcp.CompilerOptions = "/t:winexe"
break
}
}
$cdcp.IncludeDebugInformation = $chkIDbg.Checked
$cdcp.GenerateInMemory = $chkIMem.Checked
if ($lboRefs.Items.Count -ne 0) {
for ($i = 0; $i -lt $lboRefs.Items.Count; $i++) {
$cdcp.ReferencedAssemblies.Add($lboRefs.Items[$i].ToString())
}
}
$cdcp.WarningLevel = 3
$cdcp.OutputAssembly = $txtName.Text
$script:make = $cscp.CompileAssemblyFromSource($cdcp, $rtbEdit.Text)
$make.Errors | % {
if ($_.Line -ne 0 -and $_.Column -ne 0) {
$err = $_.Line.ToString() + '.' + ($_.Column - 1).ToString()
}
elseif ($_.Line -ne 0 -and $_.Column -eq 0) {
$err = $_.Line.ToString() + ', 0'
}
elseif ($_.Line -eq 0 -and $_.Column -eq 0) {
$err = '*'
}
if (!($_.IsWarning)) {
$lstBugs.ForeColor = [Drawing.Color]::Crimson
$itm = $lstBugs.Items.Add($err, 14)
}
else {
$lstBugs.ForeColor = [Drawing.Color]::Gray
$itm = $lstBugs.Items.Add($err, 15)
}
$itm.SubItems.Add($_.ErrorNumber)
$itm.SubItems.Add($_.ErrorText)
}
}#if
}
function Open-Document {
Watch-UnsavedData
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$sr = New-Object IO.StreamReader $_.FileName
$rtbEdit.Text = $sr.ReadToEnd()
$sr.Close()
$tpBasic.Text = $_.FileName
$tpBasic.ImageIndex = 2
$script:uns = $false
}
}
}
function Save-Document {
if ($rtbEdit.Text -ne "") {
Save-WorkspaceData
}
}
function Save-DocumentQuickly {
if ($script:uns) {
if ($src -ne $null) {
Out-File $src -enc UTF8 -inp $rtbEdit.Text
$tpBasic.ImageIndex = 2
$script:uns = $false
}
else { Save-WorkspaceData }
}
}
function Save-WorkspaceData {
(New-Object Windows.Forms.SaveFileDialog) | % {
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$script:src = $_.FileName
Out-File $src -enc UTF8 -inp $rtbEdit.Text
$tpBasic.Text = $src
$tpBasic.ImageIndex = 2
$script:uns = $false
}
}
}
function Set-Opacity([object]$obj) {
$ops.Checked = $false
$frmMain.Opacity = [float]('.' + $($obj.Text)[0])
$obj.Checked = $true
}
function Start-AfterBuilding {
Invoke-Builder
if ($script:make.Errors.Count -eq 0) {Invoke-Item $txtName.Text}
}
function Watch-UnsavedData {
if ($script:uns) {
$res = [Windows.Forms.MessageBox]::Show(
" Workspace has been modified.`nDo you want to save changes before?",
$frmMain.Text, [Windows.Forms.MessageBoxButtons]::YesNoCancel,
[Windows.Forms.MessageBoxIcon]::Question
)
switch ($res) {
'Yes' { Save-WorkspaceData; $rtbEdit.Clear(); $tpBasic.Text = "Untitled"; break }
'No' { $rtbEdit.Clear(); $tpBasic.Text = "Untitled"; break }
'Cancel' { return }
}
}
else { $rtbEdit.Clear(); $tpBasic.Text = "Untitled" }
}
function Write-CursorPoint {
$sbPnl_2.Text = 'Str: ' + (Get-CursorPoint).Y.ToString() + ', Col: ' + `
(Get-CursorPoint).X.ToString()
}
##################################################################################################
$mnuITag_Click= {
$tag = "//Author: " + [Security.Principal.WindowsIdentity]::GetCurrent().Name + "`n" + `
"//Date: " + (Get-Date -f 'HH:mm:ss') + "`n`n"
if ($rtbEdit.Text -eq "") {
$rtbEdit.Text = $tag
}
else {
$rtbEdit.Text = $tag + $rtbEdit.Text
}
}
$mnuFont_Click= {
(New-Object Windows.Forms.FontDialog) | % {
$_.Font = "Lucida Console"
$_.MinSize = 10
$_.MaxSize = 12
$_.ShowEffects = $false
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$rtbEdit.Font = $_.Font
}
}
}
$mnuOpaF_Click= {
$frmMain.Opacity = 1
$ops.Checked = $false
$mnuOpaF.Checked = $true
$ops = $mnuOpaF
}
$mnuWrap_Click= {
$toggle =! $mnuWrap.Checked
$mnuWrap.Checked = $toggle
$rtbEdit.WordWrap = $toggle
}
$mnuPane_Click= {
switch ($mnuPane.Checked) {
$true { $mnuPane.Checked = $false; $scSplit.Panel2Collapsed = $true; break }
$false { $mnuPane.Checked = $true; $scSplit.Panel2Collapsed = $false; break }
}
}
$mnuSBar_Click= {
$toggle =! $mnuSBar.Checked
$mnuSBar.Checked = $toggle
$sbPanel.Visible = $toggle
}
$tsCom_1_SelectedIndexChanged= {
switch ($tsCom_1.SelectedIndex) {
"0" {$lboRefs.Items.Remove("`"System.Core.dll`""); break}
"1" {$lboRefs.Items.Add("`"System.Core.dll`""); break}
}
}
$tsCom_2_SelectedIndexChanged= {
switch ($tsCom_2.SelectedIndex) {
"0" {
$txtName.Text = $def + '\\app.exe'
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
$tsBut11.Enabled = $true
break
}
"1" {
$txtName.Text = $def + '\\lib.dll'
$chkIMem.Enabled = $true
$mnuBnRA.Enabled = $false
$tsBut11.Enabled = $false
$lboRefs.Items.Remove("`"System.Windows.Forms.dll`"")
$lboRefs.Items.Remove("`"System.Drawing.dll`"")
break
}
"2" {
$txtName.Text = $def + '\\app.exe'
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
$tsBut11.Enabled = $true
$lboRefs.Items.AddRange(@("`"System.Drawing.dll`"", "`"System.Windows.Forms.dll`""))
break
}
}
}
$rtbEdit_TextChanged= {
if ($rtbEdit.Text -ne "") {
$tpBasic.ImageIndex = 1
Write-CursorPoint
$script:uns = $true
}
else {
$tpBasic.Text = "Untitled"
$tpBasic.ImageIndex = 0
$script:uns = $false
$script:src = $null
}
}
$chkIMem_Click= {
switch ($chkIMem.Checked) {
$true {
$txtName.Text = [String]::Empty
$lblName.Enabled = $false
$txtName.Enabled = $false
$chkIDbg.Checked = $false
$chkIDbg.Enabled = $false
$tsCom_2.Enabled = $false
}
$false {
$txtName.Text = $def + '\\lib.dll'
$lblName.Enabled = $true
$txtName.Enabled = $true
$chkIDbg.Checked = $true
$chkIDbg.Enabled = $true
$tsCom_2.Enabled = $true
}
}
}
$mnuICnM_Click= {
$script:buf = $lboRefs.SelectedItem
$lboRefs.Items.Remove($lboRefs.SelectedItem)
}
$mnuIIns_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.Filter = "PE File (*.dll)|*.dll"
$_.InitialDirectory = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$lboRefs.Items.Add('"' + (Split-Path -leaf $_.FileName) + '"')
}
}
}
$frmMain_Load= {
$rtbEdit.Select()
$txtName.Text = $def + '\\app.exe'
$sbPnl_2.Text = "Str: 1, Col: 0"
$lboRefs.Items.Add("`"System.dll`"")
}
##################################################################################################
#
#this is resource section (DO NOT MODIFY THIS!)
#
$i_1 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAQRJREFUOE+Vkr0OQ1AYhk8ns7" + `
"gR9+MnEbGJhQswGSsxGCxCJHSSGI1GsbF1dAUmMbWvnv6qavskQo73Od/5fHZRFA3D0Pf9OI7TNJE1GIZhWZb" + `
"neY7ji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V0lXl4PIgAAAABJRU5ErkJggg=="
##################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$ico = [Drawing.Icon]::ExtractAssociatedIcon(($PSHome + '\\powershell_ise.exe'))
$cdcp = New-Object CodeDom.Compiler.CompilerParameters
$dict = New-Object "Collections.Generic.Dictionary[String, String]"
$dict.Add("CompilerVersion", "v3.5")
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MenuStrip
$mnuFile = New-Object Windows.Forms.ToolStripMenuItem
$mnuNDoc = New-Object Windows.Forms.ToolStripMenuItem
$mnuOpen = New-Object Windows.Forms.ToolStripMenuItem
$mnuSave = New-Object Windows.Forms.ToolStripMenuItem
$mnuQSav = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp1 = New-Object Windows.Forms.ToolStripSeparator
$mnuExit = New-Object Windows.Forms.ToolStripMenuItem
$mnuEdit = New-Object Windows.Forms.ToolStripMenuItem
$mnuUndo = New-Object Windows.Forms.ToolStripMenuItem
$mnuRedo = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp2 = New-Object Windows.Forms.ToolStripSeparator
$mnuCopy = New-Object Windows.Forms.ToolStripMenuItem
$mnuPast = New-Object Windows.Forms.ToolStripMenuItem
$mnuICut = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp3 = New-Object Windows.Forms.ToolStripSeparator
$mnuSAll = New-Object Windows.Forms.ToolStripMenuItem
$mnuITag = New-Object Windows.Forms.ToolStripMenuItem
$mnuView = New-Object Windows.Forms.ToolStripMenuItem
$mnuFont = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp4 = New-Object Windows.Forms.ToolStripSeparator
$mnuOpac = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp50 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp60 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp70 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp80 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp90 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOpaF = New-Object Windows.Forms.ToolStripMenuItem
$mnuTgls = New-Object Windows.Forms.ToolStripMenuItem
$mnuWrap = New-Object Windows.Forms.ToolStripMenuItem
$mnuPane = New-Object Windows.Forms.ToolStripMenuItem
$mnuSBar = New-Object Windows.Forms.ToolStripMenuItem
$mnuMake = New-Object Windows.Forms.ToolStripMenuItem
$mnuBAsm = New-Object Windows.Forms.ToolStripMenuItem
$mnuBnRA = New-Object Windows.Forms.ToolStripMenuItem
$mnuHelp = New-Object Windows.Forms.ToolStripMenuItem
$mnuInfo = New-Object Windows.Forms.ToolStripMenuItem
$tsTools = New-Object Windows.Forms.ToolStrip
$tsBut_1 = New-Object Windows.Forms.ToolStripButton
$tsBut_2 = New-Object Windows.Forms.ToolStripButton
$tsBut_3 = New-Object Windows.Forms.ToolStripButton
$tsBut_4 = New-Object Windows.Forms.ToolStripButton
$tsSep_1 = New-Object Windows.Forms.ToolStripSeparator
$tsBut_5 = New-Object Windows.Forms.ToolStripButton
$tsBut_6 = New-Object Windows.Forms.ToolStripButton
$tsSep_2 = New-Object Windows.Forms.ToolStripSeparator
$tsBut_7 = New-Object Windows.Forms.ToolStripButton
$tsBut_8 = New-Object Windows.Forms.ToolStripButton
$tsBut_9 = New-Object Windows.Forms.ToolStripButton
$tsSep_3 = New-Object Windows.Forms.ToolStripSeparator
$tsBut10 = New-Object Windows.Forms.ToolStripButton
$tsBut11 = New-Object Windows.Forms.ToolStripButton
$tsSep_4 = New-Object Windows.Forms.ToolStripSeparator
$tsLab_1 = New-Object Windows.Forms.ToolStripLabel
$tsCom_1 = New-Object Windows.Forms.ToolStripComboBox
$tsLab_2 = New-Object Windows.Forms.ToolStripLabel
$tsCom_2 = New-Object Windows.Forms.ToolStripComboBox
$scSplit = New-Object Windows.Forms.SplitContainer
$tcSpace = New-Object Windows.Forms.TabControl
$tpBasic = New-Object Windows.Forms.TabPage
$rtbEdit = New-Object Windows.Forms.RichTextBox
$tcBuild = New-Object Windows.Forms.TabControl
$tpError = New-Object Windows.Forms.TabPage
$lstBugs = New-Object Windows.Forms.ListView
$chPoint = New-Object Windows.Forms.ColumnHeader
$chError = New-Object Windows.Forms.ColumnHeader
$chCause = New-Object Windows.Forms.ColumnHeader
$tpBuild = New-Object Windows.Forms.TabPage
$lblName = New-Object Windows.Forms.Label
$txtName = New-Object Windows.Forms.TextBox
$chkIDbg = New-Object Windows.Forms.CheckBox
$chkIMem = New-Object Windows.Forms.CheckBox
$tpRefer = New-Object Windows.Forms.TabPage
$lboRefs = New-Object Windows.Forms.ListBox
$mnuRefs = New-Object Windows.Forms.ContextMenuStrip
$mnuIMov = New-Object Windows.Forms.ToolStripMenuItem
$mnuICnM = New-Object Windows.Forms.ToolStripMenuItem
$mnuIBuf = New-Object Windows.Forms.ToolStripMenuItem
$mnuIIns = New-Object Windows.Forms.ToolStripMenuItem
$imgList = New-Object Windows.Forms.ImageList
$sbPanel = New-Object Windows.Forms.StatusBar
$sbPnl_1 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_2 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_3 = New-Object Windows.Forms.StatusBarPanel
#
#mnuMain
#
$mnuMain.Items.AddRange(@($mnuFile, $mnuEdit, $mnuView, $mnuMake, $mnuHelp))
#
#mnuFile
#
$mnuFile.DropDownItems.AddRange(@($mnuNDoc, $mnuOpen, $mnuSave, $mnuQSav, $mnuEmp1, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuNDoc
#
$mnuNDoc.ShortcutKeys = "Control", "N"
$mnuNDoc.Text = "&New"
$mnuNDoc.Add_Click({Watch-UnsavedData; $script:src = $null})
#
#mnuOpen
#
$mnuOpen.ShortcutKeys = "Control", "O"
$mnuOpen.Text = "&Open..."
$mnuOpen.Add_Click({Open-Document})
#
#mnuSave
#
$mnuSave.ShortcutKeys = "Control", "S"
$mnuSave.Text = "&Save"
$mnuSave.Add_Click({Save-Document})
#
#mnuQSav
#
$mnuQSav.ShortcutKeys = "F2"
$mnuQSav.Text = "&Quick Save"
$mnuQSav.Add_Click({Save-DocumentQuickly})
#
#mnuExit
#
$mnuExit.ShortcutKeys = "Control", "X"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuEdit
#
$mnuEdit.DropDownItems.AddRange(@($mnuUndo, $mnuRedo, $mnuEmp2, $mnuCopy, $mnuPast, $mnuICut, `
$mnuEmp3, $mnuSAll, $mnuITag))
$mnuEdit.Text = "&Edit"
#
#mnuUndo
#
$mnuUndo.ShortcutKeys = "Control", "Z"
$mnuUndo.Text = "&Undo"
$mnuUndo.Add_Click({$rtbEdit.Undo()})
#
#mnuRedo
#
$mnuRedo.ShortcutKeys = "Control", "D"
$mnuRedo.Text = "&Redo"
$mnuRedo.Add_Click({$rtbEdit.Redo()})
#
#mnuCopy
#
$mnuCopy.ShortcutKeys = "Control", "C"
$mnuCopy.Text = "&Copy"
$mnuCopy.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Copy()}})
#
#mnuPast
#
$mnuPast.ShortcutKeys = "Control", "V"
$mnuPast.Text = "&Paste"
$mnuPast.Add_Click({$rtbEdit.Paste()})
#
#mnuICut
#
$mnuICut.ShortcutKeys = "Del"
$mnuICut.Text = "Cut &Item"
$mnuICut.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Cut()}})
#
#mnuSAll
#
$mnuSAll.ShortcutKeys = "Control", "A"
$mnuSAll.Text = "Select &All"
$mnuSAll.Add_Click({$rtbEdit.SelectAll()})
#
#mnuITag
#
$mnuITag.ShortcutKeys = "F3"
$mnuITag.Text = "Insert &Tag"
$mnuITag.Add_Click($mnuITag_Click)
#
#mnuView
#
$mnuView.DropDownItems.AddRange(@($mnuFont, $mnuEmp4, $mnuOpac, $mnuTgls))
$mnuView.Text = "&View"
#
#mnuFont
#
$mnuFont.Text = "&Font..."
$mnuFont.Add_Click($mnuFont_Click)
#
#mnuOpac
#
$mnuOpac.DropDownItems.AddRange(@($mnuOp50, $mnuOp60, $mnuOp70, $mnuOp80, $mnuOp90, $mnuOpaF))
$mnuOpac.Text = "&Opacity"
#
#mnuOp50
#
$mnuOp50.Text = "50%"
$mnuOp50.Add_Click({Set-Opacity $mnuOp50; $ops = $mnuOp50})
#
#mnuOp60
#
$mnuOp60.Text = "60%"
$mnuOp60.Add_Click({Set-Opacity $mnuOp60; $ops = $mnuOp60})
#
#mnuOp70
#
$mnuOp70.Text = "70%"
$mnuOp70.Add_Click({Set-Opacity $mnuOp70; $ops = $mnuOp70})
#
#mnuOp80
#
$mnuOp80.Text = "80%"
$mnuOp80.Add_Click({Set-Opacity $mnuOp80; $ops = $mnuOp80})
#
#mnuOp90
#
$mnuOp90.Text = "90%"
$mnuOp90.Add_Click({Set-Opacity $mnuOp90; $ops = $mnuOp90})
#
#mnuOpaF
#
$ops = $mnuOpaF
$mnuOpaF.Checked = $true
$mnuOpaF.Text = "Opaque"
$mnuOpaF.Add_Click($mnuOpaF_Click)
#
#mnuTgls
#
$mnuTgls.DropDownItems.AddRange(@($mnuWrap, $mnuPane, $mnuSBar))
$mnuTgls.Text = "&Toggles"
#
#mnuWrap
#
$mnuWrap.Checked = $true
$mnuWrap.ShortcutKeys = "Control", "W"
$mnuWrap.Text = "&Wrap Mode"
$mnuWrap.Add_Click($mnuWrap_Click)
#
#mnuPane
#
$mnuPane.Checked = $true
$mnuPane.ShortcutKeys = "Control", "L"
$mnuPane.Text = "&Lower Pane"
$mnuPane.Add_Click($mnuPane_Click)
#
#mnuSBar
#
$mnuSBar.Checked = $true
$mnuSBar.ShortcutKeys = "Control", "B"
$mnuSBar.Text = "Status &Bar"
$mnuSBar.Add_Click($mnuSBar_Click)
#
#mnuMake
#
$mnuMake.DropDownItems.AddRange(@($mnuBAsm, $mnuBnRA))
$mnuMake.Text = "&Build"
#
#mnuBAsm
#
$mnuBAsm.ShortcutKeys = "F5"
$mnuBAsm.Text = "&Compile"
$mnuBAsm.Add_Click({Invoke-Builder})
#
#mnuBnRA
#
$mnuBnRA.ShortcutKeys = "F9"
$mnuBnRA.Text = "Compile And &Run"
$mnuBnRA.Add_Click({Start-AfterBuilding})
#
#mnuHelp
#
$mnuHelp.DropDownItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#tsTools
#
$tsTools.ImageList = $imgList
$tsTools.Items.AddRange(@($tsBut_1, $tsBut_2, $tsBut_3, $tsBut_4, $tsSep_1, $tsBut_5, `
$tsBut_6, $tsSep_2, $tsBut_7, $tsBut_8, $tsBut_9, $tsSep_3, $tsBut10, $tsBut11, `
$tsSep_4, $tsLab_1, $tsCom_1, $tsLab_2, $tsCom_2))
#
#tsBut_1
#
$tsBut_1.ImageIndex = 3
$tsBut_1.ToolTipText = "New"
$tsBut_1.Add_Click({Watch-UnsavedData; $script:src = $null})
#
#tsBut_2
#
$tsBut_2.ImageIndex = 4
$tsBut_2.ToolTipText = "Open"
$tsBut_2.Add_Click({Open-Document})
#
#tsBtn_3
#
$tsBut_3.ImageIndex = 5
$tsBut_3.ToolTipText = "Save"
$tsBut_3.Add_Click({Save-Document})
#
#tsBut_4
#
$tsBut_4.ImageIndex = 6
$tsBut_4.ToolTipText = "Quick Save"
$tsBut_4.Add_Click({Save-DocumentQuickly})
#
#tsBut_5
#
$tsBut_5.ImageIndex = 7
$tsBut_5.ToolTipText = "Undo"
$tsBut_5.Add_Click({$rtbEdit.Undo()})
#
#tsBut_6
#
$tsBut_6.ImageIndex = 8
$tsBut_6.ToolTipText = "Redo"
$tsBut_6.Add_Click({$rtbEdit.Redo()})
#
#tsBut_7
#
$tsBut_7.ImageIndex = 9
$tsBut_7.ToolTipText = "Copy"
$tsBut_7.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Copy()}})
#
#tsBut_8
#
$tsBut_8.ImageIndex = 10
$tsBut_8.ToolTipText = "Paste"
$tsBut_8.Add_Click({$rtbEdit.Paste()})
#
#tsBtn_9
#
$tsBut_9.ImageIndex = 11
$tsBut_9.ToolTipText = "Cut Item"
$tsBut_9.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Cut()}})
#
#tsBut10
#
$tsBut10.ImageIndex = 12
$tsBut10.ToolTipText = "Build"
$tsBut10.Add_Click({Invoke-Builder})
#
#tsBut11
#
$tsBut11.ImageIndex = 13
$tsBut11.ToolTipText = "Build And Run"
$tsBut11.Add_Click({Start-AfterBuilding})
#
#tsLab_1
#
$tsLab_1.Text = ".NET:"
#
#tsCom_1
#
$tsCom_1.Items.AddRange(@("v2.0", "v3.5"))
$tsCom_1.SelectedItem = "v2.0"
$tsCom_1.Add_SelectedIndexChanged($tsCom_1_SelectedIndexChanged)
#
#tsLab_2
#
$tsLab_2.Text = "Type:"
#
#tsCom_2
#
$tsCom_2.Items.AddRange(@("Console", "Library", "WinForms"))
$tsCom_2.SelectedItem = "Console"
$tsCom_2.Add_SelectedIndexChanged($tsCom_2_SelectedIndexChanged)
#
#scSplit
#
$scSplit.Dock = "Fill"
$scSplit.Panel1.Controls.Add($tcSpace)
$scSplit.Panel2.Controls.Add($tcBuild)
$scSplit.Panel2MinSize = 17
$scSplit.Orientation = "Horizontal"
$scSplit.SplitterDistance = 330
#
#tcSpace
#
$tcSpace.Controls.Add($tpBasic)
$tcSpace.Dock = "Fill"
$tcSpace.ImageList = $imgList
#
#tpBasic
#
$tpBasic.Controls.Add($rtbEdit)
$tpBasic.ImageIndex = 0
$tpBasic.Text = "Untitled"
$tpBasic.UseVisualStyleBackColor = $true
#
#rtbEdit
#
$rtbEdit.AcceptsTab = $true
$rtbEdit.Dock = "Fill"
$rtbEdit.Font = New-Object Drawing.Font("Courier New", 10)
$rtbEdit.ScrollBars = "Both"
$rtbEdit.Add_Click({Write-CursorPoint})
$rtbEdit.Add_KeyUp({Write-CursorPoint})
$rtbEdit.Add_TextChanged($rtbEdit_TextChanged)
#
#tcBuild
#
$tcBuild.Controls.AddRange(@($tpError, $tpBuild, $tpRefer))
$tcBuild.Dock = "Fill"
#
#tpError
#
$tpError.Controls.Add($lstBugs)
$tpError.Text = "Errors"
$tpError.UseVisualStyleBackColor = $true
#
#lstBugs
#
$lstBugs.Columns.AddRange(@($chPoint, $chError, $chCause))
$lstBugs.Dock = "Fill"
$lstBugs.FullRowSelect = $true
$lstBugs.GridLines = $true
$lstBugs.MultiSelect = $false
$lstBugs.ShowItemToolTips = $true
$lstBugs.SmallImageList = $imgList
$lstBugs.View = "Details"
#
#chPoint
#
$chPoint.Text = "Line"
$chPoint.Width = 50
#
#chError
#
$chError.Text = "Error"
$chError.TextAlign = "Right"
$chError.Width = 65
#
#chCause
#
$chCause.Text = "Description"
$chCause.Width = 648
#
#tpBuild
#
$tpBuild.Controls.AddRange(@($lblName, $txtName, $chkIDbg, $chkIMem))
$tpBuild.Text = "Output"
$tpBuild.UseVisualStyleBackColor = $true
#
#lblName
#
$lblName.Location = New-Object Drawing.Point(8, 8)
$lblName.Size = New-Object Drawing.Size(57, 17)
$lblName.Text = "Assembly:"
#
#txtName
#
$txtName.Anchor = "Left, Top, Right"
$txtName.Location = New-Object Drawing.Point(73, 7)
$txtName.Width = 113
#
#chkIDbg
#
$chkIDbg.Checked = $true
$chkIDbg.Location = New-Object Drawing.Point(23, 29)
$chkIDbg.Text = "Include Debug Info"
$chkIDbg.Width = 120
#
#chkIMem
#
$chkIMem.Enabled = $false
$chkIMem.Location = New-Object Drawing.Point(23, 53)
$chkIMem.Text = "Build In Memory"
$chkIMem.Width = 130
$chkIMem.Add_Click($chkIMem_Click)
#
#tpRefer
#
$tpRefer.Controls.Add($lboRefs)
$tpRefer.Text = "References"
$tpRefer.UseVisualStyleBackColor = $true
#
#lboRefs
#
$lboRefs.ContextMenuStrip = $mnuRefs
$lboRefs.Dock = "Fill"
$lboRefs.SelectionMode = "One"
#
#mnuRefs
#
$mnuRefs.Items.AddRange(@($mnuIMov, $mnuICnM, $mnuIBuf, $mnuIIns))
#
#mnuIMov
#
$mnuIMov.ShortcutKeys = "Del"
$mnuIMov.Text = "Remove Item"
$mnuIMov.Add_Click({$lboRefs.Items.Remove($lboRefs.SelectedItem)})
#
#mnuICnM
#
$mnuICnM.ShortcutKeys = "Control", "M"
$mnuICnM.Text = "Copy And Move"
$mnuICnM.Add_Click($mnuICnM_Click)
#
#mnuIBuf
#
$mnuIBuf.Text = "Insert Copied..."
$mnuIBuf.Add_Click({if ($script:buf -ne $null) {$lboRefs.Items.Add($script:buf)}})
#
#mnuIIns
#
$mnuIIns.Text = "Add Reference"
$mnuIIns.Add_Click($mnuIIns_Click)
#
#imgList
#
$i_1, $i_2, $i_3, $i_4, $i_5, $i_6, $i_7, $i_8, $i_9, $i10, $i11, $i12, $i13, `
$i14, $i15, $i16 | % {$imgList.Images.Add((Get-Image $_))}
#
#sbPanel
#
$sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2, $sbPnl_3))
$sbPanel.ShowPanels = $true
$sbPanel.SizingGrip = $false
#
#sbPnl_1
#
$sbPnl_1.AutoSize = "Spring"
#
#sbPnl_2
#
$sbPnl_2.Alignment = "Center"
$sbPnl_2.AutoSize = "Contents"
#
#sbPnl_3
#
$sbPnl_3.Width = 73
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(790, 590)
$frmMain.Controls.AddRange(@($scSplit, $sbPanel, $tsTools, $mnuMain))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.MainMenuStrip = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Snippet Compiler"
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
##################################################################################################
function frmInfo_Show {
$frmInfo = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Point(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "Snippet Compiler v3.00"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2012-2013 greg zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmInfo
#
$frmInfo.AcceptButton = $btnExit
$frmInfo.CancelButton = $btnExit
$frmInfo.ClientSize = New-Object Drawing.Size(350, 110)
$frmInfo.ControlBox = $false
$frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmInfo.ShowInTaskBar = $false
$frmInfo.StartPosition = "CenterScreen"
$frmInfo.Text = "About..."
$frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()})
[void]$frmInfo.ShowDialog()
}
##################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/new-pshash.ps1
|
new-pshash.ps1
|
#this function takes nested hashtables and converts them to nested pscustomobjects
#it can also contain arrays of hashtables, and it will turn those hashtables in the arrays
#also into PScustomobjects
function new-pshash
{
[CmdletBinding()]
PARAM(
[parameter(valuefromPipeline=$true,Mandatory=$true, position = 1)]
[HashTable]$fromHashTable,
[Parameter(position = 2)]
[String]$typename
)
process {
$obj = new-object pscustomobject -Property $fromhashtable
if ($typename) { $obj.psobject.typenames.insert(0,$typename) }
foreach($prop in $obj.psobject.properties)
{
if ($prop.value -is [hashtable])
{
$obj.$($prop.name) = new-pshash $($obj.$($prop.name))
} else
{
if ($prop.value -is [Object[]])
{
$k2 = $obj.($prop.name).count
for($index = 0; $index -lt $obj.($prop.name).count; $index++)
{
if ($obj.($prop.name)[$index] -is [hashtable])
{
$obj.$($prop.name)[$index] = new-pshash $obj.$($prop.name)[$index]
}
}
}
}
}
$obj
}
}
#test object, hash of hashes of arrays of hashes
$testobject = @{
top1 = 1
#nested of nested
nested = @{ nest = 'two'
deepernest = @{ deepest = 1; whoohoo = 2 }
}
simplearray = ( 1 , 2 , 3 )
hasharray = (
@{ name = 'karl'
age = '30' },
@{ name = 'john'
age = '40' }
)
}
$a = new-pshash $testobject karlclass
$a
|
PowerShellCorpus/PoshCode/AD FSMO Roles.ps1
|
AD FSMO Roles.ps1
|
function Get-FSMORole {
<#
.SYNOPSIS
Retrieves the FSMO role holders from one or more Active Directory domains and forests.
.DESCRIPTION
Get-FSMORole uses the Get-ADDomain and Get-ADForest Active Directory cmdlets to determine
which domain controller currently holds each of the Active Directory FSMO roles.
.PARAMETER DomainName
One or more Active Directory domain names.
.EXAMPLE
Get-Content domainnames.txt | Get-FSMORole
.EXAMPLE
Get-FSMORole -DomainName domain1, domain2
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True)]
[string[]]$DomainName = $env:USERDOMAIN
)
BEGIN {
Import-Module ActiveDirectory -Cmdlet Get-ADDomain, Get-ADForest -ErrorAction SilentlyContinue
}
PROCESS {
foreach ($domain in $DomainName) {
Write-Verbose "Querying $domain"
Try {
$problem = $false
$addomain = Get-ADDomain -Identity $domain -ErrorAction Stop
} Catch { $problem = $true
Write-Warning $_.Exception.Message
}
if (-not $problem) {
$adforest = Get-ADForest -Identity (($addomain).forest)
New-Object PSObject -Property @{
InfrastructureMaster = $addomain.InfrastructureMaster
PDCEmulator = $addomain.PDCEmulator
RIDMaster = $addomain.RIDMaster
DomainNamingMaster = $adforest.DomainNamingMaster
SchemaMaster = $adforest.SchemaMaster
}
}
}
}
}
|
PowerShellCorpus/PoshCode/ff51eafa-111d-4023-b84d-e6e62b361e34.ps1
|
ff51eafa-111d-4023-b84d-e6e62b361e34.ps1
|
@@ Get-VIServer YOURSERVER
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "Power State"
$Sheet.Cells.Item(1,3) = "Description"
$Sheet.Cells.Item(1,4) = "Number of CPUs"
$Sheet.Cells.Item(1,5) = "Memory (MB)"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-VM | Select-Object -property "Name","PowerState","Description","NumCPU","MemoryMB"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$powerstate = $objItem.PowerState
If ($PowerState -eq 1) {$power = "Powerd On"}
Else {$power = "Powerd Off"}
$Sheet.Cells.Item($intRow,2) = $power
$Sheet.Cells.Item($intRow,3) = $objItem.Description
$Sheet.Cells.Item($intRow,4) = $objItem.NumCPU
$Sheet.Cells.Item($intRow,5) = $objItem.MemoryMB
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
$Sheet = $Excel.WorkSheets.Item(2)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "Free Space"
$Sheet.Cells.Item(1,3) = "Capacity"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-Datastore | Select-Object -property "Name","FreeSpaceMB","CapacityMB"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$Sheet.Cells.Item($intRow,2) = $objItem.FreeSpaceMB
$Sheet.Cells.Item($intRow,3) = $objItem.CapacityMB
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
$Sheet = $Excel.WorkSheets.Item(3)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "State"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-VMhost | Select-Object -property "Name","State"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$state = $objItem.State
If ($state -eq 0) {$status = "Connected"}
Else {$status = "Disconnected"}
$Sheet.Cells.Item($intRow,2) = $status
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
|
PowerShellCorpus/PoshCode/Install-Module.ps1
|
Install-Module.ps1
|
function Install-Module {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[Alias("PSPath")]
[String]$ModuleFilePath
, [Switch]$Global
)
## Get the Full Path of the module file
$ModuleFilePath = Resolve-Path $ModuleFilePath
## Deduce the Module Name from the file name
$ModuleName = (ls $ModuleFilePath).BaseName
## Note: This assumes that your PSModulePath is unaltered
## Or at least, that it has the LOCAL path first and GLOBAL path second
$PSModulePath = $Env:PSModulePath -split ";" | Select -Index ([int][bool]$Global)
## Make a folder for the module
$ModuleFolder = MkDir $PSModulePath\\$ModuleName -EA 0 -EV FailMkDir
## Handle the error if they asked for -Global and don't have permissions
if($FailMkDir -and @($FailMkDir)[0].CategoryInfo.Category -eq "PermissionDenied") {
if($Global) {
throw "You must be elevated to install a global module."
} else { throw @($FailMkDir)[0] }
}
## Move the script module (and make sure it ends in .psm1)
Move-Item $ModuleFilePath $ModuleFolder
## Output A ModuleInfo object
Get-Module $ModuleName -List
<#
.Synopsis
Installs a single-file (psm1 or dll) module to the ModulePath
.Description
Supports installing modules for the current user or all users (if elevated)
.Parameter ModuleFilePath
The path to the module file to be installed
.Parameter Global
If set, attempts to install the module to the all users location in Windows\\System32...
.Example
Install-Module .\\Authenticode.psm1 -Global
Description
-----------
Installs the Authenticode module to the System32\\WindowsPowerShell\\v1.0\\Modules for all users to use.
.Example
Description
-----------
Uses Get-PoshCode (from the PoshCode module) to download the Impersonation module and then fixes it's file name, and finally installs the Impersonation module for the current user.
#>
}
|
PowerShellCorpus/PoshCode/VCenter Reporting.ps1
|
VCenter Reporting.ps1
|
<# .SYNOPSIS
Collects statistics and settings for Hosts, Datastores, and Virtual Machines
from multiple VCenters.
.DESCRIPTION
Creates Excel spreadsheet report with separate worksheets for Hosts, Datastores, and
Virtual Machines by VCenter.
.PARAMETER
none
.INPUTS
.OUTPUTS
.NOTES
Name: Get-SCE_VCenterStatisticsAndSettings.ps1
Author: Steve Jarvi
DateCreated: 10 Jan 2013
.EXAMPLE
#>
#Load PowerCLI snap-ins
Add-PSSnapin Vmware.VIMAutomation.Core
Write-Host "Getting first and last days of previous months..."
#Get the first and last days for the previous months.
$startdate = (($currentdate = get-date).addmonths(-1) | % {$_.AddDays(-($_.day -1))}).ToString("d")
$enddate = (($currentdate = get-date) | % {$_.adddays(-($_.day))}).ToString("d")
Write-Host "Start date is $startdate."
Write-Host "End date is $enddate."
#VCenters list:
$VCenters = "vcenter1","vcenter2","vcenter3"
#New Excel ComObject, add workbook:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
#Loop through VCenters.
foreach ($VC in $VCenters){
#Connect to VCenter.
connect-viserver $VC
#Add worksheet named Guest by VCenter.
$currentsheet = $workbook.worksheets.add()
$currentsheet.name = "Guest - " + "$VC"
#Get virtual machines in current VCenter.
$VMs = Get-VM | ?{$_.powerstate -eq "PoweredOn"}
#Create multidimensional array sized by number of VMs, plus 1 for header, and number of columns:
$MDArray = New-Object 'object[,]' ($vms.count+1),14
$row = 1
$col = 0
#Enter column names for first row:
$MDArray[0,0] = "VM Name"
$MDArray[0,1] = "Resource Pool"
$MDArray[0,2] = "Allocated CPU"
$MDArray[0,3] = "Avg. CPU (MHz)"
$MDArray[0,4] = "Allocated Mem (MB)"
$MDArray[0,5] = "Avg. Mem Usage (%)"
$MDArray[0,6] = "Mem Usage (MB)"
$MDArray[0,7] = "VMDK(s) / Capacity / Type"
$MDArray[0,8] = "VMDK Avg. (KBps)"
$MDArray[0,9] = "Nic Type"
$MDArray[0,10] = "Network Avg. (KBps)"
$MDArray[0,11] = "Hrdwr Ver."
$MDArray[0,12] = "VMTools Ver."
$MDArray[0,13] = "VM Operating System"
$vmnumber = 1
$vmcount = $vms.count
#Loop through VMs in current VCenter:
foreach ($vm in $VMs){
#Progress update:
Write-Host "Currently building $vm's statistics into table."
Write-Host "Working $vmnumber of $vmcount VMs."
$vmnumber++
#Use PowerCLI's "Get-Stat" to pull VM statistics for the previous month.
$vmstats = Get-Stat -Entity $vm.name -Start $startdate -Finish $enddate -EA SilentlyContinue
#Set variables for statistics by type used:
$cpuuse = $vmstats | ?{$_.metricid -eq "cpu.usagemhz.average"}
$memuse = $vmstats | ?{$_.metricid -eq "mem.usage.average"}
$dskuse = $vmstats | ?{$_.metricid -eq "disk.usage.average"}
$netuse = $vmstats | ?{$_.metricid -eq "net.usage.average"}
#Build table of VMs' statistics and settings into multidimensional array:
$MDArray[$row,$col] = [string]($vm.name)
$col++
$MDArray[$row,$col] = [string]($vm.resourcepool.name)
$col++
$MDArray[$row,$col] = [string]($vm.NumCpu)
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($cpuuse | Measure-Object Value -Average).Average),2))
$col++
$MDArray[$row,$col] = [string]$vm.MemoryMB
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($memuse | Measure-Object Value -Average).Average),2))
$col++
$MDArray[$row,$col] = [string]$([math]::round((([Math]::Round((($memuse | Measure-Object Value -Average).Average),2))/100*($vm.memoryMB)),2))
$col++
$HDDSize = Get-HardDisk $vm.name | Sort Name
$HDDList = $null
foreach ($HD in $HDDSize) {
$DiskType = $HD.StorageFormat
$DiskName = $HD.Name
$DiskSize = $HD.CapacityKB / 1048576
$DiskSize = "{0:N2}" -f $DiskSize
$HDDList += "$DiskName"+"/ "+ "$DiskSize" + "/ " + "$DiskType`r`n"
}
$MDArray[$row,$col] = [string]$HDDList
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($dskuse | Measure-Object Value -Average).Average),2))
$col++
$MDArray[$row,$col] = [string]$vm.NetworkAdapters.type
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($netuse | Measure-Object Value -Average).Average),2))
$col++
$MDArray[$row,$col] = [string]$vm.version
$col++
Try {
$MDArray[$row,$col] = ($vm.ExtensionData.guest.ToolsVersion.tostring())
}
Catch {
$MDArray[$row,$col] = "Not Installed"
}
$col++
$MDArray[$row,$col] = [string]$vm.ExtensionData.guest.GuestFullName
$col = 0
$row++
}
#Create Excel interop object for aligning cell content:
[reflection.assembly]::loadWithPartialname("Microsoft.Office.Interop.Excel") | out-Null
$xlConstants = "microsoft.office.interop.excel.Constants" -as [type]
#Create range of Excel cells to match multidimensional array
#and add array to sheet:
$cells = "A1:N" + ($vms.count+1)
$sheetname = "Guest - " + "$VC"
$worksheet = $workbook.Worksheets.Item("$sheetname")
$range = $worksheet.Range("$cells")
$range.Value2 = $MDArray
#Align and autofit cells:
$range.HorizontalAlignment = $xlConstants::xlCenter
$range.VerticalAlignment = $xlConstants::xlCenter
$range.Rows.AutoFit() | Out-Null
$range.Columns.AutoFit() | Out-Null
#Get Hosts for current VCenter:
$VMHosts = Get-VMHost
#New worksheet for Hosts at current VCenter:
$currentsheet = $workbook.worksheets.add()
$currentsheet.name = "Host - " + "$VC"
#Create multidimensional array sized by number of Hosts, plus 1 for header, and number of columns:
$MDArray = New-Object 'object[,]' ($vms.count+1),7
$row = 1
$col = 0
$MDArray[0,0] = "Host Name"
$MDArray[0,1] = "CPU (MHz)"
$MDArray[0,2] = "CPU Used (MHz)"
$MDArray[0,3] = "% CPU Used"
$MDArray[0,4] = "Mem (GB)"
$MDArray[0,5] = "Host Memory(GB)"
$MDArray[0,6] = "% Mem Used"
$vmhostnum = $vmhosts.count
$count = 1
#Loop through Hosts at current VCenter:
foreach ($vmhost in $vmhosts){
$name = $vmhost.name.split(".")[0]
#Progress update:
Write-Host "Currently building $name's statistics into table."
Write-Host "Working $count of $vmhostnum Hosts."
$hoststats = Get-Stat -Entity $vmhost -Start $startdate -Finish $enddate -EA SilentlyContinue
$cpuuse = $hoststats | ?{$_.metricid -eq "cpu.usagemhz.average"}
$cpupcnt = $hoststats | ?{$_.metricid -eq "cpu.usage.average"}
$memuse = $hoststats | ?{$_.metricid -eq "mem.usage.average"}
$MDArray[$row,$col] = [string]$vmhost.name.split(".")[0]
$col++
$MDArray[$row,$col] = [string]$vmhost.cputotalmhz
$col++
$MDArray[$row,$col] = [string]$vmhost.cpuusagemhz
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($cpuuse | Measure-Object Value -Average).Average),2))
$col++
$MDArray[$row,$col] = [string]([math]::Round((($vmhost.MemoryUsageMB)/1024),2))
$col++
$MDArray[$row,$col] = [string]([math]::Round((($vmhost.MemoryTotalMB)/1024),2))
$col++
$MDArray[$row,$col] = [string]([Math]::Round((($memuse | Measure-Object Value -Average).Average),2))
$col = 0
$row++
$count++
}
[reflection.assembly]::loadWithPartialname("Microsoft.Office.Interop.Excel") | out-Null
$xlConstants = "microsoft.office.interop.excel.Constants" -as [type]
$cells = "A1:G" + ($vmhosts.count+1)
$sheetname = "Host - " + "$VC"
$worksheet = $workbook.Worksheets.Item("$sheetname")
$range = $worksheet.Range("$cells")
$range.Value2 = $MDArray
$range.HorizontalAlignment = $xlConstants::xlCenter
$range.VerticalAlignment = $xlConstants::xlCenter
$range.Rows.AutoFit() | Out-Null
$range.Columns.AutoFit() | Out-Null
$datastores = get-datastore
$currentsheet = $workbook.worksheets.add()
$currentsheet.name = "Datastores - " + "$VC"
$MDArray = New-Object 'object[,]' ($datastores.count+1),4
$row = 1
$col = 0
$MDArray[0,0] = "Datastore"
$MDArray[0,1] = "Total Space (GB)"
$MDArray[0,2] = "Free Space (GB)"
$MDArray[0,3] = "% Free"
foreach ($DS in $datastores){
$MDArray[$row,$col] = [string]$DS.name
$col++
$MDArray[$row,$col] = [string]([math]::round((($DS.capacitymb)/1024),2))
$col++
$MDArray[$row,$col] = [string]([math]::round((($DS.freespacemb)/1024),2))
$col++
$MDArray[$row,$col] = [string]([math]::round(($DS.freespacemb/$DS.capacitymb),2)*100) + " %"
$col = 0
$row++
}
[reflection.assembly]::loadWithPartialname("Microsoft.Office.Interop.Excel") | out-Null
$xlConstants = "microsoft.office.interop.excel.Constants" -as [type]
$cells = "A1:D" + ($datastores.count+1)
$sheetname = "Datastores - " + "$VC"
$worksheet = $workbook.Worksheets.Item("$sheetname")
$range = $worksheet.Range("$cells")
$range.Value2 = $MDArray
$range.HorizontalAlignment = $xlConstants::xlCenter
$range.VerticalAlignment = $xlConstants::xlCenter
$range.Rows.AutoFit() | Out-Null
$range.Columns.AutoFit() | Out-Null
Disconnect-VIServer $VC -Confirm:$false
}
|
PowerShellCorpus/PoshCode/Get-VMCreationReport.ps1
|
Get-VMCreationReport.ps1
|
# Report VMs created per month.
# Before you begin run Alan's "Who Created that VM?" script.
# http://www.virtu-al.net/2010/02/23/who-created-that-vm/
function Get-VMCreationReport {
Get-VM | Group {
if ($_.CustomFields["CreatedOn"] -as [DateTime] -ne $null) {
"{0:Y}" -f [DateTime]$_.CustomFields["CreatedOn"]
} else {
"Unknown"
}
}
}
# To create a CSV of this stuff try:
# Get-VMCreationReport | select Count, Name, { $_.Group -as [String] } |
# export-csv c:\\report.csv -NoTypeInformation
|
PowerShellCorpus/PoshCode/Get-Constructor_2.ps1
|
Get-Constructor_2.ps1
|
function Get-Constructor {
PARAM( [Type]$type )
$type.GetConstructors() |
Format-Table @{
l="$($type.Name) Constructors"
e={ "New-Object $($type.FullName) $(($_.GetParameters() | ForEach { "[{0}] `${1}" -f $($_.ToString() -split " ") }) -Join ", ")" }
}
}
Set-Alias gctor Get-Constructor
|
PowerShellCorpus/PoshCode/VMtoolsUpgrade_1.ps1
|
VMtoolsUpgrade_1.ps1
|
#####################################################################
# TIAA-CREF VMWare Standard Scripts - PowerCLI
#
# Purpose: "Check and upgrade Tools during power cycling"
# Author: David Chung
# Support: IT Infrastructure
# Docs: N/A
#
# Instruction: 1. Create CSV file with list of servers
# 2. Execute script from PowerCLI
# 3. Enter virtual server name
#
#####################################################################
$viserver = read-host "Please enter vCenter Server:"
connect-viserver $viserver
$vms = Import-Csv c:\\server.csv
foreach ($vm.name in $vms)
{
Write-Host $vm.name " - Disabling VMTools Update at Power Cycle"
$vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfig.Tools.ToolsUpgradePolicy = "Manual"
Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)}
}
|
PowerShellCorpus/PoshCode/43a28a15-5023-4feb-a71f-abe95aa0f2a6.ps1
|
43a28a15-5023-4feb-a71f-abe95aa0f2a6.ps1
|
param
(
[Parameter(
Mandatory=$true,
Position = 0,
ValueFromPipeline=$true,
HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log."
)]
[ValidateNotNullOrEmpty()]
[string]
$Path,
[Parameter(
Position = 1,
HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar."
)]
[ValidateNotNullOrEmpty()]
[string]
$Delimiter = " ",
[Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")]
[Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]
$Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8
)
begin
{
$fieldNames = @()
$output = New-Object Object
Add-Member -InputObject $output -MemberType NoteProperty -Name "DateTime" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ClientHost" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "UserName" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Service" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Machine" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerIp" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerPort" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Method" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ScriptPath" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "QueryString" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceStatus" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceSubStatus" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Win32Status" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesSent" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesRecived" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ProcessingTime" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "ProtocolVersion" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Host" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "UserAgent" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Cookie" -Value $null
Add-Member -InputObject $output -MemberType NoteProperty -Name "Referer" -Value $null
}
process
{
foreach($line in Get-Content -Path $Path -Encoding $Encoding)
{
if($line.StartsWith("#Fields: "))
{
$fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter));
}
elseif(-not $line.StartsWith("#"))
{
$fieldValues = @($line.Split($Delimiter));
for($i = 0; $i -lt $fieldValues.Length; $i++)
{
$name = $fieldNames[$i]
$value = $fieldValues[$i]
switch($name)
{
"date" { $output.DateTime = [DateTime]::Parse($value) }
"time" { $output.DateTime += [TimeSpan]::Parse($value) }
"c-ip" { $output.ClientHost = [System.Net.IPAddress]::Parse($value) }
"cs-username" { $output.UserName = if($value -eq '-') { $null } else { $value } }
"s-sitename" { $output.Service = $value }
"s-computername" { $output.Machine = $value }
"s-ip" { $output.ServerIp = [System.Net.IPAddress]::Parse($value) }
"s-port" { $output.ServerPort = [int]$value }
"cs-method" { $output.Method = $value }
"cs-uri-stem" { $output.ScriptPath = [System.Web.HttpUtility]::UrlDecode($value) }
"cs-uri-query" { $output.QueryString = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } }
"sc-status" { $output.ServiceStatus = [int]$value }
"sc-substatus" { $output.ServiceSubStatus = [int]$value }
"sc-win32-status" { $output.Win32Status = [BitConverter]::ToInt32([BitConverter]::GetBytes([UInt32]($value)), 0) }
"sc-bytes" { $output.BytesSent = [UInt64]$value }
"cs-bytes" { $output.BytesRecived = [UInt64]$value }
"time-taken" { $output.ProcessingTime = [int]$value }
"cs-version" { $output.ProtocolVersion = $value }
"cs-host" { $output.Host = if($value -eq '-') { $null } else { $value } }
"cs(User-Agent)" { $output.UserAgent = if($value -eq '-') { $null } else { $value } }
"cs(Cookie)" { $output.Cookie = if($value -eq '-') { $null } else { $value } }
"cs(Referer)" { $output.Referer = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } }
}
}
Write-Output $output
}
}
}
|
PowerShellCorpus/PoshCode/Hack ESX MOTD.ps1
|
Hack ESX MOTD.ps1
|
$screen = @"
You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
@"
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/Invoke-Member.ps1
|
Invoke-Member.ps1
|
##############################################################################\n##\n## Invoke-Member\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\nEnables easy access to methods and properties of pipeline objects.\n\n.EXAMPLE\n\nPS >"Hello","World" | .\\Invoke-Member Length\n5\n5\n\n.EXAMPLE\n\nPS >"Hello","World" | .\\Invoke-Member -m ToUpper\nHELLO\nWORLD\n\n.EXAMPLE\n\nPS >"Hello","World" | .\\Invoke-Member Replace l w\nHewwo\nWorwd\n\n#>\n\n[CmdletBinding(DefaultParameterSetName= "Member")]\nparam(\n\n ## A switch parameter to identify the requested member as a method.\n ## Only required for methods that take no arguments.\n [Parameter(ParameterSetName = "Method")]\n [Alias("M","Me")]\n [switch] $Method,\n\n ## The name of the member to retrieve\n [Parameter(ParameterSetName = "Method", Position = 0)]\n [Parameter(ParameterSetName = "Member", Position = 0)]\n [string] $Member,\n\n ## Arguments for the method, if any\n [Parameter(\n ParameterSetName = "Method", Position = 1,\n Mandatory = $false, ValueFromRemainingArguments = $true)]\n [object[]] $ArgumentList = @(),\n\n ## The object from which to retrieve the member\n [Parameter(ValueFromPipeline = $true)]\n $InputObject\n )\n\nbegin\n{\n Set-StrictMode -Version Latest\n}\n\nprocess\n{\n ## If the user specified a method, invoke it\n ## with any required arguments.\n if($psCmdlet.ParameterSetName -eq "Method")\n {\n $inputObject.$member.Invoke(@($argumentList))\n }\n ## Otherwise, retrieve the property\n else\n {\n $inputObject.$member\n }\n}
|
PowerShellCorpus/PoshCode/Print Cluster Comparison.ps1
|
Print Cluster Comparison.ps1
|
<#################################################################
# Print Cluster - Printer Comparison #
# #
# This script does a comparison between two print clusters and #
# looks for differences between the source and destination. It #
# has been tested with printer clusters running Server 2003 and #
# 2008. The prompts will ask for the cluster name and then the #
# resource identifier for the cluster resource. You'll have to #
# get those yourself or code something in to loop through the #
# registry and guess. #
# #
# Note: The script will not report extra printers on the #
# destination. #
# #
# -Alex Stone 7/25/2011 #
#################################################################>
#Set initial variables and collect source server information as well as destination cluster identifier.
#Turns the code interpreter into a syntax Nazi
Set-StrictMode -Version Latest
#Source/Destination Servers and cluster reg keys.
$sserver = Read-Host "Please enter the source server name and press enter:"
$shive = Read-Host "Please enter the cluster resource hive of the source server:"
$dserver = Read-Host "Please enter the destination server name and press enter:"
$dhive = Read-Host "Please enter the cluster resource hive of the destination server:"
#Open remote registries and collect Local Machine key.
$sbase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $sserver)
$dbase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $dserver)
#Store "Printer" subkey for each.
$sprinters = $sbase.OpenSubKey("Cluster").OpenSubKey("Resources").OpenSubKey($shive).OpenSubKey("Parameters").OpenSubKey("Printers")
$dprinters = $dbase.OpenSubKey("Cluster").OpenSubKey("Resources").OpenSubKey($dhive).OpenSubKey("Parameters").OpenSubKey("Printers")
#Outer loop to run through printers on the source.
foreach ($sprnname in $sprinters.GetSubKeyNames())
{
#Open each printer subkey and then work store the attributes to be used in the inner loop.
$sprinter = $sprinters.OpenSubKey($sprnname)
$cname = $sprinter.GetValue("Name")
$cdriver = $sprinter.GetValue("Printer Driver")
$cshare = $sprinter.GetValue("Share Name")
$clocation = $sprinter.GetValue("Location")
$cproc = $sprinter.GetValue("Print Processor")
$cport = $sprinter.GetValue("Port")
#Set initial name match to key the rest of the comparisons
$namematch = $false
#Inner loop to work through the destination printers.
foreach ($dprnname in $dprinters.GetSubKeyNames())
{
#Open each printer subkey and then work store the attributes to be used in the inner loop.
$dprinter = $dprinters.OpenSubKey($dprnname)
$dname = $dprinter.GetValue("Name")
$ddriver = $dprinter.GetValue("Printer Driver")
$dshare = $dprinter.GetValue("Share Name")
$dlocation = $dprinter.GetValue("Location")
$dproc = $dprinter.GetValue("Print Processor")
$dport = $dprinter.GetValue("Port")
#Comparison to determine printer name match.
if ($cname -eq $dname)
{
#Set the name match flag to true.
$namematch = $true
#Set initial boolean values to false.
$drivermatch = $false
$sharematch = $false
$locmatch = $false
$procmatch = $false
$portmatch = $false
#Because of name match execute remaining comparisons.
#Driver comparison - This is a very basic comparison that counts the total number of words in the drivers names from each server.
#It then determines which is longer and loops through that one and looks for matches with the other. It creates a running count of the matches.
#If the number of matches divided into the total number of words results in a ratio of .7 or higher, it considers it a match. The ratio can be adjusted below.
$cdrivera = $cdriver.split(" ")
$ddrivera = $ddriver.split(" ")
$drvtot = $cdrivera.count + $ddrivera.count
$drvscore = 0
if ($cdrivera.count -ge $ddrivera.count) {$longdrive = $cdrivera } else {$longdrive = $ddrivera}
if ($cdrivera.count -ge $ddrivera.count) {$shortdrive = $ddrivera } else {$shortdrive = $cdrivera}
for ($i=0; $i -le $longdrive.count; $i++)
{
for ($c=0; $c -le $shortdrive.count; $c++)
{
if ($longdrive[$i] -match $shortdrive[$c]) {$drvscore++}
}
}
if (($drvscore*2)/($drvtot) -ge .7) {$drivermatch = $true}
#Share Name Comparison
if ($cshare -eq $dshare) {$sharematch = $true}
#Location Comparison
if ($clocation -eq $dlocation) {$locmatch = $true}
#Processor Comparison
if ($cproc -eq $dproc) {$procmatch = $true}
#Port Match
if ($cport -match "IP_") {$cport = $cport.Substring(3,$cport.Length-3)}
if ($dport -match "IP_") {$dport = $dport.Substring(3,$dport.Length-3)}
if ($cport -eq $dport) {$portmatch = $true}
}
}
#Output line. If we didn't find a matching printer let the user know otherwise present the comparison results.
if ($namematch -eq $false) {$cname + " is missing from the destination!"} else {$cname+" Driver: "+$drivermatch+" Share: "+$sharematch+" Location: "+$locmatch+" Processor: "+$procmatch+" Port: "+$portmatch}
#Reset name match flag.
$namematch = $false
}
|
PowerShellCorpus/PoshCode/Force 64 bit for script.ps1
|
Force 64 bit for script.ps1
|
# am I running in 32 bit shell?
if ($pshome -like "*syswow64*") {
write-warning "Restarting script under 64 bit powershell"
# relaunch this script under 64 bit shell
# if you want powershell 2.0, add -version 2 *before* -file parameter
& (join-path ($pshome -replace "syswow64", "sysnative") powershell.exe) -file `
(join-path $psscriptroot $myinvocation.mycommand) @args
# exit 32 bit script
exit
}
# start of script for 64 bit powershell
write-warning "hello from $pshome"
write-warning "My original arguments $args"
|
PowerShellCorpus/PoshCode/Get-ChildItemRecurse_1.ps1
|
Get-ChildItemRecurse_1.ps1
|
function Get-ChildItemRecurse {
<#
.Synopsis
Does a recursive search through a PSDrive up to n levels.
.Description
Does a recursive directory search, allowing the user to specify the number of
levels to search.
.Parameter path
The starting path.
.Parameter fileglob
(optional) the search string for matching files
.Parameter levels
The numer of levels to recurse.
.Example
# Get up to three levels of files
PS> Get-ChildItemRecurse *.* -levels 3
.Notes
NAME: Get-ChildItemRecurse
AUTHOR: tojo2000
#Requires -Version 2.0
#>
Param([Parameter(Mandatory = $true,
ValueFromPipeLine = $false,
Position = 0)]
[string]$path = '.',
[Parameter(Mandatory = $false,
Position = 1,
ValueFromPipeLine = $false)]
[string]$fileglob = '*.*',
[Parameter(Mandatory = $false,
Position = 2,
ValueFromPipeLine = $false)]
[int]$levels = 0)
if (-not (Test-Path $path)) {
Write-Error "$path is an invalid path."
return $false
}
$files = @(Get-ChildItem $path)
foreach ($file in $files) {
if ($file -like $fileglob) {
Write-Output $file
}
@@ if ($file.GetType().FullName -eq 'System.IO.DirectoryInfo') {
if ($file.PSIsContainer) {
if ($levels -gt 0) {
Get-ChildItemRecurse -path $file.FullName `
-fileglob $fileglob `
-levels ($levels - 1)
}
}
}
}
|
PowerShellCorpus/PoshCode/IniFile Functions _1.0.ps1
|
IniFile Functions _1.0.ps1
|
function Get-IniSection($inifile,$section)
{
$sections = select-string "^\\[.*\\]" $inifile
if(!$section) {
return $sections | %{$_.Line.Trim("[]")}
}
$start = 0
switch($sections){
{$_.Line.Trim() -eq "[$section]"}{
$start = $_.LineNumber -1
}
default {
if($start){
return (gc $inifile)[($start)..($start + ($_.LineNumber-2 - $start))]
}
}
}
$lines = gc $inifile
return $lines[$start..($lines.length-1)]
}
function Get-IniValue($inifile,$section,$name)
{
$section = Get-IniSection $inifile $section
($section | Select-String "^\\s*$name\\s*=").Line.Split("=",2)[1]
}
function Set-IniValue($inifile,$section,$name,$value)
{
$lines = gc $inifile
$sections = select-string "^\\[.*\\]" $inifile
$start,$end = 0,0
for($l=0; $l -lt $sections.Count; ++$l){
if($sections[$l].Line.Trim() -eq "[$section]") {
$start = $sections[$l].LineNumber
if($l+1 -ge $sections.Count) {
$end = $lines.length-1;
} else {
$end = $sections[$l+1].LineNumber -2
}
}
}
if($start -and $end) {
$done = $false
for($l=$start;$l -le $end;++$l){
if( $lines[$l] -match "^\\s*$name\\s*=" ) {
$lines[$l] = "{0} = {1}" -f $name, $value
$done = $true
break;
}
}
if(!$done) {
$output = $lines[0..$start]
$output += "{0} = {1}" -f $name, $value
$output += $lines[($start+1)..($lines.Length-1)]
$lines = $output
}
}
Set-Content $inifile $lines
}
##
## This is a ... different way of doing it,
## which will be faster if you need to read lots of values
#### HOWEVER ####
## I don't recommend using Set-IniFile, because it will loose any comments etc
##
function Get-IniFile {
param([string]$inifile=$(Throw "You must specify the name of an ini file!"))
$INI = @{}
$s,$k,$v = $null
foreach($line in (gc $inifile | ? {$_[0] -ne ";" -and $_.Trim().Length -gt 0})) {
$k,$v = $line.Split("=",2)
if($v -eq $null) {
$s = $k.Trim("[]")
$INI[$s] = @{}
} else {
$INI[$s][$k.Trim()] = $v.Trim()
}
}
return $INI
}
function Set-IniFile {
param([HashTable]$ini,[string]$inifile=$(Throw "You must specify the name of an ini file!"))
[string[]]$inistring = @()
foreach($section in $ini.Keys) {
#Add-Content $inifile ("[{0}]" -f $section)
$inistring += ("`n[{0}]" -f $section)
foreach($key in $ini[$section].Keys) {
$inistring += ("{0} = {1}" -f $key, $ini[$section][$key])
}
}
# make the write be atomic ...
Set-Content $inifile $inistring
}
|
PowerShellCorpus/PoshCode/Invoke-BinaryProcess.ps1
|
Invoke-BinaryProcess.ps1
|
##############################################################################\n##\n## Invoke-BinaryProcess\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\nInvokes a process that emits or consumes binary data.\n\n.EXAMPLE\n\nInvoke-BinaryProcess binaryProcess.exe -RedirectOutput |\n Invoke-BinaryProcess binaryProcess.exe -RedirectInput\n\n#>\n\nparam(\n ## The name of the process to invoke\n [string] $ProcessName,\n\n ## Specifies that input to the process should be treated as\n ## binary\n [Alias("Input")]\n [switch] $RedirectInput,\n\n ## Specifies that the output of the process should be treated\n ## as binary\n [Alias("Output")]\n [switch] $RedirectOutput,\n\n ## Specifies the arguments for the process\n [string] $ArgumentList\n)\n\nSet-StrictMode -Version Latest\n\n## Prepare to invoke the process\n$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo\n$processStartInfo.FileName = (Get-Command $processname).Definition\n$processStartInfo.WorkingDirectory = (Get-Location).Path\nif($argumentList) { $processStartInfo.Arguments = $argumentList }\n$processStartInfo.UseShellExecute = $false\n\n## Always redirect the input and output of the process.\n## Sometimes we will capture it as binary, other times we will\n## just treat it as strings.\n$processStartInfo.RedirectStandardOutput = $true\n$processStartInfo.RedirectStandardInput = $true\n\n$process = [System.Diagnostics.Process]::Start($processStartInfo)\n\n## If we've been asked to redirect the input, treat it as bytes.\n## Otherwise, write any input to the process as strings.\nif($redirectInput)\n{\n $inputBytes = @($input)\n $process.StandardInput.BaseStream.Write($inputBytes, 0, $inputBytes.Count)\n $process.StandardInput.Close()\n}\nelse\n{\n $input | % { $process.StandardInput.WriteLine($_) }\n $process.StandardInput.Close()\n}\n\n## If we've been asked to redirect the output, treat it as bytes.\n## Otherwise, read any input from the process as strings.\nif($redirectOutput)\n{\n $byteRead = -1\n do\n {\n $byteRead = $process.StandardOutput.BaseStream.ReadByte()\n if($byteRead -ge 0) { $byteRead }\n } while($byteRead -ge 0)\n}\nelse\n{\n $process.StandardOutput.ReadToEnd()\n}
|
PowerShellCorpus/PoshCode/Fast vMotion with GUI.ps1
|
Fast vMotion with GUI.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.3.0
# Generated On: 7/21/2009 2:07 PM
# Generated By: afokkema
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$button4 = New-Object System.Windows.Forms.Button
$linkLabel1 = New-Object System.Windows.Forms.LinkLabel
$checkedListBox4 = New-Object System.Windows.Forms.CheckedListBox
$checkedListBox3 = New-Object System.Windows.Forms.CheckedListBox
$label5 = New-Object System.Windows.Forms.Label
$label4 = New-Object System.Windows.Forms.Label
$button3 = New-Object System.Windows.Forms.Button
$checkedListBox2 = New-Object System.Windows.Forms.CheckedListBox
$button2 = New-Object System.Windows.Forms.Button
$label3 = New-Object System.Windows.Forms.Label
$checkedListBox1 = New-Object System.Windows.Forms.CheckedListBox
$label2 = New-Object System.Windows.Forms.Label
$label1 = New-Object System.Windows.Forms.Label
$textBox1 = New-Object System.Windows.Forms.TextBox
$button1 = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$button3_OnClick=
{
#TODO: Place custom script here
foreach($vmname in $checkedListBox1.CheckedItems)
{
$checkedListBox3.Items.Add($vmname)
}
foreach($vmhostname in $checkedListBox2.CheckedItems)
{
$checkedListBox4.Items.Add($vmhostname)
}
[bool]$selected = $true
for ($i = 0; $i -lt $checkedListBox3.Items.Count; $i++) {
$checkedListBox3.SetItemChecked( $i, $selected )
}
[bool]$selected = $true
for ($i = 0; $i -lt $checkedListBox4.Items.Count; $i++) {
$checkedListBox4.SetItemChecked( $i, $selected )
}
}
$button2_OnClick=
{
#TODO: Place custom script here
foreach($vm in $checkedListBox3.CheckedItems)
{
Get-VM -Name $vm | Move-VM -Destination (Get-VMHost $checkedListBox4.CheckedItems)
}
# MessageBox
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.MessageBox]::Show("Selected VM's are migrated")
$checkedListBox3.Items.Clear()
$checkedListBox4.Items.Clear()
[bool]$selected = $false
for ($i = 0; $i -lt $checkedListBox1.Items.Count; $i++) {
$checkedListBox1.SetItemChecked( $i, $selected )
}
[bool]$selected = $false
for ($i = 0; $i -lt $checkedListBox2.Items.Count; $i++) {
$checkedListBox2.SetItemChecked( $i, $selected )
}
}
$button4_OnClick=
{
#TODO: Place custom script here
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
#Close Form
$form1.close()
}
$handler_button1_Click=
{
#TODO: Place custom script here
if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $textBox1.Text
#Get VM's
Get-VM | % { [void]$checkedListBox1.items.add($_.Name) }
#Get VMHost (ESX Servers)
Get-VMHost | % { [void]$checkedListBox2.items.add($_.Name) }
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
}
#----------------------------------------------
#region Generated Form Code
$form1.Text = 'Fast vMotion'
$form1.Name = 'form1'
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 507
$System_Drawing_Size.Height = 595
$form1.ClientSize = $System_Drawing_Size
$button4.TabIndex = 19
$button4.Name = 'button4'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button4.Size = $System_Drawing_Size
$button4.UseVisualStyleBackColor = $True
$button4.Text = 'Close..'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 418
$System_Drawing_Point.Y = 554
$button4.Location = $System_Drawing_Point
$button4.DataBindings.DefaultDataSourceUpdateMode = 0
$button4.add_Click($button4_OnClick)
$form1.Controls.Add($button4)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 84
$System_Drawing_Size.Height = 23
$linkLabel1.Size = $System_Drawing_Size
$linkLabel1.TabIndex = 17
$linkLabel1.Text = 'www.ict-freak.nl'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 411
$System_Drawing_Point.Y = 15
$linkLabel1.Location = $System_Drawing_Point
$linkLabel1.TabStop = $True
$linkLabel1.DataBindings.DefaultDataSourceUpdateMode = 0
$linkLabel1.Name = 'linkLabel1'
$form1.Controls.Add($linkLabel1)
$checkedListBox4.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 232
$System_Drawing_Size.Height = 94
$checkedListBox4.Size = $System_Drawing_Size
$checkedListBox4.DataBindings.DefaultDataSourceUpdateMode = 0
$checkedListBox4.Name = 'checkedListBox4'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 261
$System_Drawing_Point.Y = 413
$checkedListBox4.Location = $System_Drawing_Point
$checkedListBox4.Sorted = $True
$checkedListBox4.TabIndex = 16
$form1.Controls.Add($checkedListBox4)
$checkedListBox3.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 231
$System_Drawing_Size.Height = 94
$checkedListBox3.Size = $System_Drawing_Size
$checkedListBox3.DataBindings.DefaultDataSourceUpdateMode = 0
$checkedListBox3.Name = 'checkedListBox3'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 413
$checkedListBox3.Location = $System_Drawing_Point
$checkedListBox3.Sorted = $True
$checkedListBox3.TabIndex = 15
$form1.Controls.Add($checkedListBox3)
$label5.TabIndex = 13
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$label5.Size = $System_Drawing_Size
$label5.Text = 'Selected ESX Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 324
$System_Drawing_Point.Y = 398
$label5.Location = $System_Drawing_Point
$label5.DataBindings.DefaultDataSourceUpdateMode = 0
$label5.Name = 'label5'
$form1.Controls.Add($label5)
$label4.TabIndex = 11
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$label4.Size = $System_Drawing_Size
$label4.Text = 'Selected VM''s'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 398
$label4.Location = $System_Drawing_Point
$label4.DataBindings.DefaultDataSourceUpdateMode = 0
$label4.Name = 'label4'
$form1.Controls.Add($label4)
$button3.TabIndex = 9
$button3.Name = 'button3'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button3.Size = $System_Drawing_Size
$button3.UseVisualStyleBackColor = $True
$button3.Text = 'Select..'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 525
$button3.Location = $System_Drawing_Point
$button3.DataBindings.DefaultDataSourceUpdateMode = 0
$button3.add_Click($button3_OnClick)
$form1.Controls.Add($button3)
$checkedListBox2.FormattingEnabled = $True
$checkedListBox2.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 232
$System_Drawing_Size.Height = 304
$checkedListBox2.Size = $System_Drawing_Size
$checkedListBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$checkedListBox2.Name = 'checkedListBox2'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 261
$System_Drawing_Point.Y = 85
$checkedListBox2.Location = $System_Drawing_Point
$checkedListBox2.Sorted = $True
$checkedListBox2.TabIndex = 8
$form1.Controls.Add($checkedListBox2)
$button2.TabIndex = 7
$button2.Name = 'button2'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 74
$System_Drawing_Size.Height = 23
$button2.Size = $System_Drawing_Size
$button2.UseVisualStyleBackColor = $True
$button2.Text = 'VMotion..'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 554
$button2.Location = $System_Drawing_Point
$button2.DataBindings.DefaultDataSourceUpdateMode = 0
$button2.add_Click($button2_OnClick)
$form1.Controls.Add($button2)
$label3.TabIndex = 6
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 78
$System_Drawing_Size.Height = 23
$label3.Size = $System_Drawing_Size
$label3.Text = 'Select VM''s'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 73
$System_Drawing_Point.Y = 59
$label3.Location = $System_Drawing_Point
$label3.DataBindings.DefaultDataSourceUpdateMode = 0
$label3.Name = 'label3'
$form1.Controls.Add($label3)
$checkedListBox1.FormattingEnabled = $True
$checkedListBox1.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 232
$System_Drawing_Size.Height = 304
$checkedListBox1.Size = $System_Drawing_Size
$checkedListBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$checkedListBox1.Name = 'checkedListBox1'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 85
$checkedListBox1.Location = $System_Drawing_Point
$checkedListBox1.MultiColumn = $false
$checkedListBox1.TabIndex = 5
$checkedListBox1.Sorted = $True
$form1.Controls.Add($checkedListBox1)
$label2.TabIndex = 4
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 88
$System_Drawing_Size.Height = 351
$label2.Size = $System_Drawing_Size
$label2.Text = 'Destination:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 324
$System_Drawing_Point.Y = 59
$label2.Location = $System_Drawing_Point
$label2.DataBindings.DefaultDataSourceUpdateMode = 0
$label2.Name = 'label2'
$form1.Controls.Add($label2)
$label1.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 87
$System_Drawing_Size.Height = 23
$label1.Size = $System_Drawing_Size
$label1.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 12
$label1.Location = $System_Drawing_Point
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$label1.Name = 'label1'
$form1.Controls.Add($label1)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 152
$System_Drawing_Size.Height = 20
$textBox1.Size = $System_Drawing_Size
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$textBox1.Name = 'textBox1'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 106
$System_Drawing_Point.Y = 12
$textBox1.Location = $System_Drawing_Point
$textBox1.TabIndex = 1
$form1.Controls.Add($textBox1)
$button1.TabIndex = 0
$button1.Name = 'button1'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = 'Login..'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 264
$System_Drawing_Point.Y = 12
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($handler_button1_Click)
$form1.Controls.Add($button1)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/5c778a26-8386-434c-8824-00c38db7c470.ps1
|
5c778a26-8386-434c-8824-00c38db7c470.ps1
|
param([Parameter(Mandatory=$true)][string]$Path,[Parameter(Mandatory=$true)][string]$Destination)
Get-ChildItem -Path $Path | Where-Object { !$_.PSIsContainer } | foreach {
$Target = Join-Path -Path $Destination -ChildPath (Split-Path -Leaf $_)
if ( Test-Path -Path $Target -PathType Leaf ) {
$PrevTargetBkup=([System.IO.Path]::ChangeExtension($Target, ".old"))
if ( Test-Path -Path $PrevTargetBkup -PathType Leaf ) {
Remove-Item -Force -Path $PrevTargetBkup
}
Rename-Item -Path $Target -NewName ([System.IO.Path]::ChangeExtension($Target, ".old"))
}
Copy-Item -Path $_ -Destination $Target
}
|
PowerShellCorpus/PoshCode/Test-EmptyFolder.ps1
|
Test-EmptyFolder.ps1
|
function Test-EmptyFolder {
<#
.SYNOPSIS
Tests for empty folders.
.DESCRIPTION
The Test-EmptyFolder function tests if a specified folder is empty by checking if it
contains files or folders. The function returns the folder path and a boolean value for empty.
.PARAMETER Path
Specifies the path of the folder to test.
.EXAMPLE
Test-EmptyFolder
Returns if the current path is an empty folder.
.EXAMPLE
Test-EmptyFolder C:\\temp
Returns if the path C:\\temp is an empty folder.
.EXAMPLE
dir $env:TEMP -Recurse | Test-EmptyFolder
Gets a directory listing of the TEMP folder including recursive items and
passes each object into the pipeline testing for empty folders.
.INPUTS
System.String
.OUTPUTS
PSObject
.NOTES
Name: Test-EmptyFolder
Author: Rich Kusak
Created: 2011-09-25
LastEdit: 2011-10-03 10:44
Version: 1.0.0.0
.LINK
http://msdn.microsoft.com/en-us/library/kx74h1k4.aspx
#>
[CmdletBinding()]
param (
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
if (Test-Path -LiteralPath $_) {$true} else {
throw "The argument '$_' does not specify an existing path."
}
})]
[Alias('FullName')]
[string]$Path = '.'
)
begin {
$properties = 'Path','IsEmpty'
} # begin
process {
if (Test-Path -LiteralPath $Path -PathType Leaf) {
return Write-Verbose "The path '$Path' is a file. Only folders are tested."
}
try {
$folder = Get-Item $Path -Force -ErrorAction Stop
} catch {
return Write-Error $_
}
try {
$isEmpty = ($folder.GetFiles().Count -eq 0) -and ($folder.GetDirectories().Count -eq 0)
} catch {
return Write-Error $_.Exception.InnerException.Message
}
New-Object PSObject -Property @{
'Path' = $folder.FullName
'IsEmpty' = $isEmpty
} | Select $properties
} # process
} # function Test-EmptyFolder
|
PowerShellCorpus/PoshCode/Backup-EventLogs.ps1
|
Backup-EventLogs.ps1
|
Function Backup-EventLogs
{
<#
.SYNOPSIS
Backup Eventlogs from remote computer
.DESCRIPTION
This function backs up all logs on a Windows computer that have events written in them. This
log is stored as a .csv file in the current directory, where the filename is the ComputerName+
Logname+Date+Time the backup was created.
.PARAMETER ComputerName
The NetBIOS name of the computer to connect to.
.EXAMPLE
Backup-EventLogs -ComputerName dc1
.NOTES
May need to be a user with rights to access various logs, such as security on remote computer.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Backup-EventLogs
#>
Param
(
[string]$ComputerName
)
Begin
{
$EventLogs = Get-WinEvent -ListLog * -ComputerName $ComputerName
}
Process
{
Foreach ($EventLog in $EventLogs)
{
If ($EventLog.RecordCount -gt 0)
{
$BackupFilename = "$($ComputerName)-$($EventLog.LogName)-"+(Get-Date -format "yyy-MM-dd HH-MM-ss").ToString()+".csv"
Get-WinEvent -LogName $EventLog.LogName -ComputerName $ComputerName |Export-Csv -Path ".\\$($BackupFilename)"
}
}
}
End
{
Return $?
}
}
|
PowerShellCorpus/PoshCode/ConvertTo-Hex_10.ps1
|
ConvertTo-Hex_10.ps1
|
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx
param ( [string]$SidString )
# Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring
# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength
#Convert to bytes
$sid.GetBinaryForm( $sidBytes, 0 )
# Iterate through bytes, converting each to the hexidecimal equivalent
$hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") }
# Join the hex array into a single string for output
$hexArr -join ''
|
PowerShellCorpus/PoshCode/Get-PerformanceCounter.ps1
|
Get-PerformanceCounter.ps1
|
function Get-PerformanceCounter {
<#
.Synopsis
Gets one or more Performance Counter objects.
.Description
This function will use .NET to retrieve a single Counter or all counters
for a particular Instance and Category.
.Parameter category
The Performance Counter Category.
.Parameter instance
(optional) If the Category is Multi-Instance, the Instance chosen. For
example, if you are querying the LogicalDisk category, the Instance would
be the drive letter. When querying a Multi-Instance Category, this
option is mandatory.
.Parameter counter
(optional) The name of the Counter. If you specify this option, only one
counter will be returned.
.Parameter computer
(optional) The target computer.
.Example
# Get all Counters for Category LogicalDisk and Instance C:
Get-PerformanceCounter LogicalDisk C:
.Example
# Get only the Current Disk Queue Length counter
Get-PerformanceCounter LogicalDisk C: 'Current Disk Queue Length'
.Notes
NAME: Get-PerformanceCounter
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
.Links
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(v=VS.100).aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecountercategory.aspx
#>
param([Parameter(Mandatory = $true, Position = 0)]
[string]$category,
[Parameter(Mandatory = $false, Position = 1)]
[string]$instance,
[Parameter(Mandatory = $false, Position = 2)]
[string]$counter,
[Parameter(Mandatory = $false, Position = 3)]
[string]$computer)
try{
if ($computer) {
$perf = New-Object System.Diagnostics.PerformanceCounterCategory `
$category $computer
} else {
$perf = New-Object System.Diagnostics.PerformanceCounterCategory `
$category
}
} catch {
Write-Host 'ERROR: Failed to create new Category object'
Write-Host $Error[0].ToString()
return
}
if (-not ($instance -or $counter)) {
try {
return $perf.GetCounters()
} catch {
Write-Host 'Unable to list counters for that Category.'
Write-Host $Error[0].ToString()
return
}
}
if (-not $counter) {
try {
return $perf.GetCounters($instance)
} catch {
Write-Host 'Unable to list counters for that Category and Instance.'
Write-Host $Error[0].ToString()
return
}
}
if (-not $computer) {
$computer = '.'
}
if ($instance) {
try {
return New-Object System.Diagnostics.PerformanceCounter($category,
$counter,
$instance,
$computer)
} catch {
Write-Host 'Unable to retrieve that Counter.'
Write-Host $Error[0].ToString()
return
}
} else {
try {
return New-Object System.Diagnostics.PerformanceCounter($category,
$counter,
'',
$computer)
} catch {
Write-Host 'Unable to retrieve that Counter.'
Write-Host $Error[0].ToString()
return
}
}
}
|
PowerShellCorpus/PoshCode/Get-ProxyAddress_1.ps1
|
Get-ProxyAddress_1.ps1
|
Param (
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
HelpMessage="Enter SMTP address to search for in Active-Directory."
)]
[string]$objSMTP
)
Function Get-ProxyAddresses ([string]$Address){
$objAD = $null
$objAD = Get-QADObject -LdapFilter "(proxyAddresses=*$Address*)" -IncludeAllProperties -SizeLimit 0 -ErrorAction SilentlyContinue
Write-Output $objAD
}#Close Function
#Validate Quest PSSnapin is loaded
Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
#Run Function to search AD for SMTP address
$Results = $null
$Results = Get-ProxyAddresses -Address $objSMTP | Select-Object Name,DisplayName,ObjectClass,Email,AccountisDisabled,AccountisLockedOut,MailNickName,LegacyExchangeDN -ErrorAction SilentlyContinue
IF($Results -eq $null){
Write-Host ""
Write-Host "No Object Found with .attribute[proxyAddress] containing $objSMTP."}
Else{$Results | Format-List *}
#End
|
PowerShellCorpus/PoshCode/Set-Prompt_1.ps1
|
Set-Prompt_1.ps1
|
param([Alias("copy","demo")][Switch]$Pasteable)
# This should go OUTSIDE the prompt function, it doesn't need re-evaluation
# We're going to calculate a prefix for the window title
# Our basic title is "PoSh - C:\\Your\\Path\\Here" showing the current path
if(!$global:WindowTitlePrefix) {
# But if you're running "elevated" on vista, we want to show that ...
if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) )
{
$global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain} (ADMIN)"
} else {
$global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain}"
}
}
if($Pasteable) {
function global:prompt {
Write-host "<#PS " -NoNewLine -fore gray
# FIRST, make a note if there was an error in the previous command
$err = !$?
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
# Also, put the path in the title ... (don't restrict this to the FileSystem
$Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# my New-Script and Get-PerformanceHistory functions use history IDs
# So, put the ID of the command in, so we can get/invoke-history easier
# eg: "r 4" will re-run the command that has [4]: in the prompt
$global:lastCommandId = (Get-History -count 1).Id
$global:nextCommandId = $global:lastCommandId + 1
# Output prompt string
# If there's an error, set the prompt foreground to "Red", otherwise, "Yellow"
if($err) { $fg = "Red" } else { $fg = "Yellow" }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}${nextCommandId}${Stack}]" -NoNewLine -Fore $fg
Write-host " #>" -NoNewLine -fore gray
return " "
}
} else {
function global:prompt {
# FIRST, make a note if there was an error in the previous command
$err = !$?
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
# Also, put the path in the title ... (don't restrict this to the FileSystem
$Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# my New-Script and Get-PerformanceHistory functions use history IDs
# So, put the ID of the command in, so we can get/invoke-history easier
# eg: "r 4" will re-run the command that has [4]: in the prompt
$global:lastCommandId = (Get-History -count 1).Id
$global:nextCommandId = $global:lastCommandId + 1
# Output prompt string
# If there's an error, set the prompt foreground to "Red", otherwise, "Yellow"
if($err) { $fg = "Red" } else { $fg = "Yellow" }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}${nextCommandId}${Stack}]:" -NoNewLine -Fore $fg
return " "
}
}
# SIG # Begin signature block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cBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUAYxB1OGv
# +gSNgLzV07nPJLNuFvQwDQYJKoZIhvcNAQEBBQAEggEAFM65fpcjQcDiRslwg9hl
# Mf8sVPS5hOxSFkOH6SuOXOFggJTnpqH7Oiz9/67y7ndGhmb4h22WsW3sWIS29zGt
# ZchjJk8mKcTzZB8foS0xJNLbYu8yGzDRdItUN3Hq1bvK+1B8RIcpY7NfTshQmsiD
# ZWzhBM82vaGp03cXzzLrAhiKDIcFI43P2LQbjz5rtcl3aJHiK0y9pYq5v9Fk76jk
# B5oNwvbWi9TLt8GEUYp48zRXLYP/Nnr3HJLcA4BHzfmAjopZGw54Oprr87LqXxv3
# OrArwdsdjw6HOMk2NW0txZm1f0wR3O6Tt2KZjWzB0Ru7GjHkKj618OVebDvON755
# lw==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/ASPX Mailbox (2 of 6).ps1
|
ASPX Mailbox (2 of 6).ps1
|
public partial class MailboxTasks : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append("this.value = 'Please wait...';");
sbValid.Append("this.disabled = true;");
sbValid.Append("document.all.btnNext.disabled = true;");
sbValid.Append(ClientScript.GetPostBackEventReference(this.btnNext,""));
sbValid.Append(";");
this.btnNext.Attributes.Add("onclick", sbValid.ToString());
if (IsPostBack)
{
Server.Transfer("MailboxConfirm.aspx", true);
}
}
}
|
PowerShellCorpus/PoshCode/ProgressMessage .ps1
|
ProgressMessage .ps1
|
#Generated Form Function
function ProgressMessage {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 29/01/2013 11:01 AM
# Generated By: admstpierdj
########################################################################
param( #parameters with default values assigned
[String]$LabelText="Message",
[String]$FormTitle="Form Title",
# [int]$nSecondsToWait=3,
# [int]$Buttons = 0,
[int]$FontSize = 12,
[String]$ICOpath=""
)
If ( Get-Variable -Name ProgMsgForm1 -Scope Global -ErrorAction SilentlyContinue ) {
$ProgMsgForm1.close() #Kill previous Progress Message to prevent lost handles
}
If ($LabelText -eq ""){
Return
}
$LabelText="`r`n "+$LabelText+" `r`n " #add space around the message
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion
#region Generated Form Objects
$global:ProgMsgForm1 = New-Object System.Windows.Forms.Form
$ProgMsgLabel1 = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#region Generated Form Code
$ProgMsgForm1.AutoSize = $True
$ProgMsgForm1.AutoSizeMode = 0
# $System_Drawing_Size = New-Object System.Drawing.Size
#$System_Drawing_Size.Height = 113
#$System_Drawing_Size.Width = 255
# $ProgMsgForm1.ClientSize = $System_Drawing_Size
$ProgMsgForm1.DataBindings.DefaultDataSourceUpdateMode = 0
#add Icon to dialog
If ( ($ICOpath -ne "") -and (Test-Path "$ICOpath") ) {
Try { #If the ICO file is NFG, ignore and move on
$ProgMsgForm1.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon("$ICOpath")
} catch { } #use default ICO
}
$ProgMsgForm1.Name = "form1"
$ProgMsgForm1.StartPosition = 1 #Center of the Screen
$ProgMsgForm1.Text = "$FormTitle"
# $ProgMsgLabel1.AutoEllipsis = $True #handle text that goes beyond width of Label control
$ProgMsgLabel1.AutoSize = $True
$ProgMsgLabel1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
# $System_Drawing_Point.X = 10
# $System_Drawing_Point.Y = 10
$ProgMsgLabel1.Location = $System_Drawing_Point
$ProgMsgLabel1.Name = "label1"
# $System_Drawing_Size = New-Object System.Drawing.Size
## $System_Drawing_Size.Height = 13
## $System_Drawing_Size.Width = 35
# $ProgMsgLabel1.Size = $System_Drawing_Size
$ProgMsgLabel1.TabIndex = 0
$ProgMsgLabel1.Text = "$LabelText"
$ProgMsgLabel1.TextAlign = 2
$ProgMsgLabel1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",$FontSize,1,3,1)
$ProgMsgForm1.Controls.Add($ProgMsgLabel1)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $ProgMsgForm1.WindowState
#Init the OnLoad event to correct the initial state of the form
$ProgMsgForm1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
#$ProgMsgForm1.ShowDialog()| Out-Null #ShowDialog waits until it is closed
$ProgMsgForm1.Show() #show forms and keep on going
$ProgMsgForm1.activate() #Make sure its on top
return $ProgMsgForm1 #need to do this to kill form later (now optional b/c $ProgMsgForm1 is made global)
} #End Function
#Call the Function
$ProgressObj=ProgressMessage "this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display this is text to display" "My title"
Echo "doing other stuff"
Start-Sleep -Second 2
Echo "doing other stuff"
Start-Sleep -Second 2
#$ProgressObj.Close() #if you forget to close previous, it stays on the screen and you cant kill it!
$ProgressObj=ProgressMessage "LEt's see if this works too"
Echo "doing other stuff"
Start-Sleep -Second 3
Echo "doing other stuff"
Start-Sleep -Second 2
#$ProgressObj.Close()
ProgressMessage "" #close progress message
|
PowerShellCorpus/PoshCode/Computer Inventory_2.ps1
|
Computer Inventory_2.ps1
|
# ========================================================
#
# Script Information
#
# Title: Remote Computer Inventory
# Author: Assaf Miron
# Originally created: 21/06/2008
# Original path: Computer-Inventory.PS1
# Description: Collects Remote Computer Data Using WMI and Registry Access
# Outputs all information to a Data Grid Form and to a CSV Log File
#
# ========================================================
#region Constructor
# Import Assembly
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
# Log File where the results are Saved
$LogFile = "C:\\Monitoring\\Test-Monitor.csv"
# Check to see if the Log File Directory exists
If((Test-Path ($LogFile.Substring(0,$logFile.LastIndexof("\\")))) -eq $False)
{
# Create The Directory
New-Item ($LogFile.Substring(0,$logFile.LastIndexof("\\"))) -Type Directory
}
#endregion
#region Form Creation
#~~< Form1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Form1 = New-Object System.Windows.Forms.Form
$Form1.AutoSize = $TRUE
$Form1.ClientSize = New-Object System.Drawing.Size(522, 404)
$Form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$Form1.Text = "Computer Inventory"
#~~< Panel1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Panel1 = new-object System.Windows.Forms.Panel
$Panel1.Dock = [System.Windows.Forms.DockStyle]::Fill
$Panel1.Location = new-object System.Drawing.Point(0, 24)
$Panel1.Size = new-object System.Drawing.Size(522, 380)
$Panel1.TabIndex = 20
$Panel1.Text = ""
#~~< btnRun >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnRun = New-Object System.Windows.Forms.Button
$btnRun.Enabled = $FALSE
$btnRun.Location = New-Object System.Drawing.Point(431, 30)
$btnRun.Size = New-Object System.Drawing.Size(75, 23)
$btnRun.TabIndex = 2
$btnRun.Text = "Run"
$btnRun.UseVisualStyleBackColor = $TRUE
$btnRun.add_Click({ RunScript($btnRun) })
#~~< Label1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Label1 = New-Object System.Windows.Forms.Label
$Label1.AutoSize = $False#$TRUE
$Label1.Location = New-Object System.Drawing.Point(12, 31)
$Label1.Size = New-Object System.Drawing.Size(163, 13)
$Label1.TabIndex = 15
$Label1.Text = "File containing Computer Names"
#~~< TextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$TextBox1 = New-Object System.Windows.Forms.TextBox
$TextBox1.Location = New-Object System.Drawing.Point(177, 30)
$TextBox1.Size = New-Object System.Drawing.Size(161, 20)
$TextBox1.TabIndex = 0
$TextBox1.Text = ""
#~~< btnBrowse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnBrowse = New-Object System.Windows.Forms.Button
$btnBrowse.Location = New-Object System.Drawing.Point(347, 30)
$btnBrowse.Size = New-Object System.Drawing.Size(75, 23)
$btnBrowse.TabIndex = 1
$btnBrowse.Text = "Browse"
$btnBrowse.UseVisualStyleBackColor = $TRUE
$btnBrowse.add_Click({ BrowseFile($btnBrowse) })
#~~< DataGridView1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$DataGridView1 = new-object System.Windows.Forms.DataGridView
$DataGridView1.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$DataGridView1.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize
$DataGridView1.Location = New-Object System.Drawing.Point(12, 59)
$DataGridView1.Size = New-Object System.Drawing.Size(497, 280)
$DataGridView1.TabIndex = 4
$DataGridView1.ClipboardCopyMode = [System.Windows.Forms.DataGridViewClipboardCopyMode]::Disable
$DataGridView1.Text = ""
#~~< ProgressBar1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ProgressBar1 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar1.Anchor = ([System.Windows.Forms.AnchorStyles] ([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right ))
$ProgressBar1.Location = New-Object System.Drawing.Point(12, 345)
$ProgressBar1.Size = New-Object System.Drawing.Size(410, 23)
$ProgressBar1.TabIndex = 5
$ProgressBar1.Text = ""
#~~< btnExit >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnExit = New-Object System.Windows.Forms.Button
$btnExit.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right))
$btnExit.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$btnExit.Location = New-Object System.Drawing.Point(431, 345)
$btnExit.Size = New-Object System.Drawing.Size(78, 23)
$btnExit.TabIndex = 3
$btnExit.Text = "Exit"
$btnExit.UseVisualStyleBackColor = $TRUE
$btnExit.add_Click({ CloseForm($btnExit) })
#~~< MenuStrip1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$MenuStrip1 = new-object System.Windows.Forms.MenuStrip
$MenuStrip1.Location = new-object System.Drawing.Point(0, 0)
$MenuStrip1.Size = new-object System.Drawing.Size(292, 24)
$MenuStrip1.TabIndex = 6
$MenuStrip1.Text = "MenuStrip1"
#~~< FileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$FileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$FileToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$FileToolStripMenuItem.Text = "File"
#~~< OpenLogFileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$OpenLogFileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$OpenLogFileToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$OpenLogFileToolStripMenuItem.Text = "Open Log File"
$OpenLogFileToolStripMenuItem.add_Click({Open-file($OpenLogFileToolStripMenuItem)})
#~~< ExitToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ExitToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$ExitToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$ExitToolStripMenuItem.Text = "Exit"
$ExitToolStripMenuItem.add_Click({CloseForm($ExitToolStripMenuItem)})
$FileToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($OpenLogFileToolStripMenuItem, $ExitToolStripMenuItem)))
#~~< HelpToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$HelpToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$HelpToolStripMenuItem.Size = new-object System.Drawing.Size(40, 20)
$HelpToolStripMenuItem.Text = "Help"
#~~< AboutToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$AboutToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$AboutToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$AboutToolStripMenuItem.Text = "About"
$AboutToolStripMenuItem.add_Click({Show-About($AboutToolStripMenuItem)})
#~~< HowToToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$HowToToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$HowToToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$HowToToolStripMenuItem.Text = "How To?"
$HowToToolStripMenuItem.add_Click({Show-HowTo($HowToToolStripMenuItem)})
$HelpToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($AboutToolStripMenuItem, $HowToToolStripMenuItem)))
$MenuStrip1.Items.AddRange([System.Windows.Forms.ToolStripItem[]](@($FileToolStripMenuItem, $HelpToolStripMenuItem)))
$Panel1.Controls.Add($MenuStrip1)
$Panel1.Controls.Add($btnRun)
$Panel1.Controls.Add($Label1)
$Panel1.Controls.Add($TextBox1)
$Panel1.Controls.Add($btnBrowse)
$Panel1.Controls.Add($ProgressBar1)
$Panel1.Controls.Add($btnExit)
$Panel1.Controls.Add($DataGridView1)
$Panel1.Controls.Add($Menu)
$Form1.Controls.Add($Panel1)
#~~< Ping1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Ping1 = New-Object System.Net.NetworkInformation.Ping
#~~< OpenFileDialog1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$OpenFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog1.Filter = "Text Files|*.txt|CSV Files|*.csv|All Files|*.*"
$OpenFileDialog1.InitialDirectory = "C:"
$OpenFileDialog1.Title = "Open Computers File"
#~~< objNotifyIcon >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
# Assign an Icon and Icon Type For the NotifyIcon Object
$objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people15.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
#endregion
#region Functions
function out-DataTable
# Function Creates a New Data Table that will be set as the Data Source of the Data Grid View
# Thanks to /\\/\\o\\/\\/ http:\\\\thePowerShellGuy.com
{
$dt = New-Object Data.datatable
$First = $TRUE
foreach ($item in $Input)
{
$DR = $DT.NewRow()
$Item.PsObject.get_properties() | foreach {
if ($first)
{
$Col = New-Object Data.DataColumn
$Col.ColumnName = $_.Name.ToString()
$DT.Columns.Add($Col) }
if ($_.value -eq $null)
{
$DR.Item($_.Name) = "[empty]"
}
elseif ($_.IsArray) {
$DR.Item($_.Name) = [string]::Join($_.value, ";")
}
else
{
$DR.Item($_.Name) = $_.value
}
}
$DT.Rows.Add($DR)
$First = $FALSE
}
return @(, ( $dt ))
}
function Join-Data
# Function Joins arrays and Strings to a Single Object with Members
# I Used the same principle of the Out-DataTable and converted it to Join Objects into one
# Using the Add-Member cmdlet. the Function writes to a predefiend object named $DataObject
{
param($objName="") # This parameter is used for objects that don't have member other than Length like Strings
foreach ($item in $Input)
{
$Item.PsObject.get_properties() | foreach{
if ($_.value -eq $null)
{
$DataObject | Add-Member noteproperty $_.Name "[empty]"
}
elseif ($_.IsArray) {
$DataObject | Add-Member noteproperty $_.Name [string]::Join($_.value, ";")
}
elseif ($objName -ne "") {
$DataObject | Add-Member noteproperty $objName $Item
}
else
{
$DataObject | Add-Member noteproperty $_.Name $_.value -Force
}
}
}
return @(,$DataObject)
}
function Get-Reg {
# Function Connects to a remote computer Registry using the Parameters it recievs
param(
$Hive,
$Key,
$Value,
$RemoteComputer="." # If not enterd Local Computer is Selected
)
# Connect to Remote Computer Registry
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $RemoteComputer)
# Open Remote Sub Key
$regKey= $reg.OpenSubKey($Key)
if($regKey.ValueCount -gt 0) # check if there are Values
{$regKey.GetValue($Value)} # Return Value
}
function Get-WMIItem {
# Function Retreives a specific Item from a remote computer's WMI
param(
$Class,
$RemoteComputer=".", # If not enterd Local Computer is Selected
$Item,
$Query="", # If not enterd an empty WMI SQL Query is Entered
$Filter="" # If not enterd an empty Filter is Entered
)
if ($Query -eq "") # No Specific WMI SQL Query
{
# Execute WMI Query, Return only the Requsted Items
gwmi -Class $Class -ComputerName $RemoteComputer -Filter $Filter -Property $Item | Select $Item
}
else # User Entered a WMI SQL Query
{gwmi -ComputerName $RemoteComputer -Query $Query | select $Item}
}
function Show-NotifyIcon {
# Function Controls the Notification Icon
# Changes its Title and Text
param(
$Title,
$Text
)
# Change Notify Icon Title
$objNotifyIcon.BalloonTipTitle = $Title
# Change Notify Icon Text
$objNotifyIcon.BalloonTipText = $Text
# Show Notify Icon for 10 Secs
$objNotifyIcon.Visible = $TRUE
$objNotifyIcon.ShowBalloonTip(10000)
}
#endregion
#region Event Loop
function Main
# Main Function, Runs the Form
{
[System.Windows.Forms.Application]::EnableVisualStyles()
[System.Windows.Forms.Application]::Run($Form1)
}
#endregion
#region Event Handlers
function BrowseFile($object)
# Function for Running the OpenFileDialog
# Used when Clicking on the Browse Button
{
$OpenFileDialog1.showdialog()
$TextBox1.Text = $OpenFileDialog1.FileName
$btnRun.Enabled = $TRUE
}
function Open-File( $object ){
# Function Open the Log File
if(Test-Path $LogFile){
Invoke-Item $LogFile
}
}
function Show-PopUp
# Function for Showing Custom Pop up Forms
{
param(
$PopupTitle,
$PopupText
)
#~~< PopupForm >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupForm = New-Object System.Windows.Forms.Form
$PopupForm.ClientSize = New-Object System.Drawing.Size(381, 356)
$PopupForm.ControlBox = $false
$PopupForm.ShowInTaskbar = $false
$PopupForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterParent
$PopupForm.Text = $PopupTitle
#~~< PopupColse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupColse = New-Object System.Windows.Forms.Button
$PopupColse.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$PopupColse.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$PopupColse.Location = New-Object System.Drawing.Point(137, 321)
$PopupColse.Size = New-Object System.Drawing.Size(104, 23)
$PopupColse.TabIndex = 0
$PopupColse.Text = "Close"
$PopupColse.UseVisualStyleBackColor = $true
$PopupForm.AcceptButton = $PopupColse
$PopupForm.CancelButton = $PopupColse
#~~< PopupHeader >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupHeader = New-Object System.Windows.Forms.Label
$PopupHeader.Font = New-Object System.Drawing.Font("Calibri", 15.75, ([System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Italic)), [System.Drawing.GraphicsUnit]::Point, ([System.Byte](0)))
$PopupHeader.Location = New-Object System.Drawing.Point(137, 9)
$PopupHeader.Size = New-Object System.Drawing.Size(104, 23)
$PopupHeader.TabIndex = 2
$PopupHeader.Text = $PopupTitle
$PopupHeader.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
#~~< PopUpTextArea >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopUpTextArea = New-Object System.Windows.Forms.Label
$PopUpTextArea.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$PopUpTextArea.Location = New-Object System.Drawing.Point(12, 15)
$PopUpTextArea.Size = New-Object System.Drawing.Size(357, 265)
$PopUpTextArea.TabIndex = 1
$PopUpTextArea.Text = $PopupText
$PopUpTextArea.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$PopupForm.Controls.Add($PopupHeader)
$PopupForm.Controls.Add($PopUpTextArea)
$PopupForm.Controls.Add($PopupColse)
# Show Form
$PopupForm.Add_Shown({$PopupForm.Activate()})
[void]$PopupForm.showdialog()
}
function Show-About( $object ){
# Function Opens the About Page
$AboutText = @("
Script Title: Remote Computer Inventory`n
Script Author: Assaf Miron`n
Script Description: Collects Remote Computer Data Using WMI and Registry Access Outputs all information to a Data Grid Form and to a CSV Log File.`n
Log File Name: $LogFile")
Show-Popup -PopupTitle "About" -PopupText $AboutText
}
function Show-HowTo( $object ){
# Function Opens the Help Page
$HowToText = @("
1. Click on the Browse Button and select a TXT or a CSV File Containing Computer Names`n
2. After File is Selected click on the Run Button.`n
3. You will see a Notify Icon with the Coresponding Text.`n
4. The Script has begon collecting Remote Computer Inventory!`n
`nWhen The script is Done you will see a Popup Message and all data will be presented in the DataGrid.`n
** Because Poweshell works only in MTA mode there is no Option Copying the Data off the DataGrid...`n
5. All Data will be Exported to a Log File Located Here: $LogFile")
Show-Popup -PopupTitle "How To?" -PopupText $HowToText
}
function CloseForm($object)
# Function End the Program
{
$Form1.Close()
}
function RunScript($object)
# Function Runs the Program and starts collecting data
{
# Create an Array of Computers Enterd in the Input File
$arrComputers = Get-Content -path $textBox1.Text -encoding UTF8
# Create an Array to Keep all Computers Objects
$AllComputers = @()
# Init the Progress bar to it's Maximum Value
if(($arrComputers -is [array]) -eq $FALSE) { $ProgressBar1.Maximum = 1 }
else { $ProgressBar1.Maximum = $arrComputers.Count }
$ProgressBar1.Minimum = 0
$ProgressBar1.Value = 0
$ProgressBar1.Step = 1 # Define the Progress bar Step value
# Scan all Computers in the Array $arrComputers
foreach ($strComputer in $arrComputers)
{
# Uses the Ping Command to check if the Computer is Alive
if($Ping1.Send($strComputer).Status -eq "Success"){
Show-NotifyIcon -Title "Retriving Computer Information" -Text "Scanning $strComputer For Hardware Data"
# Collect Computer Details from Win32_computersystem Using WMI
$ComputerDet = Get-WMIItem -Class "Win32_computersystem" -RemoteComputer $strComputer -Item Caption,Domain,SystemType,Manufacturer,Model,NumberOfProcessors,TotalPhysicalMemory,UserName
if($ComputerDet.Caption.Length -gt 1) # Check to See if Any data was Collected at all
{
#region Total Memory Formating
# Check Total Physical Memory Size and Format it acourdingly
if($ComputerDet.TotalPhysicalMemory -ge 1GB){
$ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1GB).Tostring("# GB")} # Format to GB
else {$ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1MB).Tostring("# MB")} # Format to MB
#endregion
#region CPU Name
# Collect CPU Name Using WMI
$CPUName = Get-WMIItem -Class "Win32_Processor" -RemoteComputer $strComputer -Item Name
# CPU Names Can Contain Multiple Values, in Order to Insert Them into the DataGridView I Divde them to String with ";" Seperators
$arrCPUNames = @()
foreach($CPU in $CPUName){
$arrCPUNames = $CPU.Name.Trim()+";"+$arrCPUNames # the Sting of the CPU Name has White Space in The Begining - Trim It
}
#endregion
#region Operating System Data
# Collect Operating System and Service Pack Information Usin WMI
$OS = Get-WMIItem -Class "win32_operatingsystem" -RemoteComputer $strComputer -Item Caption,csdversion
#endregion
#region Chassis Type
# Collect Machine Chassis Using WMI
$ChassisType = Get-WMIItem -Class Win32_SystemEnclosure -RemoteComputer $strComputer -Item ChassisTypes
# Select Machine Chassis
switch ($ChassisType.ChassisTypes) {
1 {$ChassisType = "Other"}
2 {$ChassisType = "Unknown"}
3 {$ChassisType = "Desktop"}
4 {$ChassisType = "Low Profile Desktop"}
5 {$ChassisType = "Pizza Box"}
6 {$ChassisType = "Mini Tower"}
7 {$ChassisType = "Tower"}
8 {$ChassisType = "Portable"}
9 {$ChassisType = "Laptop"}
10 {$ChassisType = "Notebook"}
11 {$ChassisType = "Handheld"}
12 {$ChassisType = "Docking Station"}
13 {$ChassisType = "All-in-One"}
14 {$ChassisType = "Sub-Notebook"}
15 {$ChassisType = "Space Saving"}
16 {$ChassisType = "Lunch Box"}
17 {$ChassisType = "Main System Chassis"}
18 {$ChassisType = "Expansion Chassis"}
19 {$ChassisType = "Sub-Chassis"}
20 {$ChassisType = "Bus Expansion Chassis"}
21 {$ChassisType = "Peripheral Chassis"}
22 {$ChassisType = "Storage Chassis"}
23 {$ChassisType = "Rack Mount Chassis"}
24 {$ChassisType = "Sealed- PC"}
default {$ChassisType = "Unknown"}
}
#endregion
#region Automatic Updates
# Collect the Automatic Updates Options Using Registry Access
$AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "AUOptions"
# Collect the Automatic Updates Install Day Using Registry Access
$AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallDay"
# Collect the Automatic Updates Install Time Using Registry Access
$AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallTime"
if($AUOptions -eq $null){ # Automatic Updates is defined in Group Policy
$AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "AUOptions"
$AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallDay"
$AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallTime"
}
switch ($AUOptions){ # Check Wich Automatic Update Option is Selected
1 {$AUClient = "Automatic Updates is Turnd off."}
2 {$AUClient = "Notify for download and notify for install "}
3 {$AUClient = "Auto download and notify for install "}
4 {
switch ($AUDay) # Check on What day the Automatic Update Installs
{
0 {$InstDay = "Every Day"}
1 {$InstDay = "Sunday"}
2 {$InstDay = "Monday"}
3 {$InstDay = "Tuesday"}
4 {$InstDay = "Wensday"}
5 {$InstDay = "Thursday"}
6 {$InstDay = "Friday"}
7 {$InstDay = "Saturday"}
}
# Check on What time the Automatic Update Installs
if ($AUTime -le 12) { $AUTime = $AUTime.ToString() + " AM" } else { $AUTime = ($AUTime -12) + " PM" }
$AUClient = "Auto download and schedule the install - "+$InstDay+" "+$AUTime}
Defualt {"Automatic Updates is not Set."} # No setting Collected
}
#endregion
#region Computer Total Health
# Collect Avialable Memory with WMI
$AvialableMem = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Memory" -RemoteComputer $strComputer -Item "AvailableMBytes"
# Collect Disk Queue,Queue Length, Processor time Data Using WMI
$DiskQueue = Get-WMIItem -Class "Win32_PerfFormattedData_PerfDisk_LogicalDisk" -RemoteComputer $strComputer -Item CurrentDiskQueueLength
$QueueLength = Get-WMIItem -Class "Win32_PerfFormattedData_PerfNet_ServerWorkQueues" -RemoteComputer $strComputer -Item QueueLength
$Processor = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Processor" -RemoteComputer $strComputer -Item PercentProcessorTime
$intHealth = 0 # integer for Collecting Computer Total Health
# Using the Avialable Memory to Check Computer Totla Health
if($AvialableMem.AvailableMBytes -lt 4) { $intHealth += 1; $strHealth += "Low Free Memory;" }
# Using Current Disk Queue Length to Check Computer Total Health
if($DiskQueue.CurrentDiskQueueLength -gt 2) { $intHealth += 1; $strHealth += "High Disk Queue;" }
# Using Queue Length to Check Computer Total Health
if($QueueLength.QueueLength -gt 4) { $intHealth += 1; $strHealth += "Long Disk Queue;" }
# Using Processor Time(%) to Check Computer Total Health
if($Processor.PercentProcessorTime -gt 90) { $intHealth += 1; $strHealth += "Processor Usage Over 90%;" }
# If the integer is Bigger than 1 so the computer is Unhealthy, Describe Computer Problems
# Else The Computer is Healthy
if($intHealth -gt 1) { $ComputerTotalHealth = "UnHealthy, " + $strHealth } else { $ComputerTotalHealth = "Healthy" }
#endregion
#region Avialable Memory Formating
# Format Avialable Memory MB
$AvialableMem.AvailableMBytes = $AvialableMem.AvailableMBytes.ToString("# MB")
#endregion
#region Disk Drive Info
# Collect Disk Drive Information Using WMI
$DriveInfo = Get-WMIItem -Class "Win32_LogicalDisk" -RemoteComputer $strComputer -Item Caption,Size,FreeSpace
# Format Every Drive Size and Free Space
foreach($DRSize in $DriveInfo)
{ # Check Object Size and Format Acourdingly
if($DRSize.Size -ge 1GB){
$DRSize.Size = ($DRSize.Size/1GB).ToString("# GB") } # Format to GB
else { $DRSize.Size = ($DRSize.Size/1MB).ToString("# MB") } # Format to MB
if($DRSize.FreeSpace -ge 1GB){
$DRSize.FreeSpace = ($DRSize.FreeSpace/1GB).ToString("# GB") } # Format to GB
else { $DRSize.FreeSpace = ($DRSize.FreeSpace/1MB).ToString("# MB") } # Format to MB
}
# Disk Drives Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrDiskDrives = @()
$arrDiskSize = @()
$arrDiskFreeSpace = @()
foreach($Drive in $DriveInfo){
$arrDiskDrives = $Drive.Caption+";"+$arrDiskDrives
$arrDiskSize = $Drive.Size+";"+$arrDiskSize
$arrDiskFreeSpace = $Drive.FreeSpace+";"+$arrDiskFreeSpace
}
#endregion
#region IP Addresses
# Collect IPAddresses Using WMI, Filter only Enabled IPs
$IPAddress = Get-WmiItem -Class "Win32_NetworkAdapterConfiguration" -Filter "IPEnabled = True" -RemoteComputer $strComputer -Item IPAddress
# IPAddress Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrIPAddress = @()
foreach($IP in $IPAddress){
$arrIPAddress = $IP.IPAddress[0]+";"+$arrIPAddress
}
#endregion
#region Time Zone
# Collect Time Zone Information Using WMI
$TimeZone = Get-WMIItem -Class "Win32_TimeZone" -RemoteComputer $strComputer -Item Bias,StandardName
$TimeZone.Bias = $TimeZone.Bias/60
#endregion
#region System Restore Status
# Collect System Restore Information Using Remote Registry
$SysRestoreStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SystemRestore" -Value "DisableSR"
if ($SysRestoreStatus -eq 0) { $SysRestoreStatus = "Enabled" } else { $SysRestoreStatus = "Disabled" }
#endregion
#region Offline Files Status
# Collect Offline Files Information Using Remote Registry
$OfflineFolStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\NetCache" -Value "Enabled"
if ($OfflineFolStatus -eq 1) { $OfflineFolStatus = "Enabled" } else { $OfflineFolStatus = "Disabled" }
#endregion
#region Printers
# Collect Printers Information Using WMI
$Printers = Get-WMIItem -Class "Win32_Printer" -RemoteComputer $strComputer -Item Name,PortName,Caption
# Printers Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrPrinters = @()
foreach($Printer in $Printers){
$arrPrinters = $Printer.Name+"("+$Printer.PortName+");"+$arrPrinters
}
#endregion
#region BIOS Serial Number
# Collect BIOS Serial Number Using WMI
$BIOSSN = Get-WMIItem -Class "Win32_Bios" -RemoteComputer $strComputer -Item SerialNumber
#endregion
#region Network Drives
# Collect Network Drives Using WMI
$NetDrives = Get-WMIItem -Query "Select * From Win32_LogicalDisk Where DriveType = 4" -RemoteComputer $strComputer -Item DeviceID,ProviderName
# Network Drives Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrNetDrives = @()
foreach($NetDrive in $NetDrives){
$arrNetDrives = $NetDrive.DeviceID+"("+$NetDrive.ProviderName+");"+$arrNetDrives
}
#endregion
#region Anti-Virus Client Data
# Collect Anti-Virus Info Using Remote Registry
$AVParentServer = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Intel\\LANDesk\\VirusProtect6\\CurrentVersion" -Value "Parent"
# Read the Anti-Virus Virus Definition File and Format it to an actual Date
$VirusDefFile = "C:\\Program Files\\Common Files\\Symantec Shared\\VirusDefs\\definfo.dat"
If(Test-Path $VirusDefFile){
$AVDefs = Get-Content $VirusDefFile | where { $_ -match "CurDefs" }
$AVDefs = $AVDefs.Substring(8)
$AVDefs = [datetime]($AVDefs.Substring(5,1) + "/" + $AVDefs.Substring(6,2) + "/" + $AVDefs.substring(0,4))
}
Else { $AVDefs = "" }
#endregion
#region Operating Systems Hotfixes
# Collect all Hotfix Information Using WMI
$HotFixes = Get-WMIItem -Class "Win32_QuickFixEngineering" -RemoteComputer $strComputer -Item Description,HotFixID,ServicePackInEffect
# HotFixes Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrHotFixes = @()
foreach($Fix in $HotFixes){
if($Fix.Description -eq ""){
if($Fix.HotFixID -eq "File 1"){ $arrHotFixes = $Fix.ServicePackInEffect+";"+$arrHotFixes }
else { $arrHotFixes =$Fix.HotFixID+";"+$arrHotFixes }
}
else { $arrHotFixes = $Fix.Description+";"+$arrHotFixes }
}
#endRegion
#region Remote Desktop Status
# Collect Remote Desktop Protocol Status Using Remote Registry
$RDPStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fAllowToGetHelp"
if($RDPStatus -eq 0) {$RDPStatus = "Enabled" } else {$RDPStatus = "Disabled" }
#endregion
#region Remote Assistance Status
# Collect Remote Assistance Status Using Remote Registry
$RAStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fDenyTSConnections"
if($RAStatus -eq 1) {$RAStatus = "Enabled" } else {$RAStatus = "Disabled" }
#endregion
# Change the Notify Icon to Show Exporting Text
Show-NotifyIcon -Text "Exporting $strComputer Information" -Title "Exporting..."
#region Check the Null Valued Paramters
# If one of the Parameters are Null, Enter Space (looks better in the Table)
if($ComputerDet -eq $Null){ $ComputerDet = " " }
if($ChassisType -eq $Null){ $ChassisType = " " }
if($BIOSSN -eq $Null){ $BIOSSN = " " }
if($CPUName -eq $Null){ $CPUName = " " }
if($AvialableMem -eq $Null){ $AvialableMem = " " }
if($OS -eq $Null){ $OS = " " }
if($SP -eq $Null){ $SP = " " }
if($IPAddress -eq $Null){ $IPAddress = " " }
if($HotFixes -eq $Null){ $HotFixes = " " }
if($arrDiskDrives -eq $Null){ $arrDiskDrives=" " }
if($arrDiskFreeSpace -eq $Null){ $arrDiskFreeSpace=" " }
if($arrDiskSize -eq $Null){ $arrDiskSize=" " }
if($RDPStatus -eq $Null){ $RDPStatus = " " }
if($RAStatus -eq $Null){ $RAStatus = " " }
if($AUClient -eq $Null){ $AUClient = " " }
if($AVParentServer -eq $Null){ $AVParentServer = " " }
if($AVDefs -eq $Null){ $AVDefs = " " }
if($Printers -eq $Null){ $Printers = " " }
if($ComputerTotalHealth -eq $Null){ $ComputerTotalHealth = " " }
#endregion
#region Creating the Data Object - $DataObject
# Create an Empty psObject, $DataObjcet - Used by this Name in the Join-Data Function
$DataObject = New-Object psobject
# Join all the Data to the DataObject
$ComputerDet | Join-Data # Contians Multiple Values, No need to Define a Name
$ChassisType | Join-Data -objName "Chassis Type" # String with no Values - Define a Name
$BIOSSN | Join-Data # Contians Multiple Values, No need to Define a Name
$CPUName | Join-Data # Contians Multiple Values, No need to Define a Name
$AvialableMem | Join-Data # Contians Multiple Values, No need to Define a Name
$OS.Caption | Join-Data -objName "Operating System" # Contians Multiple Values, Caption Value canot be overwritten - Define a Name to a certian Value
$OS.CsdVersion | Join-Data -objName "Service Pack" # String with no Values - Define a Name
$arrIPAddress | Join-Data -objName "IP Addresses" # String with no Values - Define a Name
$arrHotFixes| Join-Data -objName "HotFixes" # String with no Values - Define a Name
$arrDiskDrives| Join-Data -objName "Disk Drives" # String with no Values - Define a Name
$RDPStatus.ToString() | Join-Data -objName "Remote Desktop" # String with no Values - Define a Name
$RAStatus.ToString() | Join-Data -objName "Remote Assistance" # String with no Values - Define a Name
$AUClient | Join-Data -objName "Automatic Updates" # String with no Values - Define a Name
$AVParentServer | Join-Data -objName "Anti-Virus Server" # String with no Values - Define a Name
$AVDefs | Join-Data -objName "Anti-Virus Defs" # String with no Values - Define a Name
$arrPrinters | Join-Data -objName "Printers" # String with no Values - Define a Name
$ComputerTotalHealth | Join-Data -objName "Computer Totla Health" # String with no Values - Define a Name
#endregion
$AllComputers += $DataObject
#region Exporting data
# Export the DataObject to the DataGridView Using the out-DataTable
$DataTable = $AllComputers | out-dataTable
# Define Data Grid's Data Source to the DataTable we Created
$DataGridView1.DataSource = $DataTable.psObject.baseobject
$DataGridView1.Refresh() # Refresh the Table View in order to View the new lines
# Export all the Data to the Log File
$AllComputers | Export-Csv -Encoding OEM -Path $LogFile
#endregion
}
}
else { # No Ping to Computer
$objNotifyIcon.BalloonTipIcon = "Error"
Show-NotifyIcon -Title "$strComputer is not avialable" -Text "No Ping to $strComputer.`nNo Data was Collected"
$objNotifyIcon.BalloonTipIcon = "Info"
}
$ProgressBar1.PerformStep()
}
#region Finishing - Script is Done
# Assign an Icon and Icon Type For the NotifyIcon Object
$objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people5.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
# Pop Up a Message box
$MSGObject = new-object -comobject wscript.shell
$MSGResult = $MSGObject.popup("Script Has Finished Running!",0,"I'm Done",0)
# Show Notify Icon with Finishing Text
$objNotifyIcon.BalloonTipText = "Done!`nFile Saved in "+$LogFile
$objNotifyIcon.Visible = $TRUE
$objNotifyIcon.ShowBalloonTip(10000)
$objNotifyIcon.Visible = $FALSE # Set to False so that the Notify Icon will Disapear after the Script is Done
#endregion
}
Main # This call must remain below all other event functions
#endregion
|
PowerShellCorpus/PoshCode/Quickstats from VMware.ps1
|
Quickstats from VMware.ps1
|
connect-VIServer yourserver
# Written by Alan Renouf - Check http://teckinfo.blogspot.com for more examples
# This can easily be changed to pass parameters or be used as a function
# Set the following 3 variables for your needs
# Example stats are:
# % CPU Usage - cpu.usage.average
# Mhz CPU Usage - cpu.usageMHZ.average
# % Memory Usage - mem.usage.average
# Kbps Network Usage - net.usage.average
# Kbps Disk Usage - disk.usage.average
$Caption = "CPU Usage"
$Stat = "cpu.usage.average"
$NumToReturn = 20
$categories = @()
$values = @()
$chart = new-object -com OWC11.ChartSpace.11
$chart.Clear()
$c = $chart.charts.Add(0)
$c.Type = 4
$c.HasTitle = "True"
$series = ([array] $chart.charts)[0].SeriesCollection.Add(0)
Get-Stat -Entity (Get-vm) -Stat $stat -MaxSamples 1 -Realtime |Sort-Object Value -Descending | Select-Object Entity, Value -First $NumToReturn | foreach-object {
$categories += $_.Entity.Name
$values += $_.Value * 1
}
$series.Caption = $Caption
$series.SetData(1, -1, $categories)
$series.SetData(2, -1, $values)
$filename = (resolve-path .).Path + "\\Chart.jpg"
$chart.ExportPicture($filename, "jpg", 800, 500)
invoke-item $filename
|
PowerShellCorpus/PoshCode/PS2WCF.ps1
|
PS2WCF.ps1
|
# Call WCF Services With PowerShell V1.0 22.12.2008
#
# by Christian Glessner
# Blog: http://www.iLoveSharePoint.com
# Twitter: http://twitter.com/cglessner
# Codeplex: http://codeplex.com/iLoveSharePoint
#
# requires .NET 3.5
# load WCF assemblies
[void][System.Reflection.Assembly]::LoadWithPartialName("System.ServiceModel")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Runtime.Serialization")
# get metadata of a service
function global:Get-WsdlImporter($wsdlUrl=$(throw "parameter -wsdlUrl is missing"), $httpGet)
{
if($httpGet -eq $true)
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet
}
else
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange
}
$mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient((New-Object System.Uri($wsdlUrl)),$mode)
$mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue
$metadataSet = $mexClient.GetMetadata()
$wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet)
return $wsdlImporter
}
# Generate wcf proxy types
function global:Get-WcfProxy($wsdlImporter, $wsdlUrl, $proxyPath)
{
if($wsdlImporter -eq $null -and $wsdlUrl -eq $null)
{
throw "parameter -wsdlImporter or -wsdlUrl must be specified"
}
else
{
if($wsdlImporter -eq $null)
{
$script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl
trap [Exception]
{
$script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl -httpGet $true
continue
}
}
}
$generator = new-object System.ServiceModel.Description.ServiceContractGenerator
foreach($contractDescription in $script:wsdlImporter.ImportAllContracts())
{
[void]$generator.GenerateServiceContractType($contractDescription)
}
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
if($proxyPath -eq $null)
{
[void]$parameters.GenerateInMemory = $true
}
else
{
$parameters.OutputAssembly = $proxyPath
}
$providerOptions = new-object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
[void]$providerOptions.Add("CompilerVersion","v3.5")
$compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions)
$result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit);
if($result.Errors.Count > 0)
{
throw "Proxy generation failed"
}
foreach($type in $result.CompiledAssembly.GetTypes())
{
if($type.BaseType.IsGenericType)
{
if($type.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" )
{
$type
}
}
}
}
|
PowerShellCorpus/PoshCode/Resize-Image.ps1
|
Resize-Image.ps1
|
## NOTE: Destination must end in .bmp, .gif, .png, .wmp, .jpeg or .tiff
param($source = "C:\\Windows\\Web\\Wallpaper\\Windows\\img0.jpg", $destination = "$Home\\Pictures\\thumb0.png", $scale = 0.25)
Add-Type -Assembly PresentationCore
## Open and resize the image
$image = New-Object System.Windows.Media.Imaging.TransformedBitmap (New-Object System.Windows.Media.Imaging.BitmapImage $source),
(New-Object System.Windows.Media.ScaleTransform $scale,$scale)
## Put it on the clipboard (just for fun)
[System.Windows.Clipboard]::SetImage( $image )
## Write out an image file:
$stream = [System.IO.File]::Open($destination, "OpenOrCreate")
$encoder = New-Object System.Windows.Media.Imaging.$([IO.Path]::GetExtension($destination).substring(1))BitmapEncoder
$encoder.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($image))
$encoder.Save($stream)
$stream.Dispose()
|
PowerShellCorpus/PoshCode/Map a Network Drive_1.ps1
|
Map a Network Drive_1.ps1
|
function MapNetDrive
{
param(
#Non-Boolean parameters (Values)
#
[Parameter(Position=0,Mandatory=$true)]
[string]$DriveLetter="Z:",
[Parameter(Position=1,Mandatory=$true)]
[string]$Path,
#Boolean switches (On/Off)
#
[Parameter(Position=2,Mandatory=$false)]
[switch]$Credentials,
[Parameter(Position=3,Mandatory=$false)]
[switch]$Stay,
[Parameter(Position=4,Mandatory=$false)]
[switch]$Force
)
#Creates new WScript.Network object called "$map" and allows it to access MapNetworkDrive(), EnumNetworkDrives(),
#and RemoveNetworkDrive() methods.
#
$map=New-Object -ComObject WScript.Network
#Uses EnumNetworkDrives() and "-contains" operator to determine if specified drive already exists. If so, and "$Force"
#parameter is not present to force an override, it outputs a message to the user. Then uses "Try/Catch" statement to
#catch any other general errors that might prevent removal of drive.
#
if($map.EnumNetworkDrives() -contains $DriveLetter)
{
if(!$Force)
{throw "Can't map $driveLetter because it's already mapped. Use -Force to override."}
try
{$map.RemoveNetworkDrive($DriveLetter,$Force.ToBool(),$Stay.ToBool())}
catch
{
Write-Error -Exception $_.Exception.InnerException -Message "Error removing '$driveLetter'
$($_.Exception.InnerException.InnerException.Message)"
}
}
#Maps new network drive, checking first if "$Credentials" parameter is passed. If so, a System.Management.Automation.PSCredential object
#called "$creds" is created and instantiated to result value of "Get-Credential" Cmdlet. Because of its type, "$creds" has access to the
#individual "UserName" and "Password" property values when the user submits them at the prompt.
#
#"$Stay" is placeholder for "bUpdateProfile" argument of the MapNetworkDrive() method, which determines whether the new
#drive is saved as part of the user's profile. It's value here is determined by the presence of the "$Stay" switch.
#
if($Credentials)
{
[System.Management.Automation.PSCredential]$creds=$(Get-Credential) #-Credential $($(Get-WmiObject -Class Win32_ComputerSystem).UserName)
$map.MapNetworkDrive($DriveLetter,$Path,$Stay.ToBool(),$creds.UserName,$creds.GetNetworkCredential().Password)
}
else {$map.MapNetworkDrive($DriveLetter,$Path,$Stay.ToBool())}
#Opens newly created drive letter in Windows Explorer
#
$explore=New-Object -ComObject Shell.Application
$explore.Open($DriveLetter)
}
|
PowerShellCorpus/PoshCode/List AD Users CSV_2.ps1
|
List AD Users CSV_2.ps1
|
$NumDays = 0
$LogDir = ".\\User-Accounts.csv"
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findall() | select `
@{e={$_.properties.cn};n='Display Name'},`
@{e={$_.properties.samaccountname};n='Username'},`
@{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},`
@{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'}
$users | Export-CSV -NoType $LogDir
|
PowerShellCorpus/PoshCode/NIC Performance.ps1
|
NIC Performance.ps1
|
$cat = New-Object system.Diagnostics.PerformanceCounterCategory("Network Interface")
$inst = $nic.GetInstanceNames()
foreach ( $nic in $inst ) {
$a = $nic.GetCounters( $nic )
$a | ft CounterName, { $_.NextValue() } -AutoSize
}
|
PowerShellCorpus/PoshCode/Get-DPMRecoveryPointRepo.ps1
|
Get-DPMRecoveryPointRepo.ps1
|
<#
.SYNOPSIS
Get-DPMRecoveryPointReport
.DESCRIPTION
This script sets up the basic framework that I use for all my scripts.
.PARAMETER DPMServerName
The FQDN of your DPM server
.EXAMPLE
Get-DPMRecoveryPointReport -DPMServerName dpm.company.com
Name BackupTime Server DataSource Location
---- ---------- ------ ---------- --------
P:\\ 7/23/2011 12:01:07 AM fs.company.com P:\\ on fs.company.com Disk
P:\\ 7/24/2011 12:01:11 AM fs.company.com P:\\ on fs.company.com Disk
P:\\ 7/25/2011 12:01:44 AM fs.company.com P:\\ on fs.company.com Disk
P:\\ 7/26/2011 12:01:26 AM fs.company.com P:\\ on fs.company.com Disk
Description
-----------
The basic usage and output of this script.
.NOTES
ScriptName: Get-DPMRecoveryPointReport
Created By: Jeff Patton
Date Coded: July 28, 2011
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
You will need the DPM Snap-ins in order for this to work.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/Get-DPMRecoveryPointReport
#>
Param
(
$DPMServerName = "dpm.company.com"
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
# Dotsource in the functions you need.
$ProtectionGroups = Get-ProtectionGroup -DPMServerName $DPMServerName
$Report = @()
if (Get-PSSnapin -Name 'Microsoft.DataProtectionManager.PowerShell')
{ }
else
{
try
{
Add-PSSnapin -Name 'Microsoft.DataProtectionManager.PowerShell'
}
Catch
{
Return $Error[0].Exception.InnerException.Message.ToString().Trim()
}
}
}
Process
{
If ($ProtectionGroups)
{
foreach ($ProtectionGroup in $ProtectionGroups)
{
if ($ProtectionGroup)
{
$DataSources = Get-Datasource -ProtectionGroup $ProtectionGroup
foreach ($DataSource in $DataSources)
{
$RecoveryPoints = Get-RecoveryPoint -Datasource $DataSource
foreach ($RecoveryPoint in $RecoveryPoints)
{
$ThisRecoveryPoint = New-Object -TypeName PSObject -Property @{
Name = $RecoveryPoint.UserFriendlyName
BackupTime = $RecoveryPoint.RepresentedPointInTime
DataSource = "$($RecoveryPoint.DataSource.Name) on $($RecoveryPoint.DataSource.ProductionServerName)"
Server = $RecoveryPoint.DataSource.ProductionServerName
Location = $RecoveryPoint.DataLocation
}
$Report += $ThisRecoveryPoint
}
}
}
}
}
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
Return $Report
}
|
PowerShellCorpus/PoshCode/Logger.psm1 0.2.ps1
|
Logger.psm1 0.2.ps1
|
<#
Name : Universal Log4Net Logging Module (Logger.psm1)
Version : 0.2
Author : Joel Bennett (MVP)
Site : http://www.HuddledMasses.org/
Version History:
0.2 - Configless release.
Now configures with inline XML, and supports switches to create "reasonable" default loggers
Changed all the functions to Write-*Log so they don't overwrite the cmdlets
Added -Logger parameter to take the name of the logger to use (it must be created beforehand via Get-Logger)
Created aliases for Write-* to override the cmdlets -- these are easy for users to remove without breaking the module
** NEED to write some docs, but basically, this is stupid simple to use, just:
Import-Module Logger
Write-Verbose "This message will be saved in your profile folder in a file named PowerShellLogger.log (by default)"
To change the defaults for your system, edit the last line in the module!!
0.1 - Initial release. http://poshcode.org/1744 (Required config: http://poshcode.org/1743)
Uses Log4Net : http`://logging.apache.org/log4net/download.html
Documentation: http`://logging.apache.org/log4net/release/sdk/
NOTES:
By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host.
This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts)
To avoid this behavior, remove the aliases after importing it
Import-Module Logger; Remove-Item Alias:Write-*
Write-Warning "This is your warning"
Write-Debug "You should know that..."
Write-Verbose "Everything would be logged, otherwise"
***** NOTE: IT ONLY OVERRIDES THE DEFAULTS FOR SCRIPTS *****
It currently has no effect on error/verbose/warning that is logged from cmdlets.
#>
Add-Type -Path $PSScriptRoot\\log4net.dll
function Get-Logger {
param(
[Parameter(Mandatory=$false)]
[string]$LoggerName = "*"
,
[Parameter(Mandatory=$false)]
[ValidateSet("DEBUG","INFO","WARN","ERROR","FATAL","VERBOSE","HOST","WARNING")]
[string]$LogLevel = "DEBUG"
,
[Parameter(Mandatory=$false)]
[string]$LogFolder = $PSScriptRoot
, [Switch]$Force
, [Switch]$Console
, [Switch]$EventLog
, [Switch]$Trace
, [Switch]$File
, [Switch]$RollingFile
)
$Script:Logger = [log4net.LogManager]::GetCurrentLoggers() | Where-Object { $_.Logger.Name -Like $LoggerName }
if(!$script:Logger -or $Force -and $LoggerName -ne "*") {
if($LogLevel -eq "VERBOSE") { $LogLevel = "INFO" }
if($LogLevel -eq "HOST") { $LogLevel = "INFO" }
if($LogLevel -eq "WARNING") { $LogLevel = "WARN" }
$AppenderRefs = ''
if($EventLog) { $AppenderRefs += "<appender-ref ref=""EventLogAppender"" />`n" }
if($Trace) { $AppenderRefs += "<appender-ref ref=""TraceAppender"" />`n" }
if($File) { $AppenderRefs += "<appender-ref ref=""FileAppender"" />`n" }
if($RollingFile) { $AppenderRefs += "<appender-ref ref=""RollingFileAppender"" />`n" }
if($Console -or ($AppenderRefs.Length -eq 0)) { $AppenderRefs += "<appender-ref ref=""ColoredConsoleAppender"" />`n" }
$Script:Logger = [log4net.LogManager]::GetLogger($LoggerName)
[xml]$config = @"
<log4net>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="FATAL" />
<foreColor value="Red, HighIntensity" />
<backColor value="White, HighIntensity" />
</mapping>
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Green, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="Cyan, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="$LoggerName" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="$LogFolder\\$LoggerName.Log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="$LogFolder\\$LoggerName.Log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
</root>
<logger name="$LoggerName">
<level value="$LogLevel" />
$AppenderRefs
</logger>
</log4net>
"@
[log4net.Config.XmlConfigurator]::Configure( $config.log4net )
}
return $Script:Logger
}
function Set-Logger {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[log4net.Core.LogImpl]$Logger
)
$script:Logger = $Logger
}
function Push-LogContext {
param(
[Parameter(Mandatory=$true)]
[string]$Name
)
[log4net.NDC]::Push($Name)
}
function Pop-LogContext {
[log4net.NDC]::Pop()
}
function Write-DebugLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.debug($Message) #Write-Debug
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Debug
.ForwardHelpCategory Cmdlet
#>
}
function Write-VerboseLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info($Message)
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Verbose
.ForwardHelpCategory Cmdlet
#>
}
function Write-WarningLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.warn($Message) #Write-Warning
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Warning
.ForwardHelpCategory Cmdlet
#>
}
function Write-ErrorLog {
[CmdletBinding(DefaultParameterSetName='NoException')]
param(
[Parameter(ParameterSetName='WithException', Mandatory=$true)]
[System.Exception]
${Exception},
[Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Parameter(ParameterSetName='WithException')]
[Alias('Msg')]
[AllowNull()]
[AllowEmptyString()]
[System.String]
${Message},
[Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)]
[System.Management.Automation.ErrorRecord]
${ErrorRecord},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Management.Automation.ErrorCategory]
${Category},
[Parameter(ParameterSetName='WithException')]
[Parameter(ParameterSetName='NoException')]
[System.String]
${ErrorId},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Object]
${TargetObject},
[System.String]
${RecommendedAction},
[Alias('Activity')]
[System.String]
${CategoryActivity},
[Alias('Reason')]
[System.String]
${CategoryReason},
[Alias('TargetName')]
[System.String]
${CategoryTargetName},
[Alias('TargetType')]
[System.String]
${CategoryTargetType}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.error($Message,$Exception) #Write-Error
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Error
.ForwardHelpCategory Cmdlet
#>
}
function Write-HostLog {
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[System.Object]
${Object},
[Switch]
${NoNewline},
[System.Object]
${Separator} = $OFS,
[System.ConsoleColor]
${ForegroundColor},
[System.ConsoleColor]
${BackgroundColor}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info(($Object -join $Separator)) #Write-Verbose
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Host
.ForwardHelpCategory Cmdlet
#>
}
Set-Alias Write-Debug Write-DebugLog
Set-Alias Write-Verbose Write-VerboseLog
Set-Alias Write-Warning Write-WarningLog
Set-Alias Write-Error Write-ErrorLog
#Set-Alias Write-Host Write-HostLog
Export-ModuleMember -Function * -Alias *
$script:Logger = Get-Logger "PowerShellLogger" -RollingFile -LogFolder (Split-Path $Profile.CurrentUserAllHosts)
## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
|
PowerShellCorpus/PoshCode/foreach-withexception.ps1
|
foreach-withexception.ps1
|
function foreach-withexception ([scriptblock]$process,$outputexception)
{
begin { $global:foreachex = @() }
process {
try
{
$local:inputitem = $_
&$process
}
catch
{
$local:exceptionitem = 1 | select-object object,exception
$local:exceptionitem.object = $local:inputitem
$local:exceptionitem.exception = $_
$global:foreachex += $local:exceptionitem
}
}
end {}
}
set-alias %ex foreach-withexception
100..-5 | %ex { "yo $_" ; 1 / $_ }
$lastex
|
PowerShellCorpus/PoshCode/Convert Raw SID to SID_2.ps1
|
Convert Raw SID to SID_2.ps1
|
#For intel concerning how to convert raw hex SID to Standard SID got to
#http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx
#to convert Hex to Dec
function Convert-HEXtoDEC
{
param($HEX)
ForEach ($value in $HEX)
{
[string][Convert]::ToInt32($value,16)
}
}
#to reassort decimal values to correct hex in order to cenvert them
function Reassort
{
param($chaine)
$a = $chaine.substring(0,2)
$b = $chaine.substring(2,2)
$c = $chaine.substring(4,2)
$d = $chaine.substring(6,2)
$d+$c+$b+$a
}
# this is the main function
# it splits the waxw sid into different parts and then converts the values
# finally it brings the converted SID value.
# you can supply an array of raw sid
function ConvertSID
{
param($chaine32)
foreach($chaine in $chaine32) {
[INT]$SID_Revision = $chaine.substring(0,2)
[INT]$Identifier_Authority = $chaine.substring(2,2)
[INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8)))
$chaine1 = $chaine.substring(24,8)
$chaine2 = $chaine.substring(32,8)
$chaine3 = $chaine.substring(40,8)
$chaine4 = $chaine.substring(48,8)
[string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1))
[string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2))
[string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3))
[string]$UID=Convert-HextoDEC(Reassort($chaine4))
#"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID
"S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID"
}
}
|
PowerShellCorpus/PoshCode/Snippet Compiler.ps1
|
Snippet Compiler.ps1
|
$def = (gci $MyInvocation.MyCommand.Name).Directory.ToString()
#################################################################################################
$mnuAtom_Click= {
if ($txtEdit.Text -ne "") {
$res = [Windows.Forms.MessageBox]::Show("Do you want to save data before?", `
$frmMain.Text, [Windows.Forms.MessageBoxButtons]::YesNoCancel, `
[Windows.Forms.MessageBoxIcon]::Question)
switch ($res) {
'Yes' {
(New-Object Windows.Forms.SaveFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
Out-File $_.FileName -enc UTF8 -input $txtEdit.Text
}
}
break
}
'No' { $txtEdit.Clear(); break; }
'Cancel' { return }
}
}#if
}
$mnuOpen_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$sr = New-Object IO.StreamReader $_.FileName
$txtEdit.Text = $sr.ReadToEnd()
$sr.Close()
}
}
}
$mnuFont_Click= {
(New-Object Windows.Forms.FontDialog) | % {
$_.Font = "Lucida Console"
$_.MinSize = 10
$_.MaxSize = 12
$_.ShowEffects = $false
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$txtEdit.Font = $_.Font
}
}
}
$mnuWrap_Click= {
$toggle =! $mnuWrap.Checked
$mnuWrap.Checked = $toggle
$txtEdit.WordWrap = $toggle
}
$mnuToS1_Click= {
switch ($mnuToS1.Checked) {
$true { $mnuToS1.Checked = $false; $scSplt1.Panel2Collapsed = $true; break }
$false { $mnuToS1.Checked = $true; $scSplt1.Panel2Collapsed = $false; break }
}
}
$mnuToS2_Click= {
switch ($mnuToS2.Checked) {
$true { $mnuToS2.Checked = $false; $scSplt2.Panel2Collapsed = $true; break }
$false { $mnuToS2.Checked = $true; $scSplt2.Panel2Collapsed = $false; break }
}
}
$mnuSBar_Click= {
$toggle =! $mnuSbar.Checked
$mnuSBar.Checked = $toggle
$sbPanel.Visible = $toggle
}
$mnuBnRA_Click= {
Invoke-Builder
if ($script:make.Errors.Count -eq 0) { Invoke-Item $txtIOut.Text }
}
$chkExec_Click= {
switch ($chkExec.Checked) {
$true {
$txtIOut.Text = $def + '\\app.exe'
$chkWApp.Enabled = $true
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
break
}
$false {
$txtIOut.Text = $def + '\\lib.dll'
$chkWApp.Enabled = $false
$chkImem.Enabled = $true
$mnuBnRA.Enabled = $false
break
}
}#switch
}
$chkWApp_Click= {
switch ($chkWApp.Checked) {
$true {
$lboRefs.Items.AddRange(@("`"System.Drawing.dll`"", "`"System.Windows.Forms.dll`""))
break
}
$false {
$lboRefs.Items.Remove("`"System.Windows.Forms.dll`"")
$lboRefs.Items.Remove("`"System.Drawing.dll`"")
break
}
}#switch
}
$btnRAdd_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.Filter = "PE File (*.dll)|*.dll"
$_.InitialDirectory = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$lboRefs.Items.Add('"' + (Split-Path -leaf $_.FileName) + '"')
}
}
}
$frmMain_Load= {
$txtIOut.Text = $def + '\\app.exe'
$sbPnl_2.Text = "Str: 1, Col: 0"
$lboRefs.Items.AddRange(@("`"System.dll`"", "`"System.Core.dll`""))
}
#################################################################################################
function Invoke-Builder {
$lstView.Items.Clear()
if ($txtEdit.Text -ne "") {
$cdcp.GenerateExecutable = $chkExec.Checked
if ($chkWApp.Checked) { $cdcp.CompilerOptions = "/t:winexe" }
$cdcp.IncludeDebugInformation = $chkIDbg.Checked
$cdcp.GenerateInMemory = $chkImem.Checked
if ($lboRefs.Items.Count -ne 0) {
for ($i = 0; $i -lt $lboRefs.Items.Count; $i++) {
$cdcp.ReferencedAssemblies.Add($lboRefs.Items[$i].ToString())
}
}
$cdcp.WarningLevel = 3
$cdcp.OutputAssembly = $txtIOut.Text
$script:make = $cscp.CompileAssemblyFromSource($cdcp, $txtEdit.Text)
$make.Errors | % {
if (!($_.IsWarning)) { $lstView.ForeColor = [Drawing.Color]::Crimson }
else { $lstView.ForeColor = [Drawing.Color]::Gray }
if ($_.Line -ne 0 -and $_.Column -ne 0) {
$itm = $lstView.Items.Add($_.Line.ToString() + ', ' + ($_.Column - 1).ToString())
}
elseif ($_.Line -ne 0 -and $_.Column -eq 0) {
$itm = $lstView.Items.Add($_.Line.ToString() + ', 0')
}
elseif ($_.Line -eq 0 -and $_.Column -eq 0) {
$itm = $lstView.Items.Add('*')
}
$itm.SubItems.Add($_.ErrorNumber)
$itm.SubItems.Add($_.ErrorText)
}
}#if
}
function Get-CursorPoint {
$z = $txtEdit.SelectionStart
$y = $txtEdit.GetLineFromCharIndex($z) + 1
$x = $z - $txtEdit.GetFirstCharIndexOfCurrentLine()
return (New-Object Drawing.Point($x, $y))
}
function Write-CursorPoint {
$sbPnl_2.Text = 'Str: ' + (Get-CursorPoint).Y.ToString() + ', Col: ' + `
(Get-CursorPoint).X.ToString()
}
#################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$dict = New-Object "Collections.Generic.Dictionary[String, String]"
$dict.Add("CompilerVersion", "v3.5")
$cscp = New-Object Microsoft.CSharp.CSharpCodeProvider($dict)
$cdcp = New-Object CodeDom.Compiler.CompilerParameters
$ico = [Drawing.Icon]::ExtractAssociatedIcon($($PSHome + '\\powershell_ise.exe'))
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuAtom = New-Object Windows.Forms.MenuItem
$mnuOpen = New-Object Windows.Forms.MenuItem
$mnuEmp1 = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuEdit = New-Object Windows.Forms.MenuItem
$mnuUndo = New-Object Windows.Forms.MenuItem
$mnuEmp2 = New-Object Windows.Forms.MenuItem
$mnuCopy = New-Object Windows.Forms.MenuItem
$mnuPast = New-Object Windows.Forms.MenuItem
$mnuICut = New-Object Windows.Forms.MenuItem
$mnuEmp3 = New-Object Windows.Forms.MenuItem
$mnuSAll = New-Object Windows.Forms.MenuItem
$mnuView = New-Object Windows.Forms.MenuItem
$mnuFont = New-Object Windows.Forms.MenuItem
$mnuTgls = New-Object Windows.Forms.MenuItem
$mnuWrap = New-Object Windows.Forms.MenuItem
$mnuToS1 = New-Object Windows.Forms.MenuItem
$mnuToS2 = New-Object Windows.Forms.MenuItem
$mnuSBar = New-Object Windows.Forms.MenuItem
$mnuMake = New-Object Windows.Forms.MenuItem
$mnuBAsm = New-Object Windows.Forms.MenuItem
$mnuBnRA = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$scSplt1 = New-Object Windows.Forms.SplitContainer
$scSplt2 = New-Object Windows.Forms.SplitContainer
$lstView = New-Object Windows.Forms.ListView
$chPoint = New-Object Windows.Forms.ColumnHeader
$chError = New-Object Windows.Forms.ColumnHeader
$chCause = New-Object Windows.Forms.ColumnHeader
$txtEdit = New-Object Windows.Forms.TextBox
$lblLab1 = New-Object Windows.Forms.Label
$txtIOut = New-Object Windows.Forms.TextBox
$gboMake = New-Object Windows.Forms.GroupBox
$chkExec = New-Object Windows.Forms.CheckBox
$chkWApp = New-Object Windows.Forms.CheckBox
$chkIDbg = New-Object Windows.Forms.CheckBox
$chkIMem = New-Object Windows.Forms.CheckBox
$lblLab2 = New-Object Windows.Forms.Label
$lboRefs = New-Object Windows.Forms.ListBox
$btnRAdd = New-Object Windows.Forms.Button
$sbPanel = New-Object Windows.Forms.StatusBar
$sbPnl_1 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_2 = New-Object Windows.Forms.StatusBarPanel
$mnuRefs = New-Object Windows.Forms.ContextMenu
$mnuMove = New-Object Windows.Forms.MenuItem
#
#mnuMain
#
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuEdit, $mnuView, $mnuMake, $mnuHelp))
#
#mnuFile
#
$mnuFile.MenuItems.AddRange(@($mnuAtom, $mnuOpen, $mnuEmp1, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuAtom
#
$mnuAtom.Shortcut = "F3"
$mnuAtom.Text = "Nu&Clear..."
$mnuAtom.Add_Click($mnuAtom_Click)
#
#mnuOpen
#
$mnuOpen.Shortcut = "CtrlO"
$mnuOpen.Text = "&Open"
$mnuOpen.Add_Click($mnuOpen_Click)
#
#mnuEmp1
#
$mnuEmp1.Text = "-"
#
#mnuExit
#
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuEdit
#
$mnuEdit.MenuItems.AddRange(@($mnuUndo, $mnuEmp2, $mnuCopy, $mnuPast, `
$mnuICut, $mnuEmp3, $mnuSAll))
$mnuEdit.Text = "&Edit"
#
#mnuUndo
#
$mnuUndo.Shortcut = "CtrlZ"
$mnuUndo.Text = "&Undo"
$mnuUndo.Add_Click({$txtEdit.Undo()})
#
#mnuEmp2
#
$mnuEmp2.Text = "-"
#
#mnuCopy
#
$mnuCopy.Shortcut = "CtrlC"
$mnuCopy.Text = "&Copy"
$mnuCopy.Add_Click({if ($txtEdit.SelectionLength -ge 0) {$txtEdit.Copy()}})
#
#mnuPast
#
$mnuPast.Shortcut = "CtrlV"
$mnuPast.Text = "&Paste"
$mnuPast.Add_Click({$txtEdit.Paste()})
#
#mnuICut
#
$mnuICut.Shortcut = "Del"
$mnuICut.Text = "Cut &Item"
$mnuICut.Add_Click({if ($txtEdit.SelectedText -ne "") {$txtEdit.Cut()}})
#
#mnuEmp3
#
$mnuEmp3.Text = "-"
#
#mnuSAll
#
$mnuSAll.Shortcut = "CtrlA"
$mnuSAll.Text = "Select &All"
$mnuSAll.Add_Click({$txtEdit.SelectAll()})
#
#mnuView
#
$mnuView.MenuItems.AddRange(@($mnuFont, $mnuTgls))
$mnuView.Text = "&View"
#
#mnuFont
#
$mnuFont.Text = "Font..."
$mnuFont.Add_Click($mnuFont_Click)
#
#mnuTgls
#
$mnuTgls.MenuItems.AddRange(@($mnuWrap, $mnuToS1, $mnuToS2, $mnuSBar))
$mnuTgls.Text = "&Toggles"
#
#mnuWrap
#
$mnuWrap.Checked = $true
$mnuWrap.Shortcut = "CtrlW"
$mnuWrap.Text = "&Wrap Mode"
$mnuWrap.Add_Click($mnuWrap_Click)
#
#mnuToS1
#
$mnuToS1.Checked = $true
$mnuToS1.Text = "Building &Progress..."
$mnuToS1.Add_Click($mnuToS1_Click)
#
#mnuToS2
#
$mnuToS2.Shortcut = "F12"
$mnuToS2.Text = "Building P&roperties"
$mnuToS2.Add_Click($mnuToS2_Click)
#
#mnuSBar
#
$mnuSBar.Checked = $true
$mnuSBar.Shortcut = "CtrlB"
$mnuSBar.Text = "Status &Bar"
$mnuSBar.Add_Click($mnuSBar_Click)
#
#mnuMake
#
$mnuMake.MenuItems.AddRange(@($mnuBAsm, $mnuBnRA))
$mnuMake.Text = "&Build"
#
#mnuBAsm
#
$mnuBAsm.Shortcut = "F5"
$mnuBAsm.Text = "&Compile"
$mnuBAsm.Add_Click({Invoke-Builder})
#
#mnuBnRA
#
$mnuBnRA.Shortcut = "F9"
$mnuBnRA.Text = "Compile And &Run"
$mnuBnRA.Add_Click($mnuBnRA_Click)
#
#mnuHelp
#
$mnuHelp.MenuItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#scSplt1
#
$scSplt1.Dock = "Fill"
$scSplt1.Orientation = "Horizontal"
$scSplt1.Panel1.Controls.Add($scSplt2)
$scSplt1.Panel2.Controls.Add($lstView)
$scSplt1.SplitterDistance = 100
$scSplt1.SplitterWidth = 1
#
#scSplt2
#
$scSplt2.Dock = "Fill"
$scSplt2.Panel1.Controls.Add($txtEdit)
$scSplt2.Panel2.Controls.Add($gboMake)
$scSplt2.Panel2Collapsed = $true
$scSplt2.SplitterDistance = 100
$scSplt2.SplitterWidth = 1
#
#lstView
#
$lstView.Columns.AddRange(@($chPoint, $chError, $chCause))
$lstView.Dock = "Fill"
$lstView.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lstView.FullRowSelect = $true
$lstView.GridLines = $true
$lstView.MultiSelect = $false
$lstView.ShowItemToolTips = $true
$lstView.View = "Details"
#
#chPoint
#
$chPoint.Text = "Line"
$chPoint.Width = 50
#
#chError
#
$chError.Text = "Error"
$chError.TextAlign = "Right"
$chError.Width = 65
#
#chCause
#
$chCause.Text = "Description"
$chCause.Width = 650
#
#txtEdit
#
$txtEdit.AcceptsTab = $true
$txtEdit.Dock = "Fill"
$txtEdit.Font = New-Object Drawing.Font("Courier New", 10)
$txtEdit.Multiline = $true
$txtEdit.ScrollBars = "Both"
$txtEdit.Add_Click({Write-CursorPoint})
$txtEdit.Add_KeyUp({Write-CursorPoint})
$txtEdit.Add_TextChanged({Write-CursorPoint})
#
#gboMake
#
$gboMake.Controls.AddRange(@($lblLab1, $txtIOut, $chkExec, $chkWApp, `
$chkIDbg, $chkIMem, $lblLab2, $lboRefs, $btnRAdd))
$gboMake.Dock = "Fill"
$gboMake.Font = New-Object Drawing.Font("Microsoft Sans Serif", 10)
$gboMake.Text = "Building Parameters"
#
#lblLab1
#
$lblLab1.Location = New-Object Drawing.Point(21, 33)
$lblLab1.Text = "Output:"
$lblLab1.Width = 50
#
#txtIOut
#
$txtIOut.Location = New-Object Drawing.Point(71, 31)
$txtIOut.Width = 163
#
#chkExec
#
$chkExec.Checked = $true
$chkExec.Location = New-Object Drawing.Point(23, 63)
$chkExec.Text = "Create Executable"
$chkExec.Width = 160
$chkExec.Add_Click($chkExec_Click)
#
#chkWApp
#
$chkWApp.Location = New-Object Drawing.Point(43, 83)
$chkWApp.Text = "WinForm Application"
$chkWApp.Width = 160
$chkWApp.Add_Click($chkWApp_Click)
#
#chkIDbg
#
$chkIDbg.Checked = $true
$chkIDbg.Location = New-Object Drawing.Point(23, 103)
$chkIDbg.Text = "Include Debug Information"
$chkIDbg.Width = 185
#
#chkIMem
#
$chkIMem.Enabled = $false
$chkIMem.Location = New-Object Drawing.Point(23, 123)
$chkIMem.Text = "Build In Memory"
$chkIMem.Width = 160
#
#lblLab2
#
$lblLab2.Location = New-Object Drawing.Point(23, 173)
$lblLab2.Size = New-Object Drawing.Size(79, 17)
$lblLab2.Text = "References:"
#
#lboRefs
#
$lboRefs.ContextMenu = $mnuRefs
$lboRefs.Location = New-Object Drawing.Point(23, 193)
$lboRefs.SelectionMode = "One"
$lboRefs.Size = New-Object Drawing.Size(213, 137)
#
#btnRAdd
#
$btnRAdd.Location = New-Object Drawing.Point(63, 337)
$btnRAdd.Text = "Add Reference"
$btnRAdd.Width = 130
$btnRAdd.Add_Click($btnRAdd_Click)
#
#sbPanel
#
$sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2))
$sbPanel.ShowPanels = $true
$sbPanel.SizingGrip = $false
#
#sbPnl_1
#
$sbPnl_1.Width = 589
#
#sbPnl_2
#
$sbPnl_2.Alignment = "Center"
$sbPnl_2.AutoSize = "Contents"
#
#mnuRefs
#
$mnuRefs.MenuItems.AddRange(@($mnuMove))
#
#mnuMove
#
$mnuMove.Shortcut = "Del"
$mnuMove.Text = "Remove Item"
$mnuMove.Add_Click({$lboRefs.Items.Remove($lboRefs.SelectedItem)})
#
#frmMain
#
$frmMain.BackColor = [Drawing.Color]::FromArgb(249, 253, 255)
$frmMain.ClientSize = New-Object Drawing.Size(790, 550)
$frmMain.Controls.AddRange(@($scSplt1, $sbPanel))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.MaximizeBox = $false
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Snippet Compiler"
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
#################################################################################################
function frmInfo_Show {
$frmInfo = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Point(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "Snippet Compiler v2.01"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2012-2013 greg zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmInfo
#
$frmInfo.AcceptButton = $btnExit
$frmInfo.CancelButton = $btnExit
$frmInfo.ClientSize = New-Object Drawing.Size(350, 110)
$frmInfo.ControlBox = $false
$frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmInfo.ShowInTaskBar = $false
$frmInfo.StartPosition = "CenterScreen"
$frmInfo.Text = "About..."
$frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()})
[void]$frmInfo.ShowDialog()
}
#################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/Get-LocalGroupMember_4.ps1
|
Get-LocalGroupMember_4.ps1
|
function Get-LocalGroupMember
{
<#
.Synopsis
Get the local group membership.
.Description
Get the local group membership.
.Parameter ComputerName
Name of the Computer to get group members (Default localhost.)
.Parameter Group
Name of the group to get members from (Default Administrators.)
.Example
Get-LocalGroupMember
Description
-----------
Get Administrators group Members for the localhost
.Example
Get-LocalGroupMember -Computer MyPC -group User
Description
-----------
Get Members of Users Group from MyPC
.Example
$Servers | Get-LocalGroupMember -group "Remote Desktop Users"
Description
-----------
Get Members of Users Group from "Remote Desktop Users" on all $Servers
.OUTPUTS
PSCustomObject
.INPUTS
System.String
.Link
N/A
.Notes
NAME: Get-LocalGroupMember
AUTHOR: YetiCentral\\bshell
Website: www.bsonposh.com
LASTEDIT: 10/13/2009 18:25:15
#Requires -Version 2.0
#>
[Cmdletbinding()]
Param(
[alias('dnsHostName')]
[Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$ComputerName = $Env:COMPUTERNAME,
[Parameter()]
[string]$Group= "Administrators"
)
begin {
Write-Verbose " [Get-LocalGroupMember] :: Start Begin"
function GetGroupMembers($Server,$Group)
{
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Server = $Server"
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Group = $Group"
$GroupObject = Get-WMIObject win32_group -filter "LocalAccount='$true' AND Name='$Group'" -computername $Server -
$Query = "SELECT * FROM Win32_GroupUser WHERE GroupComponent = `"Win32_Group.Domain='$Server',Name='$Group'`""
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$Query = $Query"
$GroupUsers = get-wmiobject -Query $Query -computername $Server -ea STOP
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: Processing Group Members "
if($GroupUsers)
{
foreach($User in $GroupUsers)
{
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$User.PartComponent = $($User.PartComponent
$RegEx = '\\\\\\\\{0}\\\\root\\\\cimv2\\:Win32_.*\\="(?<Domain>.*)",Name="(?<User>.*)"' -f $Server
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: RegEx = $RegEx "
$User.PartComponent -match $Regex | out-null
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: Creating Custom Object "
$myobj = @{}
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.ComputerName = $Server"
$myobj.ComputerName = $Server
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.UserName = $($matches.User)"
$myobj.UserName = $matches.User
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.Domain = $($matches.Domain)"
$myobj.Domain = $matches.Domain
Write-Verbose " [Get-LocalGroupMember] :: GetGroupMembers :: `$myobj.Group = $Group"
$myobj.Group = $Group
$obj = New-Object PSObject -Property $myobj
$obj.PSTypeNames.Clear()
$obj.PSTypeNames.Add('BSonPosh.LocalGroup')
$obj
}
}
}
Write-Verbose " [Get-LocalGroupMember] :: End Begin"
}
process {
Write-Verbose " [Get-LocalGroupMember] :: Start Process"
if($ComputerName -match "(.*)(\\$)$")
{
$ComputerName = $ComputerName -replace "(.*)(\\$)$",'$1'
}
if(Test-Host $ComputerName -TCPPort 135)
{
Write-Verbose " [Get-LocalGroupMember] :: Processing Computer: $ComputerName"
try
{
GetGroupMembers $ComputerName $Group
}
catch
{
Write-Host " Host [$ComputerName] Failed with Error: $($Error[0])" -ForegroundColor Red
}
}
else
{
Write-Host " Host [$ComputerName] Failed Connectivity Test " -ForegroundColor Red
}
Write-Verbose " [Get-LocalGroupMember] :: End Process"
}
}
|
PowerShellCorpus/PoshCode/Query MagisterWebservice.ps1
|
Query MagisterWebservice.ps1
|
<#
.TITLE
Haal-WisMasLeerling.ps1
.AUTHOR
Paul Wiegmans (p [dot] wiegmans [at] bonhoeffer [dot] nl)
.DATE
2013-01-30
.DESCRIPTION
Send a webquery to Schoolmaster Magister web service and request data
from the list WISMASLEERLING.
Doe een webquery naar Magister webservice en haal de lijst WISMASLEERLING op.
.NOTES
.LINK
http://ict.bonhoeffer.nl
#>
Import-Module ActiveDirectory
Set-StrictMode -Version 2
$mijnpad = Split-Path -parent $MyInvocation.MyCommand.Definition
$mijnbasename = $([System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Definition))
$logging = $true # geef uitvoer naar logfile
$outputting = $true # geef uitvoer naar console
$outputVreemdetekens = $true # geef uitvoer naar console indien vreemde tekens opgemerkt
$aantal = 0
$SOAPLayout = "WISMASLEERLINGEN"
$SOAPusername = "username"
$SOAPpasswd = "password"
Function Write-Log ($tekst) {
<# stuur uitvoer naar een logfile en naar console #>
$logtekst = ("{0:0###}: {1}" -f ($aantal, $tekst))
if ($outputting) {
Write-Host $logtekst
}
if ($Logging) {
#$logtekst | Out-File "$mijnpad\\$mijnbasename.log" -Append
}
}
function Doe-Webquery ([string]$Url, [System.Text.Encoding]$encoding = [System.Text.Encoding]::UTF7) {
# .SYNOPSIS
# Voert een SOAP webquery uit
# .DESCRIPTION
# Voert een SOAP webquery uit.
# Retourneert het resultaat van de qebquery in een array met string
# .PARAMETER Url
# De URL van de webquery
# .PARAMETER ENcoding
# De [system.text.encoding] encoding van de webquery
# .EXAMPLE
# $lines = Doe-Webquery "https://bonhoeffer.swp.nl:8800/doc?Bladibla..."
# .NOTES
# Auteur: Paul Wiegmans
# Datum: 30 mrt 2012
$request = [System.Net.WebRequest]::Create($Url)
try {
$response = $request.GetResponse()
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
exit
}
$requestStream = $response.GetResponseStream()
# We must read the Magister webquery in UTF7 to preserve the accents!
$readStream = new-object System.IO.StreamReader( $requestStream, $Encoding )
$result = $readStream.ReadToEnd() -split "`n" # convert to array of strings
$readStream.Close()
$response.Close()
return $result
}
Function Ophalen-Magister () {
<# Haal leerlinglijst op van Magister via SOAP #>
# kale URL is https://bonhoeffer.swp.nl:8800/doc?Function=GetData&Library=Data&SessionToken=adfeeder%3Belo.33&Layout=Basistest&Parameters=leerjaar%3D1213&Type=CSV
$SOAPUrl = "https://bonhoeffer.swp.nl:8800/doc?Function=GetData"`
+"&Library=Data&SessionToken=$SOAPusername%3B$SOAPpasswd&Layout=$SOAPlayout"`
+"&Parameters=leerjaar%3D1213&Type=CSV"
$iso88591 = [System.Text.Encoding]::GetEncoding("ISO-8859-1")
$UTF7 = [System.Text.Encoding]::UTF7
$data = Doe-Webquery $SOAPUrl $UTF7
if ($data -is [string]) {
if (($data.contains("Fout")) -or ($data.contains('ResultMessage'))) {
# haal opnieuw met andere encoding zodat foutmelding zichtbaar wordt.
$data = Doe-Webquery $SOAPUrl $iso88591
Write-Log $SOAPUrl
Throw "Webquery retourneert fout (1): $data"
}
}
if ($data[0] -is [string]) {
if ($data[0].contains("Fout_nummer") ) {
Write-Log $SOAPUrl
Throw "Webquery retourneert fout (2): $data"
}
}
return ($data | Out-String) -replace "`r`r","`r"
}
function VerwijderVreemdeTekens($n) {
<# vervangt alle niet-alfabettekens door gelijkende alfabettekens #>
$VervangTabel = @(`
"±n","Ļe","ļe","Ķe","ķe","ßa","õa","÷o","¾o","’i","·u","¹u","ńc","ŖS","Üs","Üs","²y","-","'")
# 'Mo¹rik' Ibßnez' 'Ŗromofsk²'
foreach ($letter in $VervangTabel) {
$n = $n -replace $letter[0], $letter[1]
}
return $n
}
Function VertaalTekens ($n) {
<# VertaalTekens vervangt alle vreemde tekens uit webquery naar de juiste tekens,
voor speciaal geval Ŗromofsk² . Dit doet een eerst conversie van vreemde tekens
uit de data in ANSI-codering naar herkenbare vreemde tekens, zodat deze later
vervangen, door romeinse tekens. Leer de code door uitvoer "onvertaald.txt"
te zien in hexeditor XVI32.
#>
return $n -replace [char]138, "Ŗ" -replace [char]0x9a, "Ü"
}
# --------------------------------------------------------------------
# --- M A I N ---
# --------------------------------------------------------------------
Write-Host " "
Write-Log "Start --- "
# resultaat bestaat uit regels tekst gescheiden door 0D, 0D, 0A
# dit is gelijk aan `r `r `n
$onvertaald = Ophalen-magister
$onvertaald | Out-File "$mijnpad\\onvertaald.txt"
$csv = vertaaltekens $onvertaald | ConvertFrom-Csv -Delimiter ";" # maak array met records
$csv | Export-CSV -Path "$mijnpad\\wismasleerling.csv" -Encoding UTF8 -NoTypeInformation
Write-Log ("Gegevens in webquery: {0}" -f $csv.count)
if (($csv.Count -lt 1490) -or ($csv.Count -ge 1570)) {
throw "Webquery geeft onwaarschijnlijk aantal resultaten. Uitvoering stopt."
}
$csv | Out-GridView; exit
|
PowerShellCorpus/PoshCode/Disable AD Users.ps1
|
Disable AD Users.ps1
|
$NumDays = 90
$LogDir = ".\\Disabled-User-Accounts.log"
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findall()
Write-Output `n`n"----------------------------------------" "ACCOUNTS OLDER THAN "$NumDays" DAYS" "PROCESSED ON:" $currentDate "----------------------------------------" `
| Out-File $LogDir -append
if ($users.Count -eq 0)
{
Write-Output " No account needs to be disabled." | Out-File $LogDir -append
}
else
{
foreach ($user in $users)
{
# Read the user properties
[string]$adsPath = $user.Properties.adspath
[string]$displayName = $user.Properties.displayname
[string]$samAccountName = $user.Properties.samaccountname
[string]$lastLogonInterval = $user.Properties.lastlogontimestamp
# Disable the user
$account=[ADSI]$adsPath
$account.psbase.invokeset("AccountDisabled", "True")
$account.setinfo()
# Convert the date and time to the local time zone
$lastLogon = [System.DateTime]::FromFileTime($lastLogonInterval)
Write-Output " Disabled user " $displayName" | Username: "$samAccountName" | Last Logon: "$lastLogon"`n" `
| Out-File $LogDir -append
}
}
|
PowerShellCorpus/PoshCode/User Entitlement Auditor.ps1
|
User Entitlement Auditor.ps1
|
$date = ( get-date ).ToString('yyyy-MM-dd-hh-mm')
$inpath = "C:\\InputDir\\"
$outpath = "C:\\Archive\\"
$FileList = @(Get-Childitem $inpath)
# Output CSV formatted report with members properly split up and unwanted domains/users removed:
$ResultFile = [System.IO.Path]::GetTempFileName()
$ADMembersOutfile = [System.IO.Path]::GetTempFileName()
$ReportFile = "C:\\EntitlementsAuditProject\\$date-UserEntitlementAuditTripWireFINALresult.csv"
# Wanted Local Groups
$WantedLocals = @("Administrators","Users")
# List of unwanted users to filter out:
$BadUsers = @("(null)", "")
# List of unwanted domains and system accounts to remove:
$BadDomains = @("NT AUTHORITY","NT SERVICE")
# Master function that calls all other functions in order
Function Main {
# Runs Split-Member function against Landesk output report and saves results to output file
Parse-XMLtoCSV $ResultFile
# Runs function that joins the two CSV files based on commonalities in the domain members field
JoinCSVs $ResultFile $ADMembersOutfile $ReportFile
# Ends Main function
}
# Function used to filter out unwanted Members. Function is called by Split-Member function
Function Is-ValidMember([string] $membername) {
# Creates array based on splitting resultant Members field data further where backslashes "\\" exist
$parts = $membername.Split("\\\\")
# Logic operators used to filter out unwanted users and domains
$BadDomains -notcontains $parts[0] -and $BadUsers -notcontains $parts[$parts.Length - 1]
# Ends Is-ValidMember function
}
Function Is-ValidLocalGroup([string] $localgroupname) {
$WantedLocals -contains $localgroupname
}
Function Parse-XMLtoCSV ([string] $outfile) {
$FileList | ForEach-Object {
Foreach ($file in $FileList) {
[xml]$xml = Get-Content $inpath$file
$xml.ReportOutput.ReportBody.ReportSection |
Foreach-Object {
$system = $_.Name
$_.ReportSection |
Foreach-Object {
$group = $_.name
$_.ReportSection.ReportSection.ReportSection |
Foreach-Object {
$_.String |
Foreach-Object {
If ($_."#TEXT" -ne $null) {
New-Object Object |
Add-Member NoteProperty "System" $system -PassThru |
Add-Member NoteProperty "LocalGroup" $group -PassThru |
Add-Member NoteProperty "LocalMembers" $_."#TEXT" -PassThru |
}
}
}
}
} | Where-Object { Is-ValidMember $_.LocalMembers } | Export-Csv -NoTypeInformation $outfile
}
Move-Item $inpath$file $outpath$file
}
}
# Function that pulls AD user and group data from domain controllers and outputs the data to a temp file. Function is called by JoinCSVs function
Function GetADMembersofGroups ([string] $outfile2) {
# Quest AD cmdlet is used here to get all Global Security groups in AD and pipes out results to next part
Get-QADGroup -SearchRoot "DC=dsl,DC=dittdsh,DC=org" -GroupType "Security" `
-GroupScope "Global" |
# Starts ForEach-Object loop
ForEach-Object {
# Sets up $NTAccount variable
$NTAccount = $_.NTAccountName
# Sets up $Domain variable
$Domain = $_.Domain
# Sets up GroupName variable
$GroupName =$_.Name
# Sets up CatGroupName variable which concatenates $Domain and $GroupName system strings into one string for later use
$CatGroupName = [System.String]::Concat($Domain,$GroupName)
# Quest AD cmdlet is used here to get all members of AD groups that were pulled above
Get-QADGroupMember -Identity $NTAccount -DontUseDefaultIncludedProperties -IncludedProperties `
"SamAccountName","Name"
# Ends ForEach-Object loop, pipes results to next process and starts another ForEach-Object loop
} | ForEach-Object {
# Variable used to equate $curr to current point in CSV array. This is necessary for processing items in a class as "$_" is not allowed
$curr = $_
# Uses New-Object to create a new class named Object and pipes results out for further processing so that properties can be added to the class
New-Object Object |
# Adds property to Object class based on concatenated $Domain and $GroupName strings, changes column name to GlobalMembers and pipes results
# out for further processing "-PassThru" is necessary in order to get Add-Member to output results
Add-Member NoteProperty "GlobalMembers" $CatGroupName -PassThru |
# Adds property to Object class based on Name column in input file, renames to Username and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member NoteProperty "Username" $curr.Name -PassThru |
# Adds property to Object class based on SamAccountName column in input file, renames to LogonID and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member NoteProperty "LogonID" $curr.SamAccountName -PassThru |
# Ends Object class processing loop, sorts objects by GlobalMembers colum and exports out to another temp CSV file
} | Sort-Object {$_.GlobalMembers} | Export-Csv -NoTypeInformation $outfile2
# Ends GetADMembersofGroups function
}
# Starts JoinCSVs function which joins the two temp files together based on the Domain Member columns in each file
Function JoinCSVs ([string] $infile2, [string] $infile3, [string] $outfile3) {
# Sets up $csv1 variable to hold all of the CSV data from the first temp file
$csv1 = Import-Csv $infile2
# Calls the GetADMembersofGroups function
GetADMembersofGroups $infile3
# Sets up $csv2 variable to hold all of the CSV data from the second temp file
$csv2 = Import-Csv $infile3
# Pipes data from first temp file into ForEach-Object loop
$csv1 | ForEach-Object {
# Variable used to equate $record to current point in CSV array. This is necessary for processing items in a class as "$_" is generally not allowed
$record = $_
# Sets up $matches variable which contains contents of second temp file ran through filter grabbing all matches of Domain Groups in both files
$matches = $csv2 | Where-Object {$_.GlobalMembers -eq $record.LocalMembers}
# Starts if loop to process $matches variable where there are matches between the two files. Where no match is found, process is moved to else loop
if ($matches){
# Pushes output of $matches variable through pipe and into a ForEach-Object loop
$matches | ForEach-Object{
# Uses New-Object to create a new class named Object and pipes results out for further processing so that properties can be added to the class
New-Object Object |
# Adds property to Object class based on Username column from 2nd file and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Username $_.Username -PassThru |
# Adds property to Object class based on LogonID column from 2nd file and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty LogonID $_.LogonID -PassThru |
# Adds property to Object class based on LocalMembers column from 1st file and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Members $record.LocalMembers -PassThru |
# Adds property to Object class based on Localgroup column from 1st file and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Localgroup $record.Localgroup -PassThru |
# Adds property to Object class based on System column from 1st file and pipes results out for further processing
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty System $record.System -PassThru |
# Ends ForEach-Object loop
}
# Ends if loop
}
# starts else loop for lines in the files that don't match
else {
# Uses New-Object to create a new class named Object and pipes results out for further processing so that properties can be added to the class
New-Object Object |
# Adds property to Object class for Username column and pipes out a null result as a placeholder for the CSV file
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Username $null -PassThru |
# Adds property to Object class for LogonID column and pipes out a null result as a placeholder for the CSV file
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty LogonID $null -PassThru |
# Adds property to Object class based on LocalMembers column from first file and pipes out results
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Members $_.LocalMembers -PassThru |
# Adds property to Object class based on Localgroup column from first file and pipes out results
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty Localgroup $_.Localgroup -PassThru |
# Adds property to Object class based on System column from first file and pipes out results
# "-PassThru" is necessary in order to get Add-Member to output results
Add-Member noteproperty System $_.System -PassThru |
# Ends else loop
}
# Ends ForEach-Object loop, pipes out results and exports them to the final result file
} | Export-Csv -NoTypeInformation $outfile3
# Removes the first temp file
Remove-Item -Force $infile2
# Removes the second temp file
Remove-Item -Force $infile3
# Ends JoinCSVs function
}
# Starts Main function, which is when the script runs completely
. Main
|
PowerShellCorpus/PoshCode/Invoke-V2Script.ps1
|
Invoke-V2Script.ps1
|
# Function may be useful for people who want to play with CTP1 for PowerShell 3 but need to use v2 scripts.
function Invoke-V2Script {
<#
.Synopsis
Will run script currently edited in ISE using powershell V2.
.Description
Will run script currently edited ISE. If it's not saved - it will automatically save it.
Difference between this command and F5 is that script will be launched using powershell V2.
.Example
Invoke-Script
Will run a script/ scriptblock using currently opened file.
#>
[CmdletBinding()]
param ()
if ($file = $psISE.CurrentFile) {
if (Test-Path $file.FullPath) {
Write-Verbose 'File exists...'
if (-not $File.IsSaved) {
$file.Save()
}
} else {
Write-Verbose 'Save a file as random .ps1 and run'
$NewName = Join-Path ([io.path]::GetTempPath()) ([io.path]::GetRandomFileName() + '.ps1')
$file.SaveAs($NewName)
$FullName = (Get-Item $NewName).FullName
powershell -Version 2 -NoProfile -File $FullName
return
}
if ((Get-Item $file.FullPath).extension -eq '.ps1') {
Write-Verbose 'Normal script, need to run it!'
powershell -Version 2 -NoProfile -File $file.FullPath
}
} else {
throw 'No file opened in current tab or tried to use it outside PowerShell ISE!'
}
}
try {
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Invoke V2 Script', { Invoke-V2Script }, 'CTRL + F5')
} catch {
Write-Warning 'Could not add shortcut. Adding menu item without it...'
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('Invoke V2 Script', { Invoke-V2Script }, $null)
}
|
PowerShellCorpus/PoshCode/Pivot-Object.ps1
|
Pivot-Object.ps1
|
#.Synopsis
# Pivot multiple objects which have properties that are name, value pairs
#.Description
# Takes a series of objects where there are multiple rows which have a pair of columns where the values are different on ech row with the name and value of an additional property, and outputs new objects which have those new properties on them.
#
#.Parameter GroupOnColumn
# The name of the property to merge on. Items with the same value in this column will be combined.
#.Parameter NameColumn
# The name of the property that has the names of the new properties to create.
#.Parameter ValueColumn
# The name of the property that has the values of the new properties to create
#.Parameter InputObject
# The input objects. These can be passed on the pipeline as well (or instead).
#.Parameter Jagged
# If Jagged is set, the objects that return only have the properties defined on them. Otherwise, all properties that are defined for any object are assinged (with null values) on all objects that are output.
#.Example
# Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value
#
# Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects.
#
#.Example
#@"
# ID, Attribute, Value, SamAccountName
# 12276, StdHrsPerWeek, 40, J8329029
# 12276, UserStyle, Fixed, J8329029
# 2479, LeaverId, L1153731, X5969731
# 2479, LastDayOffice, 20 Feb 2009, X5969731
#"@.Split("`n") | ConvertFrom-Csv | Pivot-Objects SamAccountName Attribute Value
#
#
#
#.Notes
# Author: Joel Bennett
#
#
# function Pivot-Object {
PARAM(
[string]$GroupOnColumn
, [string]$NameColumn
, [string]$ValueColumn
, [object[]]$InputObject=@()
, [switch]$Jagged
)
PROCESS {
if($_) {
$InputObject += $_
}
}
END {
if($InputObject[0] -isnot [PSObject]) {
$first = new-object PSObject $first
} else { $first = $InputObject[0] }
[string[]]$extra = @( $first.PSObject.Properties |
&{PROCESS{$_.Name}} |
Where { ($columns -notcontains $_) -and
(@($NameColumn,$ValueColumn) -notContains $_)
} )
[string[]]$columns = @($GroupOnColumn) + $extra +
@($InputObject | Select-Object -Expand $NameColumn | Sort-Object -Unique)
ForEach($item in $InputObject | group-Object $GroupOnColumn) {
$thing = New-Object PSObject |
Add-Member -Type NoteProperty -Name $GroupOnColumn -Value $item.Name -passthru
foreach($name in $extra) {
Add-Member -input $thing -MemberType NoteProperty -Name $name -Value $item.Group[0].$name
}
foreach($i in $item.Group) {
Add-Member -Input $thing -Type NoteProperty -Name $i.$NameColumn -Value $i.$ValueColumn
}
if($Jagged) {
Write-Output $thing
} else {
Write-Output $thing | select $columns
}
}
}
#}
|
PowerShellCorpus/PoshCode/Poshboard Inactive AD Ac.ps1
|
Poshboard Inactive AD Ac.ps1
|
@@ # UpdateADPC.ps1, to be run outside of Poshboard
function Get-DomainComputerAccounts
{
# Use Directory Services object to attach to the domain
$searcher = new-object DirectoryServices.DirectorySearcher([ADSI]"")
#Leaving the ADSI statement empty = attach to your root domain
# Filter down to computer accounts
$searcher.filter = "(&(objectClass=computer))"
# Cache the results
$searcher.CacheResults = $true
$searcher.SearchScope = “Subtree”
$searcher.PageSize = 1000
# Find anything you can that matches the definition of being a computer object
$accounts = $searcher.FindAll()
# Check to make sure we found some accounts
if($accounts.Count -gt 0)
{
foreach($account in $accounts)
{
# Property that contains the last password change in long integer format
$pwdlastset = $account.Properties["pwdlastset"];
# Convert the long integer to normal DateTime format
$lastchange = [datetime]::FromFileTimeUTC($pwdlastset[0]);
# Determine the timespan between the two dates
$datediff = new-TimeSpan $lastchange $(Get-Date);
# Create an output object for table formatting
$obj = new-Object PSObject;
# Add member properties with their name and value pair
$obj | Add-Member NoteProperty ComputerName($account.Properties["name"][0]);
$obj | Add-Member NoteProperty LastPasswordChange($lastchange);
$obj | Add-Member NoteProperty DaysSinceChange($datediff.Days);
# Write the output to the screen
Write-Output $obj;
}
}
}
Get-DomainComputerAccounts | Where-Object {$_.DaysSinceChange -gt 30} | sort dayssincechange | Export-CSV C:\\temp\\AD.csv -NoType
@@ #Poshboard Code
$dash = new-pbdashboard -Name "Object Password Age Method" -MaxColumns 1
$exclude = "UnixServer01","NetworkAppliance","Server01","Server02","Server03"
add-pbitem $dash (import-csv c:\\temp\\AD.csv | where {$exclude -notcontains $_.ComputerName} | out-pbdatagrid ComputerName,DaysSinceChange,LastPasswordChange -name "Computer accounts older than 30 days" -fontsize 10 -showgrouppane 0)
$dash
|
PowerShellCorpus/PoshCode/Test-WebDAV.ps1
|
Test-WebDAV.ps1
|
function Test-WebDav ()
{
param ( $Url = "$( throw 'URL parameter is required.')" )
$xhttp = New-Object -ComObject msxml2.xmlhttp
$xhttp.open("OPTIONS", $url, $false)
$xhttp.send()
if ( $xhttp.getResponseHeader("DAV") ) { $true }
else { $false }
}
|
PowerShellCorpus/PoshCode/Close by window title_1.ps1
|
Close by window title_1.ps1
|
using System;
using System.Text;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CloseByTitle")]
[assembly: AssemblyVersion("3.5.0.0")]
namespace CloseByTitle {
internal static class WinAPI {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
internal static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
}
internal class frmMain : Form {
public frmMain() {
InitializeComponent();
}
private TextBox txtTitle;
private Button btnClose;
private void InitializeComponent() {
this.txtTitle = new TextBox();
this.btnClose = new Button();
//
//txtTitle
//
this.txtTitle.Location = new Point(16, 16);
this.txtTitle.Width = 190;
//
//btnClose
//
this.btnClose.Location = new Point(220, 15);
this.btnClose.Text = "Close it!";
this.btnClose.Click += new EventHandler(btnClose_Click);
//
//frmMain
//
this.Controls.AddRange(new Control[] {this.txtTitle, this.btnClose});
this.ClientSize = new Size(310, 65);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += new EventHandler(frmMain_Load);
}
private static string GetText(IntPtr hWnd) {
int len = WinAPI.GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(len + 1);
len = WinAPI.GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString(0, len);
}
private void btnClose_Click(object sender, EventArgs e) {
int pid, res;
string search = txtTitle.Text, window = null;
if (!WinAPI.EnumWindows(new WinAPI.EnumWindowsProc((hWnd, lParam) => {
window = GetText(hWnd);
if (!string.IsNullOrEmpty(window) && window.Contains(search)) {
res = WinAPI.GetWindowThreadProcessId(hWnd, out pid);
//there is an exception if rights are not enough
if (res != 0) Process.GetProcessById(pid).Kill();
}
return true;
}), IntPtr.Zero)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
private void frmMain_Load(object sender, EventArgs e) {
Assembly assem = typeof(frmMain).Assembly;
string title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(assem,
typeof(AssemblyTitleAttribute))).Title;
this.Text = title;
}
}
internal sealed class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new frmMain());
}
}
}
|
PowerShellCorpus/PoshCode/Invoke-Sql_2.ps1
|
Invoke-Sql_2.ps1
|
<#
.SYNOPSIS
Runs a T-SQL Query and optional outputs results to a delimited file.
.DESCRIPTION
Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file.
.EXAMPLE
PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'"
This example connects to Z003\\sqlprod2.Orders and executes a stored procedure which does not return a result set
.EXAMPLE
PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\\Scripts\\accounts.txt" -Delimiter ","
This example connects to Z003\\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file
.NOTES
Version History
v1.0 - Chad Miller - 12/14/2010 - Initial release
IMPORTANT!!! The EventLog source which is set to the application needs to be registered with
the Event log:
New-EventLog -LogName Application -Source $Application
#>
param(
#ServerInstance is Mandatory!
[Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance,
#Database is Mandatory!
[Parameter(Position=1, Mandatory=$false)] [string]$Database,
#Query is Mandatory!
[Parameter(Position=2, Mandatory=$false)] [string]$Query,
[Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1",
[Parameter(Position=4, Mandatory=$false)] [string]$FilePath,
[Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|",
#If UserName isn't supplied a trusted connection will be used
[Parameter(Position=5, Mandatory=$false)] [string]$UserName,
[Parameter(Position=6, Mandatory=$false)] [string]$Password,
[Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600,
[Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15
)
#This must be run as administrator on Windows 2008 and higher!
New-EventLog -LogName Application -Source $Application -EA SilentlyContinue
$Error.Clear()
#######################
function Invoke-SqlCmd2
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [string]$Query,
[Parameter(Position=3, Mandatory=$false)] [string]$UserName,
[Parameter(Position=4, Mandatory=$false)] [string]$Password,
[Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout,
[Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout
)
try {
if ($Username)
{ $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
else
{ $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout }
$conn=new-object System.Data.SqlClient.SQLConnection
$conn.ConnectionString=$ConnectionString
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
Write-Output ($ds.Tables[0])
}
finally {
$conn.Dispose()
}
} #Invoke-SqlCmd2
#######################
# MAIN #
#######################
if ($PSBoundParameters.Count -eq 0)
{
get-help $myInvocation.MyCommand.Path -full
break
}
try {
$msg = $null
$msg += "Application/Job Name: $Application`n"
$msg += "Query: $Query`n"
$msg += "ServerInstance: $ServerInstance`n"
$msg += "Database: $Database`n"
$msg += "FilePath: $FilePath`n"
Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg"
$dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout
if ($FilePath)
{
if ($dt)
{ $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation }
else #Query Returned No Output!
{Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" }
}
Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg"
}
catch {
$Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" )
Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception"
throw
}
|
PowerShellCorpus/PoshCode/Create-Printers_2.ps1
|
Create-Printers_2.ps1
|
###########################################################################"
#
# NAME: Create-Printers.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
# BLOG: http://blog.powershell.no
#
# COMMENT: Simple script to bulk-create printers on a print-server. Printers are imported from a csv-file.
# Running the script from Windows Server 2003 returns an access denied error, possibly due to the impersonation-model in Windows Server 2003.
# Created and tested from Windows Server 2008 against a remote Windows Server 2003 print-server.
# Should work from Windows Vista, Windows 7, Windows Server 2008 and Windows Server 2008 R2 against remote print-servers (2000/2003/2008/2008 R2)
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 07.11.2009 - Initial release
#
###########################################################################"
function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_Printer").createInstance()
$print.drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID = $args[6]
$print.Put()
}
function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_TCPIPPrinterPort").createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=1
$port.HostAddress= $args[2]
$port.Put()
}
$printers = Import-Csv c:\\printers.csv
foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}
|
PowerShellCorpus/PoshCode/lol.ps1
|
lol.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/partial application.ps1
|
partial application.ps1
|
Set-StrictMode -Version 2
$commonParameters = @("Verbose",
"Debug",
"ErrorAction",
"WarningAction",
"ErrorVariable",
"WarningVariable",
"OutVariable",
"OutBuffer")
<#
.SYNOPSIS
Support function for partially-applied cmdlets and functions.
#>
function Get-ParameterDictionary {
[outputtype([Management.Automation.RuntimeDefinedParameterDictionary])]
[cmdletbinding()]
param(
[validatenotnull()]
[management.automation.commandinfo]$CommandInfo,
[validatenotnull()]
[management.automation.pscmdlet]$PSCmdletContext = $PSCmdlet
)
# dictionary to hold dynamic parameters
$rdpd = new-object Management.Automation.RuntimeDefinedParameterDictionary
try {
# grab parameters from function
if ($CommandInfo.parametersets.count > 1) {
$parameters = $CommandInfo.ParameterSets[[string]$CommandInfo.DefaultParameterSet].parameters
} else {
$parameters = $CommandInfo.parameters.getenumerator() | % {$CommandInfo.parameters[$_.key]}
}
$parameters | % {
write-verbose "testing $($_.name)"
# skip common parameters
if ($commonParameters -like $_.Name) {
write-verbose "skipping common parameter $($_.name)"
} else {
$rdp = new-object management.automation.runtimedefinedparameter
$rdp.Name = $_.Name
$rdp.ParameterType = $_.ParameterType
# tag new parameters to match this function's parameterset
$pa = new-object system.management.automation.parameterattribute
$pa.ParameterSetName = $PSCmdletContext.ParameterSetName
$rdp.Attributes.Add($pa)
$rdpd.add($_.Name, $rdp)
}
}
} catch {
Write-Warning "Error getting parameter dictionary: $_"
}
# return
$rdpd
}
<#
.SYNOPSIS
Function that accepts a FunctionInfo or CmdletInfo reference and one or more parameters
and returns a FunctionInfo bound to those parameter(s) and their value(s.)
.DESCRIPTION
Function that accepts a FunctionInfo or CmdletInfo reference and one or more parameters
and returns a FunctionInfo bound to those parameter(s) and their value(s.)
Any parameters "merged" into the function are removed from the available parameters for
future invocations. Multiple chained merge-parameter calls are permitted.
.EXAMPLE
First, we define a simple function:
function test {
param($a, $b, $c, $d);
"a: $a; b: $b; c:$c; d:$d"
}
Now we merge -b parameter into functioninfo with the static value of 5, returning a new
functioninfo:
ps> $x = merge-parameter (gcm test) -b 5
We execute the new functioninfo with the & (call) operator, passing in the remaining
arguments:
ps> & $x -a 2 -c 4 -d 9
a: 2; b: 5; c: 4; d: 9
Now we merge two new parameters in, -c with the value 3 and -d with 5:
ps> $y = merge-parameter $x -c 3 -d 5
Again we call $y with the remaining named parameter -a:
ps> & $y -a 2
a: 2; b: 5; c: 3; d: 5
.EXAMPLE
Cmdlets can also be subject to partial application. In this case we create a new
function with the returned functioninfo:
ps> si function:get-function (merge-parameter (gcm get-command) -commandtype function)
ps> get-function
<lists all commands of commandtype "function">
.PARAMETER _CommandInfo
The FunctionInfo or CmdletInfo into which to merge (apply) parameter(s.)
The parameter is named with a leading underscore character to prevent parameter
collisions when exposing the targetted command's parameters and dynamic parameters.
.INPUTS
FunctionInfo or CmdletInfo
.OUTPUTS
FunctionInfo
#>
function Merge-Parameter {
[OutputType([Management.Automation.FunctionInfo])]
[CmdletBinding()]
param(
[parameter(position=0, mandatory=$true)]
[validatenotnull()]
[validatescript({
($_ -is [management.automation.functioninfo]) -or `
($_ -is [management.automation.cmdletinfo])
})]
[management.automation.commandinfo]$_Command
)
dynamicparam {
# strict mode compatible check for parameter
if ((test-path variable:_command)) {
# attach input functioninfo's parameters to self
Get-ParameterDictionary $_Command $PSCmdlet
}
}
begin {
write-verbose "merge-parameter: begin"
# copy our bound parameters, except common ones
$mergedParameters = new-object 'collections.generic.dictionary[string,object]' $PSBoundParameters
# remove our parameters, leaving only target function/CommandInfo's args to curry in
$mergedParameters.remove("_Command") > $null
# remove common parameters
$commonParameters | % {
if ($mergedParameters.ContainsKey($_)) {
$mergedParameters.Remove($_) > $null
}
}
}
process {
write-verbose "merge-parameter: process"
# temporary function name
$temp = [guid]::NewGuid()
$target = $_Command
# splat our fixed named parameter(s) and then splat remaining args
$partial = {
[cmdletbinding()]
param()
# begin dynamicparam
dynamicparam
{
$targetRdpd = Get-ParameterDictionary $target $PSCmdlet
# remove fixed parameters
$mergedParameters.keys | % {
$targetRdpd.remove($_) > $null
}
$targetRdpd
}
begin {
write-verbose "i have $($mergedParameters.count) fixed parameter(s)."
write-verbose "i have $($targetrdpd.count) remaining parameter(s)"
}
# end dynamicparam
process {
$boundParameters = $PSCmdlet.MyInvocation.BoundParameters
# remove common parameters (verbose, whatif etc)
$commonParameters | % {
if ($boundParameters.ContainsKey($_)) {
$boundParameters.Remove($_) > $null
}
}
# invoke command with fixed parameters and passed parameters (all named)
. $target @mergedParameters @boundParameters
if ($args) {
write-warning "received $($args.count) arg(s) not part of function."
}
}
}
# emit function/CommandInfo
new-item -Path function:$temp -Value $partial.GetNewClosure()
}
end {
# cleanup
rm function:$temp
}
}
new-alias papp Merge-Parameter -force
Export-ModuleMember -Alias papp -Function Merge-Parameter, Get-ParameterDictionary
|
PowerShellCorpus/PoshCode/Xml Module 4.8.ps1
|
Xml Module 4.8.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
# Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
# Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
# Version 4.3 Added a Path parameter set to Format-XML so you can specify xml files for prety printing
# Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
# Work around possible variable slipping on null values by:
# 1) allowing -param:$value syntax (which doesn't fail when $value is null)
# 2) testing for -name syntax on the value and using it as an attribute instead
# Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
# Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
# Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
# Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
if(!$xlr8r::Get["Stack"]) {
$xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["Dictionary"]) {
$xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
filter Format-XML {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Path
# The path to an xml document (on disc or any other content provider).
#.Parameter Indent
# The indent level (defaults to 2 spaces)
#.Example
# [xml]$xml = get-content Data.xml
# C:\\PS>Format-Xml $xml
#.Example
# get-content Data.xml | Format-Xml
#.Example
# Format-Xml C:\\PS\\Data.xml
#.Example
# ls *.xml | Format-Xml
#
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
[xml]$Xml
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PsPath")]
[string]$Path
,
[Parameter(Mandatory=$false)]
$Indent=2
)
## Load from file, if necessary
if($Path) { [xml]$xml = Get-Content $Path }
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}
Set-Alias fxml Format-Xml -EA 0
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter XPath
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
#.Parameter RemoveNamespace
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Hashtable]$Namespace
,
[Switch]$RemoveNamespace
)
BEGIN {
function Select-Node {
PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager)
BEGIN {
foreach($node in $xml) {
if($NamespaceManager -is [Hashtable]) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Namespace.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
}
foreach($path in $xpath) {
$node.SelectNodes($path, $nsManager)
} } } }
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace -Xml $Xml
}
Select-Node $Xml $XPath $NSM
}
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
[Xml]$node = Remove-XmlNamespace -Xml $node
}
Select-Node $node $XPath $NSM
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace -Xml $Xml
}
Select-Node $Xml $XPath $NSM
}
}
}
Set-Alias slxml Select-Xml -EA 0
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
[CmdletBinding(DefaultParameterSetName="Reader")]
param(
[Parameter(ParameterSetName="ByNode",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlNode]$Node
,
[Parameter(ParameterSetName="Reader",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
,
[Parameter(Position=2,Mandatory=$false)]
[Alias("Parameters")]
[hashtable]$Arguments
)
PROCESS {
if($PSCmdlet.ParameterSetName -eq "ByNode") {
$XmlReader = New-Object Xml.XmlNodeReader $node
}
$output = New-Object IO.StringWriter
$argList = $null
if($Arguments) {
$argList = New-Object System.Xml.Xsl.XsltArgumentList
foreach($arg in $Arguments.GetEnumerator()) {
$namespace, $name = $arg.Key -split ":"
## Fix namespace
if(!$name) {
$name = $Namespace
$namespace = ""
}
Write-Verbose "ns:$namespace name:$name value:$($arg.Value)"
$argList.AddParam($name,"$namespace",$arg.Value)
}
}
$StyleSheet.Transform( $XmlReader, $argList, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
,
[Alias("Parameters")]
[hashtable]$Arguments
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
$OFS = "`n"
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader "$Xslt" )) ))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet $Arguments
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Node $Xml $StyleSheet $Arguments
}
}
}
Set-Alias cvxml Convert-Xml -EA 0
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
#,
# [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
# [ValidateNotNullOrEmpty()]
# [Alias("StyleSheet")]
# [String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
Convert-Node -Node $Xml $StyleSheet
}
}
"Xml" {
$Xml | Convert-Node $StyleSheet
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Node $Xml $StyleSheet
}
}
}
Set-Alias rmns Remove-XmlNamespace -EA 0
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [string]$xml = New-XDocument rss -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# C:\\PS>$xml.ToString()
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#
# Description
# -----------
# This example shows the creation of a complete RSS feed with a single item in it.
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.
#
#
#.Example
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
# Description
# -----------
# This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString().
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.#
#
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
# Write-Verbose "Preparsed DSL: $attrib"
$attrib = ConvertFrom-XmlDsl $attrib
Write-Verbose "Reparsed DSL: $attrib"
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) {
$value = ConvertFrom-XmlDsl $value
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} else {
Write-Verbose "XAttribute $attrib = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
))
}
}
Set-Alias xml New-XDocument -EA 0
Set-Alias New-Xml New-XDocument -EA 0
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute -EA 0
Set-Alias New-XmlAttribute New-XAttribute -EA 0
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
# BEGIN {
# if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
# $tag = $($script:NameSpaceStack.Peek()) + $tag
# if( $script:NameSpaceStack.Count -gt 0 ) {
# $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() )
# } else {
# $script:NameSpaceStack.Push( $null )
# }
# } else {
# $script:NameSpaceStack.Push( $tag.Namespace )
# }
# }
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} elseif($value -match "-(?!\\d)\\w") {
$args = @($value)+@($args)
} elseif($value -ne $null) {
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
)
}
# END {
# $null = $script:NameSpaceStack.Pop()
# }
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function ConvertFrom-XmlDsl {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) }
[Array]::Reverse( $duds )
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
######## CliXml
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [type]::gettype("System.Management.Automation.Deserializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
$sr = new-object System.IO.StringReader $xmlString
$xr = new-object System.Xml.XmlTextReader $sr
$deserializer = $ctor.invoke($xr)
$method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
while (!$done.invoke($deserializer, @()))
{
try {
$method.invoke($deserializer, "")
} catch {
write-warning "Could not deserialize $string: $_"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [type]::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()
}
}
######## Xaml
# if($PSVersionTable.CLRVersion -ge "4.0"){
# trap { continue }
# [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null
# if("System.Xaml.XamlServices" -as [type]) {
# }
# }
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUlQ5L584Qz0SNfIkR1t7nIJfC
# Friggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEa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lLyxQXIF+fmW
# ix2qQJ4UC6B1pjjv/Fv5KMuSDpgLOhLtzQeubmeqBGjeoumaPvYgvPsn6rYvBxWY
# 9wdP8VCGVCIrEsUUyAuXoxzpFJk80PAX08bdvcOkQ7GQ13HEN4JBDtDTYHFV9M7v
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get Active Sync devices _1.ps1
|
Get Active Sync devices _1.ps1
|
<#
.SYNOPSIS
Get-InactiveActiveSyncDevices pulls all user mailboxes with an Active Sync partnership and then selects the Active Sync devices that haven't synced in the specified period. These devices are sorted in ascending order and placed in a HTML table which is emailed to the specified user using a specified reply to address and SMTP server
PLEASE TEST BEFORE RUNNING THIS SCRIPT IN PRODUCTION
.DESCRIPTION
The script 1st checks to see if Implicit remoting is needed to load the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010), this is done by seeing it the $ExchangeConnectionUri variable does not have a $NULL value. If it contains a URI then create a new PSsession using the current credentials and import the session. If Implict remoting isn't needed then verify that the required PSsnapin (Microsoft.Exchange.Management.PowerShell.E2010) is loaded and if not try to load it locally. Then Get-InactiveActiveSyncDevices uses Get-CasMailbox to pull all the user mailboxes (Not Discovery or CAS mailboxes) with Active Sync device partnerships and saves them to a variable called $ActiveSyncMailboxes. It then walks through each mailbox and uses Get-ActiveSyncDeviceStatistics to pull DeviceType, DeviceUserAgent, DeviceID, LastSyncAttemptTime, LastSuccessSync for each mailboxís separate Active Sync device partnership and puts these properties in addition to the full name associated with the mailbox into a hashtable called $UserActiveSyncStats. The reason why Get- ActiveSyncDeviceStatistics isnít used exclusively is because it does not have a property that stores just the name of the user who owns the Active Sync device, only a full Active Directory path to the Active Sync device. This hash table is used to create a custom PowerShell Object which is then added to $ActiveSyncDeviceList. A variable called $MatchingActiveSyncDevices holds all the Active Sync devices in $ActiveSyncDeviceList that havenít synced to the Exchanger server in less than or equal to the number of hours specified in $HourInterval . $MatchingActiveSyncDevices is then checked to see if itís an empty array or not. If it contains items an HTML header is created to format the table for the HTML email report and saved in a variable called $HTMLHeader . Then The Body of the email contains all of the criteria matching Active Sync devices from $MatchingActiveSyncDevices in ascending order which is converted to HTML using the HTML header information created earlier in $HTMLHeader. Otherwise a the body contains a message stating that no devices matched the given criteria.. An Email is then sent out to the user specified in $to from the address specified in $from using the email server specified in $SmtpServer. The body is generated from the sorted Active Synce Devices in $ActiveSyncDeviceList.
.PARAMETER to
The email address the email report will go to
.PARAMETER from
The email address the email report will come from
.PARAMETER SmtpServer
The IP address or DNS name of the SMTP server that will be used to send the email report
.PARAMETER HourInterval
The interval in hours. Any mailbox that hasn't synced to the Exchnage server
.PARAMETER ExchangeConnectionUri
URI of Powershell Session on an Exchange 2010 server. Used if the PC running this script does not have the required PSsnapin loaded
.EXAMPLE
Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer Mail.company.com -HourInterval 24
Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com
.EXAMPLE
Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer 10.10.50.100 -HourInterval 24
Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com
.EXAMPLE
Get-InactiveActiveSyncDevices -to User@company.com -from ActiveSyncDeviceReport@Company.com -SmtpServer 10.10.50.100 -HourInterval 24 -ExchangeConnectionUri http://mail.company.com/PowerShell/
Send an email report of all Active Sync devices that haven't synced to the mail server in the past 24 hours to User@company.com from ActiveSyncDeviceReport@Company.com through the email server with the DNS name of Mail.company.com using the Exchange Connection Uri of http://mail.company.com/PowerShell/ in order to use implicit remoting to pull in the required PSsnapin
.NOTES
NAME: Get-InactiveActiveSyncDevices
AUTHOR: John Mello
AUTHOR WEBSITE: mellositmusings.com
LASTEDIT: 02/17/2013
KEYWORDS: Exchange 2010, Active Synce
.LINK
Latest version can be found at :
http://gallery.technet.microsoft.com/scriptcenter/Get-Active-Sync-devices-9bfb5116
#Requires -Version 2.0
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True,HelpMessage="Enter a email address to send the report too")]
[string]$to,
[Parameter(Mandatory=$True,HelpMessage="Enter the email address the report should come from")]
[string]$from,
[Parameter(Mandatory=$True,HelpMessage="Enter the IP or DNS name of the mail server that will send the report")]
[string]$SmtpServer,
[Parameter(Mandatory=$True,HelpMessage="Enter the hour interval to check against (e.g. 24)")]
[int]$HourInterval,
$ExchangeConnectionUri = $NULL
)
Write-Verbose "Checking if implict remoting to an Exchnage 2010 server was specified"
if ($ExchangeConnectionUri -eq $NULL)
{
Write-Verbose "Checking for Microsoft.Exchange.Management.PowerShell.E2010 PSSnapin"
if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $NULL )
{
Write-Verbose "Microsoft.Exchange.Management.PowerShell.E2010 not installed, intalling now"
Add-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010
}
Else
{
Write-Verbose "Microsoft.Exchange.Management.PowerShell.E2010 PSSnapin is installed"
}
}
Else
{
Write-Verbose "Creating Implict remoting to $ExchangeConnectionUri"
$ExchangeImplictSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchangeConnectionUri -Authentication Kerberos
Write-Verbose "Importing session"
Import-PSSession $ExchangeImplictSession
}
Write-Verbose "Get all Mailboxes using Get-CASMailbox and filter by the HasActiveSyncDevicePartnership property but do not include CAS or Discovery Mailboxes"
$ActiveSyncMailboxes = Get-CASMailbox -ResultSize unlimited -Filter{(HasActiveSyncDevicePartnership -eq $true) -AND (name -notlike "cas_*") -AND (name -notlike "DiscoverysearchMailbox*")}
Write-Verbose "Start Processing list"
$ActiveSyncDeviceList = $ActiveSyncMailboxes |
ForEach-Object {
Write-Verbose 'Pull the active sync device/devices from the current mailbox in $ActiveSyncMailboxes'
$CurrentDevice = Get-ActiveSyncDeviceStatistics ñMailbox $_.Identity
$VerboseNameHold=$_.Name
Write-Verbose "Use an IF statement to check if the Mailbox belonging to $VerboseNameHold has multiple Active Sync Devices"
If ($CurrentDevice -is [Array])
{
Write-Verbose "User $VerboseNameHold has multiple Active Sync devices"
$Index = 0
Write-Verbose "Active sync device index = $Index"
$VerboseTotalDeviceHold = $CurrentDevice.count
$VerboseIndexHold = $Index + 1
ForEach($Device in $CurrentDevice)
{
Write-Verbose "Current mailbox belonging to $VerboseNameHold has multiple devices currently on device # $VerboseIndexHold of $VerboseTotalDeviceHold"
Write-Verbose "Putting Active Device Statistics into a hash table"
$UserActiveSyncStats = @{
Name=$_.Name
DeviceType=$CurrentDevice[$index].DeviceType
DeviceUserAgent=$CurrentDevice[$index].DeviceUserAgent
DeviceID=$CurrentDevice[$index].DeviceID
LastSyncAttemptTime=$CurrentDevice[$index].LastSyncAttemptTime
LastSuccessSync=$CurrentDevice[$index].LastSuccessSync
}
Write-Verbose 'Creating a new Object using the $UserActiveSyncStats hashtable to create the properties, this will become an array entry in $ActiveSyncDeviceList'
New-Object -TypeName PSObject -Property $UserActiveSyncStats
$index++
$VerboseIndexHold++
Write-Verbose "Active Sync Device index incremented to $index"
}
}
Else
{
Write-Verbose "Current mailbox beloning to $VerboseNameHold does not have multiple devices"
Write-Verbose "Putting Active Device Statistics into a hash table"
$UserActiveSyncStats = @{
Name=$_.Name
DeviceType=$CurrentDevice.DeviceType
DeviceUserAgent=$CurrentDevice.DeviceUserAgent
DeviceID=$CurrentDevice.DeviceID
LastSyncAttemptTime=$CurrentDevice.LastSyncAttemptTime
LastSuccessSync=$CurrentDevice.LastSuccessSync
}
Write-Verbose 'Creating a new Object using the $UserActiveSyncStats hashtable to create the properties, this will become an array entry in $ActiveSyncDeviceList'
New-Object -TypeName PSObject -Property $UserActiveSyncStats
}
}
$CurrentDateandTime = Get-date
Write-Verbose "Saving Current date ($CurrentDateandTime) to a variable so that the same date is used for comparison to specified interval ($HoustsInterval)"
$date = $CurrentDateandTime.AddHours(-$HourInterval)
Write-Verbose "Subtracting ${HourInterval}hrs from todays date"
Write-Verbose "Finding devices that haven't synced since $date"
$MatchingActiveSyncDevices = $ActiveSyncDeviceList | Where-Object {$_.LastSuccessSync -le $date}
Write-Verbose 'Checking $MatchingActiveSyncDevices to see if it contains any devices that match tne criteria'
If ($MatchingActiveSyncDevices.count -gt 0)
{
Write-Verbose '$MatchingActiveSyncDevices is not an empty array, devices that match the criteria have been found'
Write-Verbose "Creating html header for email body"
$HTMLHeader = "<Style>"
$HTMLHeader = $HTMLHeader + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse}"
$HTMLHeader = $HTMLHeader + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: DarkGray}"
$HTMLHeader = $HTMLHeader + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: PaleTurquoise}"
$HTMLHeader = $HTMLHeader + "</Style>"
Write-Verbose "Creating email body which incldues all devices that havent synced in the ${HourInterval}hrs"
$body = $MatchingActiveSyncDevices |
sort LastSuccessSync |
ConvertTo-html -head $HTMLHeader -Property Name,LastSuccessSync,DeviceType,DeviceUserAgent,DeviceID,LastSyncAttemptTime |
Out-String
}
Else
{
Write-Verbose '$MatchingActiveSyncDevices is an empty array, no devices that match the criteria have been found'
$body = "All Active Sync devices have synced with the Exchange Server within the past ${HourInterval}hrs"
}
Write-Verbose "Creating Email Subject"
$Subject = "Active Sync device report for "
$Subject += $CurrentDateandTime.ToShortDateString()
$Subject += " : "
$Subject += $MatchingActiveSyncDevices.count
$Subject += " devices haven't synced in the past ${HourInterval}hrs since "
$Subject += $CurrentDateandTime.ToShortTimeString()
$Subject += " today"
Write-Verbose "Sending email from $from to $to via the following email server : $SmtpServer"
Send-MailMessage -to $to -Subject $Subject -From $from -SmtpServer $SmtpServer -Body $Body -BodyAsHtml
|
PowerShellCorpus/PoshCode/ADFS local update.ps1
|
ADFS local update.ps1
|
Add-PSSnapin Microsoft.Adfs.Powershell
Import-Module MSOnline
$cred = Get-Credential
$AdfsServer = Read-Host "Please type the name of the ADFS server"
Write-Host "Connecting to MSOnline..."
Connect-MsolService -credential:$cred
Write-Host "Setting the local ADFS server..."
Set-MSOLADFSContext -Computer:$AdfsServer
Write-Host "Updating the ADFS server configuration..."
Update-ADFSCertificate -CertificateType:Token-signing -Urgent:$True
|
PowerShellCorpus/PoshCode/Get-MailboxImportRequest.ps1
|
Get-MailboxImportRequest.ps1
|
# .Synopsis
# Use the Get-MailboxImportRequestProgress cmdlet to view detailed information about pst import progress.
# .Description
# The Get-MailboxImportRequestProgress cmdlet displays statistics on imports currently in progress that help determine if a import is likely to complete successfully. To accureately evaluate the current progress of an import examine the durration it has been running and the number of times the estimated number of items have been transferred.
#
# The following may indicate an import is stalled and will neither Complete or Fail:
# * Item % is over 200
# * ItemsLeft is -2000 or lower
# * BytesTransferred is under 1MB and Durration is over 2 hours
#
# Using ScanPST may repair the damange to the pst and allow it to complete successfully. Otherwise, the only other option is to use the full Outlook client.
#
# .Example
# Get-MailboxImportRequest -Status InProgress|Get-MailboxImportRequestProgress
# .Example
# Get-MailboxImportRequestProgress|ft -auto
[CmdletBinding()]
PARAM ()
BEGIN {
# We need this because 2.0 broke adding default properties the old way.
# https://connect.microsoft.com/PowerShell/feedback/details/487938/v2-0-rtm-defining-default-properties-for-custom-objects-no-longer-works
Function Set-DefaultProperties {
PARAM (
[PSObject]$Object,
[string[]]$DefaultProperties
)
$name = $Object.PSObject.TypeNames[0]
$xml = "<?xml version='1.0' encoding='utf-8' ?><Types><Type>"
$xml += "<Name>$($name)</Name>"
$xml += "<Members><MemberSet><Name>PSStandardMembers</Name><Members>"
$xml += "<PropertySet><Name>DefaultDisplayPropertySet</Name><ReferencedProperties>"
foreach( $default in $DefaultProperties ) {
$xml += "<Name>$($default)</Name>"
}
$xml += "</ReferencedProperties></PropertySet></Members></MemberSet></Members>"
$xml += "</Type></Types>"
$file = "$($env:Temp)\\$name.ps1xml"
Out-File -FilePath $file -Encoding "UTF8" -InputObject $xml -Force
$typeLoaded = $host.Runspace.RunspaceConfiguration.Types | where { $_.FileName -eq $file }
if( $typeLoaded -ne $null ) {
Write-Verbose "Type Loaded"
Update-TypeData
}
else {
Update-TypeData $file
}
}
}
PROCESS
{
# Mailbox Import requests were piped in
if($_)
{
if($_.Identity.GetType() -eq [Microsoft.Exchange.MailboxReplicationService.RequestJobObjectId])
{
$temp = $_|Get-MailboxImportRequestStatistics|select,@{n="ItemsLeft";e={$_.estimatedtransferitemcount - $_.itemstransferred}} @{n="Item %";e={[int]($_.itemstransferred/$_.estimatedtransferitemcount * 100)}},@{n="Total %";e={$_.percentcomplete}},@{n="Durration";e={$_.TotalInProgressDuration}},*
} else { Write-Warning "Invalid Mailbox Import Request ID" }
# We just want all imports in progress
} else {
$temp = Get-MailboxImportRequest -status InProgress|Get-MailboxImportRequestStatistics|select @{n="ItemsLeft";e={$_.estimatedtransferitemcount - $_.itemstransferred}},@{n="Item %";e={[int]($_.itemstransferred/$_.estimatedtransferitemcount * 100)}},@{n="Total %";e={$_.percentcomplete}},@{n="Durration";e={$_.TotalInProgressDuration}},*
}
# Define the default property set
$temp |% {
$_.PSObject.TypeNames.Insert(0,’Microsoft.Exchange.MailboxReplicationService.MailboxImportRequest#Progress’)
}
Set-DefaultProperties @($temp)[0] @(‘TargetAlias','StatusDetail','BytesTransferred','ItemsTransferred','ItemsLeft','Item %','Total %','Durration')
$temp
}
|
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP3)_3.ps1
|
Set-Wallpaper (CTP3)_3.ps1
|
#requires -version 2.0
## Set-Wallpaper - set your windows desktop wallpaper
###################################################################################################
## Usage:
## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Wallpaper\\Dual Monitor\\mandolux-tiger.jpg" "Tile"
## ls *.jpg | get-random | Set-Wallpaper
## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch"
###################################################################################################
## History:
## v0.5 First release (on #PowerShell@irc.freenode.net)
## v1.0 Public release (http://www.poshcode.org/488)
## - Added Style: Tile|Center|Stretch
## v1.1 (http://poshcode.org/491)
## - Added "NoChange" style to just use the style setting already set
## - Made the Style parameter to the cmdlet optional
## v2.0 This Release
## - Updated for CTP3, and made it run as a script instead of a function.
## v2.1 Moved SystemParametersInfo Update after registry update section
###################################################################################################
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
[Wallpaper.Style]
$Style = "NoChange"
)
BEGIN {
try {
$WP = [Wallpaper.Setter]
} catch {
$WP = add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tile, Center, Stretch, NoChange
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tile :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.NoChange :
break;
}
key.Close();
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
}
}
}
"@ -Passthru
}
}
PROCESS {
Write-Verbose "Setting Wallpaper ($Style) to $(Convert-Path $Path)"
$WP::SetWallpaper( (Convert-Path $Path), $Style )
}
|
PowerShellCorpus/PoshCode/PowerCLI 4.1.ps1
|
PowerCLI 4.1.ps1
|
$vmPath = "[Storage1] MyVM/MyVM.vmx"
$vm = New-VM –VMHost "192.168.1.10" –VMFilePath $vmPath -Name MyVM
# Check if there is an error and if so – handle it
if (!$?) {
if ($error[0].Exception –is [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.DuplicateName]) {
# A VM with the same name already exists. Change the name and try again.
$vm = New-VM –VMHost "192.168.1.10" –VMFilePath $vmPath –Name "myVM (1)"
} elseif ($error[0].Exception –is [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InsufficientResourcesFault]) {
# There aren’t enough resources on this host. Try again on another host.
$vm = New-VM –VMHost "192.168.1.12" –VMFilePath $vmPath
} else {
# Handle unexpected exceptions here …
}
}
|
PowerShellCorpus/PoshCode/chkhash_8.ps1
|
chkhash_8.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++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
if ($i -ge $args2.count) {break}
$exclude+=@($args2[$i]) # collect array of excluded directories.
if (($i+1) -ge $args2.count) {break}
} while ($args2[$i+1] -notlike "-*")
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath) # Load database
}
else
{
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)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
$xfiles+=@($f) # then add file + hash to list
continue
}
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Get-CalendarWeek_2.ps1
|
Get-CalendarWeek_2.ps1
|
# Get-CalendarWeek by Holger Adam
# Simple function to retrieve the calendar week to a given or the current date.
function Get-CalendarWeek {
param(
$Date = (Get-Date)
)
# get current culture object
$Culture = [System.Globalization.CultureInfo]::CurrentCulture
# retrieve calendar week
$Culture.Calendar.GetWeekOfYear($Date, $Culture.DateTimeFormat.CalendarWeekRule, $Culture.DateTimeFormat.FirstDayOfWeek)
}
|
PowerShellCorpus/PoshCode/Colorize Subversion SVN_5.ps1
|
Colorize Subversion SVN_5.ps1
|
# detect source control management software
function findscm {
$scm = ''
:selectscm foreach ($_ in @('svn', 'hg')) {
$dir = (Get-Location).ProviderPath.trimEnd("\\")
while ($dir.Length -gt 3) {
if (Test-Path ([IO.Path]::combine(($dir), ".$_"))) {
$scm = $_
break selectscm
}
$dir = $dir -Replace '\\\\[^\\\\]+$', ''
}
}
return $scm
}
# draw output
function drawlines($colors, $cmd) {
$scm = findscm
if (!$cmd -or !$scm) { return }
foreach ($line in (&$scm ($cmd).split())) {
$color = $colors[[string]$line[0]]
if ($color) {
write-host $line -Fore $color
} else {
write-host $line
}
}
}
# svn stat
function st {
drawlines @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } "stat $args"
}
# svn update
function su {
drawlines @{ "A"="Magenta"; "D"="Red"; "U"="Green"; "C"="Yellow"; "G"="Blue"; } "up $args"
}
# svn diff
function sd {
drawlines @{ "@"="Magenta"; "-"="Red"; "+"="Green"; "="="DarkGray"; } "diff $args"
}
|
PowerShellCorpus/PoshCode/Send-File.ps1
|
Send-File.ps1
|
##############################################################################\n##\n## Send-File\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\nSends a file to a remote session.\n\n.EXAMPLE\n\nPS >$session = New-PsSession leeholmes1c23\nPS >Send-File c:\\temp\\test.exe c:\\temp\\test.exe $session\n\n#>\n\nparam(\n ## The path on the local computer\n [Parameter(Mandatory = $true)]\n $Source,\n\n ## The target path on the remote computer\n [Parameter(Mandatory = $true)]\n $Destination,\n\n ## The session that represents the remote computer\n [Parameter(Mandatory = $true)]\n [System.Management.Automation.Runspaces.PSSession] $Session\n)\n\nSet-StrictMode -Version Latest\n\n## Get the source file, and then get its content\n$sourcePath = (Resolve-Path $source).Path\n$sourceBytes = [IO.File]::ReadAllBytes($sourcePath)\n$streamChunks = @()\n\n## Now break it into chunks to stream\nWrite-Progress -Activity "Sending $Source" -Status "Preparing file"\n$streamSize = 1MB\nfor($position = 0; $position -lt $sourceBytes.Length;\n $position += $streamSize)\n{\n $remaining = $sourceBytes.Length - $position\n $remaining = [Math]::Min($remaining, $streamSize)\n\n $nextChunk = New-Object byte[] $remaining\n [Array]::Copy($sourcebytes, $position, $nextChunk, 0, $remaining)\n $streamChunks += ,$nextChunk\n}\n\n$remoteScript = {\n param($destination, $length)\n\n ## Convert the destination path to a full filesytem path (to support\n ## relative paths)\n $Destination = $executionContext.SessionState.`\n Path.GetUnresolvedProviderPathFromPSPath($Destination)\n\n ## Create a new array to hold the file content\n $destBytes = New-Object byte[] $length\n $position = 0\n\n ## Go through the input, and fill in the new array of file content\n foreach($chunk in $input)\n {\n Write-Progress -Activity "Writing $Destination" `\n -Status "Sending file" `\n -PercentComplete ($position / $length * 100)\n\n [GC]::Collect()\n [Array]::Copy($chunk, 0, $destBytes, $position, $chunk.Length)\n $position += $chunk.Length\n }\n\n ## Write the content to the new file\n [IO.File]::WriteAllBytes($destination, $destBytes)\n\n ## Show the result\n Get-Item $destination\n [GC]::Collect()\n}\n\n## Stream the chunks into the remote script\n$streamChunks | Invoke-Command -Session $session $remoteScript `\n -ArgumentList $destination,$sourceBytes.Length
|
PowerShellCorpus/PoshCode/Reset SharePoint Alerts.ps1
|
Reset SharePoint Alerts.ps1
|
Function Reset-Alerts
{
<#
.Synopsis
Resets alerts for the specified site.
.Description
By default this resets scheduled alerts for the specified site.
This can also reset all alerts for the site and/or for a specific user.
This is inspired by: http://gallery.technet.microsoft.com/scriptcenter/877d2abd-fce9-4545-b223-7637936dd888
.Parameter Url
The url of the site to fix. Required Parameter.
.Parameter User
Optional UserName to reset.
.Parameter All
Reset all alerts.
.Example
Reset all scheduled alerts for the specific site. This operation can not be undone!
PS > Reset-Alerts -url "http://teams/sites/newteam"
.Example
Reset all scheduled alerts for the specified user for this specific site. This operation can not be undone!
PS > Reset-Alerts -url "http://teams/sites/newteam" -user "username"
.Example
Reset all alerts for the specific site. This operation can not be undone!
PS > Reset-Alerts -url "http://teams/sites/newteam" -All
.Example
Reset all alerts for the specified user for this specific site. This operation can not be undone!
PS > Reset-Alerts -url "http://teams/sites/newteam" -user "username" -All
.Notes
NAME: Reset-Alerts
AUTHOR: Alan Oakland
LASTEDIT: 3/29/2013
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
Param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)][ValidateNotNullOrEmpty()][String] $Url,
[Parameter(Mandatory=$false, ValueFromPipeline=$False)][string] $user = $null,
[Switch]$All = $false
)
#Try catch for entire script
try
{
$site = Get-SPWeb -Identity $URL
#Try Catch for reading alerts
try
{
if ($All -eq $true)
{
$siteAlerts = $site.Alerts
}
else
{
$siteAlerts = $site.Alerts | Where-Object {$_.AlertFrequency -ne "Immediate"}
}
if (($user -ne $null) -and ($user -ne ""))
{
$siteAlerts = $siteAlerts | Where-Object {$_.User -like "NSIGHT\\$($user)"}
}
Write-Host "There are $($site.Alerts.Count.ToString()) alerts for $($site.Title) Site ($($site.URL))"
foreach ($alert in $siteAlerts)
{
if ($alert.user -ne $null)
{
Write-Host "Processing user $($alert.user)";
#Try catch for restarting alert
try
{
if($pscmdlet.ShouldProcess($_.ID, "restarting alert: $($alert.Title) for $($alert.user.DisplayName) on site {$URL}"))
{
$alert.Status = [Microsoft.SharePoint.SPAlertStatus]::Off
$alert.Update();
$alert.Status = [Microsoft.SharePoint.SPAlertStatus]::On
$alert.Update();
Write-Host "Restarted alert: $($alert.Title) for $($alert.user.DisplayName) on site {$URL}"
}
}
catch
{
Write-Error "Failure restarting alert: $($alert.Title) for $($alert.user.DisplayName) on site {$URL}"
}
}
}
}
catch
{
Write-Error "Failure reading alerts from SPWeb {$_.URL}"
throw
}
$site.Dispose()
}
catch
{
Write-Error $_
throw
}
}
#Only add the snap in if it is not already loaded.
if(-not (Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue))
{
#Add the SharePoint Snap in, but stop script if this fails
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
Write-Output "Initialized SharePoint Snap In"
}
# Example to reset all scheduled alerts on a site
# Reset-Alerts -url "http://sharepoint/sites/myteam"
# Example to reset all scheduled alerts on all sites in a site collection
# This has not been tested
<#
$sites = Get-SPWeb -Site $Url -limit All
foreach ($site in $sites)
{
Reset-Alerts -url "http://sharepoint"
}
#>
|
PowerShellCorpus/PoshCode/New-CodeSigningCert_2.ps1
|
New-CodeSigningCert_2.ps1
|
## New-CodeSigningCert.ps1
########################################################################################################################
## Does the setup needed to self-sign PowerShell scripts ...
## Generates a "test" self-signed root Certificate Authority
## And then generates a code-signing certificate (and signs it with the CA certificate)
## OPTIONALLY (specify -import or -importall) imports the certificates to the store(s)
########################################################################################################################
## NOTE: Uses OpenSSL (because it's xcopy redistributable -- wake up Microsoft)
## In order for this to work you should KEEP the script in the folder with OpenSsl.exe
## Also, it is VERY important that you properly provide passwords and the locale data...
## You can obviously reorder the parameters however you like, and hard-code some of the values in the parameters, but
## you need to make sure that if you use this to generate multiple certificates, that you preserve all of the certs
## and keep track of all your passwords so you don't lock yourself out of any of them.
########################################################################################################################
## Usage:
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" Jaykul@HuddledMasses.org HuddledMasses.org Mystery Rochester "New York" US -importall -OpenSSLLocation C:\\Users\\Joel\\Documents\\WindowsPowershell\\PoshCerts\\bin -CAPassword MyCleverRootPassword -CodeSignPassword EvenMoreCleverPasswords
##
## If I hard-coded the company/dept/etc ... I could use this to generate certs for all my devs:
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" FakeEmail@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword MarksPassword
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" FakeEmail2@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword JessesPassword
##
## For the signed scripts to work, I just have to -import on the devices where the scripts need to run:
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" -import
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" -import
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -import
##
## On the developers' workstations, I need to use Get-PfxCertificate to sign, or else run -importall
## That will load the codesigning cert in their "my" store, and will only require the password for the initial import
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -importall -CodeSignPassword MyCodeSignPassword
########################################################################################################################
## History
## 1.0 - Initial public release
## 1.1 - Bug fix release to make it easier to use...
## 1.2 - Bug fix to get the ORG and COMMON NAME set correctly -- Major whoops!
##
Param(
$CertStorageLocation = (join-path (split-path $Profile) "Certs"),
$UserName = (Read-Host "User name")
, $email
, $company
, $department
, $city
, $state
, $country
, $RootCAName = "Self-Signed-Root-CA"
, $CodeSignName = "$UserName Code-Signing"
, $alias = "PoshCert",
[string]$keyBits = 4096,
[string]$days = 365,
[string]$daysCA = (365 * 5),
[switch]$forceNew = $false,
[switch]$importall = $false,
[switch]$import = ($false -or $importall),
## we ask you to specify the CA password and your codesign password
## You can leave these null when importing on end-user desktops
$CAPassword = $null,
$CodeSignPassword = $null,
## You really shouldn't pass these unless you know what you're doing
$OpenSSLLocation = $null,
$RootCAPassword = $Null,
$CodeSignCertPassword = $null
)
function Get-UserEmail {
if(!$script:email) {
$script:email = (Read-Host "Email address")
}
return $script:email
}
function Get-RootCAPassword {
if(!$script:RootCAPassword) {
if(!$script:CAPassword) {
$script:CAPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Root CA Password")).GetNetworkCredential().Password)
}
## Then down here we calculate large passwords to actually use:
## This works as long as you keep the same company name and root ca name
$script:RootCAPassword = [Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CaPassword)), ([Text.Encoding]::UTF8.GetBytes("$company$RootCAName")), "SHA1", 5).GetBytes(64) )
}
return $script:RootCAPassword
}
function Get-CodeSignPassword {
if(!$script:CodeSignCertPassword) {
if(!$script:CodeSignPassword) {
$script:CodeSignPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Code Signing Password")).GetNetworkCredential().Password)
}
## This works as long as you keep the same PFX password and email address
$script:CodeSignCertPassword = ([Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CodeSignPassword)), ([Text.Encoding]::UTF8.GetBytes((Get-UserEmail))), "SHA1", 5).GetBytes(64) ))
}
return $script:CodeSignCertPassword
}
function Get-SslConfig {
Param (
$keyBits,
$Country = (Read-Host "Country (2-Letter code)"),
$State = (Read-Host "State (Full Name, no intials)"),
$city = (Read-Host "City"),
$company = (Read-Host "Company Name (or Web URL)"),
$orgUnit = (Read-Host "Department (team, group, family)"),
$CommonName,
$email = (Read-Host "Email Address")
)
@"
# OpenSSL example configuration file for BATCH certificate generation
# This definition stops the following lines choking if HOME isn't defined.
HOME = .
RANDFILE = $($ENV::HOME)/.rnd
# To use this configuration with the "-extfile" option of the "openssl x509" utility
# name here the section containing the X.509v3 extensions to use:
#extensions = code_sign
####################################################################
[ req ]
default_bits = {0}
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
#attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
# req_extensions = v3_ca # Other extensions to add to a certificate request?
## Passwords for private keys could be specified here, instead of on the commandline
# input_password = secret
# output_password = secret
## Set the permitted string types...
## Some software crashes on BMPStrings or UTF8Strings, so we'll stick with
string_mask = nombstr
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = {1}
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = {2}
localityName = Locality Name (eg, city)
localityName_default = {3}
0.organizationName = Organization Name (eg, company)
0.organizationName_default = {4}
# we can do this but it is not usually needed
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = {5}
commonName = Common Name (eg, YOUR name)
commonName_default = {6}
commonName_max = 64
emailAddress = Email Address
emailAddress_default = {7}
emailAddress_max = 64
# SET-ex3 = SET extension number 3
# [ req_attributes ]
# challengePassword = A challenge password
# challengePassword_min = 4
# challengePassword_max = 20
# unstructuredName = An optional company name
[ v3_ca ]
## Extensions for a typical CA
## PKIX recommendations:
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
## PKIX suggests we should include email address in subject alt name
# subjectAltName=email:copy
## But really they want it *only* there or the certs are "deprecated"
# subjectAltName=email:move
## And the issuer details
# issuerAltName=issuer:copy
## This is what PKIX recommends
basicConstraints = critical,CA:true
## some broken software chokes on critical extensions, so you could do this instead.
#basicConstraints = CA:true
## For a normal CA certificate you would want to specify this.
## But it will cause problems for our self-signed certificate.
# keyUsage = cRLSign, keyCertSign
## You might want the netscape-compatible stuff too
# nsCertType = sslCA, emailCA
[ code_sign ]
# These extensions are added when we get a code_signing cert
## PKIX recommendations:
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
## PKIX suggests we should include email address in subject alt name
# subjectAltName=email:copy
## But really they want it *only* there or the certs are "deprecated"
# subjectAltName=email:move
## And the issuer details
# issuerAltName=issuer:copy
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# If nsCertType is omitted, the certificate can be used for anything *except* object signing.
# We just want to allow everything including object signing:
nsCertType = server, client, email, objsign
# This is the vital bit for code-signing
extendedKeyUsage = critical, serverAuth,clientAuth,codeSigning
# This is typical in keyUsage for a client certificate.
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always,issuer:always
"@ -f $keyBits,$Country,$State,$city,$company,$orgUnit,$CommonName,$email
}
if(!$OpenSSLLocation) {
## You should be running the script from the OpenSsl folder
$OpenSSLLocation = Split-Path $MyInvocation.MyCommand.Path
Write-Debug "OpenSSL: $OpenSSLLocation"
}
if( Test-Path $OpenSslLocation ) {
## The OpenSslLoction needs to actually have OpenSsl in it ...
$files = ls (Join-Path $OpenSSLLocation "*.[de][lx][el]") -include libeay32.dll,ssleay32.dll,OpenSSL.exe # libssl32.dll,
if($files.count -lt 3) {
THROW "You need to configure a location where OpenSSL can be run from"
}
} else { THROW "You need to configure a location where OpenSSL can be run from" }
## Don't touch these
[string]$SslCnfPath = (join-path (Convert-Path $CertStorageLocation) PoshOpenSSL.config)
New-Alias OpenSsl (join-path $OpenSSLLocation OpenSSL.exe)
if( !(Test-Path $CertStorageLocation) ) {
New-Item -type directory -path $CertStorageLocation | Push-Location
$forceNew = $true
} else {
Push-Location $CertStorageLocation
}
Write-Debug "SslCnfPath: $SslCnfPath"
Write-Debug "OpenSsl: $((get-alias OpenSsl).Definition)"
## Process the CSR and generate a pfx file
if($forceNew -or (@(Test-Path "$CodeSignName.crt","$CodeSignName.pfx") -contains $false)) {
## Generate the private code-signing key and a certificate signing request (csr)
if($forceNew -or (@(Test-Path "$CodeSignName.key","$CodeSignName.csr") -contains $false)) {
## Generate the private root CA key and convert it into a self-signed certificate (crt)
if($forceNew -or (@(Test-Path "$RootCAName.key","$RootCAName.crt") -contains $false)) {
## Change configuration before -batch processing root key
$CommonName = "$company Certificate Authority"
$orgUnit = "$department Certificate Authority"
$email = Get-UserEmail
Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file
OpenSsl genrsa -out "$RootCAName.key" -des3 -passout pass:$(Get-RootCAPassword) $keyBits
OpenSsl req -new -x509 -days $daysCA -key "$RootCAName.key" -out "$RootCAName.crt" -passin pass:$(Get-RootCAPassword) -config $SslCnfPath -batch
}
## Change configuration before -batch processing code-signing key
$CommonName = "$UserName"
$orgUnit = "$department"
$email = Get-UserEmail
Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file
OpenSsl genrsa -out "$CodeSignName.key" -des3 -passout pass:$(Get-CodeSignPassword) $keyBits
OpenSsl req -new -key "$CodeSignName.key" -out "$CodeSignName.csr" -passin pass:$(Get-CodeSignPassword) -config $SslCnfPath -batch
}
## Use the root CA key to process the CSR and sign the code-signing key in one step...
OpenSsl x509 -req -days $days -in "$CodeSignName.csr" -CA "$RootCAName.crt" -CAcreateserial -CAkey "$RootCAName.key" -out "$CodeSignName.crt" -setalias $alias -extfile $SslCnfPath -extensions code_sign -passin pass:$(Get-RootCAPassword)
## Combine the signed certificate and the private key into a single file and specify a new password for it ...
OpenSsl pkcs12 -export -out "$CodeSignName.pfx" -inkey "$CodeSignName.key" -in "$CodeSignName.crt" -passin pass:$(Get-CodeSignPassword) -passout pass:$script:CodeSignPassword
}
Pop-Location
if($import) {
## Now we need to import the certificates to the computer so we can use them...
## Sadly, the PowerShell Certificate Provider is read-only, so we need to do this by hand
trap {
if($_.Exception.GetBaseException() -is [UnauthorizedAccessException]) {
write-error "Cannot import certificates as 'Root CA' or 'Trusted Publisher' except in an elevated console."
continue
}
}
## In order to be able to use scripts signed by these certs
## The root cert that signed the code-signing certs must be loaded into the "Root" store
$lm = new-object System.Security.Cryptography.X509certificates.X509Store "root", "LocalMachine"
$lm.Open("ReadWrite")
$lm.Add( (Get-PfxCertificate "$CertStorageLocation\\$RootCAName.crt") )
if($?) {
Write-Host "Successfully imported root certificate to trusted root store" -fore green
}
$lm.Close()
## In order to avoid the "untrusted publisher" prompt
## The public code-signing cert must be loaded into the "TrustedPublishers" store
$tp = new-object System.Security.Cryptography.X509certificates.X509Store "TrustedPublisher", "LocalMachine"
$tp.Open("ReadWrite")
$tp.Add( (Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.crt") )
if($?) {
Write-Host "Successfully imported code-signing certificate to trusted publishers store" -fore green
}
$tp.Close()
if($importall) {
## It's a good practice to go ahead and put our private certificates in "OUR" store too
### Otherwise we have to load it each time from the pfx file using Get-PfxCertificate
##### $cert = Get-PfxCertificate "$CodeSignName.pfx"
##### Set-AuthenticodeSignature -Cert $cert -File Test-Script.ps1
$my = new-object System.Security.Cryptography.X509certificates.X509Store "My", "CurrentUser"
$my.Open( "ReadWrite" )
Get-CodeSignPassword
$my.Add((Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.pfx")) #$script:CodeSignPassword, $DefaultStorage)
if($?) {
Write-Host "Successfully imported code-signing certificate to 'my' store" -fore yellow
}
$my.Close()
}
}
# SIG # Begin signature block
# MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJg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WeRBKAL
# b3H6CVX0H5nRh9PLa2a4WxbYHM6IxCOa/Z8clH4veAZbs5Zq5mtjLV14u8PszAYM
# 4P/H0sXHMZYb9nj0vKjsZdxOlM0g6JHqUszE40tND/5dFuzdr3Tyu/aC6/j/ZFGZ
# jdyaM88kE88qAU9Bs2M18LsSUJx6GsdlXwDD4eCBRH59+QtAnQZB4HUL5KkF53DG
# J0WtRuI+wWmeMU9nNtDMQgSGJev0LVEJ2Ui+UsVA+RvWH04VCBrzlXi2TLzS9bCQ
# 5Fo/t/czCbC4m/WrXQyYNDoHtI/fXE2ctSPq2QQaDF9Bu65MuMGzWa3iFSFmq0uA
# nYivtHSlgyqhPBBmu8fspePkye7PzYoH2Gpykp17R5fBx+rQriKjTkZcGNdAGdQY
# j7SEC93e0KjtZRQA+ABxmVacmNrO6NGbMN2Zd8Pheham1T38V3aWjKvq2d94iUfh
# dgqvWhSu6zw0yE/NaJPTKnixN0j+up/Y7jSO9Cytvl4TNWJkFjDp+u0exl4s6eQ5
# cspbWHwWyYWyg7e0YaclbL7mPygvjxQDWOWgMN9cddvHCq8fiq6VPNTJqeLB
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Test-FileLock.ps1
|
Test-FileLock.ps1
|
filter Test-FileLock {
if ($args[0]) {$filepath = gi $(Resolve-Path $args[0]) -Force} else {$filepath = gi $_.fullname -Force}
if ($filepath.psiscontainer) {return}
$locked = $false
trap {
Set-Variable -name locked -value $true -scope 1
continue
}
$inputStream = New-Object system.IO.StreamReader $filepath
if ($inputStream) {$inputStream.Close()}
@{$filepath = $locked}
}
|
PowerShellCorpus/PoshCode/JSON 1.7.ps1
|
JSON 1.7.ps1
|
#requires -version 2.0
# Version History:
# v 0.5 - First Public version
# v 1.0 - Made ConvertFrom-Json work with arbitrary JSON
# - switched to xsl style sheets for ConvertTo-JSON
# v 1.1 - Changed ConvertFrom-Json to handle single item results
# v 1.2 - CodeSigned to make a fellow geek happy
# v 1.3 - Changed ConvertFrom-Json to handle zero item results (I hope)
# v 1.4 - Added -File parmeter set to ConvertFrom-Json
# - Cleaned up some error messages
# v 1.5 - Corrected handling of arrays
# v 1.6 - Corrected pipeline binding on ConvertFrom-Json
@@# v 1.7 - Added a New-Json which converts simple hashtables...
#
# There is no help (yet) because I keep forgetting that I haven't written help yet.
# Full RoundTrip capability:
#
# > ls | ConvertTo-Json | ConvertFrom-Json
# > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json
#
# You may frequently want to use the DEPTH or NoTypeInformation parameters:
#
# > ConvertTo-Json -Depth 2 -NoTypeInformation
#
# But then you have to specify the type when you reimport (and you can't do that for deep objects).
# This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject).
# For Example:
#
# > PS | Select PM, WS, CPU, ID, ProcessName |
# >> ConvertTo-json -NoType |
# >> convertfrom-json -Type System.Diagnostics.Process
#
# However, you *can* use PSOjbect as your type when re-importing:
#
# > $Json = Get-Process |
# >> Select PM, WS, CPU, ID, ProcessName, @{n="SnapshotTime";e={Get-Date}} |
# >> ConvertTo-Json -NoType
#
# > $Json | ConvertFrom-json -Type PSObject
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Write-Stream {
PARAM(
[Parameter(Position=0)]$stream,
[Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
function Read-Stream {
PARAM(
[Parameter(Position=0,ValueFromPipeline=$true)]$Stream
)
process {
$bytes = $Stream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}}
function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
$mStream = New-Object System.IO.MemoryStream
}
PROCESS {
$json | Write-Stream -Stream $mStream
}
END {
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Convert-XmlToJson {
PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml)
PROCESS {
$mStream = New-Object System.IO.MemoryStream
$jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
try
{
$xml.Save($jsonWriter)
$bytes = $mStream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}
finally
{
$jsonWriter.Close()
$mStream.Dispose()
}
}
}
@@function New-Json {
@@[CmdletBinding()]
@@param([Parameter(ValueFromPipeline=$true)][HashTable]$InputObject)
@@begin {
@@ $ser = @{}
@@ $jsona = @()
@@}
@@process {
@@ $jsoni =
@@ foreach($input in $InputObject.GetEnumerator() | Where { $_.Value } ) {
@@ if($input.Value -is [Hashtable]) {
@@ '"'+$input.Key+'": ' + (New-JSon $input.Value)
@@ } else {
@@ $type = $input.Value.GetType()
@@ if(!$Ser.ContainsKey($Type)) {
@@ $Ser.($Type) = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type
@@ }
@@ $stream = New-Object System.IO.MemoryStream
@@ $Ser.($Type).WriteObject( $stream, $Input.Value )
@@ '"'+$input.Key+'": ' + (Read-Stream $stream)
@@ }
@@ }
@@
@@ $jsona += "{`n" +($jsoni -join ",`n")+ "`n}"
@@}
@@end {
@@ if($jsona.Count -gt 1) {
@@ "[$($jsona -join ",`n")]"
@@ } else {
@@ $jsona
@@ }
@@}}
## Rather than rewriting ConvertTo-Xml ...
Function ConvertTo-Json {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject
,
[Parameter(Mandatory=$false)][Int]$Depth=1
,
[Switch]$NoTypeInformation
)
END {
## You must output ALL the input at once
## ConvertTo-Xml outputs differently if you just have one, so your results would be different
$input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson
}
}
Function Convert-CliXmlToJson {
PARAM(
[Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml
)
BEGIN {
$xmlToJsonXsl = @'
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
CliXmlToJson.xsl
Copyright (c) 2006,2008 Doeke Zanstra
Copyright (c) 2009 Joel Bennett
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
-->
<xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/>
<xsl:strip-space elements="*"/>
<!--contant-->
<xsl:variable name="d">0123456789</xsl:variable>
<!-- ignore document text -->
<xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/>
<!-- string -->
<xsl:template match="text()">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="."/>
</xsl:call-template>
</xsl:template>
<!-- Main template for escaping strings; used by above template and for object-properties
Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string -->
<xsl:template name="escape-string">
<xsl:param name="s"/>
<xsl:text>"</xsl:text>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:template>
<!-- Escape the backslash (\\) before everything else. -->
<xsl:template name="escape-bs-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'\\')">
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/>
</xsl:call-template>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="substring-after($s,'\\')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Escape the double quote ("). -->
<xsl:template name="escape-quot-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'"')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'"'),'\\"')"/>
</xsl:call-template>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="substring-after($s,'"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash
or double quote here, because they don't replace characters (� becomes \\t), but they prefix
characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be
processed first. This function can't do that. -->
<xsl:template name="encode-string">
<xsl:param name="s"/>
<xsl:choose>
<!-- tab -->
<xsl:when test="contains($s,'	')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'	'),'\\t',substring-after($s,'	'))"/>
</xsl:call-template>
</xsl:when>
<!-- line feed -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\n',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<!-- carriage return -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\r',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- number (no support for javascript mantise) -->
<xsl:template match="text()[not(string(number())='NaN' or
(starts-with(.,'0' ) and . != '0'))]">
<xsl:value-of select="."/>
</xsl:template>
<!-- boolean, case-insensitive -->
<xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template>
<xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template>
<!-- root object(s) -->
<xsl:template match="*" name="base">
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<!-- check type of node -->
<xsl:choose>
<!-- null nodes -->
<xsl:when test="count(child::node())=0">null</xsl:when>
<!-- other nodes -->
<xsl:otherwise>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<!-- end of type check -->
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- properties of objects -->
<xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)>1]">
<xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/>
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise>
<xsl:text>{</xsl:text>
<xsl:if test="../@Type">
<xsl:text>"__type":</xsl:text>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="../@Type"/>
</xsl:call-template>
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:choose>
<xsl:when test="not(child::node())">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:null</xsl:text>
</xsl:when>
<xsl:when test="$inArray">
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<!--
<xsl:when test="not(@Name) and not(@Type)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
-->
<xsl:when test="not(@Name)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- convert root element to an anonymous container -->
<xsl:template match="/">
<xsl:apply-templates select="node()"/>
</xsl:template>
</xsl:stylesheet>
'@
}
PROCESS {
if(Get-Member -InputObject $xml -Name root) {
Write-Verbose "Ripping to Objects"
$xml = $xml.root.Objects
} else {
Write-Verbose "Was already Objects"
}
Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl
}
}
Function ConvertFrom-Xml {
[CmdletBinding(DefaultParameterSetName="AutoType")]
PARAM(
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)]
[Xml.XmlNode]
$xml
,
[Parameter(Mandatory=$true,ParameterSetName="ManualType")]
[Type]$Type
,
[Switch]$ForceType
)
PROCESS{
if(Get-Member -InputObject $xml -Name root) {
return $xml.root.Objects | ConvertFrom-Xml
} elseif(Get-Member -InputObject $xml -Name Objects) {
return $xml.Objects | ConvertFrom-Xml
}
$propbag = @{}
foreach($name in Get-Member -InputObject $xml -MemberType Properties | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) {
Write-Verbose "$Name Type: $($xml.$Name.type)"
$propbag."$Name" = Convert-Properties $xml."$name"
}
if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type }
if($ForceType -and $Type) {
try {
$output = New-Object $Type -Property $propbag
} catch {
$output = New-Object PSObject -Property $propbag
$output.PsTypeNames.Insert(0, $xml.__type)
}
} else {
$output = New-Object PSObject -Property $propbag
if($Type) {
$output.PsTypeNames.Insert(0, $Type)
}
}
Write-Output $output
}
}
Function Convert-Properties {
param($InputObject)
switch( $InputObject.type ) {
"object" {
return (ConvertFrom-Xml -Xml $InputObject)
break
}
"string" {
$MightBeADate = $InputObject.get_InnerText() -as [DateTime]
## Strings that are actually dates (*grumble* JSON is crap)
if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) {
return $MightBeADate
} else {
return $InputObject.get_InnerText()
}
break
}
"number" {
$number = $InputObject.get_InnerText()
if($number -eq ($number -as [int])) {
return $number -as [int]
} elseif($number -eq ($number -as [double])) {
return $number -as [double]
} else {
return $number -as [decimal]
}
break
}
"boolean" {
return [bool]::parse($InputObject.get_InnerText())
}
"null" {
return $null
}
"array" {
[object[]]$Items = $( foreach( $item in $InputObject.GetEnumerator() ) {
Convert-Properties $item
} )
return $Items
}
default {
return $InputObject
break
}
}
}
Function ConvertFrom-Json {
[CmdletBinding(DefaultParameterSetName="StringInput")]
PARAM(
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="File")]
[Alias("PSPath")]
[string]$File
,
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1,ParameterSetName="StringInput")]
[string]$InputObject
,
[Parameter(Mandatory=$true)]
[Type]$Type
,
[Switch]$ForceType
)
BEGIN {
[bool]$AsParameter = $PSBoundParameters.ContainsKey("File") -or $PSBoundParameters.ContainsKey("InputObject")
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "File") {
[string]$InputObject = @(Get-Content $File) -Join "`n"
$null = $PSBoundParameters.Remove("File")
}
else
{
$null = $PSBoundParameters.Remove("InputObject")
}
[Xml.XmlElement]$xml = (Convert-JsonToXml $InputObject).Root
if($xml) {
if($xml.Objects) {
$xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters
}elseif($xml.Item -and $xml.Item -isnot [System.Management.Automation.PSParameterizedProperty]) {
$xml.Item | ConvertFrom-Xml @PSBoundParameters
}else {
$xml | ConvertFrom-Xml @PSBoundParameters
}
} else {
Write-Error "Failed to parse JSON with JsonReader"
}
}
}
#########
### The JSON library is dependent on Convert-Xml from my Xml script module
function Convert-Node {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -ErrorAction 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
New-Alias fromjson ConvertFrom-Json
New-Alias tojson ConvertTo-Json
#New-Alias ipjs Import-Json
#New-Alias epjs Export-Json
#Import-Json, Export-Json,
Export-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUqJs83rUpkJfARRWW/QJzu773
# OXuggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy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PoshCode/Xml Module 6.0.ps1
|
Xml Module 6.0.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
# Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
# Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
# Version 4.3 Added a Path parameter set to Format-Xml so you can specify xml files for prety printing
# Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
# Work around possible variable slipping on null values by:
# 1) allowing -param:$value syntax (which doesn't fail when $value is null)
# 2) testing for -name syntax on the value and using it as an attribute instead
# Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
# Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
# Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
# Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace
# Version 5.0 Added Update-Xml to allow setting xml attributes or node content
# Version 6.0 Major cleanup, breaking changes.
# - Added Get-XmlContent and Set-XmlContent for loading/saving XML from files or strings
# - Removed Path and Content parameters from the other functions (it greatly simplifies thost functions, and makes the whole thing more maintainable)
# - Updated Update-Xml to support adding nodes "before" and "after" other nodes, and to support "remove"ing nodes
&{
$local:xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$local:xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
if(!$xlr8r::Get["Dictionary"]) {
$xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" )
}
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
function Import-Xml {
#.Synopsis
# Load an XML file as an XmlDocument
param(
# Specifies a string that contains the XML to load, or a path to a file which has the XML to load (wildcards are permitted).
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath","Path")]
[String[]]$Content
,
# If set, loads XML with all namespace qualifiers removed, and all entities expanded.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
[Text.StringBuilder]$XmlContent = [String]::Empty
[bool]$Path = $true
}
process {
if($Path -and ($Path = Test-Path @($Content)[0] -EA 0)) {
foreach($file in Resolve-Path $Content) {
$xml = New-Object System.Xml.XmlDocument;
if($file.Provider.Name -eq "FileSystem") {
$xml.Load( $file.ProviderPath )
} else {
$ofs = "`n"
$xml.LoadXml( ([String](Get-Content $file)) )
}
if($RemoveNamespace) {
[System.Xml.XmlNode[]]$Xml = @(Remove-XmlNamespace -Xml $node)
}
Write-Output $xml
}
} else {
# If the "path" parameter isn't actually a path, assume that it's actually content
foreach($line in $content) {
$null = $XmlContent.AppendLine( $line )
}
}
}
end {
if(!$Path) {
$xml = New-Object System.Xml.XmlDocument;
$xml.LoadXml( $XmlContent.ToString() )
if($RemoveNamespace) {
$Xml = @(Remove-XmlNamespace -Xml $xml)
}
Write-Output $xml
}
}}
Set-Alias ipxml Import-Xml
Set-Alias ipx Import-Xml
Set-Alias Get-Xml Import-Xml
Set-Alias gxml Import-Xml
Set-Alias gx Import-Xml
function Export-Xml {
param(
[Parameter(Mandatory=$true, Position=1)]
[Alias("PSPath")]
[String]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[Xml]$Xml
)
process {
$xml.Save( $Path )
}
}
Set-Alias epxml Export-Xml
Set-Alias epx Export-Xml
Set-Alias Set-Xml Export-Xml
Set-Alias sxml Export-Xml
Set-Alias sx Export-Xml
function Format-Xml {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Path
# The path to an xml document (on disc or any other content provider).
#.Parameter Indent
# The indent level (defaults to 2 spaces)
#.Example
# [xml]$xml = get-content Data.xml
# C:\\PS>Format-Xml $xml
#.Example
# get-content Data.xml | Format-Xml
#.Example
# Format-Xml C:\\PS\\Data.xml
#.Example
# ls *.xml | Format-Xml
#
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
[xml]$Xml
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PsPath")]
[string]$Path
,
[Parameter(Mandatory=$false)]
$Indent=2
)
process {
## Load from file, if necessary
if($Path) { [xml]$xml = Get-Content $Path }
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}}
Set-Alias fxml Format-Xml -EA 0
Set-Alias fx Format-Xml -EA 0
function Select-XmlNodeInternal {
[CmdletBinding()]
param([Xml.XmlNode[]]$Xml, [String[]]$XPath, [Hashtable]$NamespaceManager)
begin {
Write-Verbose "XPath = $($XPath -join ',')"
foreach($node in $xml) {
if($NamespaceManager) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $NamespaceManager.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
Write-Verbose "Names = $($nsManager | % { @{ $_ = $nsManager.LookupNamespace($_) } } | Out-String)"
}
foreach($path in $xpath) {
$node.SelectNodes($path, $nsManager)
}
}
}}
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
[Parameter(ParameterSetName="Content",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
[Parameter(Position=5,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
$XmlNodes = New-Object System.Xml.XmlNode[] 1
if($PSCmdlet.ParameterSetName -eq "Content") {
$XmlNodes = ConvertTo-Xml $Content -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $XmlNodes $XPath $NSM
}
}
process {
switch($PSCmdlet.ParameterSetName) {
"Path" {
$node = ConvertTo-Xml $Path -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $node $XPath $NSM
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
[Xml]$node = Remove-XmlNamespace -Xml $node
}
Select-XmlNodeInternal $node $XPath $NSM
}
}
}
}}
Set-Alias slxml Select-Xml -EA 0
Set-Alias slx Select-Xml -EA 0
function Update-Xml {
#.Synopsis
# The Update-XML cmdlet lets you use XPath queries to replace text in nodes in XML documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Allows you to update an attribute value, xml node contents, etc.
#
#.Notes
# We still need to implement RemoveNode and RemoveAttribute and even ReplaceNode
[CmdletBinding(DefaultParameterSetName="Set")]
param(
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="Before",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$Before
,
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="After",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$After
,
# If set, the new value will be added as a new child of the node identified by the XPath
[Parameter(ParameterSetName="Append",Mandatory=$true)]
[Switch]$Append
,
# If set, the node identified by the XPath will be removed instead of set
[Parameter(ParameterSetName="Remove",Mandatory=$true)]
[Switch]$Remove
,
# If set, the node identified by the XPath will be Replace instead of set
[Parameter(ParameterSetName="Replace",Mandatory=$true)]
[Switch]$Replace
,
# Specifies an XPath for the node to update. This could be an element node *or* an attribute node (remember: //element/@attribute )
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$XPath
,
# The new value to place in the xml
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[String]$Value
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Output the XML documents after adding updating them
[Switch]$Passthru
)
process
{
foreach($XmlNode in $Xml) {
$select = @{}
$select.Xml = $XmlNode
$select.XPath = $XPath
if($Namespace) {
$select.Namespace = $Namespace
}
$document =
if($XmlNode -is [System.Xml.XmlDocument]) {
$XmlNode
} else {
$XmlNode.get_OwnerDocument()
}
if($xValue = $Value -as [Xml]) {
$xValue = $document.ImportNode($xValue.SelectSingleNode("/*"), $true)
}
$nodes = Select-Xml @Select | Where-Object { $_ }
if(@($nodes).Count -eq 0) { Write-Warning "No nodes matched your XPath, nothing will be updated" }
foreach($node in $nodes) {
$select.XPath = "$XPath/parent::*"
$parent = Select-Xml @Select
if(!$xValue) {
if($node -is [System.Xml.XmlAttribute] -and $Value.Contains("=")) {
$aName, $aValue = $Value.Split("=",2)
if($aName.Contains(":")){
$ns,$name = $aName.Split(":",2)
$xValue = $document.CreateAttribute( $name, $Namespace[$ns] )
} else {
$xValue = $document.CreateAttribute( $aName )
}
$xValue.Value = $aValue
}
}
switch($PSCmdlet.ParameterSetName) {
"Before" {
$null = $parent.InsertBefore( $xValue, $node )
}
"After" {
$null = $parent.InsertAfter( $xValue, $node )
}
"Append" {
$null = $parent.AppendChild( $xValue )
}
"Remove" {
$null = $parent.RemoveChild( $node )
}
"Replace" {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $parent.ReplaceChild( $xValue, $node )
}
"Set" {
if(!$xValue -and $node."#text") {
$node."#text" = $Value
} else {
if($node -is [System.Xml.XmlElement]) {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $node.set_innerXml("")
$null = $node.AppendChild($xValue)
}
elseif($node -is [System.Xml.XmlAttribute]) {
$node.Value = $Value
} else {
Write-Warning "$XPath selects a node of type $($node.GetType()), which we haven't handled. Please add that handler!"
}
}
}
}
}
if($Passthru) {
Write-Output $XmlNode
}
}
}}
Set-Alias uxml Update-Xml -EA 0
Set-Alias ux Update-Xml -EA 0
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
[CmdletBinding(DefaultParameterSetName="Reader")]
param(
[Parameter(ParameterSetName="ByNode",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlNode]$Node
,
[Parameter(ParameterSetName="Reader",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
,
[Parameter(Position=2,Mandatory=$false)]
[Alias("Parameters")]
[hashtable]$Arguments
)
PROCESS {
if($PSCmdlet.ParameterSetName -eq "ByNode") {
$XmlReader = New-Object Xml.XmlNodeReader $node
}
$output = New-Object IO.StringWriter
$argList = $null
if($Arguments) {
$argList = New-Object System.Xml.Xsl.XsltArgumentList
foreach($arg in $Arguments.GetEnumerator()) {
$namespace, $name = $arg.Key -split ":"
## Fix namespace
if(!$name) {
$name = $Namespace
$namespace = ""
}
Write-Verbose "ns:$namespace name:$name value:$($arg.Value)"
$argList.AddParam($name,"$namespace",$arg.Value)
}
}
$StyleSheet.Transform( $XmlReader, $argList, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
# Documentation TODO
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies one or more XML nodes to process.
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies an Xml StyleSheet to transform with...
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String]$Xslt
,
# Specify arguments to the XSL Transformation
[Alias("Parameters")]
[hashtable]$Arguments
)
begin {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path $Xslt -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path $Xslt)"
$StyleSheet.Load( (Resolve-Path $Xslt) )
} else {
$OFS = "`n"
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $Xslt))))
}
}
process {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments
}
}
}
Set-Alias cvxml Convert-Xml -EA 0
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$Xml | Convert-Node $StyleSheet
}
}
Set-Alias rmns Remove-XmlNamespace -EA 0
Set-Alias rmxns Remove-XmlNamespace -EA 0
######## Helper functions for working with CliXml
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [type]::gettype("System.Management.Automation.Deserializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
$sr = new-object System.IO.StringReader $xmlString
$xr = new-object System.Xml.XmlTextReader $sr
$deserializer = $ctor.invoke($xr)
$method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
while (!$done.invoke($deserializer, @()))
{
try {
$method.invoke($deserializer, "")
} catch {
write-warning "Could not deserialize $string: $_"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [type]::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()
}
}
######## From here down is all the code related to my XML DSL:
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [string]$xml = New-XDocument rss -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# C:\\PS>$xml.ToString()
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#
# Description
# -----------
# This example shows the creation of a complete RSS feed with a single item in it.
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.
#
#
#.Example
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
# Description
# -----------
# This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString().
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.#
#
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
# Write-Verbose "Preparsed DSL: $attrib"
$attrib = ConvertFrom-XmlDsl $attrib
Write-Verbose "Reparsed DSL: $attrib"
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) {
$value = ConvertFrom-XmlDsl $value
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} else {
Write-Verbose "XAttribute $attrib = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
))
}
}
Set-Alias xml New-XDocument -EA 0
Set-Alias New-Xml New-XDocument -EA 0
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute -EA 0
Set-Alias New-XmlAttribute New-XAttribute -EA 0
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} elseif($value -match "-(?!\\d)\\w") {
$args = @($value)+@($args)
} elseif($value -ne $null) {
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
)
}
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function ConvertFrom-XmlDsl {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) }
[Array]::Reverse( $duds )
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
######## Xaml
# if($PSVersionTable.CLRVersion -ge "4.0"){
# trap { continue }
# [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null
# if("System.Xaml.XamlServices" -as [type]) {
# }
# }
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Import-Xml, Export-Xml, ConvertTo-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUiMRLI7iLPeWuXLdb7lMdZlym
# fzCgggUrMIIFJzCCBA+gAwIBAgIQHCAgf57pVOnJcjKrMO/dtjANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTExMDQyNTAwMDAwMFoXDTEyMDQyNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEd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D53tH0wpC+icLoK+f/DPzi6xqJVOaQ1oruFk94RYNRAFGcgWInqKc2Gvsf6P
# rA==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/ConvertTo-CliXml.ps1
|
ConvertTo-CliXml.ps1
|
function ConvertTo-CliXml {
param(
[parameter(position=0,mandatory=$true,valuefrompipeline=$true)]
[validatenotnull()]
[psobject]$object
)
begin {
$type = [type]::gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlwriter]), $null)
$sw = new-object io.stringwriter
$xw = new-object xml.xmltextwriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance")
}
process {
try {
$method.invoke($serializer, $object)
} catch {
write-warning "Could not serialize $($object.gettype()): $_"
}
}
end {
$done.invoke($serializer, @())
$sw.ToString()
}
}
|
PowerShellCorpus/PoshCode/Autoload Module 1.2.ps1
|
Autoload Module 1.2.ps1
|
#Requires -Version 2.0
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## Provides significant memory benefits over pre-loading all your functions, and significant performance benefits over using plain scripts. Can also *inject* functions into Modules so they inherit the module scope instead of the current local scope.
## Please see the use example in the script below
## Version History
## v 1.2 - 2011.05.02
## - Exposed the LoadNow alias and the Resolve-Autoloaded function
## v 1.1 - 2011.02.09
## Added support for autoloading scripts (files that don't have a "function" in them)
## v 1.0 - 2010.10.20
## Officially out of beta -- this is working for me without problems on a daily basis.
## Renamed functions to respect the Verb-Noun expectations, and added Export-ModuleMember
## beta 8 - 2010.09.20
## Finally fixed the problem with aliases that point at Invoke-Autoloaded functions!
## beta 7 - 2010.06.03
## Added some help, and a function to force loading "now"
## Added a function to load AND show the help...
## beta 6 - 2010.05.18
## Fixed a bug in output when multiple outputs happen in the END block
## beta 5 - 2010.05.10
## Fixed non-pipeline use using $MyInvocation.ExpectingInput
## beta 4 - 2010.05.10
## I made a few tweaks and bug fixes while testing it's use with PowerBoots.
## beta 3 - 2010.05.10
## fix for signed scripts (strip signature)
## beta 2 - 2010.05.09
## implement module support
## beta 1 - 2010.04.14
## Initial Release
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script (for our example: C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 )
## 3) Import the Autoload Module
## 5) Run this command (or add it to your profile):
<#
New-Autoload C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
function Invoke-Autoloaded {
#.Synopsis
# This function was autoloaded, but it has not been parsed yet.
# Use Get-AutoloadHelp to force parsing and get the correct help (or just invoke the function once).
#.Description
# You are seeing this help because the command you typed was imported via the New-Autoload command from the Autoload module. The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the Get-AutoloadHelp function.
#
# For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: Get-AutoloadHelp Get-PerformanceHistory
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
return Resolve-Autoloaded $CommandName
}#DynamicParam
begin {
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName -> $FunctionName"
#Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
$global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function )
Write-Verbose "Autoloaded Command: $($Command|Out-String)"
$scriptCmd = {& $command @PSBoundParameters | Write-Output }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($myInvocation.ExpectingInput)
}
process
{
Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)"
try {
if($_) {
$steppablePipeline.Process($_)
} else {
$steppablePipeline.Process()
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Invoke-Autoloaded End: $CommandName"
}
}#Invoke-Autoloaded
function Get-AutoloadHelp {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
$null = Resolve-Autoloaded $CommandName
Get-Help $CommandName
}
function Resolve-Autoloaded {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Name")]
[String]$CommandName
)
$OriginalCommandName = "($CommandName)"
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
$OriginalCommandName += "($CommandName)"
Write-Verbose "Resolve-Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command $OriginalCommandName!" }
Write-Verbose "Resolve-Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Autoloading:`nScriptName: $ScriptName `nModuleName: $ModuleName `nFunctionName: $FunctionName"
if(!$ScriptName){ $ScriptName = $CommandName }
if(!$FunctionName){ $FunctionName = $CommandName }
if($ModuleName) {
$Module = Get-Module $ModuleName
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
$function = $false
ForEach($token in $tokens) {
if($prev -and $token.Content -eq "# SIG # Begin signature block") {
$script = $script.SubString(0, $token.Start )
}
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) {
$script = $script.Insert( $prev.Start, "global:" )
$function = $true
Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')"
}
$prev = $token
}
if(!$function) {
$script = "function global:$Functionname { $script }"
}
if($Module) {
$script = Invoke-Expression "{ $Script }"
Write-Verbose "Importing Function into $($Module) module."
&$Module $Script | Out-Null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
} else {
Write-Verbose "Importing Function without module."
Invoke-Expression $script | out-null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
if($CommandName -eq $FunctionName) {
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)"
} else {
Set-Alias $CommandName $FunctionName -Scope Global
Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)"
}
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}
function New-Autoload {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName")]
$Alias = $Name
,
[Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
$Function = $Alias
,
[Parameter(Position=3,Mandatory=$false)]
[String]$Module
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
)
begin {
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
} else {
$null = $xlr8r::Remove( "PSParser" )
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
}
process {
for($i=0;$i -lt $Name.Count;$i++){
if($Alias -is [Scriptblock]) {
$a = $Name[$i] | &$Alias
} elseif($Alias -is [Array]) {
$a = $Alias[$i]
} else {
$a = $Alias
}
if($Function -is [Scriptblock]) {
$f = $Name[$i] | &$Function
} elseif($Function -is [Array]) {
$f = $Function[$i]
} else {
$f = $Function
}
Write-Verbose "Set-Alias $Module\\$a Invoke-Autoloaded -Scope $Scope"
Set-Alias $a Invoke-Autoloaded -Scope $Scope
$Script:AutoloadHash[$a] = $Name[$i],$Module,$f
Write-Verbose "$($Script:AutoloadHash.Count) `$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
}
}
}
Set-Alias Autoload New-Autoload
Set-Alias LoadNow Resolve-Autoloaded
New-Variable -Name AutoloadHash -Value @{} -Scope Script -Description "The Autoload alias-to-script cache" -Option ReadOnly -ErrorAction SilentlyContinue
Export-ModuleMember -Function New-Autoload, Invoke-Autoloaded, Get-AutoloadHelp, Resolve-Autoloaded -Alias *
|
PowerShellCorpus/PoshCode/16ca876b7bb7ac8c2f362b52.ps1
|
16ca876b7bb7ac8c2f362b52.ps1
|
#.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
# 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
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
PowerShellCorpus/PoshCode/New-MailBoxViaUI.ps1
|
New-MailBoxViaUI.ps1
|
# Requires ShowUI 1.3
function New-MailBoxViaUI {
$MailboxInfo = UniformGrid -ControlName "GetMailboxInfo" -Columns 2 {
Label "First Name:"
TextBox -Name FirstName
Label "Last Name:"
TextBox -Name "LastName"
Label "Mailbox Name:"
TextBox -Name "Name"
Button -Content "Cancel" -IsCancel -On_Click {
Get-ParentControl |
Close-Control
}
Button "Ok" -IsDefault -On_Click {
Get-ParentControl |
Set-UIValue -passThru |
Close-Control
}
} -On_Load {
$this.Children[1].Focus()
} -On_PreviewMouseLeftButtonDown {
if($_.Source -notmatch ".*\\.(TextBox|Button)") { $ShowUI.ActiveWindow.DragMove() }
} -Show
New-Mailbox @MailboxInfo
}
|
PowerShellCorpus/PoshCode/ASPX Mailbox (6 of 6).ps1
|
ASPX Mailbox (6 of 6).ps1
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Net.Mail;
public partial class MailboxTaskResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Here are the results of the Domain mailbox task request...<br /><br />");
runposh("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin");
// Variable Definition
string strAdminID = Session["AdminID"].ToString();
string strUserDN = Session["DirPath"].ToString();
string strOldAddress = Session["OldAddress"].ToString();
string strNewAddress = Session["NewAddress"].ToString();
string strAction = Session["Action"].ToString();
string strAdminName = Session["AdminUser"].ToString();
string strLastName = Session["LastName"].ToString();
string strCompany = Session["Agency"].ToString();
string strDivisionOU = Session["DivisionOU"].ToString();
bool blKeepAddress = (bool)Session["blKeepAddress"];
// remove leading and trailing spaces from input strings
strAdminID = strAdminID.Trim();
strUserDN = strUserDN.Trim();
strLastName = strLastName.Trim();
strCompany = strCompany.Trim();
strOldAddress = strOldAddress.Trim();
strAction = strAction.Trim();
strAdminName = strAdminName.Trim();
strDivisionOU = strDivisionOU.Trim();
//Find out what we are doing
switch (strAction.ToLower())
{
case "create mailbox":
fnCreateMailbox(strUserDN, strLastName, strCompany, strAdminName, strDivisionOU);
break;
case "delete mailbox":
fnDeleteMailbox(strAdminID, strUserDN, strAdminName);
break;
case "change address":
fnChangeAddress(strAdminID, strUserDN, strOldAddress, strNewAddress, strAdminName, strCompany, blKeepAddress);
break;
}
}
protected void fnCreateMailbox(string strUserDN, string strLastName, string strCompany, string strAdminName, string strDivisionOU)
{
/*
* Function to create the mailbox
* Requires the user's ADsPath, Last Name, and Company (Agency)
*/
string strAgency = "";
string strKey = "";
string strExchangeParam = "";
int iLastNameNum = 0;
Array arrExchParam;
string strSubject = "";
string strBody = "";
string strAction = "";
Collection<PSObject> colCreateResults;
#region Scripting Dictionary
//Build the scripting dictionary for determining the server/storage group/database
Dictionary<string, string> objDict = new Dictionary<string, string>();
objDict.Add("ABC", "Server1:SG7:MBX7");
objDict.Add("DEF", "Server2:SG7:MBX7");
objDict.Add("AAS", "Server1:SG1:MBX1");
objDict.Add("AAD", "Server1:SG2:MBX2");
objDict.Add("DEP", "Server2:SG7:MBX7");
objDict.Add("DSS", "Server3:SG5:MBX5");
objDict.Add("DAD", "Server2:SG1:MBX1");
objDict.Add("DSQ", "Server2:SG2:MBX2");
objDict.Add("LOL", "Server3:SG4:MBX4");
objDict.Add("BRB", "Server2:SG5:MBX5");
objDict.Add("DNA", "Server2:SG6:MBX6");
objDict.Add("MOD", "Server3:SG3:MBX3");
objDict.Add("SOM", "Server3:SG4:MBX4");
objDict.Add("MOM", "Server2:SG1:MBX1");
objDict.Add("PAL", "Server3:SG6:MBX6");
objDict.Add("HIT", "Server3:SG1:MBX1");
objDict.Add("DOG", "Server3:SG2:MBX2");
objDict.Add("CAE", "Server1:SG3:MBX3");
objDict.Add("CAT", "Server1:SG4:MBX4");
objDict.Add("ENA", "Server3:SG4:MBX4");
objDict.Add("KAM", "Server2:SG3:MBX3");
objDict.Add("MAK", "Server2:SG4:MBX4");
objDict.Add("SJM", "Server2:SG7:MBX7");
objDict.Add("TIK", "Server4:SG1:MBX1");
objDict.Add("ILI", "Server4:SG2:MBX2");
objDict.Add("OOP", "Server4:SG3:MBX3");
objDict.Add("POW", "Server4:SG4:MBX4");
objDict.Add("WQA", "Server4:SG5:MBX5");
#endregion
#region Agency Selector
strAgency = strCompany.Trim().ToUpper();
strKey = strAgency;
#region HHS
if (strAgency == "HHS")
{
iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
if (iLastNameNum < 69)
{
strKey = strAgency + "1"; //Put A through D in 1st Storage Group
}
else if (iLastNameNum < 73)
{
strKey = strAgency + "2"; //Put E through H in 2nd Storage Group
}
else if (iLastNameNum < 77)
{
strKey = strAgency + "3"; //Put I through L in 3rd Storage Group
}
else if (iLastNameNum < 81)
{
strKey = strAgency + "4"; //Put M through P in 4th Storage Group
}
else if (iLastNameNum < 85)
{
strKey = strAgency + "5"; //Put Q through T in 5th Storage Group
}
else
{
strKey = strAgency + "6"; //Put U through Z in 6th Storage Group
}
}
#endregion
#region MDT
if (strAgency == "MDT")
{
iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
if (iLastNameNum < 70)
{
strKey = strAgency + "1"; //Put A through E in 1st Storage Group
}
else if (iLastNameNum < 75)
{
strKey = strAgency + "2"; //Put F through J in 2nd Storage Group
}
else if (iLastNameNum < 79)
{
strKey = strAgency + "3"; //Put K through N in 3rd Storage Group
}
else if (iLastNameNum < 84)
{
strKey = strAgency + "4"; //Put O through S in 4th Storage Group
}
else
{
strKey = strAgency + "5"; //Put T through Z in 5th Storage Group
}
}
#endregion
#region DLI
if (strAgency == "DLI")
{
if (strDivisionOU == "BSD")
{
strKey = strAgency + "2"; //Put BSD in the 2nd Storage Group
}
else if (strDivisionOU == "CSD")
{
strKey = strAgency + "1"; //Put CSD in the 1st Storage Group
}
else if (strDivisionOU == "ERD")
{
strKey = strAgency + "2"; //Put ERD in 2nd Storage Group
}
else if (strDivisionOU == "JSD")
{
strKey = strAgency + "1"; //Put JSD in 1st Storage Group
}
else if (strDivisionOU == "RAD")
{
strKey = strAgency + "2"; //Put RAD in 2nd Storage Group
}
else if (strDivisionOU == "UID")
{
strKey = strAgency + "2"; //Put UID in 2nd Storage Group
}
else if (strDivisionOU == "WCC")
{
strKey = strAgency + "1"; //Put RAD in 1st Storage Group
}
}
#endregion
#region DOA
if (strAgency == "DOA")
{
if (strDivisionOU == "ADM")
{
strKey = strAgency + "1"; //Put ADM in the 1st Storage Group
}
else if (strDivisionOU == "ITSD")
{
strKey = strAgency + "2"; //Put ITSD in 2nd Storage Group
}
else if (strDivisionOU == "MLOT")
{
strKey = strAgency + "1"; //Put MLOT in the 1st Storage Group
}
else if (strDivisionOU == "MPERA")
{
strKey = strAgency + "1"; //Put MPERA in 1st Storage Group
}
else if (strDivisionOU == "OPD")
{
strKey = strAgency + "2"; //Put OPD in 2nd Storage Group
}
else if (strDivisionOU == "TRS")
{
strKey = strAgency + "1"; //Put TRS in 1st Storage Group
}
else
{
strKey = strAgency + "4"; //Put others in 4th Storage Group
}
}
#endregion
#region COR DNR DOJ DOR FWP
if ((strAgency == "COR") || (strAgency == "DNR") || (strAgency == "DOJ") || (strAgency == "DOR") || (strAgency == "FWP"))
{
iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
if (iLastNameNum < 78)
{
strKey = strAgency + "1"; //Put A through M in 1st Storage Group
}
else
{
strKey = strAgency + "2"; //Put N through Z in 2nd Storage Group
}
}
#endregion
#endregion
objDict.TryGetValue(strKey, out strExchangeParam);
arrExchParam = strExchangeParam.Split(':');
Response.Write("Mailbox Creation attempt for " + strUserDN + " on Exchange server " + arrExchParam.GetValue(0));
{
// Verify that exchange specific AD properties exist, and set them if they don't
strAction = "$user = [ADSI]^LDAP://" + strUserDN.Substring(1).Substring(0,strUserDN.Length -2) +"^";
strAction = strAction.Replace("^", "\\"");
colCreateResults = runposh(strAction);
strAction = "$attribute = $user.msExchVersion; if (!$attribute){$user.put('msExchVersion', '4535486012416')};$user.setinfo()";
colCreateResults = runposh(strAction);
strAction = "$attribute = $user.msExchRecipientDisplayType; if (!$attribute){$user.put('msExchRecipientDisplayType', '1073741824')};$user.setinfo()";
colCreateResults = runposh(strAction);
strAction = "$attribute = $user.msExchRecipientTypeDetails; if (!$attribute){$user.put('msExchRecipientTypeDetails', '1')};$user.setinfo()";
colCreateResults = runposh(strAction);
//Now, create the mailbox
strAction = "Enable-Mailbox -identity " + strUserDN + " -Database " + arrExchParam.GetValue(0) + "\\\\" + arrExchParam.GetValue(1) + "\\\\" + arrExchParam.GetValue(2);
colCreateResults = runposh(strAction);
if (colCreateResults.Count > 0)
{
//Disable Active Sync
strAction = "Set-CASMailbox -identity " + strUserDN + " –ActiveSyncEnabled $false";
colCreateResults = runposh(strAction);
Response.Write("Mailbox creation was successful.<br /><br />");
Response.Write("You will need to wait approximately 10 minutes for the mailbox to be available, due to Exchange and Active Directory replication latencies.<br /><br />");
strSubject = strAdminName + " Created a mailbox";
strBody = strAdminName + " created a mailbox associated with " + strUserDN + "\\r\\n\\r\\n";
strBody = strBody + "This mailbox was created on " + arrExchParam.GetValue(0) + "\\r\\n\\r\\n";
fnSendMail(strSubject, strBody);
}
else if (colCreateResults.Count == 0)
{
Response.Write("<br /><br />There was an error creating the mailbox. Please contact the Service Desk at x2000 to report this error. Include the logon ID of the user you were attempting to create the mailbox for, and any error shown below.<br /><br />");
strAction = "$error[0]";
colCreateResults = runposh(strAction);
if (colCreateResults.Count > 0)
{
string strErrorText = colCreateResults[0].ToString();
Response.Write("The error is: <b><span style='color:Red'>" + strErrorText + "</b></span><br />");
}
else if (colCreateResults.Count == 0)
{
Response.Write("An unknown error occured.");
}
}
}
}
protected void fnDeleteMailbox(string strAdminID, string strUserDN, string strAdminName)
{
/*
* Function to Delete user's mailbox
* Requires the Admin ID and user's ADsPath
*/
// remove leading and trailing spaces from input strings
strAdminID = strAdminID.Trim();
strUserDN = strUserDN.Trim();
strAdminName = strAdminName.Trim();
Collection<PSObject> colDeleteResults;
string strDeleteAction;
Response.Write("Mailbox Deletion attempt for " + strUserDN);
strDeleteAction = "$ConfirmPreference = 'none';set-Mailbox -Identity " + strUserDN + " -EmailAddresses $null -EmailAddressPolicyEnabled $false";
colDeleteResults = runposh(strDeleteAction);
strDeleteAction = "Disable-Mailbox -identity " + strUserDN + ";$ConfirmPreference = 'high'";
colDeleteResults = runposh(strDeleteAction);
if (colDeleteResults.Count == 0)
{
Response.Write("Mailbox deletion was successful.<br /><br /> You will need to wait approximately 10 minutes for the mailbox to disappear, due to Exchange and Active Directory replication latencies.");
string strSubject = strAdminName + " Deleted a mailbox";
string strBody = strAdminName + " deleted the mailbox associated with " + strUserDN;
fnSendMail(strSubject, strBody);
}
else if (colDeleteResults.Count != 0)
{
Response.Write("There was an error disabling the mailbox. Please contact the ITSD Customer Support Center at x2000 to report this error. Include the logon ID of the user whose mailbox you were attemting to disable");
}
}
protected void fnChangeAddress(string strAdminID, string strUserDN, string strOldAddress, string strNewAddress, string strAdminName, string strCompany, bool blKeepAddress)
{
/*
* Function to change User's Primary SMTP Address
* Requires the user's ADsPath and desired address
*/
// remove leading and trailing spaces from input strings
strAdminID = strAdminID.Trim();
strUserDN = strUserDN.Trim();
strOldAddress = strOldAddress.Trim();
strNewAddress = strNewAddress.Trim();
strAdminName = strAdminName.Trim();
Collection<PSObject> colChangeResults;
string strChangeAction = "";
string strBody = "";
string strSubject = "";
// First, findout if requested address is already in use
strChangeAction = "Get-Recipient -Filter{EmailAddresses -eq '" + strNewAddress + "@domain.com'} |select Name";
colChangeResults = runposh(strChangeAction);
if (colChangeResults.Count == 0)
{
// Requested address is available
Response.Write("Your requested address, " + strNewAddress + "@domain.com, is available<br />");
// if blKeepAddress = false, delete old addresses in SMTP only
if (blKeepAddress == false)
{
strChangeAction = "set-mailbox -identity " + strUserDN + " -PrimarySmtpAddress " + strNewAddress + "@domain.com -EmailAddressPolicyEnabled $false";
colChangeResults = runposh(strChangeAction);
do
{
strChangeAction = "get-mailbox -identity " + strUserDN + " |select PrimarySmtpAddress";
colChangeResults = runposh(strChangeAction);
} while (colChangeResults[0].ToString().Split('=')[1].Remove(colChangeResults[0].ToString().Split('=')[1].Length - 1).ToLower() != strNewAddress.ToLower() + "@domain.com");
strChangeAction = "$mailbox = Get-Mailbox -identity " + strUserDN;
colChangeResults = runposh(strChangeAction);
strChangeAction = "$mailbox.EmailAddresses | foreach { if (!$_.IsPrimaryAddress -and ($_.PrefixString -eq 'SMTP')) {$mailbox.EmailAddresses -= $_}}";
colChangeResults = runposh(strChangeAction);
strChangeAction = "start-sleep 5";
colChangeResults = runposh(strChangeAction);
strChangeAction = "set-mailbox -identity " + strUserDN + " -EmailAddresses $mailbox.EmailAddresses";
colChangeResults = runposh(strChangeAction);
}
else
{
strChangeAction = "set-mailbox -identity " + strUserDN + " -PrimarySmtpAddress " + strNewAddress + "@domain.com -EmailAddressPolicyEnabled $false";
colChangeResults = runposh(strChangeAction);
}
Response.Write("We have changed the primary SMTP address on " + strUserDN + "<br />");
Response.Write("From: " + strOldAddress + "<br />To: " + strNewAddress + "@domain.com<br />");
Response.Write("Please allow approximately 10 minutes for this change to replicate.");
strSubject = strOldAddress + " Address Change";
strBody = "SMTP Address change from " + strOldAddress + " to " + strNewAddress + "@domain.com on " + strUserDN + " by " + strAdminName + "\\r\\n\\r\\n";
fnSendMail(strSubject, strBody);
}
else if (colChangeResults.Count != 0)
{
// Requested address is NOT available
Response.Write("A duplicate address exists");
Response.Write("Your requested address is: " + strNewAddress + "@domain.com<br />");
string strFoundName = colChangeResults[0].ToString().Substring(7).Substring(0, colChangeResults[0].ToString().Length - 8);
Response.Write("Duplicate address found at: " + strFoundName + "<br />");
}
}
protected void fnSendMail(string strSubject, string strBody)
{
// Send mail to postmaster
MailMessage mail = new MailMessage();
mail.From = new MailAddress("postmaster@domain.com");
mail.To.Add(new MailAddress("postmaster@domain.com"));
mail.Subject = strSubject;
mail.Body = strBody;
SmtpClient client = new SmtpClient();
client.Host = "mail.domain.com";
client.Send(mail);
}
protected Collection<PSObject> runposh(string strCommand)
{
Runspace rs = GetRunspace();
Pipeline currentPipeline = GetPipeline(rs, strCommand);
if (currentPipeline.PipelineStateInfo.State == PipelineState.NotStarted)
{
Collection<PSObject> results = currentPipeline.Invoke();
currentPipeline.Dispose();
Cache.Remove("currentPipe");
return (results);
}
else
{
return null;
}
}
protected Runspace GetRunspace()
{
if (Cache["rs"] == null)
{
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
Cache["rs"] = rs;
}
return (Runspace)Cache["rs"];
}
protected Pipeline GetPipeline(Runspace rs, string strCommand)
{
if (Cache["currentPipe"] == null)
{
Pipeline currentPipeline = rs.CreatePipeline(strCommand);
Cache["currentPipe"] = currentPipeline;
}
return (Pipeline)Cache["currentPipe"];
}
}
|
PowerShellCorpus/PoshCode/Get-User_5.ps1
|
Get-User_5.ps1
|
function Get-User($user)
{
# this function should be passed the CN of the user to be returned
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))"
$user = $searcher.FindOne()
[System.Collections.Arraylist]$names = $user.Properties.PropertyNames
[System.Collections.Arraylist]$props = $user.Properties.Values
$userobj = New-Object System.Object
for ($i = 0; $i -lt $names.Count)
{
$userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i])
$i++
}
$userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset)
$userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp)
return $userobj
}
|
PowerShellCorpus/PoshCode/Email Forwarding - O365.ps1
|
Email Forwarding - O365.ps1
|
<#
Author: Matt Schmitt
Date: 11/28/12
Version: 1.0
From: USA
Email: ithink2020@gmail.com
Website: http://about.me/schmittmatt
Twitter: @MatthewASchmitt
Description
A script for forwarding and unforwarding email for users in Office 365.
#>
Write-Host ""
Write-Host ""
Write-Host "PowerShell Forward / Unforward Email Tool"
Write-Host ""
Write-Host ""
Write-Host "Connecting to the Office 365 Exchange PowerShell Session..."
Write-Host ""
Write-Host ""
Write-Host ""
# This block connects to the Office 365 Exchange PowerShell Session
$cred = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection
Set-ExecutionPolicy remotesigned -Force
Import-PSSession $Session
# Clears Screen
cls
# Name and Description of Script
Write-Host ""
Write-Host "PowerShell Forward / Unforward Email Tool"
Write-Host ""
Write-Host "This is used for forwarding and unforwarding other user's email."
Write-Host ""
Write-Host ""
#Asks if you want to Forward or Unforward
Write-Host "Would you like to:"
Write-Host ""
Write-Host " (1) Forward an Email"
Write-Host " (2) Unforward an Email"
Write-Host " (3) Exit"
Write-Host ""
#sets the selection to $todo
$todo = Read-Host "Please enter selection."
# Checkers for while loops
[int]$checker = 0
[int]$checker2 = 0
# This while loop checks to make sure user entered a valid entry
While ($checker -eq 0) {
#Switch to run code based on user's entery
Switch ($todo) {
#Option 1 code
"1" {
# Clears Screen
cls
Write-Host ""
Write-Host ""
Write-Host "You have selected to Forward a user's email."
Write-Host ""
Write-Host ""
#Ask for the username and sets it to $user
$user = Read-Host "Enter username of the email account that needs to be forwarded"
Write-Host ""
#Asks for the email address and sets it to $email
$email = Read-Host "Enter the email address, where the user's email should be forwared to"
Write-Host ""
#Asks about if a copy should be left and sets it to $copy
$copy = Read-Host "Would the user like a copy left in thier mailbox? (Y)es or (N)o?"
# This while loop checks to make sure user entered a valid entry
While ($checker2 -eq 0) {
#Switch to run code based on user's entery
Switch ($copy) {
# YES code
"Y" {
#sets $deliver as boolean and set variable to True
[bool]$deliver = $True
#Adjusts Checker for While loop
$checker2 += 1
}
#NO code
"N" {
#sets $deliver as boolean and set variable to False
[bool]$deliver = $False
#Adjusts Checker for While loop
$checker2 += 1
}
#Code to run if user enters invalid selection
default {
#clears screen
cls
Write-Host "You have entered and incorrect Option."
Write-Host ""
#Asks about if a copy should be left and sets it to $cop
$copy = Read-Host "Would the user like a copy left in thier mailbox? (Y)es or (N)o?"
}
}
}
Write-Host "Now Forwarding $user's email to $email..."
#This is the code that forwards the user's email
Set-Mailbox $user –ForwardingSmtpAddress $email –DeliverToMailboxAndForward $deliver
#Code to Disconnect from Office 365
Remove-PSSession $Session
Write-Host ""
Write-Host "If no errors, email has been Forwarded. If there is an error, review the error and try again."
Write-Host ""
Write-Host "Press any key to Exit."
#Adjusts Checker for While loop
$checker += 1
#Code to wait for user to press a key.
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"2" {
#Clears Screen
cls
Write-Host ""
Write-Host ""
Write-Host "You have selected to Unforward a user's email."
Write-Host ""
Write-Host ""
#Ask for the username and sets it to $user
$user = Read-Host "Enter username of the email account that needs to be forwarded"
Write-Host ""
Write-Host "Now UnForwarding $user's email."
#code for unforwarding email
Set-Mailbox $user –ForwardingSmtpAddress $null
#Code to Disconnect from Office 365
Remove-PSSession $Session
Write-Host ""
Write-Host "If no errors, email has been UnForwarded. If there is an error, review the error and try again."
Write-Host ""
Write-Host "Press any key to Exit."
#Adjusts Checker for While loop
$checker += 1
#Code to wait for user to press a key.
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"3" {
#Write-Host "You have selected Option 3"
#Code to Disconnect from Office 365
Remove-PSSession $Session
#Adjusts Checker for While loop
$checker += 1
}
#Code to run if user enters invalid selection
default {
#clears screen
cls
Write-Host "You have entered and incorrect selection. Please enter number corresponding to your selection."
Write-Host ""
Write-Host "Would you like to:"
Write-Host ""
Write-Host " (1) Forward an Email"
Write-Host " (2) Unforward an Email"
Write-Host " (3) Exit"
Write-Host ""
#Switch to run code based on user's entery
$todo = Read-Host "Please enter selection."
}
}
}
|
PowerShellCorpus/PoshCode/Get-MemoryChart_2.ps1
|
Get-MemoryChart_2.ps1
|
#.Synopsis
# Draw pie charts of server memory usage by process
#.Description
# Uses PowerBoots to draw a pipe-chart of each computer's memory use. While you wait for that information
# to be gathered, it shows you the latest xkcd comic. ##DEPEND-ON -Function Get-Comic http://poshcode.org/1003
# Uses the Transitionals library for nice transitions ##DEPEND-ON -Assembly Transitionals http://www.codeplex.com/transitionals
# Uses the Visifire libraries for the charts, of course ##DEPEND-ON -Assembly Visifire http://visifire.com
#
#.Parameter hosts
# The hostnames of the computers you want memory charts for
#.Example
# Get-MemoryChart localhost
#
# Returns a pie-chart of the memory on your local PC
#.Example
# Get-MemoryChart Server01,Server02
#
# Returns a pie-chart of the memory on Server01, and Server02
# Note that this requires WMI and authorization...
#
Param([string[]]$hosts = "localhost")
Import-Module PowerBoots
if(!(Get-Command JournalEntry -EA SilentlyContinue)) {
Add-BootsFunction -Type System.Windows.Navigation.JournalEntry
}
if(!(Get-Command Chart -EA SilentlyContinue)) {
Add-BootsContentProperty 'DataPoints', 'Series'
Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll" 2>$Null
Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\Transitionals.dll"
}
## And this is how you use a script which might not be there...
$global:comical = Get-Command Get-Comic -EA SilentlyContinue
if($comical) {
$global:comic = Get-Comic xkcd
if(!$comic) { $comical = $false } else {
$image = [system.drawing.image]::fromfile( $comic.FullName )
$global:comicwidth = $image.Width
$image.Dispose()
}
}
#$window = Boots { Image -Source $xkcd -MinHeight 100 } -Popup -Async
$limitsize = 10mb
$labellimitsize = 15mb
$window = Boots {
DockPanel {
# ListBox -DisplayMember Name -Ov global:list ` # -width 0
# -On_SelectionChanged { $global:container[0].Content = $global:list[0].SelectedItem }
# TransitionElement -Transition $(RotateTransition -Angle 45) `
Frame `
-Name TransitionBox -Ov global:container `
-MinWidth 400 -MinHeight 400 -MaxHeight 600 `
-Content {
StackPanel {
Label -FontSize 42 "Loading ..."
if($comical) {
Image -Source $comic.FullName -MaxWidth $comicwidth
}
} -'JournalEntry.Name' "Loading Screen" -Passthru
}
} -LastChildFill
} -MinHeight 400 -Async -Popup -Passthru
sleep 2;
$jobs = @()
ForEach($pc in $hosts) {
Write-Verbose "Getting procs from $pc"
$jobs += gwmi Win32_Process -ComputerName $pc -AsJob;
}
while($jobs) {
$global:job = Wait-Job -Any $jobs
Invoke-BootsWindow $window {
# if($list -is [System.Collections.ArrayList]) {
# $list = $list[0];
# $list.Padding = "2,2,5,2"
# }
$name = $($job.Location -Replace "[^a-zA-Z_0-9]" -replace "(^[0-9])",'_$1')
# $null = $list.Items.Add(
$global:container[0].Content = `
$(
Chart {
DataSeries -LabelText $job.Location {
ForEach($proc in (Receive-Job $job | Sort WorkingSetSize)) {
if($proc.WorkingSetSize -gt $limitsize) {
DataPoint -YValue $proc.WorkingSetSize -LabelText $proc.Name `
-LabelEnabled $($proc.WorkingSetSize -gt $labellimitsize) `
-ToolTipText "$($proc.Name): #YValue (#Percentage%)"
}
}
} -RenderAs Pie -ShowInLegend:$false
} -Watermark:$false -AnimationEnabled -Name $name -'JournalEntry.Name' $name -Passthru
)
# $list.SelectedIndex = $list.Items.Count - 1
}
$jobs = $jobs -ne $job
Remove-Job $job.Id
Sleep 5
}
|
PowerShellCorpus/PoshCode/Get-Cert.ps1
|
Get-Cert.ps1
|
$UsingStatements = @"
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
"@
$GetCert = @"
RemoteCertificateValidationCallback callback = delegate(
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslError)
{
X509Certificate2 x509 = new X509Certificate2(cert);
result.Add(x509);
// Print to console information contained in the certificate.
Console.WriteLine("Subject: {0}", x509.Subject);
Console.WriteLine("Issuer: {0}", x509.Issuer);
Console.WriteLine("Version: {0}", x509.Version);
Console.WriteLine("Valid Date: {0}", x509.NotBefore);
Console.WriteLine("Expiry Date: {0}", x509.NotAfter);
Console.WriteLine("Thumbprint: {0}", x509.Thumbprint);
Console.WriteLine("Serial Number: {0}", x509.SerialNumber);
Console.WriteLine("Friendly Name: {0}", x509.PublicKey.Oid.FriendlyName);
Console.WriteLine("Public Key Format: {0}", x509.PublicKey.EncodedKeyValue.Format(true));
Console.WriteLine("Raw Data Length: {0}", x509.RawData.Length);
// Console.WriteLine("Certificate to string: {0}", x509.ToString(true));
// Console.WriteLine("Certificate to XML String: {0}", x509.PublicKey.Key.ToXmlString(false));
Console.WriteLine("Added a certificate. Total: " + result.Count );
if (sslError != SslPolicyErrors.None) {
Console.WriteLine("Certificate error: " + sslError);
}
return false; // always stop, we have what we need
};
foreach(string serverName in args) {
Console.WriteLine("\\n\\nFetching SSL cert for {0}\\n", serverName);
// int secondArg = (int) ((object[]) arg)[1];
// Create a TCP/IP client socket to a machine name
TcpClient client = new TcpClient(serverName,443);
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream( client.GetStream(), false, callback, null );
try
{
sslStream.AuthenticateAsClient(serverName);
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine ("Authentication failed - closing the connection.");
}
client.Close();
}
"@
.\\Invoke-Inline $UsingStatements,$GetCert $args -ref @()
|
PowerShellCorpus/PoshCode/Get-RDPSettings.ps1
|
Get-RDPSettings.ps1
|
########################################################################################################################
# NAME
# Get-RDPSetting
#
# SYNOPSIS
# Gets some (with filter) or all properties from a RDP file.
#
# SYNTAX
# Edit-RDP [-Path] <string> [-Name] <string> [[-Value] <object>] [-PassThru]
#
# DETAILED DESCRIPTION
# This retrieves the properties for a saved RDP connection from a RDP file. The Name parameter can filter the
# list of properties to be returned.
#
# PARAMETERS
# -Path <string>
# Specifies the path to the RDP file.
#
# Required? true
# Position? 1
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Name <string>
# Specifies the name of the property or properties to get. Acts as a filter.
#
# Required? false
# Position? 2
# Default value
# Accept pipeline input? false
# Accept wildcard characters? true
#
# INPUT TYPE
#
#
# RETURN TYPE
# System.Management.Automation.PSCustomObject#RDPConnectionSetting
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>Get-RDPSetting -Path C:\\myserver.rdp
#
#
# This command gets all the properties of the "myserver" RDP file.
#
#
# -------------------------- EXAMPLE 2 --------------------------
#
# C:\\PS>Get-RDPSetting -Path C:\\myserver.rdp -Name "r*"
#
#
# This command returns all the properties that start with "r" from the "myserver" RDP file.
#
#
#Function global:Get-RDPSetting {
param(
[string]$Path = $(throw "A path to a RDP file is required."),
[string]$Name = "*"
)
$connection = Get-ChildItem -Path $path
Get-Content -Path $Path | ForEach-Object {
[Void] ($_ -match '^([^:]*):([^:]*):(.*)$')
$settingname = $Matches[1]
$type = $Matches[2]
$value = $Matches[3]
if ($settingname -like $Name) {
switch ($type) {
'b' { $datatype = "byte[]" }
'i' { $datatype = "integer" }
default { $datatype = "string" }
}
$object = "" | Select-Object Name,DataType,Value,Connection
$object.Name = $settingname
$object.DataType = $datatype
$object.Value = $value
$object.Connection = $connection.FullName
$object.PSObject.TypeNames.Insert(0,"$($object.PSObject.TypeNames[0])#RDPConnectionSetting")
$object
}
}
#}
|
PowerShellCorpus/PoshCode/New-ISEMenu.ps1
|
New-ISEMenu.ps1
|
Import-Module ShowUI
Function New-ISEMenu {
New-Grid -AllowDrop:$true -Name "ISEAddonCreator" -columns Auto, * -rows Auto,Auto,Auto,*,Auto,Auto -Margin 5 {
New-Label -Name Warning -Foreground Red -FontWeight Bold -Column 1
($target = New-TextBox -Name txtName -Column 1 -Row ($Row=1))
New-Label "Addon Menu _Name" -Target $target -Row $Row
($target = New-TextBox -Name txtShortcut -Column 1 -Row ($Row+=1))
New-Label "Shortcut _Key" -Row $Row -Target $target
($target = New-TextBox -Name txtScriptBlock -Column 1 -Row ($Row+=1) -MinHeight 141 -MinWidth 336 -AcceptsReturn:$true -HorizontalScrollBarVisibility Auto -VerticalScrollBarVisibility Auto)
New-Label "Script _Block" -Row $Row -Target $target
New-CheckBox "_Add to ISE Profile" -Name chkProfile -Row ($Row+=1)
New-StackPanel -Orientation Horizontal -Column 1 -Row ($Row+=1) -HorizontalAlignment Right {
New-Button "_Save" -Name btnSave -Width 75 -Margin "0,0,5,0" -IsDefault -On_Click {
if ($txtName.Text.Trim() -eq "" -or $txtShortcut.text.Trim() -eq "" -or $txtScriptBlock.text.Trim() -eq "") {
$Warning.Content = "You must supply all parameters"
} else {
$menuItems = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | Select -ExpandProperty DisplayName
if ($menuItems -Contains $txtName.Text) {
$Warning.Content = "Select another Name for the menu"
return
}
try {
$ScriptBlock = [ScriptBlock]::Create($txtScriptBlock.Text)
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add($txtName.Text,$ScriptBlock,$txtShortcut.Text) | Out-Null
}
catch {
$Warning.Content = "Fatal Error Creating MenuItem:`n$_"
return
}
if ($chkProfile.IsChecked) {
$profileText = "`n`#Added by ISE Menu Creator Addon if (`$psISE) { `$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(`"$($txtName.Text)`",`{$ScriptBlock`},`"$($txtShortcut.Text)`") | Out-Null } "
Add-Content -Path $profile -Value $profileText
}
$window.Close()
}
}
New-Button "Cancel" -Name btnCancel -Width 75 -IsCancel
}
} -show
}
# this will add a the "New ISE menu" menu item and load it every time you run this script!
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New ISE menu",{New-ISEMenu},"ALT+M") | Out-Null
|
PowerShellCorpus/PoshCode/Out-Wiki.ps1
|
Out-Wiki.ps1
|
################################################################################
# Out-Wiki - converts cmdlets help to media wiki (wikipedia) format
# http://dmitrysotnikov.wordpress.com/2008/08/18/out-wiki-convert-powershell-help-to-wiki-format/
# Modify the invocation line at the bottom of the script to point to your
# PowerShell snapin, and change the preface in the "generate index" section
################################################################################
# (c) Dmitry Sotnikov, http://dmitrysotnikov.wordpress.com
################################################################################
function Out-Wiki {
param($commands = $null, $outputDir = "./help")
$commandsHelp = $commands | sort-object noun | get-help -full
#create an output directory
if ( -not (Test-Path $outputDir)) {
md $outputDir | Out-Null
}
#Generate frame page
$indexFileName = $outputDir + "/index.txt"
#Generate index
@'
The ActiveRoles Management Shell for Active Directory is an Active Directoryspecific
automation and scripting shell that provides a command-line
management interface for administering directory data either via Quest
ActiveRoles Server or by directly accessing Active Directory domain
controllers. The ActiveRoles Management Shell is built on Microsoft Windows
PowerShell technology.
The following cmdlets are currently in the package:
'@ | out-file $indexFileName
foreach ($c in $commandsHelp) {
"* [[$($c.Name)]]" | out-file $indexFileName -Append
}
'[[Category:QAD cmdlets reference]]' | out-file $indexFileName -Append
#Generate all single help files
$outputText = $null
foreach ($c in $commandsHelp) {
$fileName = ( $outputDir + "/" + $c.Name + ".txt" )
"$($c.synopsis)" | out-file $fileName
# Syntax
"== Syntax ==" | out-file $fileName -Append
"<code>$(($c.syntax | out-string -width 2000).Trim())</code>" | out-file $fileName -Append
# Detailed Description
"== Detailed Description ==" | out-file $fileName -Append
"$($c.Description | out-string -width 2000)" | out-file $fileName -Append
# Related Commands
"== Related Commands ==" | out-file $fileName -Append
foreach ($relatedLink in $c.relatedLinks.navigationLink) {
if($relatedLink.linkText -ne $null -and
$relatedLink.linkText.StartsWith("about") -eq $false){
"* [[$($relatedLink.linkText)]]" | out-file $fileName -Append
}
}
# Parameters
"== Parameters ==" | out-file $fileName -Append
@'
{| class="wikitable" border=1
|-
!Name
!Description
!Required?
!Pipeline Input
!Default Value
'@ | out-file $fileName -Append
$paramNum = 0
foreach ($param in $c.parameters.parameter ) {
"|-" | out-file $fileName -Append
"!$($param.Name)" | out-file $fileName -Append
"|$(($param.Description | out-string -width 2000).Trim())" | out-file $fileName -Append
"|$($param.Required)" | out-file $fileName -Append
"|$($param.PipelineInput)" | out-file $fileName -Append
"|$($param.DefaultValue)" | out-file $fileName -Append
}
"|}" | out-file $fileName -Append
# Input Type
if (($c.inputTypes | Out-String ).Trim().Length -gt 0) {
"== Input Type ==" | out-file $fileName -Append
"$(($c.inputTypes | out-string -width 2000).Trim())" | out-file $fileName -Append
}
# Return Type
if (($c.returnValues | Out-String ).Trim().Length -gt 0) {
"== Return Values ==" | out-file $fileName -Append
"$(($c.returnValues | out-string -width 2000).Trim())" | out-file $fileName -Append
}
# Notes
if (($c.alertSet | Out-String).Trim().Length -gt 0) {
"== Notes ==" | out-file $fileName -Append
"$(($c.alertSet | out-string -Width 2000).Trim() )" | out-file $fileName -Append
}
# Examples
if (($c.examples | Out-String).Trim().Length -gt 0) {
"== Examples ==" | out-file $fileName -Append
foreach ($example in $c.examples.example) {
"==== $($example.title.Trim(('-',' ')))====" | out-file $fileName -Append
"<pre>$(($example.code | out-string ).Trim())</pre>" | out-file $fileName -Append
"$(($example.remarks | out-string -Width 2000).Trim())" | out-file $fileName -Append
}
}
'[[Category:QAD cmdlets reference]]' | out-file $fileName -Append
}
}
Out-Wiki (Get-Command -PSSnapin Quest.ActiveRoles.ADManagement) "c:\\Temp\\QADHelp"
|
PowerShellCorpus/PoshCode/Get-InstalledProgram_v_1.ps1
|
Get-InstalledProgram_v_1.ps1
|
function Get-InstalledProgram() {
param (
[String[]]$Computer,
$User
)
if ($User -is [String]) {
$Connection = Get-Credential -Credential $User
}
if ($Connection -eq $null){
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp |
where {$_.vendor -notlike "*Microsoft*" -and`
$_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"
} |
select __SERVER,Name,Version,InstallDate
$Install_soft
}
}
else {
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection |
where {$_.vendor -notlike "*Microsoft*" -and`
$_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"
} |
select __SERVER,Name,Version,InstallDate
$Install_soft
}
}
}
|
PowerShellCorpus/PoshCode/Set-Proxy.ps1
|
Set-Proxy.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[alias("Name","ComputerName")] $Computer = @($env:computername),
[switch] $ClearProxy
)
begin{
$IEsettingsKey = ".DEFAULT\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
[array]$ProxyResult = @()
function SetProxySettings($Computer){
Set-RegDWord -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyEnable -Data 0 -Force
Set-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyServer -Force
Set-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyOverride -Force
Set-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value DefaultConnectionSettings -Force
Set-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value SavedLegacySettings -Force
}
function GetProxySettings($Computer){
$Output = @()
$Output += (Get-RegDWord -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyEnable" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyServer" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyOverride" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value "DefaultConnectionSettings" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value "SavedLegacySettings" | Select-Object ComputerName,Value,Data)
return $Output
}
}
process{
if (Test-connection $Computer -quiet -count 1){
Try {
$ProxyResult += GetProxySettings $Computer
if ($ClearProxy){SetProxySettings $Computer; $ProxyResult += GetProxySettings $Computer}
}
Catch {
Write-Warning "$($error[0]) "
Break
}
}
}
end{
$ProxyResult
}
|
PowerShellCorpus/PoshCode/Get-UserWithManyGroups.ps1
|
Get-UserWithManyGroups.ps1
|
# Lists AD users who are members in too many groups
# (c) Dmitry Sotnikov
# Details at:
# http://dmitrysotnikov.wordpress.com/2009/10/12/find-users-in-too-many-groups/
# Uses free Quest AD cmdlets
$limit = 75
Get-QADUser -SizeLimit 0 -DontUseDefaultIncludedProperties |
ForEach-Object {
$groups = Get-QADGroup -ContainsIndirectMember $_.DN -SizeLimit $limit `
-DontUseDefaultIncludedProperties -WarningAction SilentlyContinue
if ($groups.Count -ge $limit) { $_ }
}
|
PowerShellCorpus/PoshCode/reconfigure-ha.ps1
|
reconfigure-ha.ps1
|
#ThePowerShellTalk
#reconfigure-ha.ps1
#take a VMhost object from the pipeline and apply the 'Reconfigure HA host' task
Process {
if ( $_ -isnot [VMware.VimAutomation.Client20.VMHostImpl] ) {
Write-Error "VMHost expected, skipping object in pipeline."
continue
}
$vmhostView = $_ | Get-View
$vmhostView.ReconfigureHostForDAS_Task()
}
|
PowerShellCorpus/PoshCode/Get-WebFile 3.6.ps1
|
Get-WebFile 3.6.ps1
|
## Get-WebFile (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.6 - Add -Passthru switch to output TEXT files
## v3.5 - Add -Quiet switch to turn off the progress reports ...
## v3.4 - Add progress report for files which don't report size
## v3.3 - Add progress report for files which report their size
## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:
## it was messing up binary files, and making mistakes with extended characters in text
## v3.1 - Unwrap the filename when it has quotes around it
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2 - adds a ton of parsing to make the output pretty
## added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
function Get-WebFile {
param(
$url = (Read-Host "The URL to download"),
$fileName = $null,
[switch]$Passthru,
[switch]$quiet
)
$req = [System.Net.HttpWebRequest]::Create($url);
$res = $req.GetResponse();
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName)))
{
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/""'")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
if($Passthru) {
$encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet )
[string]$output = ""
}
if($res.StatusCode -eq 200) {
[int]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($fileName) {
$writer.Write($buffer, 0, $count);
}
if($Passthru){
$output += $encoding.GetString($buffer,0,$count)
} elseif(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$reader.Close()
if($fileName) {
$writer.Flush()
$writer.Close()
}
if($Passthru){
$output
}
}
$res.Close();
if($fileName) {
ls $fileName
}
}
|
PowerShellCorpus/PoshCode/List AD Attributes_2.ps1
|
List AD Attributes_2.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-BogonList_3.ps1
|
Get-BogonList_3.ps1
|
function Get-BogonList {
<#
.SYNOPSIS
Gets the bogon list.
.DESCRIPTION
The Get-BogonList function retrieves the bogon prefix list maintained by Team Cymru.
A bogon prefix is a route that should never appear in the Internet routing table.
A packet routed over the public Internet (not including over VPNs or other tunnels) should never have a source address in a bogon range.
These are commonly found as the source addresses of DDoS attacks.
Bogons are defined as Martians (private and reserved addresses defined by RFC 1918 and RFC 5735) and netblocks that have not been allocated
to a regional internet registry (RIR) by the Internet Assigned Numbers Authority. Fullbogons are a larger set which also includes IP space
that has been allocated to an RIR, but not assigned by that RIR to an actual ISP or other end-user.
.PARAMETER Aggregated
Retrieves the aggreated traditional bogon list. By default the unaggregated list is retrieved.
.PARAMETER FullBogons
Retrieves the full bogon list.
.PARAMETER IPVersion
Specifies which IP version of the full bogon list will be retrieved. The FullBogons parameter is required.
The default value is version 4.
.INPUTS
None
.OUTPUTS
PSObject
.EXAMPLE
Get-BogonList
Retrieves the traditional unaggregated bogon list from Team Cymru.
.EXAMPLE
Get-BogonList -Verbose
Retrieves the traditional unaggregated bogon list from Team Cymru with additional header information.
.EXAMPLE
Get-BogonList -Aggregated
Retrieves the traditional aggregated bogon list from Team Cymru.
.EXAMPLE
Get-BogonList -FullBogons
Retrieves the full IPv4 bogon list from Team Cymru.
.EXAMPLE
Get-BogonList -FullBogons -IPVersion 6
Retrieves the full IPv6 bogon list from Team Cymru.
.NOTES
Name: Get-BogonList
Author: Rich Kusak (rkusak@cbcag.edu)
Created: 2010-01-31
LastEdit: 2011-08-14 09:26
Version: 1.3.1.0
#Requires -Version 2.0
.LINK
http://www.team-cymru.org/Services/Bogons/
#>
[CmdletBinding(DefaultParameterSetName='Traditional')]
param (
[Parameter(ParameterSetName='Traditional')]
[switch]$Aggregated,
[Parameter(ParameterSetName='Full')]
[switch]$FullBogons,
[Parameter(ParameterSetName='Full')]
[ValidateSet(4,6)]
[int]$IPVersion = 4
)
# Create a web client object
$webClient = New-Object System.Net.WebClient
if ($psCmdlet.ParameterSetName -eq 'Traditional') {
$referencePage = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/')
$traditionalUpdated = [regex]::Match($referencePage, 'Updated:.*(\\d{2}\\s\\w+\\s\\d{4})', 'IgnoreCase').Groups[1].Value
$currentVersion = [regex]::Match($referencePage, 'version:.*(\\d+\\.\\d+)', 'IgnoreCase').Groups[1].Value
if ($PSBoundParameters['Verbose']) {
# Display title, update, and version information
Write-Output 'Team Cymru Traditional Bogon List'
'Updated: {0}' -f $traditionalUpdated
'Current version: {0}' -f $currentVersion
}
# Retrieve and display the aggregated bogon list
if ($Aggregated) {
foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-agg.txt') -split "`n") {
New-Object PSObject -Property @{'Aggregated' = $bogon}
}
# Retrieve and display the unaggregated bogon list
} else {
foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-nonagg.txt') -split "`n") {
New-Object PSObject -Property @{'Unaggregated' = $bogon}
}
}
} # if ($psCmdlet.ParameterSetName -eq 'Traditional')
if ($psCmdlet.ParameterSetName -eq 'Full') {
if (-not $FullBogons) {
return Write-Error 'The FullBogons parameter is required to set the IPVersion.'
}
switch ($IPVersion) {
4 {
$bogons = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/fullbogons-ipv4.txt') -split "`n"
$propertyName = 'IPv4FullBogons'
break
}
6 {
$bogons = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/fullbogons-ipv6.txt') -split "`n"
$propertyName = 'IPv6FullBogons'
break
}
}
$fullUpdated = [regex]::Match($bogons[0], '\\(.+\\)').Value.Trim('()')
if ($PSBoundParameters['Verbose']) {
# Display title and update information
Write-Output 'Team Cymru Full Bogon List'
'Updated: {0}' -f $fullUpdated
}
# Create full bogon list output object
foreach ($bogon in $bogons -match '^\\d') {
New-Object PSObject -Property @{$propertyName = $bogon}
}
} # if ($psCmdlet.ParameterSetName -eq 'Full')
} # function Get-BogonList
|
PowerShellCorpus/PoshCode/4a02f944-afe3-4393-b3c2-0d92d77d0b82.ps1
|
4a02f944-afe3-4393-b3c2-0d92d77d0b82.ps1
|
if (Get-Process 'WRemote' -ea SilentlyContinue) {
if (Get-Process 'POS2100' -ea -ErrorAction SilentlyContinue) {
Write-Host "Restarting WinRemote"
Stop-Process -processname WRemote
Reset-Tray
#Start-Sleep -Second 2
#Invoke-Item C:\\ICOM\\POS2100\\WRemote.exe
}
else
{
Write-Host "WinRemote not running, Starting now..."
Reset-Tray
Stop-Process -processname POS2100
#Invoke-Item C:\\ICOM\\POS2100\\WRemote.exe
}
function Reset-Tray {
Add-Type -Assembly UIAutomationClient
$Window = Add-Type -Name ([char[]](65..90 | Get-Random -count 10) -join "") -Member @"
[DllImport("user32")]
public static extern IntPtr PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
public static void SendMouseMove(IntPtr hWnd, ushort x, ushort y) {
int point = (y << 16) + x;
PostMessage(hWnd, 0x200, 0, point);
}
"@ -Passthru
$tray1 = [System.Windows.Automation.AutomationElement]::RootElement.FindAll( "Descendants" , [System.Windows.Automation.Condition]::TrueCondition ) |
Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like "SysPager" }
# On Windows7 and Vista there's this, like, sub-tray thing
$tray2 = $tray1.FindAll( "Children" , [System.Windows.Automation.Condition]::TrueCondition ) |
Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -eq "User Promoted Notification Area" }
$tray = $(if($tray2) { $tray2 } else { $tray1 })
$handle = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty)
$rect = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::BoundingRectangleProperty)
$y = $rect.Height/2
for ( $x = 0; $x -lt $rect.Width; $x += 8) {
$Window::SendMouseMove( $handle, $x, $y )
}
}
|
PowerShellCorpus/PoshCode/get windows product key_7.ps1
|
get windows product key_7.ps1
|
function get-windowsproductkey([string]$computer)
{
$Reg = [WMIClass] ("\\\\" + $computer + "\\root\\default:StdRegProv")
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$STR = ''
$decodedChars | % { $str+=$_}
$STR
}
get-windowsproductkey .
|
PowerShellCorpus/PoshCode/Compile-Help_1.ps1
|
Compile-Help_1.ps1
|
# Compile-Help.ps1
# by Jeff Hillman
#
# this script uses the text and XML PowerShell help files to generate HTML help
# for all PowerShell Cmdlets, PSProviders, and "about" topics. the help topics
# are compiled into a .chm file using HTML Help Workshop.
#
# Minor tweak by John Robbins to work on x64 when looking for HHC.EXE.
param( [string] $outDirectory = ".\\PSHelp", [switch] $GroupByPSSnapIn )
function Html-Encode( [string] $value )
{
# System.Web.HttpUtility.HtmlEncode() doesn't quite get everything, and
# I don't want to load the System.Web assembly just for this. I'm sure
# I missed something here, but these are the characters I saw that needed
# to be encoded most often
$value = $value -replace "&(?![\\w#]+;)", "&"
$value = $value -replace "<(?!!--)", "<"
$value = $value -replace "(?<!--)>", ">"
$value = $value -replace "’", "'"
$value = $value -replace '["“”]', """
$value = $value -replace "\\n", "<br />"
$value
}
function Capitalize-Words( [string] $value )
{
$capitalizedString = ""
# convert the string to lower case and split it into individual words. for each one,
# capitalize the first character, and append it to the converted string
[regex]::Split( $value.ToLower(), "\\s" ) | ForEach-Object {
$capitalizedString += ( [string]$_.Chars( 0 ) ).ToUpper() + $_.SubString( 1 ) + " "
}
$capitalizedString.Trim()
}
function Get-ParagraphedHtml( [string] $xmlText )
{
$value = ""
if ( $xmlText -match "<(\\w+:)?para" )
{
$value = ""
$options = [System.Text.RegularExpressions.RegexOptions]::Singleline
foreach ( $match in [regex]::Matches( $xmlText,
"<(?:\\w+:)?para[^>]*>(?<Text>.*?)</(?:\\w+:)?para>", $options ) )
{
$value += "<p>$( Html-Encode $match.Groups[ 'Text' ].Value )</p>"
}
}
else
{
$value = Html-Encode $xmlText
}
$value
}
function Get-SyntaxHtml( [xml] $syntaxXml )
{
$syntaxHtml = ""
# generate the HTML for each form of the Cmdlet syntax
foreach ( $syntaxItem in $syntaxXml.syntax.syntaxItem )
{
if ( $syntaxHtml -ne "" )
{
$syntaxHtml += "<br /><br />`n"
}
$syntaxHtml += " $( $syntaxItem.name.get_InnerText().Trim() ) "
if ( $syntaxItem.parameter )
{
foreach ( $parameter in $syntaxItem.parameter )
{
$required = [bool]::Parse( $parameter.required )
$syntaxHtml += "<nobr>[-$( $parameter.name.get_InnerText().Trim() )"
if ( $required )
{
$syntaxHtml += "]"
}
if ( $parameter.parameterValue )
{
$syntaxHtml +=
" <$( $parameter.parameterValue.get_InnerText().Trim() )>"
}
if ( !$required )
{
$syntaxHtml += "]"
}
$syntaxHtml += "</nobr> "
}
}
$syntaxHtml += " <nobr>[<CommonParameters>]</nobr>"
}
$syntaxHtml.Trim()
}
function Get-ParameterHtml( [xml] $parameterXml )
{
$parameterHtml = ""
# generate HTML for each parameter
foreach ( $parameter in $parameterXml.parameters.parameter )
{
if ( $parameterHtml -ne "" )
{
$parameterHtml += " <br /><br />`n"
}
$parameterHtml +=
" <nobr><span class=`"boldtext`">-$( $parameter.name.get_InnerText().Trim() )"
if ( $parameter.parameterValue )
{
$parameterHtml += " <$( $parameter.parameterValue.get_InnerText().Trim() )>"
}
$parameterHtml += "</span></nobr>`n"
$parameterHtml += @"
<br />
<div id="contenttext">
$( Get-ParagraphedHtml $parameter.description.get_InnerXml().Trim() )
"@
if ( $parameter.possibleValues )
{
foreach ( $possibleValue in $parameter.possibleValues.possibleValue )
{
$parameterHtml += @"
$( $possibleValue.value.Trim() )<br />
"@
if ( $possibleValue.description.get_InnerText().Trim() -ne "" )
{
$parameterHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() )
</div>
"@
}
}
}
$parameterHtml += @"
<br />
</div>
<table class="parametertable">
<tr>
<td>Required</td>
<td>$( $parameter.required )</td>
</tr>
<tr>
<td>Position</td>
<td>$( $parameter.position )</td>
</tr>
<tr>
<td>Accepts pipeline input</td>
<td>$( $parameter.pipelineInput )</td>
</tr>
<tr>
<td>Accepts wildcard characters</td>
<td>$( $parameter.globbing )</td>
</tr>
"@
if ( $parameter.defaultValue )
{
if( $parameter.defaultValue.get_InnerText().Trim() -ne "" )
{
$parameterHtml += @"
<tr>
<td>Default Value</td>
<td>$( $parameter.defaultValue.get_InnerText().Trim() )</td>
</tr>
"@
}
}
$parameterHtml += @"
</table>
"@
}
if ( $parameterHtml -ne "" )
{
$parameterHtml += " <br /><br />`n"
}
$parameterHtml += @"
<nobr><span class="boldtext"><CommonParameters></span></nobr>
<br />
<div id="contenttext">
<p>
For more information about common parameters, type "Get-Help about_commonparameters".
</p>
</div>
"@
$parameterHtml.Trim()
}
function Get-InputHtml( [xml] $inputXml )
{
$inputHtml = ""
$inputCount = 0
# generate HTML for each input type
foreach ( $inputType in $inputXml.inputTypes.inputType )
{
if ( $inputHtml -ne "" )
{
$inputHtml += " <br /><br />`n"
}
if ( $inputType.type.name.get_InnerText().Trim() -ne "" -or
$inputType.type.description.get_InnerText().Trim() -ne "" )
{
$inputHtml += " $( $inputType.type.name.get_InnerText().Trim() )`n"
$inputHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $inputType.type.description.get_InnerXml().Trim() )
</div>
"@
$inputCount++
}
}
$inputHtml.Trim()
$inputCount
}
function Get-ReturnHtml( [xml] $returnXml )
{
$returnHtml = ""
$returnCount = 0
# generate HTML for each return value
foreach ( $returnValue in $returnXml.returnValues.returnValue )
{
if ( $returnHtml -ne "" )
{
$returnHtml += " <br /><br />`n"
}
if ( $returnValue.type.name.get_InnerText().Trim() -ne "" -or
$returnValue.type.description.get_InnerText().Trim() -ne "" )
{
$returnHtml += " $( $returnValue.type.name.get_InnerText().Trim() )`n"
$returnHtml += @"
<div id="contenttext">
$( Get-ParagraphedHtml $returnValue.type.description.get_InnerXml().Trim() )
</div>
"@
$returnCount++
}
}
$returnHtml.Trim()
$returnCount
}
function Get-ExampleHtml( [xml] $exampleXml )
{
$exampleHtml = ""
$exampleTotalCount = 0
$exampleCount = 0
foreach ( $example in $exampleXml.examples.example )
{
$exampleTotalCount++
}
# generate HTML for each example
foreach ( $example in $exampleXml.examples.example )
{
if ( $example.code -and $example.code.get_InnerText().Trim() -ne "" )
{
if ( $exampleHtml -ne "" )
{
$exampleHtml += " <br />`n"
}
if ( $exampleTotalCount -gt 1 )
{
$exampleHtml +=
" <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n"
}
$exampleCodeHtml = "$( Html-Encode $example.introduction.get_InnerText().Trim() )" +
"$( Html-Encode $example.code.get_InnerText().Trim() )"
$exampleHtml += " <div class=`"syntaxregion`">$exampleCodeHtml</div>`n"
$foundFirstPara = $false
foreach ( $para in $example.remarks.para )
{
if ( $para.get_InnerText().Trim() -ne "" )
{
# the first para is generally the description of the example.
# other para tags usually contain sample output
if ( !$foundFirstPara )
{
$exampleHtml += @"
<div id="contenttext">
<p>
$( Html-Encode $para.get_InnerText().Trim() )
</p>
</div>
"@
$foundFirstPara = $true
}
else
{
$exampleHtml += @"
<pre class="syntaxregion">$( $( ( Html-Encode $para.get_InnerText().Trim() ) -replace "<br />", "`n" ) )</pre>
"@
}
}
}
$exampleCount++
}
}
$exampleHtml.Trim()
$exampleCount
}
function Get-TaskExampleHtml( [xml] $exampleXml )
{
$exampleHtml = ""
$exampleCount = 0
$exampleTotalCount = 0
foreach ( $example in $exampleXml.examples.example )
{
$exampleTotalCount++
}
# generate HTML for each example
foreach ( $example in $exampleXml.examples.example )
{
if ( $exampleHtml -ne "" )
{
$exampleHtml += " <br />`n"
}
if ( $exampleTotalCount -gt 1 )
{
$exampleHtml += " <nobr><span class=`"boldtext`">Example $( $exampleCount + 1 )</span></nobr>`n"
}
$exampleHtml += " <div>$( Get-ParagraphedHtml $example.introduction.get_InnerXml().Trim() )</div>`n"
$exampleCodeHtml = ( Html-Encode $example.code.Trim() ) -replace "<br />", "`n"
$exampleHtml += " <pre class=`"syntaxregion`">$exampleCodeHtml</pre>"
$exampleHtml += " <div>$( Get-ParagraphedHtml $example.remarks.get_InnerXml().Trim() )</div>`n"
$exampleCount++
}
$exampleHtml.Trim()
}
function Get-LinkHtml( [xml] $linkXml )
{
$linkHtml = ""
$linkCount = 0
# generate HTML for each related link
foreach ( $navigationLink in $linkXml.relatedLinks.navigationLink )
{
if ( $navigationLink.linkText -and `
( $helpHash.Keys | Foreach-Object { $_.ToUpper() } ) -contains $navigationLink.linkText.Trim().ToUpper() )
{
$linkHtml += " $( $navigationLink.linkText.Trim() )<br />`n"
$linkCount++
}
}
$linkHtml.Trim()
$linkCount
}
function Get-TaskHtml( [xml] $taskXml )
{
$taskHtml = ""
$taskCount = 0
foreach ( $task in $taskXml.tasks.task )
{
if ( $taskHtml -ne "" )
{
$taskHtml += " <br />`n"
}
$taskHtml += " <nobr><span class=`"boldtext`">Task:</span> $( $task.title.Trim() )</nobr>`n"
$taskDescriptionHtml = ( Get-ParagraphedHtml $task.description.get_InnerXml().Trim() )
$taskHtml += " <div id=`"contenttext`">$taskDescriptionHtml</div>`n"
# add the example sections
if ( $task.examples )
{
$taskHtml += @"
<div id="contenttext">
<p>
$( Get-TaskExampleHtml ( [xml]$task.examples.get_OuterXml() ) )
</p>
</div>
"@
}
$taskCount++
}
$taskHtml.Trim()
$taskCount
}
function Get-DynamicParameterHtml( [xml] $dynamicParameterXml )
{
$dynamicParameterHtml = ""
# generate HTML for each dynamic parameter
foreach ( $dynamicParameter in $dynamicParameterXml.dynamicparameters.dynamicparameter )
{
$dynamicParameterHtml += " <nobr><span class=`"boldtext`">-$( $dynamicParameter.name.Trim() )"
if ( $dynamicParameter.type )
{
$dynamicParameterHtml += " <$( $dynamicParameter.type.name.Trim() )>"
}
$dynamicParameterHtml += "</span></nobr>`n"
$dynamicParameterHtml += @"
<br />
<div id="contenttext">
<p>
$( Html-Encode $dynamicParameter.description.Trim() )
</p>
"@
if ( $dynamicParameter.possiblevalues )
{
foreach ( $possibleValue in $dynamicParameter.possiblevalues.possiblevalue )
{
$dynamicParameterHtml += @"
<div id="contenttext">
<span class=`"boldtext`">$( $possibleValue.value )</span>
<div id="contenttext">
$( Get-ParagraphedHtml $possibleValue.description.get_InnerXml().Trim() )
</div>
</div>
"@
}
}
$dynamicParameterHtml += @"
<br />
<span class=`"boldtext`">Cmdlets Supported</span>
<div id="contenttext">
<p>
$( Html-Encode $dynamicParameter.cmdletsupported.Trim() )
</p>
</div>
</div>
<br />
"@
}
$dynamicParameterHtml.Trim()
}
function Write-AboutTopic( [string] $topicName, [string] $topicPath )
{
# just dump the contents of the about topic exactly as it is. the only changes needed
# are to encode the special HTML characters and add topic links
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() )</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
About $( Capitalize-Words ( $topicName -replace "(about)?_", " " ).Trim() )
</div>
<pre>
$( ( Html-Encode ( [string]::Join( [Environment]::NewLine, ( Get-Content -Path $topicPath ) ) ) ) -replace "<br />" )
</pre>
</body>
</html>
"@
$topicHtml = Add-Links $topicName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$topicName.html" -Encoding Ascii -Input $topicHtml
}
function Write-ProviderTopic( [string] $providerFullName, [xml] $providerXml )
{
$providerName = $providerXml.providerhelp.Name.Trim()
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>$providerName Help</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
$providerName Provider
<div style="text-align: right; padding-right: 3px;">
$( $providerFullName -replace "^\\w+\\." )
</div>
</div>
<div class="categorytitle">Drives</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.drives.get_InnerXml().Trim() )
</div>
<div class="categorytitle">Synopsis</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.synopsis.Trim() )</p>
</div>
"@
$topicHtml += @"
<div class="categorytitle">Description</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.detaileddescription.get_InnerXml().Trim() )
</div>
"@
if ( $providerXml.providerhelp.capabilities.get_InnerText().Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Capabilities</div>
<div id="contenttext">
$( Get-ParagraphedHtml $providerXml.providerhelp.capabilities.get_InnerXml().Trim() )
</div>
"@
}
$taskHtml, $taskCount = Get-TaskHtml( $providerXml.providerhelp.tasks.get_OuterXml() )
if ( $taskCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Task$( if ( $taskCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$taskHtml
</div>
"@
}
if ( $providerXml.providerhelp.dynamicparameters )
{
$topicHtml += @"
<div class="categorytitle">Dynamic Parameters</div>
<div id="contenttext">
$( Get-DynamicParameterHtml( $providerXml.providerhelp.dynamicparameters.get_OuterXml() ) )
</div>
"@
}
if ( $providerXml.providerhelp.notes.Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Notes</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.notes.Trim() )</p>
</div>
"@
}
$topicHtml += @"
<div class="categorytitle">Related Links</div>
<div id="contenttext">
<p>$( Html-Encode $providerXml.providerhelp.relatedlinks.Trim() )</p>
</div>
<br />
</body>
</html>
"@
$topicHtml = Add-Links $providerName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$providerFullName.html" -Encoding Ascii -Input $topicHtml
}
function Write-CmdletTopic( [string] $cmdletFullName, [xml] $cmdletXml )
{
$cmdletName = $cmdletXml.command.details.name.Trim()
# add the heading, syntax section, and description
$topicHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>$cmdletName Help</title>
</head>
<body>
<div id="topicheading">
<div id="topictitle">PowerShell Help</div>
$cmdletName Cmdlet
<div style="text-align: right; padding-right: 3px;">
$( $cmdletFullName -replace "^\\w+-\\w+\\." )
</div>
</div>
<div class="categorytitle">Synopsis</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.details.description.get_InnerXml().Trim() )
</div>
<div class="categorytitle">Syntax</div>
<div id="contenttext">
<div class="syntaxregion">$( Get-SyntaxHtml ( [xml]$cmdletXml.command.syntax.get_OuterXml() ) )</div>
</div>
<div class="categorytitle">Description</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.description.get_InnerXml().Trim() )
</div>
"@
# add the parameters section
if ( $cmdletXml.command.parameters )
{
$topicHtml += @"
<div class="categorytitle">Parameters</div>
<div id="contenttext">
<p>
$( Get-ParameterHtml ( [xml]$cmdletXml.command.parameters.get_OuterXml() ) )
</p>
</div>
"@
}
else
{
$topicHtml += @"
<div class="categorytitle">Parameters</div>
<div id="contenttext">
<p>
<nobr><span class="boldtext"><CommonParameters></span></nobr><br />
<div id="contenttext">
<p>
For more information about common parameters, type "Get-Help about_commonparameters".
</p>
</div>
</p>
</div>
"@
}
# add the input types section
if ( $cmdletXml.command.inputTypes )
{
$inputHtml, $inputCount = Get-InputHtml ( [xml]$cmdletXml.command.inputTypes.get_OuterXml() )
if ( $inputCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Input Type$( if ( $inputCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$inputHtml
</div>
"@
}
}
# add the return values section
if ( $cmdletXml.command.returnValue )
{
$returnHtml, $returnCount = Get-ReturnHtml ( [xml]$cmdletXml.command.returnValues.get_OuterXml() )
if ( $returnCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Return Value$( if ( $returnCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
$returnHtml
</div>
"@
}
}
# add the notes section
if ( $cmdletXml.command.alertSet )
{
if ( $cmdletXml.command.alertSet.get_InnerText().Trim() -ne "" )
{
$topicHtml += @"
<div class="categorytitle">Notes</div>
<div id="contenttext">
$( Get-ParagraphedHtml $cmdletXml.command.alertSet.get_InnerXml().Trim() )
</div>
"@
}
}
# add the example section
if ( $cmdletXml.command.examples )
{
$exampleHtml, $exampleCount = Get-ExampleHtml ( [xml]$cmdletXml.command.examples.get_OuterXml() )
if ( $exampleCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Example$( if ( $exampleCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
<p>
$exampleHtml
</p>
</div>
"@
}
}
# add the related links section
if ( $cmdletXml.command.relatedLinks )
{
$linkHtml, $linkCount = Get-LinkHtml ( [xml]$cmdletXml.command.relatedLinks.get_OuterXml() )
if ( $linkCount -gt 0 )
{
$topicHtml += @"
<div class="categorytitle">Related Link$( if ( $linkCount -gt 1 ) { "s" } )</div>
<div id="contenttext">
<p>
$linkHtml
</p>
</div>
<br />
"@
}
else
{
$topicHtml += " <br />`n"
}
}
else
{
$topicHtml += " <br />`n"
}
$topicHtml += @"
</body>
</html>
"@
$topicHtml = Add-Links $cmdletName $topicHtml
Out-File -FilePath "$outDirectory\\Topics\\$cmdletFullName.html" -Encoding Ascii -Input $topicHtml
}
function Add-Links( [string] $topicName, [string] $topicHtml )
{
# we only want to add links for Cmdlets and about topics
$helpHash.Keys | Where-Object { $_ -match "(^\\w+-\\w+|^about_)" } | Foreach-Object {
$searchText = $_
# keys representing Cmdlets are formatted like this:
# <Cmdlet Name>.<PSProvider name>
if ( $_ -match "^\\w+-\\w+" )
{
# we only want to search for the Cmdlet name
$searchText = $matches[ 0 ]
}
# if the search text isn't the topic being processed
if ( $searchText -ne $topicName )
{
$topicHtml = $topicHtml -replace "\\b($searchText)\\b", "<a href=`"Topics\\$_.html`"><nobr>`$1</nobr></a>"
}
}
$topicHtml
}
# file dumping functions
function Write-Hhp
{
# write the contents of the Html Help Project file
Out-File -FilePath "$outDirectory\\powershell.hhp" -Encoding Ascii -Input @"
[OPTIONS]
Binary TOC=Yes
Compatibility=1.1 or later
Compiled file=PowerShell.chm
Contents file=powershell.hhc
Default topic=Topics/default.html
Full-text search=Yes
Language=0x409 English (United States)
Title=PowerShell Help
[INFOTYPES]
"@
}
function Write-DefaultPage
{
$defaultHtml = @"
<html>
<head>
<link rel="stylesheet" type="text/css" href="powershell.css" />
<title>PowerShell Help</title>
</head>
<body style="margin: 5px 5px 5px 5px; color: #FFFFFF; background-color: #C86400;">
<h2>Windows PowerShell Help</h2>
<br />
This complied help manual contains the help for all of the built-in PowerShell Cmdlets
and PSProviders, as well as the help for any Cmdlets or PSProviders added through
Add-PSSnapin, if help for them is available. Also included are all of the "about" topics.
<br /><br />
To use this manual from the PowerShell command line, add the following function and
alias to your PowerShell profile:
<div id="contenttext">
<pre class="syntaxregion">function Get-CompiledHelp( [string] `$topic )
{
if ( `$topic )
{
# Get-Command will fail if the topic is a PSProvider or an "about" topic.
`$ErrorActionPreference = "SilentlyContinue"
# we don't want Get-Command to resolve to an application or a function
`$command = Get-Command `$topic | Where-Object { `$_.CommandType -match "Alias|Cmdlet" }
# if the topic is an alias or a Cmdlet, combine its name with
# its PSProvider to get the full name of the help file
if ( `$command -and `$command.CommandType -eq "Alias" )
{
`$topic = "`$( `$command.Definition ).`$( `$command.ReferencedCommand.PSSnapIn.Name )"
}
elseif ( `$command -and `$command.CommandType -eq "Cmdlet" )
{
`$topic = "`$( `$command.Name ).`$( `$command.PSSnapIn.Name )"
}
else
{
# check to see if we have a PSProvider
`$psProvider = Get-PSProvider `$topic
if ( `$psProvider )
{
`$topic = "`$( `$psProvider.Name ).`$( `$psProvider.PSSnapIn.Name )"
}
}
hh.exe "mk:@MSITStore:$( Resolve-Path "$outDirectory" )\\PowerShell.chm::/Topics/`$topic.html"
}
else
{
hh.exe "$( Resolve-Path "$outDirectory" )\\PowerShell.chm"
}
}
Set-Alias chelp Get-CompiledHelp</pre>
</div>
<br />
The path in the Get-CompliedHelp function corresponds to the location where this compiled
help manual was originally created. If this file is moved to another location, the path
in the function will need to be updated.
<br />
<br />
To view the help topic for Get-ChildItem, type the following:
<div id="contenttext">
<div class="syntaxregion">PS$ Get-CompiledHelp Get-ChildItem</div>
</div>
<br />
Because "ls" is an alias for Get-ChildItem, and "chelp" is an alias for Get-CompliedHelp, the following also works:
<div id="contenttext">
<div class="syntaxregion">PS$ chelp ls</div>
</div>
</body>
</html>
"@
$defaultHtml = Add-Links "" $defaultHtml
Out-File -FilePath "$outDirectory\\Topics\\default.html" -Encoding Ascii -Input $defaultHtml
}
function Write-Css
{
Out-File -FilePath "$outDirectory\\powershell.css" -Encoding Ascii -Input @"
body
{
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 70%;
width: 100%;
}
div#topicheading
{
position: relative;
left: 0px;
padding: 5px 0px 5px 10px;
border-bottom: 1px solid #999999;
color: #FFFFFF;
background-color: #C86400;
font-size: 110%;
font-weight: bold;
text-align: left;
}
div#topictitle
{
padding: 5px 5px 5px 5px;
color: #FFFFFF
font-size: 90%;
font-weight: normal;
}
div#contenttext
{
top: 0px;
padding: 0px 25px 0px 25px;
}
p { margin: 5px 0px 5px 0px; }
a:link { color: #0000FF; }
a:visited { color: #0000FF; }
a:hover { color: #3366FF; }
table.parametertable
{
margin-left: 25px;
font-size: 100%;
border-collapse:collapse
}
table.parametertable td
{
font-size: 100%;
border: solid #999999 1px;
padding: 0in 5.4pt 0in 5.4pt
}
pre.syntaxregion, div.syntaxregion
{
background: #DDDDDD;
padding: 4px 8px;
cursor: text;
margin-top: 1em;
margin-bottom: 1em;
margin-left: .6em;
color: #000000;
border-width: 1px;
border-style: solid;
border-color: #999999;
}
.categorytitle
{
padding-top: .8em;
font-size: 110%;
font-weight: bold;
text-align: left;
margin-left: 5px;
}
.boldtext { font-weight: bold; }
"@
}
### main ###
# create the topics directory
New-Item -Type Directory -Path "$outDirectory" -Force | Out-Null
New-Item -Type Directory -Path "$outDirectory\\Topics" -Force | Out-Null
"`nRetrieving help content...`n"
# initialize variables for HHC file
$hhcContentsHtml = ""
$cmdletCategoryHtml = ""
$cmdletCategoryHash = @{}
# help content hash
$helpHash = @{}
# get the Cmdlet help
Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object {
$psSnapInName = $_.Name
$helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile
# the culture needs to be added to the path on Vista
if ( !( Test-Path $helpFilePath ) )
{
$helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )"
}
if ( Test-Path $helpFilePath )
{
$helpXml = [xml]( Get-Content $helpFilePath )
$cmdletCategoryContents = ""
Get-Command -PSSnapIn $_ | Foreach-Object {
$commandName = $_.Name
$helpXml.helpitems.command | Where-Object {
$_.details.name -and $_.details.name.Trim() -imatch "\\b$commandName\\b"
} | Foreach-Object {
# add the Xml Help of the Cmdlet to the help hashtable
$helpHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $_.get_OuterXml()
$cmdletTopicItem = @"
<li><object type="text/sitemap">
<param name="Name" value="$commandName">
<param name="Local" value="Topics\\$( "{0}.{1}" -f $commandName, $psSnapInName ).html">
</object>
"@
if ( $GroupByPSSnapIn )
{
$cmdletCategoryContents += $cmdletTopicItem
}
else
{
# save the topics so they can be sorted properly and added to the HHC later
$cmdletCategoryHash[ "{0}.{1}" -f $commandName, $psSnapInName ] = $cmdletTopicItem
}
}
}
if ( $GroupByPSSnapIn )
{
# add a category in the HHC for this PSSnapIn and its Cmdlets
$cmdletCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$psSnapInName">
</object>
<ul>
$( $cmdletCategoryContents.Trim() )
</ul>
"@
}
}
}
# sort the Cmdlets so they are added to the HHC in a logical order
if ( !$GroupByPSSnapIn )
{
$cmdletCategoryHash.Keys | Sort-Object | Foreach-Object {
$cmdletCategoryHtml += $cmdletCategoryHash[ $_ ]
}
}
# add the Cmdlet category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="Cmdlet Help">
</object>
<ul>
$( $cmdletCategoryHtml.Trim() )
</ul>
"@
$providerCategoryHtml = ""
$providerCategoryHash = @{}
# get the PSProvider help
Get-PSSnapIn | Sort-Object -Property Name | Foreach-Object {
$psSnapInName = $_.Name
$helpFilePath = Join-Path $_.ApplicationBase ( ( Get-Command -PSSnapIn $_ ) | Select-Object -First 1 ).HelpFile
# the culture needs to be added to the path on Vista
if ( !( Test-Path $helpFilePath ) )
{
$helpFilePath = "$( $_.ApplicationBase )\\$( $Host.CurrentUICulture.Name )\\$( Split-Path -Leaf $helpFilePath )"
}
if ( Test-Path $helpFilePath )
{
$helpXml = [xml]( Get-Content $helpFilePath )
$providerCategoryContents = ""
Get-PSProvider | Where-Object { $_.PSSnapin.Name -eq $psSnapInName } | Foreach-Object {
$psProviderName = $_.Name
$helpXml.helpitems.providerhelp |
Where-Object { $_.name.Trim() -imatch "\\b$psProviderName\\b" } |
Foreach-Object {
$helpHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $_.get_OuterXml()
# add a category in the HHC for this PSProvider
$providerTopicItem = @"
<li><object type="text/sitemap">
<param name="Name" value="$psProviderName">
<param name="Local" value="Topics\\$( "{0}.{1}" -f $psProviderName, $psSnapInName ).html">
</object>
"@
if ( $GroupByPSSnapIn )
{
$providerCategoryContents += $providerTopicItem
}
else
{
# save the topics so they can be sorted properly and added to the HHC later
$providerCategoryHash[ "{0}.{1}" -f $psProviderName, $psSnapInName ] = $providerTopicItem
}
}
}
if ( $GroupByPSSnapIn -and $providerCategoryContents -ne "" )
{
# add a category in the HHC for this PSSnapIn and its Cmdlets
$providerCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$psSnapInName">
</object>
<ul>
$( $providerCategoryContents.Trim() )
</ul>
"@
}
}
}
# sort the PSProviders so they are added to the HHC in a logical order
if ( !$GroupByPSSnapIn )
{
$providerCategoryHash.Keys | Sort-Object | Foreach-Object {
$providerCategoryHtml += $providerCategoryHash[ $_ ]
}
}
# add the PSProvider category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="Provider Help">
</object>
<ul>
$( $providerCategoryHtml.Trim() )
</ul>
"@
# get the about topics
$about_TopicPaths = @()
$helpPath = ""
if ( Resolve-Path "$pshome\\about_*.txt" )
{
$helpPath = "$pshome"
}
elseif ( Resolve-Path "$pshome\\$( $Host.CurrentUICulture.Name )\\about_*.txt" )
{
$helpPath = "$pshome\\$( $Host.CurrentUICulture.Name )"
}
if ( Test-Path $helpPath )
{
$about_TopicPaths += Get-ChildItem "$helpPath\\about_*.txt"
}
# we SilentlyContinue with Get-ChildItem errors because the ModuleName
# for the built-in PSSnapins doesn't resolve to anything, since the assemblies
# are only in the GAC.
$about_TopicPaths += Get-PSSnapin | Foreach-Object {
( Get-ChildItem $_.ModuleName -ErrorAction "SilentlyContinue" ).DirectoryName
} | Foreach-Object {
Get-ChildItem "$_\\about_*.txt"
}
if ( $about_TopicPaths.Count -gt 0 )
{
$aboutCategoryHtml = ""
$about_TopicPaths | Sort-Object -Unique -Property @{ Expression = { $_.Name.ToUpper() } }| Foreach-Object {
# pull the topic name out of the file name
$name = ( $_.Name -replace "(.xml)?.help.txt", "`$1" )
# add the path of the topic to the help hashtable
$helpHash[ $name ] = $_.FullName
$topicName = Capitalize-Words ( $name -replace "(about)?_", " " ).Trim()
# add a category in the HHC for this about topic
$aboutCategoryHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="$topicName">
<param name="Local" value="Topics\\$name.html">
</object>
"@
}
# add the About Topics category to the HHC
$hhcContentsHtml += @"
<li><object type="text/sitemap">
<param name="Name" value="About Topics">
</object>
<ul>
$( $aboutCategoryHtml.Trim() )
</ul>
"@
}
# write the contents file
Out-File -FilePath "$outDirectory\\powershell.hhc" -Encoding Ascii -Input @"
<!doctype html public "-//ietf//dtd html//en">
<html>
<head>
<meta name="Generator" content="Microsoft® HTML Help Workshop 4.1">
<!-- Sitemap 1.0 -->
</head>
<body>
<object type="text/site properties">
<param name="Window Styles" value="0x800025">
</object>
<ul>
<li><object type="text/sitemap">
<param name="Name" value="PowerShell Help">
<param name="Local" value="Topics\\default.html">
</object>
$( $hhcContentsHtml.Trim() )
</ul>
</body>
</html>
"@
$helpHash.Keys | Sort-Object | Foreach-Object {
switch -regex ( $_ )
{
# about topic
"about_"
{
"Creating help for the $_ about topic..."
Write-AboutTopic $_ $helpHash[ $_ ]
}
# Verb-Noun: Cmdlet
"\\w+-\\w+"
{
"Creating help for the $( $_ -replace '(^\\w+-\\w+).*', '$1' ) Cmdlet..."
Write-CmdletTopic $_ $helpHash[ $_ ]
}
# PSProvider
default
{
"Creating help for the $( $_ -replace '(^\\w+).*', '$1' ) PSProvider..."
Write-ProviderTopic $_ $helpHash[ $_ ]
}
}
}
Write-DefaultPage
Write-Css
Write-Hhp
$progDir = "C:\\Program Files"
if ( $(Test-Path env:"ProgramFiles(x86)") -eq $True )
{
$progDir = $(get-item env:"ProgramFiles(x86)").value
}
if ( Test-Path $prodDir + "\\HTML Help Workshop\\hhc.exe" )
{
# compile the help
"`nCompiling the help manual...`n"
Push-Location
Set-Location $outDirectory
& $progDir + "\\HTML Help Workshop\\hhc.exe" powershell.hhp
Pop-Location
# open the help file
& "$outDirectory\\PowerShell.chm"
}
else
{
Write-Host -ForegroundColor Red @"
HTML Help Workshop is not installed, or it was not installed in its default
location of "C:\\Program Files [x86]\\HTML Help Workshop".
HTML Help Workshop is required to compile the help manual. It can be downloaded
free of charge from Microsoft:
http://www.microsoft.com/downloads/details.aspx?familyid=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en
If you do not want to install HTML Help Workshop on this machine, all of the
files necessary to compile the manual have been created here:
$( Resolve-Path $outDirectory )
Copy these files to a machine with HTML Help Workshop, and you can compile the
manual there, with the following command:
<HTML Help Workshop location>\\hhc.exe powershell.hhp
"@
}
|
PowerShellCorpus/PoshCode/Get-OLEDBData_1.ps1
|
Get-OLEDBData_1.ps1
|
###########################################################################
# Get-OLEDBData
# --------------------------------------------
# Description: This function is used to retrieve data via an OLEDB data
# connection.
#
# Inputs: $connectstring - Connection String.
# $sql - SQL statement to be executed to retrieve data.
#
# Usage: Get-OLEDBData <connction string> <SQL statement>
#
#Connection String for Excel 2007:
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
#Excel query
#'select * from [sheet1$]'
#Informix
#"password=$password;User ID=$userName;Data Source=$dbName@$serverName;Persist Security Info=true;Provider=Ifxoledbc.2"
#Oracle
#"password=$password;User ID=$userName;Data Source=$serverName;Provider=OraOLEDB.Oracle"
#SQL Server
#"Server=$serverName;Trusted_connection=yes;database=$dbname;Provider=SQLNCLI;"
###########################################################################
function Get-OLEDBData ($connectstring, $sql) {
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
return $dt
}
|
PowerShellCorpus/PoshCode/Dir for days_1.ps1
|
Dir for days_1.ps1
|
Function Create-DatePaths {
Param (
[Parameter(Position=0,Mandatory=$True)]
[DateTime] $Start,
[Parameter(Position=1,Mandatory=$True)]
[ValidateScript({$_ -gt $Start})]
[DateTime] $End,
$DestinationPath=(Join-Path $env:UserProfile "Test")
)
0..(New-TimeSpan $Start $End).Days | % {
$TargetPath = Join-Path $Destination $(Get-Date $Start -Format "yyyy\\\\MM-MMMM\\\\yyyy-MM-dd")
If (!(Test-Path $TargetPath)) { New-Item $TargetPath -ItemType Directory }
$Start = $Start.AddDays(1)
}
}
|
PowerShellCorpus/PoshCode/Get-ExchangeDBSizes_4.ps1
|
Get-ExchangeDBSizes_4.ps1
|
<#
.SYNOPSIS
Get-ExchangeDBSizes - Gather data on Exchange 2007 / 2010 Mailbox Databases.
.DESCRIPTION
Gathers data from Exchange mailbox servers.
These data include:
Server\\StorageGroup\\Database (2007) or Database (2010),
Total Size (in GB) of the disk,
Size of the .edb file (in GB),
Free disk space,
Percent Disk Free,
Total Mailboxes on the database,
White Space,
Total Free disk space,
Total Percent Free disk space
.EXAMPLE
Get-ExchangeDBSizes
.LINK
http://unlockpowershell.wordpress.com/
http://poshcode.org/1901
#>
Function Get-MountPointInfo($ServerName) {
$Summary = @()
$VolumeHash = @{}
$VolumeCapacityHash = @{}
$DatabaseSizeHash = @{}
$DatabaseFreeHash = @{}
$MountPoints = Get-WmiObject -Class Win32_Mountpoint -ComputerName $ServerName
$MailboxDatabases = Get-MailboxDatabase -Server $ServerName
$Volumes = Get-WmiObject -Class Win32_Volume -ComputerName $ServerName | Where-Object {$_.DriveType -eq 3}| Select-Object Name,FreeSpace,Capacity
$DatabaseLetters = $MailboxDatabases | Select-Object edbfilepath
foreach ($Volume in $Volumes) {
$VolumeHash.Add($Volume.name.TrimEnd("\\"),$Volume.FreeSpace)
$VolumeCapacityHash.Add($Volume.name.TrimEnd("\\"),$Volume.Capacity)
}
foreach ($drive in $DatabaseLetters)
{
$letter = $drive.EdbFilePath.Substring(0,$drive.EdbFilePath.lastIndexOf("\\"))
$DatabaseSizeHash.Add($letter.TrimEnd("\\"),$VolumeCapacityHash[$letter])
$DatabaseFreeHash.Add($letter.TrimEnd("\\"),$VolumeHash[$letter])
}
$VolumeHash.Clear()
$VolumeCapacityHash.Clear()
#Now I have all mailbox databases, along with the OS reported free space and capacity
foreach ($MP in $Mountpoints) {
$MP.directory = $MP.directory.replace("\\\\","\\").Split("=")[1].Replace("`"","")
if($DatabaseSizeHash[$MP.directory])
{
#This mountpoint is a database
$Record = new-Object PSObject
$OSfree = $DatabaseFreeHash[$MP.directory]
$OSCapacity = $DatabaseSizeHash[$MP.directory]
$DestFolder = "\\\\"+$ServerName + "\\" + $MP.directory
$colItems = (Get-ChildItem $destfolder.Replace(":","$") -Recurse| where{$_.length -ne $null} |Measure-Object -property length -sum)
if($colItems.sum -eq $null) {
$fsize = 0
} else {
$fsize = $colItems.sum
}
$TotFolderSize = $fsize + $OSfree
$percFree = "{0:P0}" -f ( $OSfree/$TotFolderSize)
$Record | add-Member -memberType noteProperty -name Server -Value $ServerName
$Record | add-Member -memberType noteProperty -name "Mount Point" -Value $MP.directory
$Record | add-Member -memberType noteProperty -name "Capacity" -Value ("{0:N2}" -f ($OSCapacity /1gb))
$Record | add-Member -memberType noteProperty -name "Used" -Value ("{0:N2}" -f ($fsize / 1gb))
$Record | add-Member -memberType noteProperty -name "Free" -Value ("{0:N2}" -f ($OSfree / 1gb))
$Record | add-Member -memberType noteProperty -name "Percent Free" -Value $percFree
$Summary += $Record
}
}
return $Summary
}
function Get-ExchangeWhiteSpace {
param(
$ComputerName = $(throw "ComputerName cannot be empty.")
)
# Convert Dates to WMI CIM dates
$tc = [System.Management.ManagementDateTimeconverter]
$Start =$tc::ToDmtfDateTime( (Get-Date).AddDays(-1).Date )
$End =$tc::ToDmtfDateTime( (Get-Date).Date)
$whiteSpace = @{}
# Create two claculated properties for InsertionStrings values
$DB = @{Name="DB";Expression={$_.InsertionStrings[1]}}
$FreeMB = @{Name="FreeMB";Expression={[int]$_.InsertionStrings[0]}}
$freespace = Get-WMIObject Win32_NTLogEvent -ComputerName $ComputerName -Filter "LogFile='Application' AND EventCode=1221 AND TimeWritten>='$Start' AND TimeWritten<='$End'" | Select-Object $DB,$FreeMB | Sort-Object DB –Unique –Descending
$freespace | ForEach-Object {$whiteSpace.Add($_.DB,$_.FreeMB)}
#Preceding function from Shay Levy http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/08/13/exchange-white-space.aspx
}
$AllServers = @()
$ServerVersion = @{}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.name
$version = Get-ExchangeServer -Identity $ServerName | Select-Object AdminDisplayVersion
if($version.admindisplayversion.major)
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.major)
}
else
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.Split()[1].split(".")[0])
}
}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.Name
if ([int]$ServerVersion[$ServerName] -gt 8)
{ #An Exchange 2010 server, so use Get-MailboxDatabase <database> -Status | Select-Object AvailableNewMailboxSpace
$whiteSpace = @{}
$Free = Get-MailboxDatabase -Server $ServerName -Status | Select-Object Server,Name,AvailableNewMailboxSpace
foreach ($item in $free)
{
$db = $ServerName+"\\"+$item.Name
$whiteSpace.Add($item.Name,[int]$item.AvailableNewMailboxSpace.split("(")[1].Split()[0]/1mb)
}
}
Else
{#not an Exchange 2010 server
. Get-ExchangeWhiteSpace $ServerName
}
$MountPoint = . Get-MountPointInfo $ServerName
foreach ($objItem in Get-MailboxDatabase -Server $ServerName)
{
$edbfilepath = $objItem.edbfilepath
$path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.Split(":")[0] + "$"+ $objItem.EdbFilePath.Split(":")[1]
$dbsize = Get-ChildItem $path
$dbpath=(Split-Path $edbfilepath.Split(":")[1] -Leaf).trimend(".edb")
if (!$MountPoint)
{
$mailboxpath = $ServerName + $edbfilepath.Split(":")[1].trimend(".edb")
$size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.Split("\\")[0]} |select-object deviceID, Freespace, Size
$freespace = ($size.freespace / 1GB)
$total = ($size.size / 1GB)
}
if ($MountPoint)
{
$mailboxpath = "$ServerName\\$dbpath"
$MPPath = $EdbFilePath.Substring(0,$EdbFilePath.LastIndexOf("\\"))
$freespace = $DatabaseFreeHash[$MPPath ] /1GB
$total = $DatabaseSizeHash[$MPPath] /1GB
}
$PercentFree = "{0:n2}" -f ($freespace / $total *100)
if (!$MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
if($MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database $mailboxpath.Split("\\")[1] |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
$ReturnedObj = New-Object PSObject
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Server\\StorageGroup\\Database" -Value $objItem.Identity
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Size (GB)" -Value ("{0:n2}" -f ($total))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Used Space (GB)" -Value ("{0:n2}" -f ($dbsize.Length/1024MB))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Free Space (GB)" -Value ("{0:n2}" -f ($freespace))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Percent Disk Free" -Value $percentfree
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "User Mailbox Count" -Value $mailboxcount.count
if ($objitem.Identity.Split("\\").Count -eq 3){$dbasename = $objitem.Identity.Substring($objitem.Identity.IndexOf("\\")+1)}
else{$dbasename = $objitem.Identity}
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "White Space (GB)" -Value ("{0:n2}" -f ($whiteSpace[$dbasename]/1024))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Free (GB)" -Value ("{0:n2}" -f ($freespace + $whiteSpace[$dbasename]/1024))
$TotalPercent = ($freespace + $whiteSpace[$dbasename]/1024) / $total *100
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Percent Free" -Value ("{0:n2}" -f ($TotalPercent))
$AllServers += $ReturnedObj
}
}
$AllServers |Export-Csv C:\\scripts\\MailboxDatabaseSizeReport.csv -NoTypeInformation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.