full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Import-Certificate_5.ps1
|
Import-Certificate_5.ps1
|
#requires -Version 2.0
function Import-Certificate
{
param
(
[IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."),
[string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."),
[switch] $LocalMachine,
[switch] $CurrentUser,
[string] $CertPassword,
[switch] $Verbose
)
begin
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
}
process
{
if ($Verbose)
{
$VerbosePreference = 'Continue'
}
if (-not $LocalMachine -and -not $CurrentUser)
{
Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'."
}
try
{
if ($_)
{
$certfile = $_
}
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword,"Exportable,MachineKeySet,PersistKeySet"
}
catch
{
Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue
}
if ($cert -and $LocalMachine)
{
$StoreScope = "LocalMachine"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
if ($cert -and $CurrentUser)
{
$StoreScope = "CurrentUser"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
}
end
{ }
}
|
PowerShellCorpus/PoshCode/New-DFSRHealthReport.ps1
|
New-DFSRHealthReport.ps1
|
<#
NAME: New-DFSRHealthReport.ps1
AUTHOR: Jan Egil Ring
EMAIL: jan.egil.ring@powershell.no
COMMENT: Script to generate a new DFS-R HTML Health Report for the Domain System Volume (SYSVOL) replication group using the native dfsradmin.exe tool.
More information:
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 30.12.2010 - Initial release
#>
#requires -version 2
#Initial variable
$ReportFilePath = "C:\\Reports\\DFS-R\\Health-report-"+(Get-Date -UFormat %Y-%m-%d)
$ReferralDC = "domain\\srv-dc-01"
$SmtpServer = "srv-smtp-01.domain.local"
$EmailFrom = "dfs-r@domain.local"
$EmailTo = "user@domain.local"
#Run DfsrAdmin.exe to generate report
DfsrAdmin.exe Health New /RgName:`"Domain System Volume`" /RefMemName:$ReferralDC /RepName:$ReportFilePath /FsCount:true
#Send HTML-report to the specified e-mail address
Send-MailMessage -From $EmailFrom -To $EmailTo -SmtpServer $SmtpServer -Subject "DFS-R Health Report 2010-12-30" -Body "The DFS-R Health Report is attched to this e-mail" -Attachments ($ReportFilePath+".html")
|
PowerShellCorpus/PoshCode/Out-Voice 2.0.ps1
|
Out-Voice 2.0.ps1
|
# ---------------------------------------------------------------------------
## <Script>
## <Author>
## Joel "Jaykul" Bennett
## </Author>
## <Description>
## Outputs text as spoken words
## </Description>
## <Usage>
## Out-Speech "Hello World"
## </Usage>
## <Version>2.0</Version>
## </Script>
# ---------------------------------------------------------------------------
param([string]$wavFile, [switch]$wait, [switch]$purge, [switch]$passthru, [string[]]$inputObject)
begin
{
if ($args -eq '-?') {
''
'Usage: Out-Speech [[-Collection] <array>]'
''
'Parameters:'
' -Collection : A collection of items to speak.'
' -? : Display this usage information'
' Switches:'
' -wavFile : Path to a wav file to write output'
' -wait : Wait for the machine to read each item (NOT asynchronous).'
' -purge : Purge all other speech requests before making this call.'
' -passthru : Pass on the input as output.'
''
'Examples:'
' PS> Out-Speech "Hello World"'
' PS> Select-RandomLine quotes.txt | Out-Speech -wait'
' PS> Get-Content "Hitchhiker''s Guide To The Galaxy.txt" | Out-Speech -wav "Hitchiker.wav"'
''
exit
}
if ($inputObject) {
Write-Output $inputObject | &($MyInvocation.InvocationName) $wavFile -wait:$wait -purge:$purge -passthru:$passthru
break;
} else {
[Reflection.Assembly]::LoadWithPartialName("System.Speech") | out-null
$speaker = new System.Speech.Synthesis.SpeechSynthesizer
if( $purge ) {
$speaker.SpeakAsyncCancelAll()
}
if( ![string]::IsNullOrEmpty( $wavFile ) ){
# this is just for your convenience, because you should wait before trying to use the file.
if(!$wait.IsPresent){$wait =$true}
$speaker.SetOutputToWaveFile( $(if( Split-Path $wavFile ) { $wavFile } else { "$pwd\\$wavFile" }) )
}
}
}
process
{
if ($_)
{
if($wait) {
$speaker.Speak( ($_ | out-string) )
} else {
$speaker.SpeakAsync( ($_ | out-string) )
}
if($passthru) { $_ }
}
}
end {
if( ![string]::IsNullOrEmpty( $wavFile ) ){
$speaker.SetOutputToDefaultAudioDevice()
}
$speaker.Dispose()
}
|
PowerShellCorpus/PoshCode/INICIAR-RDP.ps1
|
INICIAR-RDP.ps1
|
########################################################################################################################
# NAME
# Start-RDP
#
# SYNOPSIS
# Opens a remote desktop connection to another computer.
#
# SYNTAX
# Start-RDP [[-Server] <string>] [[-Width] <int>] [[-Height] <int>]
# Start-RDP -Path <string> [[-Width] <int>] [[-Height] <int>]
#
# DETAILED DESCRIPTION
# The Start-RDP cmdlet opens a new Remote Desktop connection using the Microsoft Terminal Services Client.
# Connection settings can be specified by argument or read from a standard RDP file.
#
# PARAMETERS
# -Server <string>
# Specifies the name of the server to connect to. May also include an IP address, domain, and/or port.
#
# Required? false
# Position? 1
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Width <int>
# Specifies the desired width of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 2
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Height <int>
# Specifies the desired height of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 3
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Path <string>
# Specifies the path to an RDP file to connect with (resolution settings can be overridden using the
# -Width and -Height parameters.
#
# Required? false
# Position? 4
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Console <SwitchParameter>
# Connect to a Windows Server 2003 console session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Admin <SwitchParameter>
# Connect to a Windows Server 2008 administrator session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Fullscreen <SwitchParameter>
# Open connection in full screen mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Public <SwitchParameter>
# Run Remote Desktop in public mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Span <SwitchParameter>
# Span the Remote Desktop connection across multiple monitors. Each monitor must have the same height
# and be arranged vertically.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# INPUT TYPE
# String,System.IO.FileInfo
#
# RETURN TYPE
#
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>Start-RDP
#
#
# This command opens the Terminal Services Client connection dialog to specify a connection.
#
#
# -------------------------- EXAMPLE 2 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Width 1024 -Height 768
#
#
# This command opens a new Remote Desktop connection to the server named "myserver" in a window with 1024x768 resolution.
#
#
# -------------------------- EXAMPLE 3 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Fullscreen
#
#
# This command opens a new full screen Remote Desktop connection to the server named "myserver".
#
#
# -------------------------- EXAMPLE 4 --------------------------
#
# C:\\PS>Start-RDP -Path C:\\myserver.rdp
#
#
# This command opens a new Remote Desktop connection using the specified RDP file.
#
#
#Function global:Start-RDP {
param(
[string]$Server = "",
[int]$Width = "",
[int]$Height = "",
[string]$Path = "",
[switch]$Console,
[switch]$Admin,
[switch]$Fullscreen,
[switch]$Public,
[switch]$Span
)
begin {
$arguments = ""
$dimensions = ""
$processed = $false
if ($admin) {
$arguments += "/admin "
} elseif ($console) {
$arguments += "/console "
}
if ($fullscreen) {
$arguments += "/f "
}
if ($public) {
$arguments += "/public "
}
if ($span) {
$arguments += "/span "
}
if ($width -and $height) {
$dimensions = "/w:$width /h:$height"
}
}
process {
Function script:executePath([string]$path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
}
Function script:executeArguments([string]$Server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
}
if ($_) {
if ($_ -is [string]) {
if ($_ -imatch '\\.rdp$') {
if (Test-Path $_) {
executePath $_
$processed = $true
} else {
throw "Path does not exist."
}
} else {
executeArguments $_
$processed = $true
}
} elseif ($_ -is [System.IO.FileInfo]) {
if (Test-Path $_.FullName) {
executePath $_.FullName
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.Path) {
if (Test-Path $_.Path) {
executePath $_.Path
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.DnsName) {
executeArguments $_.DnsName
$processed = $true
} elseif ($_.Server) {
executeArguments $_.Server
$processed = $true
} elseif ($_.ServerName) {
executeArguments $_.ServerName
$processed = $true
} elseif ($_.Name) {
executeArguments $_.Name
$processed = $true
}
}
}
end {
if ($path) {
if (Test-Path $path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
} else {
throw "Path does not exist."
}
} elseif ($server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
} elseif (-not $processed) {
Invoke-Expression "mstsc.exe $dimensions $arguments"
}
}
#}
|
PowerShellCorpus/PoshCode/get windows product key_3.ps1
|
get windows product key_3.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/Office 365 - get email .ps1
|
Office 365 - get email .ps1
|
$Content = '$script:showWindowAsync = Add-Type –memberDefinition @”','[DllImport("user32.dll")]','public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);','“@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru','function Show-PowerShell() {','$null = $showWindowAsync::ShowWindowAsync((Get-Process –id $pid).MainWindowHandle, 10)','}','function Hide-PowerShell() {','$null = $showWindowAsync::ShowWindowAsync((Get-Process –id $pid).MainWindowHandle, 2)','}'
Set-Content $Content -Path C:\\
Add-Module PowerShell
Hide-PowerShell
Import-Module ActiveDirectory
Import-Module MSOnline
$cred = Get-Credential
Connect-MsolService -Credential $cred
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
Import-PSSession $session
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Check Email address in Office365"
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.Text = "Please enter the email address below:"
$objForm.Controls.Add($objLabel)
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
$x
$EmailAddress = 'smtp:' + $x
$Answer = Get-Mailbox | Where-Object {$_.EmailAddresses -eq $EmailAddress} | Select-Object 'Name'
$objForm2 = New-Object System.Windows.Forms.Form
$objForm2.Text = "The Email address is asigned to account:"
$objForm2.Size = New-Object System.Drawing.Size(300,200)
$objForm2.StartPosition = "CenterScreen"
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(10,20)
$objLabel2.Size = New-Object System.Drawing.Size(280,20)
$objLabel2.Text = $Answer
$objForm2.Controls.Add($objLabel2)
$OKButton2 = New-Object System.Windows.Forms.Button
$OKButton2.Location = New-Object System.Drawing.Size(75,120)
$OKButton2.Size = New-Object System.Drawing.Size(75,23)
$OKButton2.Text = "OK"
$OKButton2.Add_Click({$objForm2.Close()})
$objForm2.Controls.Add($OKButton2)
$objForm2.Add_Shown({$objForm2.Activate()})
[void] $objForm2.ShowDialog()
$sessionName = Get-PSSession | Select-Object 'Name'
Remove-PSSession -Name $sessionName
|
PowerShellCorpus/PoshCode/Compare-DellUpdates_1.ps1
|
Compare-DellUpdates_1.ps1
|
#Requires -version 2
#Author: Nathan Linley
#Script: Computer-DellUpdates
#Site: http://myitpath.blogspot.com
#Date: 2/9/2012
param(
[parameter(mandatory=$true)][ValidateScript({test-path $_ -pathtype 'leaf'})][string]$catalogpath,
[parameter(mandatory=$true,ValueFromPipeline=$true)][string]$server
)
function changedatacase([string]$str) {
#we need to change things like this: subDeviceID="1f17" to subDeviceID="1F17"
#without changing case of the portion before the =
if ($str -match "`=`"") {
$myparts = $str.split("=")
$result = $myparts[0] + "=" + $myparts[1].toupper()
return $result
} else { return $str}
}
$catalog = [xml](get-Content $catalogpath)
$oscodeid = &{
$caption = (Get-WmiObject win32_operatingsystem -ComputerName $server).caption
if ($caption -match "2003") {
if ($caption -match "x64") { "WX64E" } else { "WNET2"}
} elseif ($caption -match "2008 R2") {
"W8R2"
} elseif ($caption -match "2008" ) {
if ($caption -match "x64") {
"WSSP2"
} else {
"LHS86"
}
}
}
write-debug $oscodeid
$systemID = (Get-WmiObject -Namespace "root\\cimv2\\dell" -query "Select Systemid from Dell_CMInventory" -ComputerName $server).systemid
$model = (Get-WmiObject -Namespace "root\\cimv2\\dell" -query "select Model from Dell_chassis" -ComputerName $server).Model
$model = $model.replace("PowerEdge","PE").replace("PowerVault","PV").split(" ") #model[0] = Brand Prefix #model[1] = Model #
$devices = Get-WmiObject -Namespace "root\\cimv2\\dell" -Class dell_cmdeviceapplication -ComputerName $server
foreach ($dev in $devices) {
$xpathstr = $parts = $version = ""
if ($dev.Dependent -match "(version=`")([A-Z\\d.-]+)`"") { $version = $matches[2] } else { $version = "unknown" }
$parts = $dev.Antecedent.split(",")
for ($i = 2; $i -lt 6; $i++) {
$parts[$i] = &changedatacase $parts[$i]
}
$depparts = $dev.dependent.split(",")
$componentType = $depparts[0].substring($depparts[0].indexof('"'))
Write-Debug $parts[1]
if ($dev.Antecedent -match 'componentID=""') {
$xpathstr = "//SoftwareComponent[@packageType='LWXP']/SupportedDevices/Device/PCIInfo"
if ($componentType -match "DRVR") {
$xpathstr += "[@" + $parts[2] + " and @" + $parts[3] + "]/../../.."
$xpathstr += "/SupportedOperatingSystems/OperatingSystem[@osVendor=`'Microsoft`' and @osCode=`'" + $osCodeID + "`']/../.."
} else {
$xpathstr += "[@" + $parts[2] + " and @" + $parts[3] + " and @" + $parts[4] + " and @" + $parts[5] + "]/../../.."
#$xpathstr += "/SupportedSystems/Brand[@prefix=`'" + $model[0] + "`']/Model[@systemID=`'" + $systemID + "`']/../../.."
$xpathstr += "/ComponentType[@value='FRMW']/.."
}
$xpathstr += "/ComponentType[@value=" + $componentType + "]/.."
} else {
$xpathstr = "//SoftwareComponent[@packageType='LWXP']/SupportedDevices/Device[@"
$xpathstr += $parts[0].substring($parts[0].indexof("componentID"))
$xpathstr += "]/../../SupportedSystems/Brand[@prefix=`'" + $model[0] + "`']/Model[@systemID=`'"
$xpathstr += $systemID + "`']/../../.."
}
Write-Debug $xpathstr
$result = Select-Xml $catalog -XPath $xpathstr |Select-Object -ExpandProperty Node
$result |Select-Object @{Name="Component";Expression = {$_.category.display."#cdata-section"}},path,vendorversion,@{Name="currentversion"; Expression = {$version}},releasedate,@{Name="Criticality"; Expression={($_.Criticality.display."#cdata-section").substring(0,$_.Criticality.display."#cdata-section".indexof("-"))}},@{Name="AtCurrent";Expression = {$_.vendorVersion -eq $version}}
}
|
PowerShellCorpus/PoshCode/Get-Parameter_16.ps1
|
Get-Parameter_16.ps1
|
function Get-Parameter
{
[OutputType('System.String')]
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String]$Command,
[Parameter(Position=1)]
[String[]]$Name=@('*'),
[Parameter()]
[ValidateSet('Name','Type','Pos','BV','BP','DV','Aliases','Mandatory','Dynamic')]
[String]$SortBy='Name',
[Parameter()]
[switch]$Descending,
[Parameter()]
[ValidateSet('Cmdlet','Function','Alias','ExternalScript')]
[String]$CommandType,
[switch]$IncludeCommonParameters
)
Process
{
if($CommandType)
{
switch($CommandType)
{
"function"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
"filter"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
default
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue
}
}
}
else
{
$cmd = Get-Command -Name $Command -CommandType Cmdlet,Function,Alias,ExternalScript -ErrorAction SilentlyContinue
}
if(!$cmd)
{
Throw "'$Name' is not a Cmdlet,Function,Filter,Alias or ExternalScript"
}
if($cmd.length -gt 1)
{
$types = $cmd | Select-Object -ExpandProperty CommandType -Unique
Throw "'$Command' is ambiguous and matches one of $($types -join ","). Use -CommandType to get only a specified type of command."
}
if($cmd.CommandType -eq 'Alias')
{
Write-Verbose "'$Name' refers to an Alias, reolving command."
$cmd = Get-Command -Name $cmd.ResolvedCommandName
}
foreach($set in $cmd.ParameterSets)
{
if($IncludeCommonParameters)
{
$p = $set.Parameters | Select-Object *
}
else
{
# Get a list of common parameters
$cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name
$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object *
}
$params = $p | Foreach-Object {$_.Name}
if($params.count -le 0 -and !$IncludeCommonParameters)
{
Throw "The specified cmdlet ('$cmd') has no parameters."
}
for($i=0;$i -le $p.length;$i++)
{
$flag=$false
for($x=0;$x -le $params[$i].length -and !($flag);$x++)
{
$regex = "^" + $params[$i].substring(0,$x)
if(($params -match $regex).count -eq 1)
{
$flag=$true
$p[$i].Aliases += $regex.substring(1).ToLower()
}
}
}
$p | Where-Object {$_.Name -like $Name} | Foreach-Object {
$PropertyName = $_.Name
$psn = $_.Attributes | Where-Object {$_.ParameterSetName}
if($psn.ParameterSetName -notmatch '__AllParameterSets')
{
$PropertyName="*$PropertyName"
}
New-Object PSObject -Property @{
ParameterSet = $set.Name
Name = $PropertyName
BV = $_.ValueFromPipeline
BP = $_.ValueFromPipelineByPropertyName
Type = $_.ParameterType.Name
Aliases = $_.Aliases
Pos = if($_.Position -lt 0) {'Named'} else {$_.Position+1}
Mandatory = $_.IsMandatory
Dynamic = $_.IsDynamic
}
} | Sort-Object -Descending:$Descending {$_.$SortBy -replace '\\*'} | Format-Table Name,Type,Pos,BV,BP,Aliases,Mandatory,Dynamic -AutoSize -GroupBy ParameterSet | Out-String
}
}
}
Set-Alias -Name gprm -Value Get-Parameter
|
PowerShellCorpus/PoshCode/Reflection Module 4.0.ps1
|
Reflection Module 4.0.ps1
|
#requires -version 2.0
# ALSO REQUIRES Autoload for some functionality
# You should create a Reflection.psd1 with the contents: @{ RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="3.5.0.0" }
#History:
# 1.0 - First public release (March 19, 2010)
# 2.0 - Private Build
# - Included the Accelerator function inline
# - Added a few default aliases
# 3.0 - September 3, 2010
# - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!)
# - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312
# 3.5 - January 28, 2011
# - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature
# - Fixed alias exporting so aliases will show up now
# - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies
# 3.6 - January 28, 2011
# - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin
# 3.7 - February 1, 2001 - NOT RELEASED
# - Added [TransformAttribute] type
# 3.8 - May 4, 2011 - NOT RELEASED
# - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649)
# 3.9 - May 25, 2011 - NOT RELEASED
# - Added "Interface" parameter to Get-Type
# 4.0 - Sept 27, 2011
# - Fix conflicts with PowerShell 3
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Collections.ObjectModel;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TransformAttribute : ArgumentTransformationAttribute {
private ScriptBlock _scriptblock;
private string _noOutputMessage = "Transform Script had no output.";
public override string ToString() {
return string.Format("[Transform(Script='{{{0}}}')]", Script);
}
public override Object Transform( EngineIntrinsics engine, Object inputData) {
try {
Collection<PSObject> output =
engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData );
if(output.Count > 1) {
Object[] transformed = new Object[output.Count];
for(int i =0; i < output.Count;i++) {
transformed[i] = output[i].BaseObject;
}
return transformed;
} else if(output.Count == 1) {
return output[0].BaseObject;
} else {
throw new ArgumentTransformationMetadataException(NoOutputMessage);
}
} catch (ArgumentTransformationMetadataException) {
throw;
} catch (Exception e) {
throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e);
}
}
public TransformAttribute() {
this.Script = ScriptBlock.Create("{`$args}");
}
public TransformAttribute( ScriptBlock Script ) {
this.Script = Script;
}
public ScriptBlock Script {
get { return _scriptblock; }
set { _scriptblock = value; }
}
public string NoOutputMessage {
get { return _noOutputMessage; }
set { _noOutputMessage = value; }
}
}
"@
function Get-Type {
<#
.Synopsis
Gets the types that are currenty loaded in .NET, or gets information about a specific type
.Description
Gets information about one or more loaded types, or gets the possible values for an enumerated type or value.
.Parameter Assembly
The Assemblies to search for types.
Can be an actual Assembly object or a regex to pass to Get-Assembly.
.Parameter TypeName
The type name(s) to search for (wildcard patterns allowed).
.Parameter BaseType
A Base type they should derive from (wildcard patterns allowed).
.Parameter Interface
An interface they should implement (wildcard patterns allowed).
.Parameter Enum
An enumeration to list all of enumeration values for
.Parameter Namespace
A namespace to restrict where we selsect types from (wildcard patterns allowed).
.Parameter Force
Causes Private types to be included
.Example
Get-Type
Gets all loaded types (takes a VERY long time to print out)
.Example
Get-Type -Assembly ([PSObject].Assembly)
Gets types from System.Management.Automation
.Example
[Threading.Thread]::CurrentThread.ApartmentState | Get-Type
Gets all of the possible values for the ApartmentState property
.Example
[Threading.ApartmentState] | Get-Type
Gets all of the possible values for an apartmentstate
#>
[CmdletBinding(DefaultParameterSetName="Assembly")]
param(
# The assembly to collect types from
[Parameter(ValueFromPipeline=$true)]
[PsObject[]]$Assembly
,
# The type names to return from
[Parameter(Mandatory=$false,Position=0)]
[String[]]$TypeName
,
# The type names to return from
[Parameter(Mandatory=$false)]
[String[]]$Namespace
,
# A Base Type they should derive from
[Parameter(Mandatory=$false)]
[String[]]$BaseType
,
# An Interface they should implement
[Parameter(Mandatory=$false)]
[String[]]$Interface
,
# The enumerated value to get all of the possibilties of
[Parameter(ParameterSetName="Enum")]
[PSObject]$Enum
,
[Parameter()][Alias("Private","ShowPrivate")]
[Switch]$Force
)
process {
if($psCmdlet.ParameterSetName -eq 'Enum') {
if($Enum -is [Enum]) {
[Enum]::GetValues($enum.GetType())
} elseif($Enum -is [Type] -and $Enum.IsEnum) {
[Enum]::GetValues($enum)
} else {
throw "Specified Enum is neither an enum value nor an enumerable type"
}
}
else {
if($Assembly -as [Reflection.Assembly[]]) {
## This is what we expected, move along
} elseif($Assembly -as [String[]]) {
$Assembly = Get-Assembly $Assembly
} elseif(!$Assembly) {
$Assembly = [AppDomain]::CurrentDomain.GetAssemblies()
}
:asm foreach ($asm in $assembly) {
Write-Verbose "Testing Types from Assembly: $($asm.Location)"
if ($asm) {
trap {
if( $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) {
$PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail")
continue asm
}
Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail"
Write-Debug $( $_.Exception.LoaderExceptions | Out-String )
continue asm
}
$asm.GetTypes() | Where {
( $Force -or $_.IsPublic ) -AND
( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND
( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND
( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND
( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 )
}
}
}
}
}
}
function Add-Assembly {
#.Synopsis
# Load assemblies
#.Description
# Load assemblies from a folder
#.Parameter Path
# Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#.Parameter Passthru
# Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output.
# Aliased to -Types
#.Parameter Recurse
# Gets the items in the specified locations and in all child items of the locations.
#
# Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("PSPath")]
[string[]]$Path = "."
,
[Alias("Types")]
[Switch]$Passthru
,
[Switch]$Recurse
)
process {
foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) {
Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic }
}
}
}
function Get-Assembly {
<#
.Synopsis
Get a list of assemblies available in the runspace
.Description
Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match
.Parameter Name
A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true, Position=0)]
[string[]]$Name = ''
)
process {
[appdomain]::CurrentDomain.GetAssemblies() | Where {
$Assembly = $_
if($Name){
$(
foreach($n in $Name){
if(Resolve-Path $n -ErrorAction 0) {
$n = [Regex]::Escape( (Resolve-Path $n).Path )
}
$Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n)
}
) -contains $True
} else { $true }
}
}
}
function Update-PSBoundParameters {
#.Synopsis
# Ensure a parameter value is set
#.Description
# Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it.
#.Parameter Name
# The name (key) of the parameter you want to set in PSBoundParameters
#.Parameter Default
# A Default value for the parameter, in case it's not already set
#.Parameter Min
# The Minimum allowed value for the parameter
#.Parameter Max
# The Maximum allowed value for the parameter
#.Parameter PSBoundParameters
# The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it)
Param(
[Parameter(Mandatory=$true, Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false, Position=1)]
$Default
,
[Parameter()]
$Min
,
[Parameter()]
$Max
,
[Parameter(Mandatory=$true, Position=99)]
$PSBoundParameters=$PSBoundParameters
)
end {
$outBuffer = $null
## If it's not set, and you passed a default, we set it to the default
if($Default) {
if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer))
{
$PSBoundParameters[$Name] = $Default
}
}
## If you passed a $max, and it's set greater than $max, we set it to $max
if($Max) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max)
{
$PSBoundParameters[$Name] = $Max
}
}
## If you passed a $min, and it's set less than $min, we set it to $min
if($Min) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min)
{
$PSBoundParameters[$Name] = $Min
}
}
$PSBoundParameters
}
}
function Get-Constructor {
<#
.Synopsis
Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type.
.Description
Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor.
.Parameter Type
The type to get the constructor for
.Parameter Force
Force inclusion of Private and Static constructors which are hidden by default.
.Parameter NoWarn
Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors.
.Example
Get-Constructor System.IO.FileInfo
Description
-----------
Gets all the information about the single constructor for a FileInfo object.
.Example
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax
Description
-----------
Displays the constructor syntax for all of the *Info objects in the System.IO namespace.
Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors.
.Example
$path = $pwd
$driveName = $pwd.Drive
$fileName = "$Profile"
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax }
Description
-----------
Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo.
Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("ParameterType")]
[Type]$Type
, [Switch]$Force
, [Switch]$NoWarn
)
process {
$type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *,
@{ name = "TypeName"; expression = { $_.ReflectedType.FullName } },
@{ name = "Definition";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "Syntax";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "SafeSyntax";
expression = {Get-MemberSignature $_}
}
if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" }
}
}
function Get-Method {
<#
.Synopsis
Returns MethodInfo for the (public) methods of the specified Type.
.Description
Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method.
.Parameter Type
The type to get methods on
.Parameter Name
The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns)
.Parameter Force
Force inclusion of Private methods and property accessors which are hidden by default.
#>
[CmdletBinding(DefaultParameterSetName="Type")]
param(
[Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Type]$Type
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)]
[String[]]$Name ="*"
, [Switch]$Definition
, [Switch]$Force
)
process {
foreach($method in
$type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } |
# Hide the Property accessor methods
Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } |
Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } )
{
$method |
Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru |
Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member AliasProperty Syntax Definition -Passthru |
#Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru
}
}
}
function Get-MemberSignature {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
[System.Reflection.MethodBase]$MethodBase,
[Switch]$Simple
)
process {
$parameters = $(
foreach($param in $MethodBase.GetParameters()) {
# Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan
Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)"
if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' }
if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' }
if($Simple) {
'{0} {1}' -f $param.ParameterType.ToString(), $param.Name
} else {
'{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.ToString().TrimEnd('&'), $param.Name
}
}
)
if($MethodBase.IsConstructor) {
"New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')"
} elseif($Simple) {
"$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))"
} elseif($MethodBase.IsStatic) {
"[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))"
} else {
"[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))"
}
}
}
function Read-Choice {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[hashtable[]]$Choices
,
[Parameter(Mandatory=$False)]
[string]$Caption = "Please choose!"
,
[Parameter(Mandatory=$False)]
[string]$Message = "Choose one of the following options:"
,
[Parameter(Mandatory=$False)]
[int[]]$Default = 0
,
[Switch]$MultipleChoice
,
[Switch]$Passthru
)
begin {
[System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() }
}
process {
$Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $(
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value
}
) )
if(!$MultipleChoice) { [int]$Default = $Default[0] }
[int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default)
if($Passthru) {
Write-Verbose "$Answer"
Write-Output $Descriptions[$Answer]
} else {
Write-Output $Answer
}
}
}
function Get-Argument {
param(
[Type]$Target
, [ref]$Method
, [Array]$Arguments
)
end {
trap {
write-error $_
break
}
$flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance"
[Type[]]$Types = @(
foreach($arg in $Arguments) {
if($arg -is [type]) {
$arg
}
else {
$arg.GetType()
}
}
)
try {
Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)"
$MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null)
$Arguments
if($MethodBase) {
$Method.Value = $MethodBase.Name
}
} catch { }
if(!$MethodBase) {
Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):"
$MethodBase = Get-Method $target $($Method.Value)
if(@($MethodBase).Count -gt 1) {
$i = 0
$i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:"
[System.Reflection.MethodBase]$MethodBase = $MethodBase[$i]
}
ForEach($parameter in $MethodBase.GetParameters()) {
$found = $false
For($a =0;$a -lt $Arguments.Count;$a++) {
if($argument[$a] -as $parameter.ParameterType) {
Write-Output $argument[$a]
if($a -gt 0 -and $a -lt $Arguments.Count) {
$Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a)
} elseif($a -eq 0) {
$Arguments = $Arguments | Select -Last ($Arguments.Count - 1)
} else { # a -eq count
$Arguments = $Arguments | Select -First ($Arguments.Count - 1)
}
$found = $true
break
}
}
if(!$Found) {
$userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)"
if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) {
Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType)
} else {
Write-Output ($userInput -as $parameter.ParameterType)
}
}
}
}
}
}
function Invoke-Member {
[CmdletBinding()]
param(
[parameter(position=10, valuefrompipeline=$true, mandatory=$true)]
[allowemptystring()]
$InputObject
,
[parameter(position=0, mandatory=$true)]
[validatenotnullorempty()]
$Member
,
[parameter(position=1, valuefromremainingarguments=$true)]
[allowemptycollection()]
$Arguments
,
[parameter()]
[switch]$Static
)
# begin {
# if(!(get-member SafeSyntax -input $Member -type Property)){
# if(get-member Name -inpup $Member -Type Property) {
# $Member = Get-Method $InputObject $Member.Name
# } else {
# $Member = Get-Method $InputObject $Member
# }
# }
# $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax )
# }
process {
# if ($InputObject)
# {
# if ($InputObject | Get-Member $Member -static:$static)
# {
if ($InputObject -is [type]) {
$target = $InputObject
} else {
$target = $InputObject.GetType()
}
if(Get-Member $Member -InputObject $InputObject -Type Properties) {
$_.$Member
}
elseif($Member -match "ctor|constructor") {
$Member = ".ctor"
[System.Reflection.BindingFlags]$flags = "CreateInstance"
$InputObject = $Null
}
else {
[System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod"
if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" }
}
[ref]$Member = $Member
[Object[]]$Parameters = Get-Argument $Target $Member $Arguments
[string]$Member = $Member.Value
Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ")
try {
Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))"
Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))"
$target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters)
} catch {
Write-Warning $_.Exception
if ($_.Exception.Innerexception -is [MissingMethodException]) {
write-warning "Method argument count (or type) mismatch."
}
}
# } else {
# write-warning "Method $Member not found."
# }
# }
}
}
function Invoke-Generic {
#.Synopsis
# Invoke Generic method definitions via reflection:
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('On')]
$InputObject
,
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
[Alias('Named')]
[string]$MethodName
,
[Parameter(Position=2)]
[Alias("Types")]
[Type[]]$ParameterTypes
,
[Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
[Object[]]$WithArgs
,
[Switch]$Static
)
begin {
if($Static) {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static"
} else {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance"
}
}
process {
$Type = $InputObject -as [Type]
if(!$Type) { $Type = $InputObject.GetType() }
if($WithArgs -and -not $ParameterTypes) {
$ParameterTypes = $withArgs | % { $_.GetType() }
} elseif(!$ParameterTypes) {
$ParameterTypes = [Type]::EmptyTypes
}
trap { continue }
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags)
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null)
}
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object {
$MI = $_
[bool]$Accept = $MI.Name -eq $MethodName
if($Accept){
Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)"
[Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name)
[Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value {
$GenericTypes -Contains $this.ParameterType
} -Passthru)
$Accept = $ParameterTypes.Count -eq $Parameters.Count
Write-Verbose " $Accept = $($Parameters.Count) Arguments"
if($Accept) {
for($i=0;$i -lt $Parameters.Count;$i++) {
$Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType))
Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)"
}
}
}
return $Accept
} | Sort { @($_.GetGenericArguments()).Count } | Select -First 1
}
Write-Verbose "Time to make generic methods."
Write-Verbose $MemberInfo
[Type[]]$GenericParameters = @()
[Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType)
for($i=0;$i -lt $ParameterTypes.Count;$i++){
Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])"
if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) {
$GenericParameters += $ParameterTypes[$i]
}
$ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru
}
$ParameterTypes | Where-Object { $_.IsGeneric }
Write-Verbose "$($GenericParameters -join ', ') generic parameters"
$MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters )
Write-Verbose $MemberInfo
if($WithArgs) {
[Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')"
$MemberInfo.Invoke( $InputObject, $Arguments )
} else {
$MemberInfo.Invoke( $InputObject )
}
} }
# get a reference to the Type
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
function Import-Namespace {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]$Namespace
,
[Switch]$Force
)
Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator
}
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
$xlr8r::AddReplace( $a, $Type)
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
param(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type[]]$Type
)
process {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","FullName")]
[string[]]$Accelerator
)
process {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
###############################################################################
##### Imported from PowerBoots
$Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree'
$DependencyProperties = @{}
if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) {
#$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) )
$DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml
}
function Get-ReflectionModule { $executioncontext.sessionstate.module }
function Set-ObjectProperties {
[CmdletBinding()]
param( $Parameters, [ref]$DObject )
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() }
if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White }
foreach ($param in $Parameters) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" }
## INGORE DEPENDENCY PROPERTIES FOR NOW :)
if($param.Key -eq "DependencyProps") {
## HANDLE EVENTS ....
}
elseif ($param.Key.StartsWith("On_")) {
$EventName = $param.Key.SubString(3)
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" }
$sb = $param.Value -as [ScriptBlock]
if(!$sb) {
$sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock
}
$Dobject.Value."Add_$EventName".Invoke( $sb );
# $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) );
# $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) );
} ## HANDLE PROPERTIES ....
else {
try {
## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here.
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray
}
if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) {
$Values = @()
foreach($sb in $param.Value) {
$Values += & (Get-ReflectionModule) $sb
}
} else {
$Values = $param.Value
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green }
Set-Property $Dobject $Param.Key $Values
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta }
if($DebugPreference -ne "SilentlyContinue") {
if( $Dobject.Value.$($param.Key) -ne $null ) {
Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green
}
}
}
catch [Exception]
{
Write-Host "COUGHT AN EXCEPTION" -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
while($DependencyProps) {
$name, $value, $DependencyProps = $DependencyProps
$name = ([string]@($name)[0]).Trim("-")
if($name -and $value) {
Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value
}
}
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host }
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() }
}
function Set-Property {
PARAM([ref]$TheObject, $Name, $Values)
$DObject = $TheObject.Value
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta }
$PropertyType = $DObject.GetType().GetProperty($Name).PropertyType
if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green}
# [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject )
# [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) )
# In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
[Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject )
[Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) )
$Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null
$TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() )
}
elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) {
$Binding = @($Values)[0];
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan}
if(!$Binding.Source -and !$Binding.ElementName) {
$Binding.Source = $DObject.DataContext
}
if($DependencyProperties.ContainsKey($Name)) {
$field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType)
if($field) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue }
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue}
$DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null
} else {
throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )"
}
} else {
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan
}
try {
$DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null
# $DObject.Add_Loaded( {
# $this.SetBinding( ($this.GetType())::ItemsSourceProperty, (Binding -Source $this.DataContext) )
# } )
if($DebugPreference -ne "SilentlyContinue") {
Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow
}
} catch {
Write-Host "Nope, was not able to set it." -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
}
elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) {
if($Values -is [System.Collections.IEnumerable]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan }
$DObject.$($Name) = $Values
} else {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan }
$DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]"
$DObject.$($Name).Add($Values)
}
}
elseif($DObject.$($Name) -is [System.Collections.IList]) {
foreach ($value in @($Values)) {
try {
$null = $DObject.$($Name).Add($value)
}
catch
{
# Write-Host "CAUGHT array problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) )
} else {
Write-Error $_.Exception
throw
}
}
}
}
else {
## If they pass an array of 1 when we only want one, we just use the first value
if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White}
try {
$DObject.$($Name) = $Values[0]
}
catch [Exception]
{
# Write-Host "CAUGHT collection value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $Values[0]) )
}else {
throw
}
}
}
else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings
{
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan}
try {
$DObject.$($Name) = $Values
} catch [Exception]
{
# Write-Host "CAUGHT value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $values) )
}else {
throw
}
}
}
}
}
function Set-DependencyProperty {
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true)]
$Property
,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Element
,
[Parameter()]
[Switch]$Passthru
)
DYNAMICPARAM {
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
$Param1 = new-object System.Management.Automation.RuntimeDefinedParameter
$Param1.Name = "Value"
# $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) )
$Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) )
if( $Property ) {
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])))
{
$Param1.ParameterType = $Property.PropertyType
}
elseif($Property -is [string] -and $Property.Contains(".")) {
$Class,$Property = $Property.Split(".")
if($DependencyProperties.ContainsKey($Property)){
$type = $DependencyProperties.$Property.Keys -like "*$Class"
if($type) {
$Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType
}
}
} elseif($DependencyProperties.ContainsKey($Property)){
if($Element) {
if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) {
$Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType
}
} else {
$Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType
}
}
else
{
$Param1.ParameterType = [PSObject]
}
}
else
{
$Param1.ParameterType = [PSObject]
}
$paramDictionary.Add("Value", $Param1)
return $paramDictionary
}
PROCESS {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red
continue
}
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))
){
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red
continue
}
$Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType))
}
else {
if("$Property".Contains(".")) {
$Class,$Property = "$Property".Split(".")
}
if( $DependencyProperties.ContainsKey("$Property" ) ) {
$fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } )
if($fields.Count -eq 0 ) {
$fields = @($DependencyProperties.$Property.Keys -like "*$Class" )
}
if($fields.Count) {
$success = $false
foreach($field in $fields) {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red
continue
}
$Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType)))
if($?) { $success = $true; break }
}
if(!$success) {
throw "food"
}
} else {
Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red
}
}
else {
Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red
}
}
if( $Passthru ) { $Element }
}
}
Add-Type -Assembly WindowsBase
function Add-ConstructorFunction {
<#
.Synopsis
Add support for a new class by creating the dynamic constructor function(s).
.Description
Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias.
Exposes all of the properties and events of the type as perameters to the function.
NOTE: The Type MUST have a default parameterless constructor.
.Parameter Assembly
The Assembly you want to generate constructors for. All public types within it will be generated if possible.
.Parameter Type
The type you want to create a constructor function for. It must have a default parameterless constructor.
.Example
Add-ConstructorFunction System.Windows.Controls.Button
Creates a new function for the Button control.
.Example
[Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction
Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
.Example
Add-ConstructorFunction -Assembly PresentationFramework
Will create constructor functions for all the WPF components in the PresentationFramework assembly.
.Links
http://HuddledMasses.org/powerboots
.ReturnValue
The name(s) of the function(s) created -- so you can export them, if necessary.
.Notes
AUTHOR: Joel Bennett http://HuddledMasses.org
LASTEDIT: 2009-01-13 16:35:23
#>
[CmdletBinding(DefaultParameterSetName="FromType")]
PARAM(
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)]
[type[]]$type
,
[Alias("FullName")]
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)]
[string[]]$Assembly
,
[Parameter()]
[string]$Path = "$PSScriptRoot\\Types_Generated"
,
[switch]$Force
,
[switch]$ShortAliases
,
[Switch]$Quiet
)
BEGIN {
[Type[]]$Empty=@()
if(!(Test-Path $Path)) {
MkDir $Path
}
$ErrorList = @()
}
END {
#Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties ))
Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties
if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." }
$ErrorList | Write-Error
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "FromAssembly") {
[type[]]$type = @()
foreach($lib in $Assembly) {
$asm = $null
trap { continue }
if(Test-Path $lib) {
$asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") )
}
if(!$asm) {
## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5
$asm = [Reflection.Assembly]::LoadWithPartialName( $lib )
}
if($asm) {
$type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and
!$_.IsAbstract -and !$_.IsInterface -and
$_.GetConstructor( "Instance,Public", $Null, $Empty, @() )}
} else {
Write-Error "Can't find the assembly $lib, please check your spelling and try again"
}
}
}
foreach($T in $type) {
$TypeName = $T.FullName
$ScriptPath = Join-Path $Path "New-$TypeName.ps1"
Write-Verbose $TypeName
## Collect all dependency properties ....
$T.GetFields() |
Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } |
ForEach-Object {
[string]$Field = $_.DeclaringType::"$($_.Name)".Name
[string]$TypeName = $_.DeclaringType.FullName
if(!$DependencyProperties.ContainsKey( $Field )) {
$DependencyProperties.$Field = @{}
}
$DependencyProperties.$Field.$TypeName = @{
Name = [string]$_.Name
PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName
}
}
if(!( Test-Path $ScriptPath ) -OR $Force) {
$Pipelineable = @();
## Get (or generate) a set of parameters based on the the Type Name
$PropertyNames = New-Object System.Text.StringBuilder "@("
$Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n"
## Add all properties
$Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") |
Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) }
$Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique
foreach ($p in $Properties) {
$null = $PropertyNames.AppendFormat(",'{0}'",$p.Name)
switch( $p.MemberType ) {
Event {
$null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name)
$null = $Parameters.AppendFormat(@'
[Parameter()]
[PSObject]${{On_{0}}}
,
'@, $p.Name)
}
Property {
if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") {
$null = $Parameters.AppendFormat(@'
[Parameter(Position=1,ValueFromPipeline=$true)]
[Object[]]${{{0}}}
,
'@, $p.Name)
$Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru)
}
elseif($p.PropertyType -eq [System.Boolean])
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Switch]${{{0}}}
,
'@, $p.Name)
}
else
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Object[]]${{{0}}}
,
'@, $p.Name)
}
}
}
}
$null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)]
[string[]]$DependencyProps
)')
$null = $PropertyNames.Remove(2,1).Append(')')
$collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true)
$ofs = "`n";
$function = $(
"
if(!( '$TypeName' -as [Type] )) {
$(
if( $T.Assembly.GlobalAssemblyCache ) {
" `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) "
} else {
" `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) "
}
)
}
## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) {
## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`"
## # `$scriptParam = `$PSBoundParameters
## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`"
## }
Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!""
function New-$TypeName {
<#
.Synopsis
Create a new $($T.Name) object
.Description
Generates a new $TypeName object, and allows setting all of it's properties.
(From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version))
.Notes
GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org
GENERATED : $(Get-Date)
ASSEMBLY : $($T.Assembly.FullName)
FULLPATH : $($T.Assembly.Location)
#>
$Parameters
BEGIN {
`$DObject = New-Object $TypeName
`$All = $PropertyNames
}
PROCESS {
"
if(!$collectable) {
"
# The content of $TypeName is not a collection
# So if we're in a pipeline, make a new $($T.Name) each time
if(`$_) {
`$DObject = New-Object $TypeName
}
"
}
@'
foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) {
$PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure()
}
Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject)
'@
if(!$collectable) {
@'
Microsoft.PowerShell.Utility\\Write-Output $DObject
} #Process
'@
} else {
@'
} #Process
END {
Microsoft.PowerShell.Utility\\Write-Output $DObject
}
'@
}
@"
}
## New-$TypeName `@PSBoundParameters
"@
)
Set-Content -Path $ScriptPath -Value $Function
}
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName"
}
}#PROCESS
}
function Import-ConstructorFunctions {
#.Synopsis
# Autoload pre-generated constructor functions and generate aliases for them.
#.Description
# Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory.
#.Parameter Path
# The path to a folder with functions to preload
param(
[Parameter()]
[Alias("PSPath")]
[string[]]$Path = "$PSScriptRoot\\Types_Generated"
)
end {
$Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" })
Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")"
foreach($script in Get-ChildItem $Paths -ErrorAction 0) {
$TypeName = $script.Name -replace 'New-(.*).ps1','$1'
$ShortName = ($TypeName -split '\\.')[-1]
Write-Verbose "Importing constructor for type: $TypeName ($ShortName)"
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-Autoload -Name $Script.FullName -Alias "New-$TypeName"
# Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String)
Get-Command "New-$TypeName"
}
}
}
#.Parameter Snapin
# The full path to where the snapin .dll is
#.Parameter OutputPath
# Force the module manifest(s) to output in a different location than where the snapin .dll is
#.Parameter ModuleName
# Override the snapin name(s) for the module manifest
#.Parameter Author
# Overrides the Company Name from the manifest when generating the module's "Author" comment
#.Parameter Passthru
# Returns the ModuleManifest (same as -Passthru on New-ModuleManifest)
#.Example
# New-ModuleManifestFromSnapin ".\\Quest Software\\Management Shell for AD" -ModuleName QAD
#
# Description
# -----------
# Generates a new module manifest file: QAD.psd1 in the folder next to the Quest.ActiveRoles.ArsPowerShellSnapIn.dll
#.Example
# New-ModuleManifestFromSnapin "C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\\" -Output $pwd
#
# Description
# -----------
# Generates module manifest files for the SqlServer PSSnapins and stores them in the current folder
function New-ModuleManifestFromSnapin {
param(
[Parameter(Mandatory=$true, Position="0", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[String[]]$Snapin
,
[Parameter()]
$OutputPath
,
[Parameter()]
$ModuleName
,
[Parameter()]
[String]$Author
,
[Switch]$Passthru
)
# $SnapinPath = $(Get-ChildItem $SnapinPath -Filter *.dll)
$EAP = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
Add-Assembly $Snapin
$ErrorActionPreference = $EAP
$SnapinTypes = Get-Assembly $Snapin | Get-Type -BaseType System.Management.Automation.PSSnapIn, System.Management.Automation.CustomPSSnapIn -WarningAction SilentlyContinue
foreach($SnapinType in $SnapinTypes) {
$Installer = New-Object $SnapinType
if(!$PSBoundParameters.ContainsKey("OutputPath")) {
$OutputPath = (Split-Path $SnapinType.Assembly.Location)
}
if(!$PSBoundParameters.ContainsKey("ModuleName")) {
$ModuleName = $Installer.Vendor
}
if(!$PSBoundParameters.ContainsKey("Author")) {
$Author = $Installer.Name
}
$ManifestPath = (Join-Path $OutputPath "$ModuleName.psd1")
Write-Verbose "Creating Module Manifest: $ManifestPath"
$RequiredAssemblies = @( $SnapinType.Assembly.GetReferencedAssemblies() | Get-Assembly | Where-Object { (Split-Path $_.Location) -eq (Split-Path $SnapinType.Assembly.Location) } | Select-Object -Expand Location | Resolve-Path -ErrorAction Continue)
# New-ModuleManifest has a bad bug -- it makes paths relative to the current location (and it does it wrong).
Push-Location $OutputPath
if($Installer -is [System.Management.Automation.CustomPSSnapIn]) {
$Cmdlets = $Installer.Cmdlets | Select-Object -Expand Name
$Types = $Installer.Types | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
$Formats = $Installer.Formats | Select-Object -Expand FileName | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
} else {
$Types = $Installer.Types | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
$Formats = $Installer.Formats | %{ $path = Resolve-Path $_ -ErrorAction Continue; if(!$path){ $_ } else { $path } }
}
if(!$Cmdlets) { $Cmdlets = "*" }
if(!$Types) { $Types = @() }
if(!$Formats) { $Formats = @() }
New-ModuleManifest -Path $ManifestPath -Author $Author -Company $Installer.Vendor -Description $Installer.Description `
-ModuleToProcess $SnapinType.Assembly.Location -Types $Types -Formats $Formats -Cmdlets $Cmdlets `
-RequiredAssemblies $RequiredAssemblies -Passthru:$Passthru `
-NestedModules @() -Copyright $Installer.Vendor -FileList @()
Pop-Location
}
}
###############################################################################
Add-Accelerator list System.Collections.Generic.List``1
Add-Accelerator dictionary System.Collections.Generic.Dictionary``2
Set-Alias aasm Add-Assemb
|
PowerShellCorpus/PoshCode/Format-HexString.ps1
|
Format-HexString.ps1
|
## Format-HexString.ps1
## Format a byte array as a hexadecimal string
##
## Example usage:
## get-content 'c:\\windows\\Coffee Bean.bmp' -encoding byte | Format-HexString | more
## Convert the input to an array of bytes. This is a strongly-typed variable,
## so that we're not trying to iterate over strings, directory entries, etc.
## [byte[]] $bytes = $(foreach($byte in $input) { $byte })
begin
{
## Store our header, and formatting information
$counter = 0
$header = " 0 1 2 3 4 5 6 7 8 9 A B C D E F"
$nextLine = "{0} " -f [Convert]::ToString($counter, 16).ToUpper().PadLeft(8, '0')
$asciiEnd = ""
## Output the header
"`r`n$header`r`n"
}
process
{
## Display each byte, in 2-digit hexidecimal, and add that to the left-hand
## side.
$nextLine += "{0:X2} " -f $_
## If the character is printable, add its ascii representation to
## the right-hand side. Otherwise, add a dot to the right hand side.
if(($_ -ge 0x20) -and ($_ -le 0xFE))
{
$asciiEnd += [char] $_
}
else
{
$asciiEnd += "."
}
$counter++;
## If we've hit the end of a line, combine the right half with the left half,
## and start a new line.
if(($counter % 16) -eq 0)
{
"$nextLine $asciiEnd"
$nextLine = "{0} " -f [Convert]::ToString($counter, 16).ToUpper().PadLeft(8, '0')
$asciiEnd = "";
}
}
end
{
## At the end of the file, we might not have had the chance to output the end
## of the line yet. Only do this if we didn't exit on the 16-byte boundary,
## though.
if(($counter % 16) -ne 0)
{
while(($counter % 16) -ne 0)
{
$nextLine += " "
$asciiEnd += " "
$counter++;
}
"$nextLine $asciiEnd"
}
""
}
|
PowerShellCorpus/PoshCode/netcast show downloader.ps1
|
netcast show downloader.ps1
|
cd M:\\Files\\Netcasts\\ShowName # switch to the diretory to store your content
Import-Module BitsTransfer # enable BITS on host machine as a file transfer method
$start=47 # start epidode number
$end=170 # end epidode number
$url="http://download.domain.com/episodes/" # URL of the download up to the directory containing the content
$file_base="Podcast-" # this is the filename of the download without the show number
$file_ext=".ogg"
for($i=$start;$i -le $end;$i++) # start the loop, and run until end of range, inclrementing by one
{
$b="{0:D3}" -f $i # cast loop counter to a string, stored as a formated number with leading zeros, example 002
$file="$file_base$b$file_ext" # Concatenatesthe file name with formated loop counter + file extension
Start-BitsTransfer -source $url$file; # download trigger,
}
|
PowerShellCorpus/PoshCode/New-XML.ps1
|
New-XML.ps1
|
### A first stab at the worlds simplest DSL:
### How to generate XML from PowerShell, in code instead of string-substitution
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
function New-Xml {
Param([String]$root)
New-Object XDocument (New-Object XDeclaration "1.0","utf-8","no"),(
New-Object XElement $(
$root
# foreach($ns in $namespace){
# $name,$url = $ns -split ":",2
# New-Object XAttribute ([XNamespace]::Xmlns + $name),$url
# }
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")),$value
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
))
}
function New-Element {
Param([String]$tag)
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")),$value
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
)
}
Set-Alias xe New-Element
####################################################################################################
###### EXAMPLE SCRIPT:
# [XNamespace]$dc = "http://purl.org/dc/elements/1.1"
#
# $xml = New-Xml rss -dc $dc -atom $atom -content $content -version "2.0" {
# xe channel {
# xe title {"Test RSS Feed"}
# xe link {"http`://HuddledMasses.org"}
# xe description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# xe ($dc + "language") {"en"}
# xe ($dc + "creator") {"Jaykul@HuddledMasses.org"}
# xe ($dc + "rights") {"Copyright 2009, CC-BY"}
# xe ($dc + "date") {(Get-Date -f u) -replace " ","T"}
# xe item {
# xe title {"The First Item"}
# xe link {"htt`p://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe description {"Ema Lazarus' Poem"}
# xe pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# $xml.ToString()
#
####### OUTPUT: (NOTE: I added the space in the http: to paste it here -- those aren't in the output)
# <rss xmlns:dc="http ://purl.org/dc/elements/1.1" version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <dc:language>en</dc:language>
# <dc:creator>Jaykul@HuddledMasses.org</dc:creator>
# <dc:rights>Copyright 2009, CC-BY</dc:rights>
# <dc:date>2009-07-26T00:50:08Z</dc:date>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
|
PowerShellCorpus/PoshCode/PowerShell Template_1.ps1
|
PowerShell Template_1.ps1
|
Function New-Script
{
$strName = $env:username
$date = get-date -format d
$name = Read-Host "Filename"
if ($name -eq "") { $name="NewTemplate" }
$email = Read-Host "eMail Address"
if ($email -eq "") { $email="youremail@yourhost.com" }
$file = New-Item -type file "$name.ps1" -force
$template=@"
###########################################################################
#
# NAME: $name.ps1
#
# AUTHOR: $strName
# EMAIL: $email
#
# COMMENT:
#
# 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 $date - Initial release
#
###########################################################################
"@ | out-file $file
ii $file
}
|
PowerShellCorpus/PoshCode/Product key_2.ps1
|
Product key_2.ps1
|
from System import Array, Char, Console
from System.Collections import ArrayList
from Microsoft.Win32 import Registry
def DecodeProductKey(digitalProductID):
map = ("BCDFGHJKMPQRTVWXY2346789").ToCharArray()
key = Array.CreateInstance(Char, 29)
raw = ArrayList()
i = 52
while i < 67:
raw.Add(digitalProductID[i])
i += 1
i = 28
while i >= 0:
if (i + 1) % 6 == 0:
key[i] = '-'
else:
k = 0
j = 14
while j >= 0:
k = (k * 256) ^ raw[j]
raw[j] = (k / 24)
k %= 24
key[i] = map[k]
j -= 1
i -= 1
return key
reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
val = reg.GetValue("DigitalProductId")
Console.WriteLine(DecodeProductKey(val))
|
PowerShellCorpus/PoshCode/vibackup-lx.ps1
|
vibackup-lx.ps1
|
Param (
$viServer,
$bakVM,
$lxDest
)
#region check
if (!$viServer) { $viServer = Read-Host -Prompt "VI Server " }
if (!$bakVM) { $bakVM = Read-Host -Prompt "VM to Backup " }
if (!$lxDest) { $lxDest = Read-Host -Prompt "Backup Path (ex. /srv/backup) " }
#endregion
#region globalvars
$encoding = "OEM"
$version = "0.5"
$scriptout = @()
#endregion
#region stkmvars
$viUser = "uusdumVMWARE"
$viPass = "1qayxsw2"
#endregion
Write-Host "viBackup Script Generator - " $version
Write-Host "--------------------------------------------"
if (($vmCon = Connect-VIServer -Protocol https $viServer) -eq "") { exit }
$vm = Get-VM $bakVM -Server $vmCon -ErrorAction SilentlyContinue
if (!$vm) {
Write-Host "No VM found."
Write-Host "Enter the Display Name from the VI Center:" -NoNewline
$tvm = Read-Host
if (!($vm=Get-VM $tvm -ErrorAction SilentlyContinue)) {
return $false
exit
}
Write-Host "You have entered 2 different Names. Please check that the VMX and the VM Name are the same!"
Write-Host -ForegroundColor yellow "Entered VMX Name: {$bakVM}"
Write-Host -ForegroundColor yellow "Entered VM Name: {$tvm}"
Write-Host -ForegroundColor yellow "Returned VM Name: {$vm}"
Write-Host -ForegroundColor yellow "IS THIS CORRECT (Yes/No)?:" -NoNewline
$sure = Read-Host
if ($sure -ne "yes") { exit }
}
#check Snapshots
if ((Get-Snapshot -VM $vm -Server $vmCon)) {
Write-Host "VM has Snapshots. No Backup possible."
return $false
exit
}
#write script
$scriptname = $vm.name + ".sh"
$vmname = $vm.Name
$vmhost = $vm.Host
#generate Text
$header = "#!/bin/bash"
$user = "USER=`"${viUser}`""
$pass = "PASS=`"${viPass}`""
$dest = "DEST=`"${lxDest}`""
$lxVM = "VM=`"${vmname}`""
#region writefile
$scriptout += $header
$scriptout += $user
$scriptout += $pass
$scriptout += $dest
$scriptout += $lxvm
$scriptout += ""
$scriptout += "BKUP=``vmrun -h https://${viserver}/sdk -u `${USER} -p `${PASS} list | grep `${VM}`` "
$scriptout += "SNAPCHECK=``vmware-cmd -H ${viserver} -T ${vmhost} -U `${USER} -P `${PASS} `"`${BKUP}`" hassnapshot`` "
$scriptout += "if [ `"`$SNAPCHECK`" != `"hassnapshot () =`" ]; then `n echo 'VM has a Snapshot. Arborting...' `n exit `n fi"
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} snapshot `"`${BKUP}`" vmBackup"
# Hard Disk
foreach ($hd in $vm.Harddisks) {
$hdname = $hd.Filename
$vifs = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname | sed 's/.vmdk/-flat.vmdk/g'```" `${DEST}/`${VM}.vmdk "
$scriptout += $vifs
}
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} deleteSnapshot `"`${BKUP}`" vmBackup"
$scriptout | Out-File $scriptname -Encoding $encoding
#endregion
Write-Host "Finished"
Write-Host "Don't forget to convert the script under *nix/Linux with dos2unix!"
|
PowerShellCorpus/PoshCode/Find-AmazonBook.ps1
|
Find-AmazonBook.ps1
|
## Requires HttpRest http://poshcode.org/691
## Add-Module HttpRest ##Or:## . HttpRest.ps1
## YOU MUST Provide an Amazon Web Services key (AWSKey) and a $Book title
####################################################################################################
Set-HttpDefaultUrl "http://ecs.amazonaws.com/onca/xml"
FUNCTION Search-Books {
PARAM( [string]$Book, [string]$AWSKey, [string]$outFile, [string]$inputDelim = ",", [int]$Count = 1 )
BEGIN {
if($Book -and $(Test-Path $Book)) {
return Get-Content $Book | Search-Books
} elseif($Book){ $Book | Search-Books }
$params = @{
Service="AWSECommerceService"
AWSAccessKeyId=$AWSKey
Operation="ItemSearch"
SearchIndex="Books"
}
}
PROCESS { if($_){ $book=$_
$bk = $book.Split($inputDelim)
$params.Title = $bk[0].Trim()
if($bk[1]) { $params.Author = $bk[1].Trim() } else { $params.Remove("Author") }
$items = Invoke-Http GET -with $params |
Receive-Http Xml "//*[local-name() = 'Item']" |
Select Asin, DetailPageUrl,
@{n="Title";e={$_.ItemAttributes.Title}},
@{n="Author";e={$_.ItemAttributes.Author}} -First $Count
if($outFile) {
ConvertTo-CSV -io $items | Add-Content -Path $outFile
} else {
$items
}
}}
}
|
PowerShellCorpus/PoshCode/Findup_17.ps1
|
Findup_17.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static System.String[] paths = new string[0];
public static System.String[] excpaths = new string[0];
public static System.String[] incpaths = new string[0];
public static System.Boolean noerr = false;
public static System.Boolean useregex = false;
public static System.Boolean includeflag = false;
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine(" ");
System.Boolean recurse = false;
System.Boolean exc = false;
System.Boolean inc = false;
List<FileInfo> files = new List<FileInfo>();
long numOfDupes = 0; // number of duplicate files found.
long dupeBytes = 0; // number of bytes in duplicates.
int i = 0;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-noerr] [-x] <files/directories/regx> [-regex]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help message.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -noerr - discards error messages.");
Console.WriteLine(" -x - eXcludes all directories\\\\files (or RegEx if -regex used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -i - Include only directories\\\\files (or RegEx if -regex used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -regex - Use Regex notation for exclude (-x) and include (-i) option.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -regex");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in it as specified by the Regex item \\"(?:jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -i \\"(?:smith)\\" -regex");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with 'jim' in it as specified by the Regex items \\"(?:jim)\\",\\"(?:smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-regex", true) == 0)
{
useregex = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-noerr", true) == 0)
{
noerr = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-i", true) == 0)
{
inc = true;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-x", true) == 0)
{
exc = true;
inc = false;
continue;
}
if (exc == true)
{
Array.Resize(ref excpaths, excpaths.Length + 1);
excpaths[excpaths.Length - 1] = args[i];
continue;
}
if (inc == true)
{
Array.Resize(ref incpaths, incpaths.Length + 1);
incpaths[incpaths.Length - 1] = args[i];
includeflag = true;
continue;
}
else
{
Array.Resize(ref paths, paths.Length + 1);
paths[paths.Length - 1] = args[i];
}
}
if (paths.Length == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help");
return;
}
Console.Write("Getting file info...");
getFiles(paths, "*.*", recurse, files);
Console.WriteLine("Completed!");
if (files.Count < 2)
{
WriteErr("Findup.exe needs at least 2 files to compare. Try findup.exe -help");
return;
}
Console.Write("Sorting file list...");
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Computing SHA512 & Size matches...");
var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>();
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) { continue; }
var breakout = false;
while (true)
{
var _SHA512 = SHA512.Create();
try
{
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string SHA512string = enc.GetString(_SHA512.Hash);
if (SizeHashName.ContainsKey(files[i].Length))
{
if (!SizeHashName[files[i].Length].ContainsKey(SHA512string))
{
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
}
else
{
SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>());
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName);
}
catch (Exception e)
{
WriteErr("Hash error: " + e.Message);
}
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
if (files[i].Length != files[i + 1].Length) { breakout = true; }
}
}
Console.WriteLine("Completed!");
foreach (var SizeGroup in SizeHashName)
{
foreach (var HashGroup in SizeGroup.Value)
{
if (HashGroup.Value.Count > 1)
{
Console.WriteLine("Duplicates (size: {0:N0} Bytes) - ", (long)SizeGroup.Key);
foreach (var FileName in HashGroup.Value)
{
Console.WriteLine(FileName);
numOfDupes++;
dupeBytes += (long)SizeGroup.Key;
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
return; // Exit after displaying statistics.
}
private static void WriteErr(string Str)
{
if (noerr == false)
Console.WriteLine(Str);
}
private static Boolean CheckExcludes(string Path)
{
foreach (var x in excpaths)
{
if (useregex == true)
{
try
{
Regex rgx = new Regex(x);
if (rgx.IsMatch(Path))
return false;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + x + " exception: " + e);
}
}
else { if (Path.ToLower().StartsWith(x.ToLower())) { return false; } }
}
return true;
}
private static Boolean CheckIncludes(string Path)
{
if (!includeflag) { return true; }
foreach (var i in incpaths)
{
if (useregex == true)
{
try
{
Regex rgx = new Regex(i);
if (rgx.IsMatch(Path))
return true;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + i + " exception: " + e);
}
}
else {if (Path.ToLower().StartsWith(i.ToLower())) { return true; }}
}
return false;
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec)
{
getFiles(d, searchPattern, recursiveFlag, returnList);
}
return;
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
catch (Exception e)
{
WriteErr("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e)
{
WriteErr("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList);
}
catch (Exception e)
{
WriteErr("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart) && CheckExcludes(dirPart) && CheckIncludes(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Import-ExcelToSQL_1.ps1
|
Import-ExcelToSQL_1.ps1
|
#Change these settings as needed
$filepath = 'C:\\Users\\u00\\Documents\\backupset.xlsx'
#Comment/Uncomment connection string based on version
#Connection String for Excel 2007:
$connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
$qry = 'select * from [backupset$]'
$sqlserver = 'Z002\\SQLEXPRESS'
$dbname = 'SQLPSX'
#Create a table in destination database with the with referenced columns and table name.
$tblname = 'ExcelData_fill'
#######################
function Get-ExcelData
{
param($connString, $qry='select * from [sheet1$]')
$conn = new-object System.Data.OleDb.OleDbConnection($connString)
$conn.open()
$cmd = new-object System.Data.OleDb.OleDbCommand($qry,$conn)
$da = new-object System.Data.OleDb.OleDbDataAdapter($cmd)
$dt = new-object System.Data.dataTable
[void]$da.fill($dt)
$conn.close()
$dt
} #Get-ExcelData
#######################
function Write-DataTableToDatabase
{
param($dt,$destServer,$destDb,$destTbl)
$connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = "$destTbl"
$bulkCopy.WriteToServer($dt)
}# Write-DataTableToDatabase
#######################
$dt = Get-ExcelData $connString $qry
Write-DataTableToDatabase $dt $sqlserver $dbname $tblname
|
PowerShellCorpus/PoshCode/New-Eicar.ps1
|
New-Eicar.ps1
|
function New-Eicar {
<#
.SYNOPSIS
New-Eicar
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
.DESCRIPTION
A function that generates the EICAR string to test ondemand scanning of antivirus products.
.PARAMETER $Path
Specifies the path to write the eicar file to.
.EXAMPLE
PS C:\\> New-Eicar -Path c:\\test
.NOTES
During testing, several AV products caused the script to hang, but it always completed after a few minutes.
.LINK
http://obscuresec.com/2013/01/New-Eicar.html
https://github.com/obscuresec/random/blob/master/New-Eicar
#>
[CmdletBinding()] Param(
[ValidateScript({Test-Path $_ -PathType 'Container'})]
[string]
$Path = "$env:temp\\"
)
[string] $FilePath = (Join-Path $Path eicar.com)
#Base64 of Eicar string
[string] $EncodedEicar = 'WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo='
If (!(Test-Path -Path $FilePath)) {
Try {
[byte[]] $EicarBytes = [System.Convert]::FromBase64String($EncodedEicar)
[string] $Eicar = [System.Text.Encoding]::UTF8.GetString($EicarBytes)
Set-Content -Value $Eicar -Encoding ascii -Path $FilePath -Force
}
Catch {
Write-Warning "Eicar.com file couldn't be created. Either permissions or AV prevented file creation."
}
}
Else {
Write-Warning "Eicar.com already exists!"
}
}
|
PowerShellCorpus/PoshCode/Get-Films (From Netflix).ps1
|
Get-Films (From Netflix).ps1
|
function Get-Films {
param($Name)
$proxy = New-ODataServiceProxy http://odata.netflix.com/Catalog/
if($Name -match "\\*") {
$sName = $Name -replace "\\*"
$Global:Films = $proxy.Titles.AddQueryOption('$filter',"substringof('$sName',Name)") | Where { $_.Name -like $Name }
} else {
$Global:Films = $proxy.Titles.AddQueryOption('$filter',"'$Name' eq Name")
}
$Films | Format-List Name, ReleaseYear, AverageRating, Url, Synopsis
Write-Host "NOTE: This data is cached in `$Films" -Fore Yellow
}
Get-Films Salt
Get-Films "The Matrix*"
Get-Films "Ernest*"
|
PowerShellCorpus/PoshCode/Reverse filename sequenc_5.ps1
|
Reverse filename sequenc_5.ps1
|
# Reverse filename sequence v 0.9
# Author: Sean Wendt
#
# This script will rename a sequenced set of files in a directory.
# For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg
# -- it will reverse the order, so the last file is now 01, the second to last 02, etc..
#
# Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars.
# -It's hardcoded to only support 5 digit numbers right now.
# -Similarly, it will only support a file sequence with up to 5 digits.
# This is the first script I've written, I know it's not great! ;)
# Help to make it better would be appreciated. Thanks.
#
$file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt"
$file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.."
$files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders
$idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg)
for ($ctr=$files.count; $ctr -gt 0 ; --$ctr)
{
if (($idx -ge 0) -and ($idx -le 9))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension)
}
elseif (($idx -ge 10) -and ($idx -le 99))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension)
}
elseif (($idx -ge 100) -and ($idx -le 999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension)
}
elseif (($idx -ge 1000) -and ($idx -le 9999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension)
}
elseif (($idx -ge 10000) -and ($idx -le 99999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension)
}
$idx #prints the index # it just completed
}
|
PowerShellCorpus/PoshCode/ISE-Lines_1.ps1
|
ISE-Lines_1.ps1
|
#requires -version 2.0
## ISE-Lines module v 1.1
## DEVELOPED FOR CTP3
## See comments for each function for changes ...
##############################################################################################################
## Provides Line cmdlets for working with ISE
## Duplicate-Line - Duplicates current line
## Conflate-Line - Conflates current and next line
## MoveUp-Line - Moves current line up
## MoveDown-Line - Moves current line down
## Delete-TrailingBlanks - Deletes trailing blanks in the whole script
##############################################################################################################
## Duplicate-Line
##############################################################################################################
## Duplicates current line
##############################################################################################################
function Duplicate-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
$line = $text[$caretLine -1]
$newText = $text[0..($caretLine -1)]
$newText += $line
$newText += $text[$caretLine..($text.Count -1)]
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, $caretColumn)
}
## Conflate-Line
##############################################################################################################
## Conflates current and next line
## v 1.1 fixed bug on last but one line and remove line continuation character while joining
##############################################################################################################
function Conflate-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
if ( $caretLine -ne $text.Count )
{
$line = $text[$caretLine -1] + $text[$caretLine] -replace ("(``)?`r", "")
$newText = @()
if ( $caretLine -gt 1 )
{
$newText = $text[0..($caretLine -2)]
}
$newText += $line
if ( $caretLine -ne $text.Count - 1)
{
$newText += $text[($caretLine +1)..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, $caretColumn)
}
}
## MoveUp-Line
##############################################################################################################
## Moves current line up
##############################################################################################################
function MoveUp-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
if ( $caretLine -ne 1 )
{
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
$line = $text[$caretLine -1]
$lineBefore = $text[$caretLine -2]
$newText = @()
if ( $caretLine -gt 2 )
{
$newText = $text[0..($caretLine -3)]
}
$newText += $line
$newText += $lineBefore
if ( $caretLine -ne $text.Count )
{
$newText += $text[$caretLine..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine - 1, $caretColumn)
}
}
## MoveDown-Line
##############################################################################################################
## Moves current line down
##############################################################################################################
function MoveDown-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
if ( $caretLine -ne $text.Count )
{
$line = $text[$caretLine -1]
$lineAfter = $text[$caretLine]
$newText = @()
if ( $caretLine -ne 1 )
{
$newText = $text[0..($caretLine -2)]
}
$newText += $lineAfter
$newText += $line
if ( $caretLine -lt $text.Count -1 )
{
$newText += $text[($caretLine +1)..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine +1, $caretColumn)
}
}
## Delete-TrailingBlanks
##############################################################################################################
## Deletes trailing blanks in the whole script
##############################################################################################################
function Delete-TrailingBlanks
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$newText = @()
foreach ( $line in $editor.Text.Split("`n") )
{
$newText += $line -replace ("\\s+$", "")
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, 1)
}
##############################################################################################################
## Inserts a submenu Lines to ISE's Custum Menu
## Inserts command Duplicate Line to submenu Lines
## Inserts command Conflate Line Selected to submenu Lines
## Inserts command Move Up Line to submenu Lines
## Inserts command Move Down Line to submenu Lines
## Inserts command Delete Trailing Blanks to submenu Lines
##############################################################################################################
if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "Line" } ) )
{
$lineMenu = $psISE.CustomMenu.Submenus.Add("_Lines", $null, $null)
$null = $lineMenu.Submenus.Add("Duplicate Line", {Duplicate-Line}, "Ctrl+Alt+D")
$null = $lineMenu.Submenus.Add("Conflate Line", {Conflate-Line}, "Ctrl+Alt+J")
$null = $lineMenu.Submenus.Add("Move Up Line", {MoveUp-Line}, "Ctrl+Shift+Up")
$null = $lineMenu.Submenus.Add("Move Down Line", {MoveDown-Line}, "Ctrl+Shift+Down")
$null = $lineMenu.Submenus.Add("Delete Trailing Blanks", {Delete-TrailingBlanks}, "Ctrl+Shift+Del")
}
|
PowerShellCorpus/PoshCode/Custom Accelerators.ps1
|
Custom Accelerators.ps1
|
#requires -version 2.0
## Custom Accelerators for PowerShell 2
####################################################################################################
## A script module for PowerShell 2 which allows the user to create their own custom type accelerators.
## Thanks to "Oisin Grehan for the discovery":http://www.nivot.org/2008/12/25/ListOfTypeAcceleratorsForPowerShellCTP3.aspx.
####################################################################################################
## Revision History
## v1.0 - Modularization of Oisin's idea, by Joel 'Jaykul' Bennett
## v2.0 - Update for RTM (nothing significant)
####################################################################################################
# get a reference to the Type
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", GList System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
PARAM(
[Parameter(Position=0)]
[Alias("Key")]
[string[]]$Accelerator
,
[Parameter(Position=1)]
[Alias("Value")]
[type]$Type
)
PROCESS {
# add a user-defined accelerator
foreach($a in $Accelerator) {
$xlr8r::Add( $a, $Type)
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
Continue;
}
throw
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
PARAM(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key")]
[string[]]$Accelerator
,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value")]
[type[]]$Type
)
PROCESS {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
PARAM(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key")]
[string[]]$Accelerator
)
PROCESS {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Add _ Get-Help -Full.ps1
|
Add _ Get-Help -Full.ps1
|
$executionContext.SessionState.InvokeCommand.PreCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
if($CommandName.StartsWith("?")) {
$RealCommandName = $CommandName.TrimStart("?")
$CommandLookupEventArgs.CommandScriptBlock = {
Get-Help $RealCommandName -Full
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
Write-Warning "DO NOT USE THIS POSTCOMMANDLOOKUPACTION EXCEPT FOR DEMONSTRATION"
$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
# Only for interactive commands (and that doesn't include "prompt")
# I should exclude out-default so we don't handle it on every pipeline, but ...
if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) {
## Create a new script block that checks for the "-??" argument
## And if -?? exists, calls Get-Help -Full instead
## Otherwise calls the expected command
$CommandLookupEventArgs.CommandScriptBlock = {
if($Args.Length -eq 1 -and $Args[0] -eq "-??") {
Get-Help $CommandName -Full
} else {
& $CommandName @args
}
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
|
PowerShellCorpus/PoshCode/Convert-PowerPack2Ps1.ps1
|
Convert-PowerPack2Ps1.ps1
|
#######################################################################
# Convert-PowerPack2Ps1
#
# Converts PowerGUI .PowerPack files to ps1 PowerShell script library
# v1 - raw conversion, no name changes, only script elements converted
######################################################################
# Example:
# & .\\Convert-PowerPack2Ps1 "ActiveDirectory.powerpack" "ActiveDirectory.ps1"
# . .\\ActiveDirectory.ps1
# Get-QADUser 'Dmitry Sotnikov' | MemberofRecursive
######################################################################
#
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com
#
#####################################################################
param(
$PowerPackFile = (throw 'Please supply path to source powerpack file'),
$OutputFilePath = (throw 'Please supply path to output ps1 file')
)
#region Functions
function IterateTree {
# processes all script nodes
param($segment)
if ( $segment.Type -like 'Script*' ) {
$name = $segment.name -replace ' |\\(|\\)', ''
$code = $segment.script.PSBase.InnerText
@"
########################################################################
# Function: $name
# Return type: $($segment.returntype)
########################################################################
function $name {
$code
}
"@ | Out-File $OutputFilePath -Append
}
# recurse folders
if ($segment.items.container -ne $null) {
$segment.items.container | ForEach-Object { IterateTree $_ }
}
}
function Output-Link {
PROCESS {
if ( $_.script -ne $null ) {
$name = $_.name -replace ' |\\(|\\)', ''
$code = $_.script.PSBase.InnerText
@"
########################################################################
# Function: $name
# Input type: $($_.type)
# Return type: $($_.returntype)
########################################################################
function $name {
$code
}
"@ | Out-File $OutputFilePath -Append
}
}
}
#endregion
$sourcefile = Get-ChildItem $PowerPackFile
if ($sourcefile -eq $null) { throw 'File not found' }
@"
########################################################################
# Generated from: $PowerPackFile
# by Convert-PowerPack2Ps1 script
# on $(get-date)
########################################################################
"@ | Out-File $OutputFilePath
$pp = [XML] (Get-Content $sourcefile)
@"
# Scripts generated from script nodes
"@ | Out-File $OutputFilePath -Append
IterateTree $pp.configuration.items.container[0]
@"
# Scripts generated from script links
"@ | Out-File $OutputFilePath -Append
$pp.configuration.items.container[1].items.container |
where { $_.id -eq '481eccc0-43f8-47b8-9660-f100dff38e14' } | ForEach-Object {
$_.items.item, $_.items.container | Output-Link
}
@"
# Scripts generated from script actions
"@ | Out-File $OutputFilePath -Append
$pp.configuration.items.container[1].items.container |
where { $_.id -eq '7826b2ed-8ae4-4ad0-bf29-1ff0a25e0ece' } | ForEach-Object {
$_.items.item, $_.items.container | Output-Link
}
|
PowerShellCorpus/PoshCode/SQLParser.ps1
|
SQLParser.ps1
|
#requires -version 2
#Uses Visual Studio Database Edition classes Microsoft.Data.Schema.ScriptDom and Microsoft.Data.Schema.Script.Sql to parse T-SQL
#Chad Miller
#http://chadwickmiller.spaces.live.com/
$PSScriptRoot = (Split-Path $MyInvocation.MyCommand.Path -Parent)
Add-Type -Path "$PSScriptRoot\\Microsoft.Data.Schema.ScriptDom.dll"
Add-Type -Path "$PSScriptRoot\\Microsoft.Data.Schema.ScriptDom.Sql.dll"
$Source = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Schema.ScriptDom;
using Microsoft.Data.Schema.ScriptDom.Sql;
using System.IO;
public class SQLParser
{
private IScriptFragment fragment;
public SQLParser(SqlVersion sqlVersion, bool quotedIdentifier, string inputScript)
{
switch (sqlVersion)
{
case SqlVersion.Sql80:
SQLParser80 (quotedIdentifier, inputScript);
break;
case SqlVersion.Sql90:
SQLParser90 (quotedIdentifier, inputScript);
break;
case SqlVersion.Sql100:
SQLParser100 (quotedIdentifier, inputScript);
break;
}
}
private void SQLParser100 (bool quotedIdentifier, string inputScript)
{
TSql100Parser parser = new TSql100Parser(quotedIdentifier);
Parse(parser, inputScript);
}
private void SQLParser90 (bool quotedIdentifier, string inputScript)
{
TSql90Parser parser90 = new TSql90Parser(quotedIdentifier);
Parse(parser90, inputScript);
}
private void SQLParser80 (bool quotedIdentifier, string inputScript)
{
TSql80Parser parser80 = new TSql80Parser(quotedIdentifier);
Parse(parser80, inputScript);
}
private void Parse(TSql100Parser parser, string inputScript)
{
IList<ParseError> errors;
using (StringReader sr = new StringReader(inputScript))
{
fragment = parser.Parse(sr, out errors);
}
if (errors != null && errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var error in errors)
{
sb.AppendLine(error.Message);
sb.AppendLine("offset " + error.Offset.ToString());
}
throw new ArgumentException("InvalidSQLScript", sb.ToString());
}
}
private void Parse(TSql90Parser parser, string inputScript)
{
IList<ParseError> errors;
using (StringReader sr = new StringReader(inputScript))
{
fragment = parser.Parse(sr, out errors);
}
if (errors != null && errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var error in errors)
{
sb.AppendLine(error.Message);
sb.AppendLine("offset " + error.Offset.ToString());
}
throw new ArgumentException("InvalidSQLScript", sb.ToString());
}
}
private void Parse(TSql80Parser parser, string inputScript)
{
IList<ParseError> errors;
using (StringReader sr = new StringReader(inputScript))
{
fragment = parser.Parse(sr, out errors);
}
if (errors != null && errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
foreach (var error in errors)
{
sb.AppendLine(error.Message);
sb.AppendLine("offset " + error.Offset.ToString());
}
throw new ArgumentException("InvalidSQLScript", sb.ToString());
}
}
public IScriptFragment Fragment
{
get { return fragment; }
}
}
"@
$refs = @("$PSScriptRoot\\Microsoft.Data.Schema.ScriptDom.dll","$PSScriptRoot\\Microsoft.Data.Schema.ScriptDom.Sql.dll")
add-type -ReferencedAssemblies $refs -TypeDefinition $Source -Language CSharpVersion3 -passThru
|
PowerShellCorpus/PoshCode/01fef1f2-03fd-4b4d-bed8-aa3c4999fedc.ps1
|
01fef1f2-03fd-4b4d-bed8-aa3c4999fedc.ps1
|
Connect-VIServer <vCenter server>
# Uncomment the next line to test this script
# $WhatIfPreference = $true
if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
Add-PSSnapin VMware.VimAutomation.Core
}
if (-not (Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue)) {
Add-PSSnapin Quest.ActiveRoles.ADManagement
}
$VMs = Get-Cluster -Name <Cluster name> | Get-VM | Sort Name
$VM = $VMs | Select -First 1
If (-not $vm.CustomFields.ContainsKey("CreatedBy")) {
Write-Host "Creating CreatedBy Custom field for all VM's"
New-CustomAttribute -TargetType VirtualMachine -Name CreatedBy | Out-Null
}
If (-not $vm.CustomFields.ContainsKey("CreatedOn")) {
Write-Host "Creating CreatedOn Custom field for all VM's"
New-CustomAttribute -TargetType VirtualMachine -Name CreatedOn | Out-Null
}
Foreach ($VM in $VMs){
If ($vm.CustomFields["CreatedBy"] -eq $null -or $vm.CustomFields["CreatedBy"] -eq ""){
Write-Host "Finding creator for $vm"
$Event = $VM | Get-VIEvent -Types Info | Where { $_.Gettype().Name -eq "VmBeingDeployedEvent" -or $_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmRegisteredEvent" -or $_.Gettype().Name -eq "VmClonedEvent"}
If (($Event | Measure-Object).Count -eq 0){
$User = "Unknown"
$Created = "Unknown"
} Else {
If ($Event.Username -eq "" -or $Event.Username -eq $null) {
$User = "Unknown"
} Else {
$User = (Get-QADUser -Identity $Event.Username).DisplayName
if ($User -eq $null -or $User -eq ""){
$User = $Event.Username
}
$Created = $Event.CreatedTime
}
}
Write "Adding info to $($VM.Name)"
Write-Host -ForegroundColor Yellow "CreatedBy $User"
$VM | Set-Annotation -CustomAttribute "CreatedBy" -Value $User | Out-Null
Write-Host -ForegroundColor Yellow "CreatedOn $Created"
$VM | Set-Annotation -CustomAttribute "CreatedOn" -Value $Created | Out-Null
}
}
|
PowerShellCorpus/PoshCode/VM Performance Report_1.ps1
|
VM Performance Report_1.ps1
|
<#
.SYNOPSIS
The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address.
.DESCRIPTION
The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3487) or run interactively.
.NOTES
File Name : Get-VMPeformanceReport.ps1
Author : Samuel Mulhearn
Version History:
Version 1.0
28 Jun 2012.
Release
.LINK
http://poshcode.org/3489
.EXAMPLE
Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt>
#>
#Change These Values
$VC = "vm-trb-vc02.th.local" #VirtualCenter
$SMTPServer = "10.247.50.25" #SMTP Server
$SendersAddress = "noreply@tribalgroup.com" #The report comes from this address
$SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3487
$CompanyLogo = "http://placehold.it/150x50"
function Out-LogFile {
#Log File Function http://poshcode.org/3232
[CmdletBinding(DefaultParameterSetName='Message')]
param(
[Parameter(ParameterSetName='Message',
Position=0,
ValueFromPipeline=$true)]
[object[]]$Message,
[Parameter(ParameterSetName='Message')]
[string]$LogFile = $global:DefaultLogPath,
[Parameter(ParameterSetName='Message')]
[int]$BlankLine = 0,
[switch]$WriteHost = $global:WriteHostPreference,
[string]$Severity = "I",
[Parameter(ParameterSetName='Message')]
[switch]$DontFormat,
[Parameter(ParameterSetName='Message')]
[string]$DateFormat = "dd-MM-yyyy HH:mm:ss",
#[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)]
[string]$Title,
[System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor,
[System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor,
[ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')]
[string]$Encoding = 'Unicode',
[switch]$Force
)
begin {
Write-Verbose "Log File: $LogFile"
if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break}
if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break}
if ( $Title ) {
$text = $Title
$Title = $null
Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
}
}
process {
if ( $Message ) {
$text = $Message
foreach ( $text in $Message ) {
if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" }
if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor}
$text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
}
}
if ( $BlankLine -gt 0 ){
for ($i = 0; $i -lt $BlankLine; $i++ ) {
"" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor }
}
}
}
end {
}
}
#end of logfile function
#New Line Variable
$nl = [Environment]::NewLine
#INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential)
#NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3487), and retrive as below
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3487)
$VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3487
$VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key)
$VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password)
#Get Datafile, this wil contain VM's to report on, and an email address to send the report to
#Datafile format: first line is email address, subsequent lines are VM's, one per line)
if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error!
{ Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)"
#$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file
}
else
{ $Datafile = $args[0] }
#From Datafile, get a log file, and a
$LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log"
$Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm"
$global:WriteHostPreference = $true
$global:DefaultLogPath = $LogFile
Out-LogFile -Message "Starting script with $datafile"
#Load PowerCLI
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{ Add-PsSnapin VMware.VimAutomation.Core }
If (!(Get-PSSnapin -Name VMware.VimAutomation.Core))
{Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E"
Exit(1)
}
#Static HTML
$HTMLPreString=@"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css">
<style type="text/css">
body {
padding: 20px;
}
h2 {
color: #3A87AD;
}
.mytable {
width: 776px;
margin: 12px;
}
.alert-info {
color: #3A87AD;
background-color: #D9EDF7;
border-color: #BCE8F1;
padding: 8px 8px 8px 14px;
margin-top: 12px;
margin-left: 12px;
margin-right: 12px;
margin-bottom: 12px;
border: 1px solid;
border-radius: 4px;
}
.chart_wrap {
width: 800px;
border-style:solid;
border-width:1px;
border-color: #DDDDDD;
margin: 0px 0px 10px 0px;
}
.chart {
text-align: center;
width: 800px;
height: 400px;
}
</style>
<title>
Virtual Machine Performance statistics
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
"@
$HTMLPreString += "$nl"
$HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl"
$HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl"
$HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl"
$HTMLPostString=@"
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script>
<script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script>
</body>
</html>
"@
#Functions for dynamic HTML
Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title)
{
#https://developers.google.com/chart/interactive/docs/examples#custom_table_example
$mystring = "<script type=`"text/javascript`">$nl"
$mystring += "function drawVisualization$UID() {$nl"
$mystring += "// Create and populate the data table. $nl"
$mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl"
$mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl"
$VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"}
$mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl"
$ColumnCount = 0
$RowCount = 0
$Statistics | % {
$ColumnCount = 0
$formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null)
$JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0)
$formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm")
$formatteddate = "new Date($formatteddate)"
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl"
$_.Group |
% {
$ColumnCount = 0
foreach ($VM in $VMs)
{
$ColumnCount += 1
If ($_.Entity.Name -eq $VM )
{ if ($Summation -eq $true)
{ $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181
$strPercent = [system.math]::round($strPercent,2)
$mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl"
}
else
{ $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" }
}
}
}
$RowCount += 1
}
$mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl"
$VisParam = "`
{ `
legend: {position: 'in',alignment:`"center`"}, `
lineWidth:`"2`", `
curveType: `"none`",`
chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},`
focusTarget:`"category`", `
hAxis: {slantedText:`"true`", format:`"E, d MMM`"},`
vAxis: {textPosition:`"out`"},`
width: 800, `
height: 400, `
title:`"$Title`"}"
$mystring += "draw(" + "$UID" + "data, $VisParam);$nl"
$mystring +="}$nl"
$mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl"
return $mystring
}
function Get-DivHTML ($UID, $Notes)
{
$tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl"
$tempHTML += " <div class=`"chart_wrap`">$nl"
$tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl"
$tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl"
$tempHTML += " </div>$nl"
$tempHTML += "</div>$nl"
return $tempHTML
}
#Main Code
#Process datafile, get VM's to report on, and an email address to send the report to
$DataTable = @(Get-Content $Datafile)
$email = $DataTable[0]
$VMs = @($DataTable[1..($DataTable.Count)])
#Connect to VC
Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null
if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails.
{ Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost
Exit (1)
}
else
{Out-LogFile -Message "Connected to vCenter ($VC)"}
#Validate VM's exist
$VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue)
$VMs | % {
$tmpvm = $_
$Exists = $false
$VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}}
If ($Exists){
Out-LogFile -Message "$_ found in vCenter inventory"
}
Else {
Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W"
$VMs = $VMs |? {$_ -ne $tmpvm}
}
}
#To add new Stat
#1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics)
#2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#3. Invent a new UID - MyUID ?
#4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title")
#5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li>
#6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart")
#Start and Finish times
$todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1)
$metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average"
$start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart
$finish = $todayMidnight
$startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm")
$finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm")
Out-LogFile -Message "Getting stats from vCenter"
#Variable for all stats combined
$Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average
Out-LogFile -Message "Got stats from vCenter"
Out-LogFile -Message "Sorting and filtering stats"
#Split stats out by each indivial metric into individual variable
$CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
$Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp)
#Creates HTML inside of <head> for javascript for the charts
Out-LogFile -Message "Creating HTML"
$HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)")
$HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)")
$HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)")
$HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)")
$HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)")
$HTMLOut += "</head>$nl"
$HTMLOut += $HTMLBodyBegin + $nl
#Navigation Tabs...
#Edit below to add a tab, when adding a new metric
$HTMLOut += @"
<div id="content">
<ul class="nav nav-tabs">
<li class="active"><a href="#Info" data-toggle="tab">Information</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#CPU" data-toggle="tab">CPU Usage</a></li>
<li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#Memory" data-toggle="tab">Memory Usage</a></li>
<li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li>
</ul>
<li>
<li><a href="#Disk" data-toggle="tab">Disk</a></li>
<li><a href="#Net" data-toggle="tab">Network</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
<div class="tab-pane fade in active" id="Info">
<div class="chart_wrap">
<div class="alert alert-info">
<strong>Information: </strong>
"@
#Info for fist tab
$HTMLOut += "Each datapoint represents resource consumption since the last datapoint `
and its value is either an average, maximum, or summation of all usage in that interval. `
Any values that are zero may actually be zero, or may indicate statistics were not `
collected over that period (for example, if a virtual machine was powered off). $nl `
The statistics displayed are from $startstring to $finishstring</div>$nl"
#Table that contains VM resource config & limits.
$HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl"
$VCVMs | % {
$tmpname =$_.Name
$tmpNumCpu = $_.NumCpu
$TmpMemoryMB = $_.MemoryMB
$tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None")
$tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None")
$HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl"
}
$HTMLOut += "</tbody></table>$nl"
$HTMLOut +=@"
</div>
</div>
"@
#Div elements that contain each chart
$HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval")
$HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory")
$HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps")
$HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval")
$HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal")
$HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0")
$HTMLOut += @"
</div>
</div>
</div>
"@
$datenow = Get-Date -Format "F"
$HTMLOut += "<h6>Report generated at $datenow<h6>$nl"
$HTMLOut += $HTMLPostString
#Finished HTML
Out-LogFile -Message "Finished building HTML, writing to $Outfile"
$HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8"
#Build Email
$body =@"
<P>Performance statistics for the Virtual Machines listed below are attached</p>
"@
$body += "<p>Statistics are from $startstring to $finishstring<p>"
$VMs | % {$body+= "<li>$_</li>" }
Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer"
#Send email
Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer
Disconnect-VIServer -Confirm:$false
Out-LogFile -Message "Disconnected from vCenter"
Out-LogFile -Message "Finished"
|
PowerShellCorpus/PoshCode/ISEFun_1.psm1.ps1
|
ISEFun_1.psm1.ps1
|
# Module version 0.2
# Author: Bartek Bielawski (@bielawb on twitter)
# Purpose: Add functionality to PowerShell ISE
# Description: Adds Add-ons menu 'ISEFun' with all functions included.
# User can add any action there using Add-MyMenuItem function
# One of functions (Copy item from history) was build using WPK - won't work if the latter is not loaded.
# There is also pretty large code for Windows Forms form (change token colors using ColorDialog)
# Edit-Function will allow you modify any function in ISE editor
# Expand-Alias will expand aliases in current file
# Edit-HelpExample will create new file $with all examples from a given command
# Show-Top will generate table of processes sorted by a given Property in separate ISE Tab, with new/ terminated processes marked
# Update-SnippetMenu and New-Snippet are designed to work with custom code snippets.
# Have ISE - Fun! ;)
# Changes:
# Version 0.2
# * Added function Edit-HelpExample
# * Added function Show-Top
# * Added custom snippets support (add/ use)
# Version 0.1
# * First public version
# * Cleaned code, added help
# * Contains functions: Edit-Function, Add-MenuItem, Set-TokenColor, Expand-Alias, Invoke-CurrentLine, Copy-HistoryItem
# * Simple menu with all functions included, together with helper function (Add-MenuItem) that should simplify adding new items if needed.
if (-not ($MyISEMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | Where-Object { $_.DisplayName -eq 'ISEFun'} ) ) {
$MyISEMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('ISEFun',$null,$null)
}
# Helper function to add menu items, exported cause it can be used also for other stuff. :>
function Add-MyMenuItem {
<#
.Synopsis
Adds items to ISEFun Add-Ons sub-menu
.Description
Function can be used to add menu items to ISEFun menu. All you need is command, name and hotkey - we will take care of the rest for you. ;)
.Example
Add-MyMenuItem 'Write-Host fooo' 'Fooo!' 'CTRL+9'
Description
-----------
This command will add item 'Fooo!' to ISEFun menu. This item will write 'fooo' to the host and can be launched using shortcut CTRL + 9
#>
PARAM (
# Script that will be launched when menu item will be selected
[Parameter(Mandatory = $true, HelpMessage = 'Command that you want to add to menu')]
[string]$Command,
# Title for the command in the menu
[string]$DisplayName,
# Hot key to use given item
[string]$HotKey = $null,
# If specified - will create submenu to hold given command
[string]$SubMenu = $null
)
if (!$DisplayName) {
$DisplayName = $Command -replace '-',' '
}
if (!$SubMenu) {
$Menu = $Script:MyISEMenu
} elseif ($Menu = $MyISEMenu.Submenus | Where-Object { $_.DisplayName -eq $SubMenu }) {
if (!($Menu.submenus)) {
$Menu = $Script:MyISEMenu
}
} else {
$Menu = $MyISEMenu.Submenus.Add($SubMenu,$null,$null)
}
if ( -not ($Menu.Submenus | Where-Object { $_.DisplayName -eq $DisplayName} ) ) {
try {
[void]$Menu.Submenus.Add($DisplayName,[scriptblock]::Create($Command),$HotKey)
} catch {
# Probably hotkey already used, adding item without it
[void]$Menu.Submenus.Add($DisplayName,[scriptblock]::Create($Command),$null)
}
}
}
Add-MyMenuItem Add-MyMenuItem 'Add items'
function Update-SnippetMenu {
<#
.Synopsis
Updates/ creates custom snippet menu.
.Description
This function will take any snippets that you have in location (either default or selected one) and add those to ISEFun 'Code Snippets' menu.
It uses .ps1 file to make it easier to modify files in ISE (with syntax highlighting and stuff...)
.Example
Update-SnippetMenu
Checks for files in $PSScriptRoot\\ISESnippets folder and add them to 'Code Snippets' menu.
#>
param (
[string]$Path = "$PSScriptRoot\\ISESnippets"
)
foreach ($file in Get-ChildItem $Path -filter *.ps1) {
$command = @"
if (!(`$file = `$psISE.CurrentFile)) {
`$file = `$psISE.CurrentPowerShellTab.Files.Add()
}
`$file.Editor.InsertText(
`$( (Get-Content $($file.FullName)) | Out-String )
)
"@
$Name = $file.BaseName -replace '_', ' '
Add-MyMenuItem $command "Instert $Name" $null 'Code Snippets'
}
}
Add-MyMenuItem Update-SnippetMenu 'Adds/ updates code snippets menu'
function New-Snippet {
<#
.Synopsis
Creates new snippet from current file/ selection.
.Description
This function will create new snippets for you. To simplify usage in ISE it has mandatory parameter for snippet name (GUI prompt).
It will by default store snippets under modules root folder in 'ISESnippets'.
.Example
New-Snippet -SnippetName 'My funny name that will have underscore instead of **?? special \\ chars'
Will create new file (with rather odd name) with current selection (or file, if nothing was selected).
All special chars and spaces will be replace with underscore ( _ ).
#>
param(
[Parameter(Mandatory = $true, HelpMessage = 'Please specify name of the snippet')]
[Alias("SN","Name")]
[string]$SnippetName,
[string]$Path = "$PSScriptRoot\\ISESnippets"
)
if ($file = $psISE.CurrentFile) {
if (!($Value = $file.Editor.SelectedText)) {
$Value = $file.Editor.Text
}
} else {
Write-Error "No files opened in this tab!"
return
}
$Name = ($SnippetName -replace '[\\s+\\\\\\*\\?]', '_') + '.ps1'
New-Item -Force -ItemType file -Path (Join-Path $Path $Name) -Value $Value | Out-Null
}
Add-MyMenuItem New-Snippet 'Create new snippet from selection/ file'
function Show-Top {
PARAM (
[int]$Count = 20,
[int]$Sleep = 5,
[string]$Property = 'WS'
)
$TopTab = $psISE.PowerShellTabs.Add()
sleep 10
if ($TopTab.CanInvoke) {
$TopTab.DisplayName = "TOP$Count - $Property"
$psISE.PowerShellTabs.SetSelectedPowerShellTab($TopTab)
$TopTab.Invoke([scriptblock]::Create(@"
Register-WmiEvent -Query "SELECT * From Win32_ProcessStartTrace"
Register-WmiEvent -Query "SELECT * From Win32_ProcessStopTrace"
`$formaterS = "{0,10} {1,10} {2,10} {3,10} {4,10} {5,10} {6,10} {7,-30}"
`$formaterD = "{0,10} {1,10:N0} {2,10:N0} {3,10:N0} {4,10:N0} {5,10:N2} {6,10} {7,-30}"
while (`$true) {
function prompt {
`$psISE.PowerShellTabs.Remove(`$psISE.CurrentPowerShellTab)
}
Clear-Host
'TOP for PowerShell ISE - from ISEFun module'
'=' * 50
`$Processes = Get-Process
`$Started = @(Get-Event | where { `$_.SourceEventArgs.NewEvent.__Class -match 'Start' } | foreach { `$_.SourceEventArgs.NewEvent.ProcessID })
`$Stopped = @(Get-Event | where { `$_.SourceEventArgs.NewEvent.__Class -match 'Stop' } | foreach { `$_.SourceEventArgs.NewEvent.ProcessID })
`$Processes += `$DisplayedProcess | where { `$Stopped -contains `$_.Id }
`$Processes = `$Processes | sort -Descending $Property
`$DisplayedProcess = `$Processes | select -First $Count
`$formaterS -f `$('Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName'.Split())
`$formaterS -f `$(@('-' * 10) * 8)
foreach (`$process in `$DisplayedProcess) {
`$ProcessString = `$formaterD -f `$process.Handles, `$(`$process.NPM / 1KB), `$(`$process.PM/1KB), `$(`$process.WS / 1KB), `$(`$process.VM / 1MB), `$process.CPU, `$process.Id, `$(`$process.Name -replace '(^.{0,29}).*', '`$1')
if (`$Stopped -contains `$process.id) {
`$ProcessString + "==> PROCESS TERMINATED"
} elseif (`$Started -contains `$process.id) {
`$ProcessString + "<== NEW PROCESS ADDED"
} else {
`$ProcessString
}
}
Get-Event | Remove-Event
"Diplay $Count processes out of `$(`$Processes.Count)"
sleep $Sleep
}
"@))
}
}
Add-MyMenuItem Show-Top
function Edit-HelpExample {
<#
.Synopsis
Simple function to copy help examples (as useable code) and it's description (as comments) to empty file in ISE
.Description
If you want to see what examples are available for a given command - that function is for you.
It can easily get all examples in a way that you can just highlight them and get results back.
Only basic testing done, so probably something is still missing...
.Example
Get-HelpExample Get-ChildItem
Copies all 7 examples from Get-ChilItem cmdlet to empty file.
.Example
Get-HelpExample Get-HelpExample
If I did everything right you will probably see this command, text that I'm currently typing and anything above/ below in this section of function
#>
param (
# Name of the command that will be used to get examples
[Parameter(Mandatory = $true, HelpMessage = 'Name of the command that will be used to get examples')]
[ValidateScript( { (Get-Help $_).Examples.example })]
[string]$Name
)
if ($psISE) {
$Editor = $psISE.CurrentPowerShellTab.Files.Add().Editor
$Editor.InsertText("# Examples from help - $Name`n")
foreach ($example in (Get-Help $Name).Examples.example) {
$Editor.InsertText(@"
<# START :=> $(($example.title) -replace '-')
$(($example.remarks | select -ExpandProperty text | where { $_ }) -join "`n")
END :=> $(($example.title) -replace '-') #>
$(($example | select -ExpandProperty code) -replace '(?m:^C:(\\\\\\w*)+>)')
"@)
}
} else {
throw "You must use this function/ script in PowerShell ISE!"
}
}
Add-MyMenuItem Edit-HelpExample 'Edit Help Example'
# Next few lines are just garbage you get when you wanna be smart and create GUI in the script.
# Forgive me for adding this stuff here, I could probably compile it in some dll and skip this but...
# ... well - it gives impression that my module is bigger than it actually is. ;)
#
# Our form to change colours... :)
$handler_bClose_Click=
{
$Main.Hide()
}
$handler_bColor_Click=
{
$Dialog = New-Object Windows.Forms.ColorDialog -Property @{
Color = [drawing.color]::FromArgb($psISE.Options.TokenColors.Item($Combo.SelectedItem).ToString())
FullOpen = $true
}
if ($Dialog.ShowDialog() -eq 'OK') {
$psISE.Options.TokenColors.Item($Combo.SelectedItem) = [windows.media.color]::FromRgb($Dialog.Color.R, $Dialog.Color.G, $Dialog.Color.B)
$Combo.ForeColor = $Dialog.Color
}
}
$handler_selectedValue = {
$Combo.ForeColor = [drawing.color]::FromArgb($psISE.Options.TokenColors.Item($Combo.SelectedItem).ToString())
$bColor.Focus()
}
$OnLoadForm_StateCorrection = {
$Main.WindowState = $InitialFormWindowState
}
$Script:Main = New-Object Windows.Forms.Form -Property @{
Text = "Token colors selector"
MaximizeBox = $False
Name = "Main"
HelpButton = $True
MinimizeBox = $False
ClientSize = New-Object System.Drawing.Size 426, 36
}
$Main.DataBindings.DefaultDataSourceUpdateMode = 0
$Combo = New-Object Windows.Forms.ComboBox -Property @{
FormattingEnabled = $True
Size = New-Object System.Drawing.Size 239, 23
Name = "Combo"
Location = New-Object System.Drawing.Point 12, 7
Font = New-Object System.Drawing.Font("Lucida Console",11.25,0,3,238)
TabIndex = 4
DropDownStyle = 'DropDownList'
}
$Combo.DataBindings.DefaultDataSourceUpdateMode = 0
$Combo.Items.AddRange($psISE.Options.TokenColors.Keys)
$Combo.Add_SelectedValueChanged($handler_SelectedValue)
$InitialFormWindowState = New-Object Windows.Forms.FormWindowState
$bClose = New-Object Windows.Forms.Button -Property @{
TabIndex = 2
Name = "bClose"
Size = New-Object System.Drawing.Size 75, 23
UseVisualStyleBackColor = $True
Text = "Close"
Location = New-Object System.Drawing.Point 338, 7
}
$bClose.DataBindings.DefaultDataSourceUpdateMode = 0
$bClose.add_Click($handler_bClose_Click)
$bColor = New-Object Windows.Forms.Button -Property @{
TabIndex = 1
Name = "bColor"
Size = New-Object System.Drawing.Size 75, 23
UseVisualStyleBackColor = $True
Text = "Color"
Location = New-Object System.Drawing.Point 257, 7
}
$bColor.DataBindings.DefaultDataSourceUpdateMode = 0
$bColor.add_Click($handler_bColor_Click)
$Main.Controls.AddRange(@($bColor,$bClose,$Combo))
$InitialFormWindowState = $Main.WindowState
$Main.add_Load($OnLoadForm_StateCorrection)
$HelpMessage = @'
This GUI will help you change you token colors.
It's updating text color as you select tokens that you want to modify.
Button 'Color' opens up color dialog.
I won't describe actions performed by 'Close' button. I hope you are able to guess it... ;)
'@
$Main.add_HelpButtonClicked( { [void][windows.forms.MessageBox]::Show($HelpMessage,'Help','OK','Information')})
function Set-TokenColor {
<#
.Synopsis
GUI to add some Token Colors.
.Description
Really. It is just that. No more to it. Seriously!
OK. GUI is pretty smart. You can select tokens that are available, color will change and match the one you currently have. See for yourself. ;)
.Example
Can't show you click-click-click example :)
#>
$Script:Main.ShowDialog()| Out-Null
}
Add-MyMenuItem Set-TokenColor
function Expand-Alias {
<#
.Synopsis
Function to expand all command aliases in current script.
.Description
If you want to expand all aliases in a script/ module that you write in PowerShell ISE - this function will help you with that.
It's using Tokenizer to find all commands, Get-Alias to find aliases and their definition, and simply replace alias with command hidden by it.
.Example
Expand-Alias
#>
# Read in current file
if (!$psISE.CurrentFile) {
throw 'No files opened!'
}
if ( -not ($Script = $psISE.CurrentFile.Editor.Text) ) {
throw 'No code!'
}
$line = $psISE.CurrentFile.Editor.CaretLine
$column = $psISE.CurrentFile.Editor.CaretColumn
if ( -not ($commands = [System.Management.Automation.PsParser]::Tokenize($Script, [ref]$null) | Where-Object { $_.Type -eq 'Command' } | Sort-Object -Property Start -Descending) ) {
return
}
foreach ($command in $commands) {
if (Get-Alias $command.Content -ErrorAction SilentlyContinue) {
# $command
$psISE.CurrentFile.Editor.Select($command.StartLine, $command.StartColumn, $command.EndLine, $command.EndColumn)
$psISE.CurrentFile.Editor.InsertText($(Get-Alias $command.Content | Select-Object -ExpandProperty Definition))
}
}
$psISE.CurrentFile.Editor.SetCaretPosition($line, $column)
}
Add-MyMenuItem Expand-Alias
function Edit-Function {
<#
.Synopsis
Simpe function to edit functions in ISE.
.Description
Need to edit function on-the-fly? Want to see how a given function looks like to change it a bit and rename it?
Or maybe just preparing module and you want to change functions you define to make sure changes will work as expected?
Well, with Edit-Function, which is very simple (thank you PowerShell team!) you can do it. :)
.Example
Edit-Function Edit-Function
Description
-----------
You can open any function that exists in your current session, including the function that you reading help to now.
Be careful with that one though. If you change it in wrong direction you may not be able to open it again and fix it.
At least not in the way you could originaly, with Edit-Function. :)
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,HelpMessage='Function name is mandatory parameter.')]
[ValidateScript({Get-Command -CommandType function $_})]
[string]
$Name
)
if (!$psISE) {
Throw 'Implemented for PowerShell ISE only!'
}
$file = $psISE.CurrentPowerShellTab.Files.Add()
$file.Editor.InsertText("function $name {`n")
$file.Editor.InsertText($(Get-Command -CommandType function $name | Select-Object -ExpandProperty definition))
$file.Editor.InsertText("}")
}
Add-MyMenuItem Edit-Function
function Copy-HistoryItem {
<#
.Synopsis
Function build using WPK to give you functionality similar to one you already have in PowerShell.exe
.Description
Display you command history and let you choose from it. Copies selected command to you commandPane.
.Example
Copy-HistoryItem
GUI, so it's not easy to show examples...
#>
try {
New-Window -Width 800 -Height 100 {
New-ListBox -On_PreviewMouseDoubleClick {
$psISE.CurrentPowerShellTab.CommandPane.InsertText($this.SelectedValue)
$this.parent.close()
} -Items $(Get-History | Select-Object -ExpandProperty CommandLine)
} -Show
} catch {
throw 'Requires WPK to work, will be rewritten soon...'
}
}
Add-MyMenuItem Copy-HistoryItem 'Copy item from History' F7
function Invoke-CurrentLine {
$Editor = $psISE.CurrentFile.Editor
$row = $Editor.CaretLine
$col = $Editor.CaretColumn
$Editor.Select($row, 1, $col, $Editor.GetLineLength($row) + 1)
[scriptblock]::Create($Editor.SelectedText).Invoke()
$Editor.SetCaretPosition($row,$col)
}
Add-MyMenuItem Invoke-CurrentLine 'Invoke Current Line' F9
New-Alias -Name edfun -Value Edit-Function
New-Alias -Name expa -Value Expand-Alias
New-Alias -Name cphi -Value Copy-HistoryItem
Export-ModuleMember -Function * -Alias *
# Get rid off menu if module is going to be unloaded.
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
[void]$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Remove($MyISEMenu)
}
|
PowerShellCorpus/PoshCode/Start-ComputerJobs_2.ps1
|
Start-ComputerJobs_2.ps1
|
#requires -version 2.0
function Start-ComputerJobs{
<#
.NOTES
Name: Start-ComputerJobs
Author: Tome Tanasovski
Created: 6/25/2010
Modified: 6/25/2010
Version: 1.2
Website: http://powertoe.wordpress.com
.SYNOPSIS
Multithreads a scriptblock with jobs
.DESCRIPTION
The Start-ComputerJobs cmdlet runs a specified scriptblock within a maximum number of simultaneously spawned Powershell jobs.
You must pass a list of ComputerNames to it. The names passed to the cmdlet will replace $computername within the scriptblock prior to starting each thread.
This can be thought of as a multithreaded approach to a foreach loop.
.PARAMETER ComputerName
Specifies a list of computers that you wish to inject into your scriptblock. The list of computer names will replace $computername in the script block. This does not actually need to be a list of computer names. It can be anything you wish to inject into your scriptblock.
.PARAMETER ScriptBlock
Specifies the commands to run in the background jobs. Enclose the commands in braces ({}) or use $ExecutionContext.InvokeCommand.NewScriptBlock to create a scriptblock.
The scriptblock must contain a $computername variable. $computername will be replaced by each entry into the pipeline or from the parameter ComputerName.
.PARAMETER Threads
Specifies the maximum number of jobs that can be simultaneously running at any given time.
This defaults to 10 if nothing is specified.
.PARAMETER Sleep
Specifies the amount of time in seconds to sleep before querying the active jobs. This defaults to 5 seconds. If your jobs are long running you will want to increase this number. If they are very quick to run you may want to decrease this number.
.EXAMPLE
$computers = "computer1","computer2","computer3","computer4","computer5"
Start-ComputerJobs -computername $computers -ScriptBlock {dir \\\\$computername\\c$}
Queries the share for each computer in the computer list. This will spawn the default 5 jobs at once with a 5 second pause between querying the jobs.
.EXAMPLE
Get-Content computerlist.txt |Start-ComputerJobs -ScriptBlock {Get-Service -ComputerName $computername} -Threads 3 -Sleep 10 -Verbose
Reads a list of computers from a file named computerlist.txt. For each computer listed it will return the results from get-service. It will do this with three simultaneous jobs and will sleep 10 seconds between querying the jobs. Verbose will tell you when each job has been launced.
.INPUTS
System.String
.OUTPUTS
PSObject
Returns the results of the commands in the job. It is the data returned from receive-job. If you're scriptblock contains write-host it will write that to the console as it is running. To avoid this you should just return objects within your scriptblock. i.e. Instead of write-host "text" just use "text"
#>
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName,
[Parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock,
[Parameter(Mandatory=$false)]
[ValidateScript({$_ -gt 0})]
[int32]$Threads = 10,
[Parameter(Mandatory=$false)]
[ValidateScript({$_ -gt 0})]
[int32]$Sleep = 5
)
BEGIN {
$firstrun = $true
$computers = @()
$curthreads = 0
$jobs = @()
$valid = $false
}
PROCESS {
if ($firstrun) {
$firstrun = $false
# Validate scriptblock - Making sure it has a $computername variable to use
if ($ScriptBlock -match '\\$computername') {
$valid = $true
} else {
Write-Error 'You must specify a scriptblock that contains a variable called $computername'
$valid = $false
}
}
if ($valid) {
foreach ($computer in $computername) {
while ($jobs.count -eq $Threads) {
$newjobs = @()
$jobs |foreach {
Receive-Job $_.id
if ($_.state -eq "Running" -or $_.HasMoreData) {
$newjobs += $_
}
else {
$_ |Remove-Job
}
}
$jobs = $newjobs
if ($jobs.count -eq $Threads) {
sleep $sleep
}
}
$runscript = $ExecutionContext.InvokeCommand.NewScriptBlock(($ScriptBlock -replace '\\$computername', "$computer"))
Write-Verbose "Starting Job for computer: $computer"
$jobs += Start-Job -ScriptBlock $runscript
$curthreads++
}
}
}
END {
while ($jobs.count -ne 0) {
$newjobs = @()
$jobs |foreach {
Receive-Job $_.id
if ($_.state -eq "Running" -or $_.HasMoreData) {
$newjobs += $_
}
else {
$_ |Remove-Job
}
}
$jobs = $newjobs
if ($jobs.count -gt 0) {
sleep $sleep
}
}
}
}
|
PowerShellCorpus/PoshCode/archive.ps1
|
archive.ps1
|
$rootDir = 'C:\\Documents and Settings\\buddyl\\My Documents\\Powershell Scripts\\';
$temp = $rootDir + 'temp'
mkdir $temp
$tempDir = $temp + '\\'
$targetFolder1 = $rootDir + 'test'
$zip1 = $tempDir + 'test1.zip'
gi $targetFolder1 | out-zip $zip1 $_
$targetFolder2 = $rootDir + 'test2'
$zip2 = $tempDir + 'test2.zip'
gi $targetFolder2 | out-zip $zip2 $_
$day = (Get-Date).get_day();
$month = (Get-Date).get_Month();
$year = (Get-Date).get_Year();
$date = $month.ToString() + "-" + $day.ToString() + "-" + $year.ToString();
$file = $rootDir + 'backup' + $date + '.zip'
gi $temp | out-zip $file $_
rmdir $temp -r
|
PowerShellCorpus/PoshCode/Get-QADGroupNesting_1.ps1
|
Get-QADGroupNesting_1.ps1
|
Param (
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
HelpMessage="DN or ObjectGUID of the AD Group."
)]
[string]$groupIdentity,
[switch]$showTree
)
#Validate Quest PSSnapin is loaded
Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
$global:numberOfRecursiveGroupMemberships = 0
$lastGroupAtALevelFlags = @()
function Get-GroupNesting ([string] $identity, [int] $level, [hashtable] $groupsVisitedBeforeThisOne, [bool] $lastGroupOfTheLevel)
{
$group = $null
$group = Get-QADGroup -Identity $identity -SizeLimit 0
if($lastGroupAtALevelFlags.Count -le $level)
{
$lastGroupAtALevelFlags = $lastGroupAtALevelFlags + 0
}
if($group -ne $null)
{
if($showTree)
{
for($i = 0; $i -lt $level - 1; $i++)
{
if($lastGroupAtALevelFlags[$i] -ne 0)
{
Write-Host -ForegroundColor Blue -NoNewline " "
}
else
{
Write-Host -ForegroundColor Blue -NoNewline "│ "
}
}
if($level -ne 0)
{
if($lastGroupOfTheLevel)
{
Write-Host -ForegroundColor Blue -NoNewline "└─"
}
else
{
Write-Host -ForegroundColor Blue -NoNewline "├─"
}
}
Write-Host -ForegroundColor Blue $group.Name
}
$groupsVisitedBeforeThisOne.Add($group.DN,$null)
$global:numberOfRecursiveGroupMemberships ++
$groupMemberShipCount = $group.memberOf.Count
if ($groupMemberShipCount -gt 0)
{
$maxMemberGroupLevel = 0
$count = 0
foreach($groupDN in $group.memberOf)
{
$count++
$lastGroupOfThisLevel = $false
if($count -eq $groupMemberShipCount){$lastGroupOfThisLevel = $true; $lastGroupAtALevelFlags[$level] = 1}
if(-not $groupsVisitedBeforeThisOne.Contains($groupDN)) #prevent cyclic dependancies
{
$memberGroupLevel = Get-GroupNesting -Identity $groupDN -Level $($level+1) -GroupsVisitedBeforeThisOne $groupsVisitedBeforeThisOne -lastGroupOfTheLevel $lastGroupOfThisLevel
if ($memberGroupLevel -gt $maxMemberGroupLevel){$maxMemberGroupLevel = $memberGroupLevel}
}
}
$level = $maxMemberGroupLevel
}
else #we've reached the top level group, return it's height
{
return $level
}
return $level
}
}
$global:numberOfRecursiveGroupMemberships = 0
$groupObj = Get-QADGroup -Identity $groupIdentity -SizeLimit 0
if($groupObj)
{
[int]$maxNestingLevel = Get-GroupNesting -Identity $groupIdentity -Level 0 -GroupsVisitedBeforeThisOne @{} -lastGroupOfTheLevel $false
Add-Member -InputObject $groupObj -MemberType NoteProperty -Name MaxNestingLevel -Value $maxNestingLevel -Force
Add-Member -InputObject $groupObj -MemberType NoteProperty -Name NestedGroupMembershipCount -Value $($global:numberOfRecursiveGroupMemberships - 1) -Force
$groupObj | Select-Object Name,DN,MaxNestingLevel,NestedGroupMembershipCount | Format-List
}
|
PowerShellCorpus/PoshCode/Remove local profiles.ps1
|
Remove local profiles.ps1
|
<#
.SYNOPSIS
This is a powershell script form to remove a users local profile from a workstation and
and gives the option to remove the users profile fromt he network.
.DESCRIPTION
This script askes for a machine name.
It displays all of the roaming profiles on that machine.
The administrator selects the profile to be removed from the machine.
The administrator selects whether the network profile is to be removed as well.
The administrator clicks the delete button and the script removes the local profile
and the network profile if the option was seleteced.
.NOTES
This script must be run as with adminstrator credentials.
Created: 08/03/13
#>
CLS
Import-Module ActiveDirectory
# Define Variables
$global:Workstation = ""
function CheckCredentials
{
# Check Credentials
$Credential = ([Security.Principal.WindowsIdentity]::GetCurrent()).Name
$CredentialTest = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if($CredentialTest -eq $false)
{
[System.Windows.Forms.MessageBox]::Show("You are not an Administrator.`n`nPlease run the script with `nAdministrator credentials." , "Not an Administrator!" , 0)
$objForm.Close()
}
}
function TestWMIConnection
{
# Test WMI Connection and update label
if(!(Get-WmiObject -class "Win32_Process" -namespace "root\\cimv2" -ComputerName $Workstation -ErrorAction SilentlyContinue))
{
$WMIConnectionLabel.ForeColor = "Red"
$WMIConnectionLabel.Text = "WMI Connection to device is DOWN."
}
else
{
$WMIConnectionLabel.ForeColor = "Green"
$WMIConnectionLabel.Text = "WMI Connection to device is OK."
}
}
function GetLocalProfiles
{
$ProfilesFoundListBox.Items.Clear()
$ProfileDetailsRichTextBox.Text = ""
$Profiles = ""
$Profiles = @(Get-WmiObject -Class Win32_UserProfile -ComputerName $Workstation -ErrorAction SilentlyContinue | ?{$_.Status -eq "2"})
# Profile Status values are (0, 1, 2, 4, 8) where a value of zero denotes unset or default
# and 1 = Temporary, 2 = Roaming, 4 = Mandatory and 8 = Corrupted.
foreach($Profile in $Profiles)
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($Profile.sid)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$Profilename = $objUser.value.split("\\")[1]
$ProfilesFoundListBox.Items.Add($Profilename.ToUpper())
$objForm.Update()
}
}
function GetProfileDetails
{
# Get AD Account Info
$ADInfo = ""
$LocalProfile = ""
$ADUserID = Get-ADUser -Identity $ProfilesFoundListBox.SelectedItem -Properties *
$ProfileInfo = "Active Directory Details:"
$ProfileInfo = $ProfileInfo + "`nName : " + $ADUserID.displayNamePrintable
$ProfileInfo = $ProfileInfo + "`nOffice : " + $ADUserID.Office
$ProfileInfo = $ProfileInfo + "`nStaff ID: " + $ADUserID.EmployeeID
$ProfileInfo = $ProfileInfo + "`nProfile : " + $ADUserID.ProfilePath
# Get Local Profile Info
$LocalProfile = Get-WmiObject -Class Win32_UserProfile -ComputerName $Workstation -ErrorAction SilentlyContinue | ?{$_.LocalPath -like "*" + $ProfilesFoundListBox.SelectedItem}
try
{
$LastDownloadTime = $LocalProfile.ConvertToDateTime($LocalProfile.LastDownloadTime).ToShortDateString()
}
catch
{
$LastDownloadTime = "Never Downloaded"
}
$LastUsedTime = $LocalProfile.ConvertToDateTime($LocalProfile.LastUseTime).ToShortDateString()
$ProfileInfo = $ProfileInfo + "`n`nLocal Profile Details:"
$ProfileInfo = $ProfileInfo + "`nProfile Path : " + $LocalProfile.LocalPath
$ProfileInfo = $ProfileInfo + "`nLast Download : " + $LastDownloadTime
$ProfileInfo = $ProfileInfo + "`nLast Used : " + $LastUsedTime
$ProfileInfo = $ProfileInfo + "`nIs Loaded : " + $LocalProfile.Loaded
$ProfileDetailsRichTextBox.Text = $ProfileInfo
if($LocalProfile.Loaded -eq $true)
{
[System.Windows.Forms.MessageBox]::Show("The selected profile is currently loaded.`nThe profile will need to be logged off.", "Profile Loaded" , 0)
}
}
function DeleteLocalProfile
{
$ConfirmDelete = [System.Windows.Forms.MessageBox]::Show("CONFIRM`n`nDelete local profile : " + $ProfilesFoundListBox.SelectedItem + "`nFrom Workstation : " + $Workstation.ToUpper() , "Local Profile Delete" , 4)
if ($ConfirmDelete -eq "YES")
{
Get-WmiObject -Class Win32_UserProfile -ComputerName $Workstation -ErrorAction SilentlyContinue | ?{$_.LocalPath -like "*" + $ProfilesFoundListBox.SelectedItem} | Remove-WmiObject
[System.Windows.Forms.MessageBox]::Show("Profile "+ $ProfilesFoundListBox.SelectedItem + " has been deleted from " + $Workstation + ".", "Profile Deleted" , 0)
}
}
function DeleteNetworkProfile
{
$ADUserID = Get-ADUser -Identity $ProfilesFoundListBox.SelectedItem -Properties *
$ConfirmDelete = [System.Windows.Forms.MessageBox]::Show("CONFIRM`n`nDelete network profile : " + $ADUserID.displayNamePrintable + "`nPath : " + $ADUserID.ProfilePath , "Network Profile Delete" , 4)
if ($ConfirmDelete -eq "YES")
{
$NetProfile = $ADUserID.ProfilePath
$NetProfile = [string]::Join('\\', $NetProfile.Split('\\')[0..$($NetProfile.Split('\\').Length-2)])
Remove-Item $NetProfile -Recurse -Force
[System.Windows.Forms.MessageBox]::Show("Network profile has been deleted.`n" + "Path : " + $NetProfile , "Profile Deleted" , 0)
}
else
{
$objForm.Close()
}
}
Function BuildForm
{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Windows.Forms.Application]::EnableVisualStyles()
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Remove Profile Tool"
$objForm.Icon = [system.drawing.icon]::ExtractAssociatedIcon($PsHome + "\\powershell.exe")
$objForm.Size = New-Object System.Drawing.Size(550,500)
$objForm.StartPosition = "CenterScreen"
$objForm.AutoSize = $True
$objForm.AutoSizeMode = "GrowOnly" # GrowAndShrink or GrowOnly
$objForm.AutoScroll = $True
$objForm.MinimizeBox = $true
$objForm.MaximizeBox = $False
$objForm.WindowState = "Normal" # Maximized, Minimized, Normal
$objForm.SizeGripStyle = "Hide" # Auto, Hide, Show
$objForm.ShowInTaskbar = $true
$objForm.Topmost = $True
$objFormFont1 = New-Object System.Drawing.Font("Arial",24,[System.Drawing.FontStyle]::Regular) # Form title font
$objFormFont2 = New-Object System.Drawing.Font("Arial",10,[System.Drawing.FontStyle]::Regular) # Form font
$objFormFont3 = New-Object System.Drawing.Font("Consolas",10,[System.Drawing.FontStyle]::Regular) # Fixed width font
# $objFormFont3 = New-Object System.Drawing.Font("Lucida Console",10,[System.Drawing.FontStyle]::Regular) # Second fixed width font
# Font styles are: Regular, Bold, Italic, Underline, Strikeout
$objForm.Font = $objFormFont2 # Applies font to whole form
$objForm.KeyPreview = $True
# $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter"){$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape"){$objForm.Close()}})
# Form Objects
# Check Credentials
CheckCredentials
#Form Title
$FormTitleLabel = New-Object System.Windows.Forms.Label
$FormTitleLabel.Location = New-Object System.Drawing.Size(10,10)
$FormTitleLabel.Autosize = $true # = New-Object System.Drawing.Size(650,40)
$FormTitleLabel.Font = $objFormFont1
$FormTitleLabel.Text = "Profile Removal Tool"
$objForm.Controls.Add($FormTitleLabel)
#Get Workstation Name
$GetWorkstationNameLabel = New-Object System.Windows.Forms.Label
$GetWorkstationNameLabel.Location = New-Object System.Drawing.Size(10,70)
$GetWorkstationNameLabel.Size = New-Object System.Drawing.Size(140,20)
$GetWorkstationNameLabel.Text = "Enter Machine Name"
$objForm.Controls.Add($GetWorkstationNameLabel)
$GetWorkstationNameTextBox = New-Object System.Windows.Forms.TextBox
$GetWorkstationNameTextBox.Location = New-Object System.Drawing.Size(155,69) # Count as (160,70) -1 to align text box
$GetWorkstationNameTextBox.Size = New-Object System.Drawing.Size(140,20)
$objForm.Controls.Add($GetWorkstationNameTextBox)
$GetWorkstationNameButton = New-Object System.Windows.Forms.Button
$GetWorkstationNameButton.Location = New-Object System.Drawing.Size(305,69) # Count as (305,70) -1 to align button
$GetWorkstationNameButton.Size = New-Object System.Drawing.Size(75,23)
$GetWorkstationNameButton.Text = "OK"
$GetWorkstationNameButton.Add_Click(
{
$Workstation = $GetWorkstationNameTextBox.Text.ToUpper()
# Update profiles found label
$ProfilesFoundLabel.Text = "Profiles found on " + $Workstation
$objForm.Controls.Add($ProfilesFoundLabel)
# Test WMI Connection
TestWMIConnection
# Get local profiles
GetLocalProfiles
})
$objForm.Controls.Add($GetWorkstationNameButton)
#WMI Connection Status
$WMIConnectionLabel = New-Object System.Windows.Forms.Label
$WMIConnectionLabel.Location = New-Object System.Drawing.Size(10,115)
$WMIConnectionLabel.Size = New-Object System.Drawing.Size(280,20)
$WMIConnectionLabel.Text = "WMI Connection to device is..."
$objForm.Controls.Add($WMIConnectionLabel)
# Found Profiles
$ProfilesFoundLabel = New-Object System.Windows.Forms.Label
$ProfilesFoundLabel.Location = New-Object System.Drawing.Size(10,150)
$ProfilesFoundLabel.Size = New-Object System.Drawing.Size(280,20)
$ProfilesFoundLabel.Text = "Profiles found on..."
$objForm.Controls.Add($ProfilesFoundLabel)
$ProfilesFoundListBox = New-Object System.Windows.Forms.ListBox
$ProfilesFoundListBox.Location = New-Object System.Drawing.Size(10,180)
$ProfilesFoundListBox.Size = New-Object System.Drawing.Size(280,200)
$ProfilesFoundListBox.Text = "Found Profiles"
$ProfilesFoundListBox.Add_Click(
{
GetProfileDetails
})
$objForm.Controls.Add($ProfilesFoundListBox)
# Profile Details
$ProfileDetailsLabel = New-Object System.Windows.Forms.Label
$ProfileDetailsLabel.Location = New-Object System.Drawing.Size(305,150)
$ProfileDetailsLabel.Size = New-Object System.Drawing.Size(280,20)
$ProfileDetailsLabel.Text = "Profile Details"
$objForm.Controls.Add($ProfileDetailsLabel)
$ProfileDetailsRichTextBox = New-Object System.Windows.Forms.RichTextBox
$ProfileDetailsRichTextBox.Location = New-Object System.Drawing.Size(305,180)
$ProfileDetailsRichTextBox.Size = New-Object System.Drawing.Size(280,200)
$ProfileDetailsRichTextBox.Font = $objFormFont3
$ProfileDetailsRichTextBox.ForeColor = "DarkGreen"
$objForm.Controls.Add($ProfileDetailsRichTextBox)
# Delete network profile checkbox
$DeleteNetProfileCheckBox = New-Object System.Windows.Forms.CheckBox
$DeleteNetProfileCheckBox.Location = New-Object System.Drawing.Size(10,390)
$DeleteNetProfileCheckBox.Size = New-Object System.Drawing.Size(280,20)
$DeleteNetProfileCheckBox.Text = "Include Network Profile in Delete"
$DeleteNetProfileCheckBox.ForeColor = "Red"
$objForm.Controls.Add($DeleteNetProfileCheckBox)
# Delete button
$DeleteButton = New-Object System.Windows.Forms.Button
$DeleteButton.Location = New-Object System.Drawing.Size(10,430)
$DeleteButton.Size = New-Object System.Drawing.Size(135,23)
$DeleteButton.Text = "Delete"
$DeleteButton.BackColor = "Red"
$DeleteButton.Forecolor = "White"
$DeleteButton.Add_Click(
{
DeleteLocalProfile
if($DeleteNetProfileCheckBox.Checked)
{
DeleteNetworkProfile
}
# Update profile info
GetLocalProfiles
})
$objForm.Controls.Add($DeleteButton)
$ExitButton = New-Object System.Windows.Forms.Button
$ExitButton.Location = New-Object System.Drawing.Size(155,430)
$ExitButton.Size = New-Object System.Drawing.Size(135,23)
$ExitButton.Text = "Exit"
$ExitButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($ExitButton)
# Status Line
$StatusLineLabel = New-Object System.Windows.Forms.Label
$StatusLineLabel.Location = New-Object System.Drawing.Size(415,430)
$StatusLineLabel.Size = New-Object System.Drawing.Size(180,40)
$StatusLineLabel.Text = "Version : 2.02"
$objForm.Controls.Add($StatusLineLabel)
# Show Form
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
} # End Function
# Application Start
BuildForm
|
PowerShellCorpus/PoshCode/Set-FileWriteable.ps1
|
Set-FileWriteable.ps1
|
function Set-FileWriteable {
#.Example
# $s = New-PSSession $ComputerName
# C:\\PS>$files = Invoke-Command $s { ls }
# ....
# C:\\PS>Set-FileWriteable $files
#
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$File
,
[switch]$Passthru
)
process {
foreach($path in @($file)) {
write-verbose "'$path' is on '$($path.PSComputerName)'"
if($path.PSComputerName) {
Invoke-Command $path.PSComputerName {
param([string[]]$path,[switch]$passthru)
$files = Get-Item $path
foreach($f in $files) {
if($f.Attributes -band [IO.FileAttributes]"ReadOnly") {
$f.Attributes = $f.Attributes -bxor [IO.FileAttributes]"ReadOnly"
}
}
write-output $files
} -Argument $path | Where { $Passthru }
} else {
$files = Get-Item $path
foreach($f in $files) {
if($f.Attributes -band [IO.FileAttributes]"ReadOnly") {
$f.Attributes = $f.Attributes -bxor [IO.FileAttributes]"ReadOnly"
}
}
if($Passthru) { write-output $files }
}
}
}
}
|
PowerShellCorpus/PoshCode/DirToday Extended.ps1
|
DirToday Extended.ps1
|
## NAME: Get-Dirty.ps1
## AUTHOR: Barry Morrison
## LASTEDIT: 07/05/2011 16:18:33
<#
.Synopsis
Get's files from today's date. Will also return narrowed results based on keyword
.Description
Get's files from today's date. Will also return narrowed results based on keyword
.Parameter Path
Will run in current directory. Path argument will allow you to define a path not in current working directory
.Parameter Keyword
Keyword argument will allow you to define a keyword to search on to narrow results.
.Example
PS C:\\scripts> .\\dirtoday.ps1
Directory: C:\\scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/5/2011 3:25 PM 114 cat
-a--- 7/5/2011 4:11 PM 2252 dirtoday.ps1
-a--- 7/5/2011 3:46 PM 848 dirtoday2.ps1
-a--- 7/5/2011 2:55 PM 110 info.txt
-a--- 7/5/2011 1:52 PM 37 test.foo
.Example
PS C:\\scripts> .\\dirtoday.ps1 -path "c:\\Users\\John Doe\\Pictures"
Directory: C:\\Users\\John Doe\\Pictures
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 7/5/2011 11:05 AM 49888 weinerdog.jpg
.Example
PS C:\\scripts> .\\dirtoday.ps1 -keyword foo
cat:2:test.foo:1:blah, blah, foo, ice cream,
test.foo:1:blah, blah, foo, ice cream,
#>
param(
[string]$Path = "",
[string]$keyword = ""
)
## Checking to see if the Keyword argument is passed -- If it is, search for $keyword
if ($keyword) {
$files = dir -Path $path | Where-Object { $_.lastwritetime -ge (get-date).date } | Select-String $keyword
## If there are not results returned, tell me!
if (!$files) {
Write-Output "Nothing Here"
}else{
## If Results exist, give them to me!
$files
}
} else {
## If not keyword argument is passed, do a simple search
$files = dir -Path $path | Where-Object { $_.lastwritetime -ge (get-date).date }
## Like above, checking to see if no results are found for the query
if (!$files) {
## Tell me if nothing exists
Write-Output "Nothing Here"
}else{
## Write results if something exists
$files
}
}
|
PowerShellCorpus/PoshCode/Get-ADGroupMembers_5.ps1
|
Get-ADGroupMembers_5.ps1
|
Function Get-ADGroupMembers
{
<#
.SYNOPSIS
Return a collection of users in an ActiveDirectory group.
.DESCRIPTION
This function returns an object that contains all the properties of a user object. This function
works for small groups as well as groups in excess of 1000.
.PARAMETER UserGroup
The name of the group to get membership from.
.PARAMETER UserDomain
The LDAP URL of the domain that the group resides in.
.EXAMPLE
Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn
name distinguishedName cn
---- ----------------- --
{Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts}
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple}
...
Description
-----------
This example shows passing in a group name, but leaving the default domain name in place.
.NOTES
The context under which this script is run must have rights to pull infromation from ActiveDirectory.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers
#>
Param
(
$UserGroup = "Domain Users",
[ADSI]$UserDomain = ("LDAP://DC=company,DC=com")
)
Begin
{
$DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path)
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))"
$DirectorySearcher.SearchRoot = $DirectoryEntry
$DirectorySearcher.PageSize = 1000
$DirectorySearcher.Filter = $LDAPFilter
$DirectorySearcher.SearchScope = "Subtree"
$SearchResult = $DirectorySearcher.FindAll()
$UserAccounts = @()
}
Process
{
foreach ($Item in $SearchResult)
{
$Group = $Item.GetDirectoryEntry()
$Members = $Group.member
If ($Members -ne $Null)
{
foreach ($User in $Members)
{
$UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)")
If ($UserObject.objectCategory.Value.Contains("Group"))
{
}
Else
{
$ThisUser = New-Object -TypeName PSObject -Property @{
cn = $UserObject.cn
distinguishedName = $UserObject.distinguishedName
name = $UserObject.name
nTSecurityDescriptor = $UserObject.nTSecurityDescriptor
objectCategory = $UserObject.objectCategory
objectClass = $UserObject.objectClass
objectGUID = $UserObject.objectGUID
objectSID = $UserObject.objectSID
showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly
}
}
$UserAccounts += $ThisUser
}
}
}
}
End
{
Return $UserAccounts
}
}
|
PowerShellCorpus/PoshCode/get-kbinfo.ps1
|
get-kbinfo.ps1
|
# -==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Author: Kris Cieslak (defaultset.blogspot.com)
# Date: 2010-05-26
# Description: Identifying knowledge base article by id number taken from
# string or filename.
#
# Parameters: filename / knowledge base number
#
# Requirements: Internet connection
#
# Usage example:
# ./get-kbinfo.ps1 KB926139
# or
# ./get-kbinfo.ps1 WindowsXP-KB926139-x86-ENU.exe
# or
# ls Windows* | % { ./get-kbinfo.ps1 $_.Name }
#
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=--=-=-=-=-=-=-=-=-=-=
PARAM ($filename = $(throw "Specifiy the file name"))
$page = New-Object System.Net.WebClient;
$kb = [regex]::match($filename,'KB\\d*|kb\\d*').ToString();
$p = $page.DownloadString('http://support.microsoft.com/kb/'+$kb)
$p = [regex]::replace( [regex]::match($p,'<h1 class="title">.*</h1>').ToString(), '<h1 class="title">|</h1>', '' )
write-host -Fore Yellow `n'[*] Filename: '$filename
write-host `n' '$p `n' ( http://support.microsoft.com/kb/'$kb' )'`n
|
PowerShellCorpus/PoshCode/ServicePWChgReset.ps1
|
ServicePWChgReset.ps1
|
# ==============================================================================================
#
# NAME: ServicePWChgReset.ps1
#
# AUTHOR: Saehrig, Steven
# DATE : 8/26/2008
#
@@# COMMENT: Please read comments on each section!
# 1st - Search Domain computers for matching name and import into array.
# 2nd - Export matching hosts from array to text file. (comment out after text file created)
# 3rd - Create CSV file of all Matching Critera with full service detail. ( so you have record of modified
# services)
# 4th - Create text file of all matching services with limited info
# 5th - Change password on matching services
# 6th - Restart services if running if not running skip restart. (with console feedback)
#
# I would like to Thank Halr9000 and glnsize from powershellcomunity.org for there guidance during this
# script creation. I would not have been able to complete this without them and i would have been spending
# alot of time manually updating every service. Granted if they actually wrote this it would be much nicer :).
# But hey everyone has to start somewhere.
# ==============================================================================================
#discover Servers for Host.txt file
function func_Forest()
{
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Domains | ForEach-Object {
Get-QADComputer -Service $_.Name -SizeLimit 0 -ErrorAction SilentlyContinue `
| Add-Member -Name 'DomainName' -MemberType NoteProperty -Value $_.Name -PassThru
}
}
#initialize Array for Output
$Array = @()
#This should be run once to fill the host file then commented out.
#Fill Array
func_forest | where { $_.Name -like 'jxr*' } | Sort-Object -property "Name" |? { $array += $_.name}
$file = $array | Out-File -FilePath c:\\txt\\host.txt -Append
#Variables
$StartName = "username"
$csvlocation = "c:\\txt\\service.csv"
$txtlocation = "c:\\txt\\service.txt"
$computer = gc c:\\txt\\host.txt
$password = "password"
$service = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
#exports discovered services for documentation of modified services
$service | Export-Csv $csvlocation
#Function Declarations
function exporttxt { #This function exports the services to a text file in limited data fields.
foreach ($i in $service) {
($i | FT systemname, Displayname, State, Startname, Status | Out-File -Append -FilePath $txtlocation )
}
}
function changepw { #This function will change the password to the variable assigned above.
foreach ($i in $service) {
(Write-Host -ForegroundColor "Yellow" "Changing password on" $i.SystemName "Service Name"$i.Name)
($i.Change($Null,$Null,$Null,$Null,$Null,$Null,$Null,$password))
(Write-Host -ForegroundColor "green" "Password Successfully Changed on" $i.SystemName "Service Name"$i.Name)
}
}
function restartsvc { #This function will restart the service for the new password to take effect.
$s = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
foreach ($i in $s) {
if ($i.State -eq "running") {
Write-Host -ForegroundColor "Yellow" "Service name" $i.SystemName "Service name"$i.Name "is" $i.state
$i.StopService()
Sleep -Seconds 20 #allow time for service to stop.
$b = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
Write-Host -ForegroundColor "RED" "Service name" $b.SystemName "Service name" $b.Name "is" $b.state
$i.StartService()
$c = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
Write-Host -ForegroundColor "Green" "Server name" $c.SystemName "Service name" $c.Name "is" $c.state }
elseif ($i.State -eq "Stopped") {
Write-Host -ForegroundColor "RED" "Service name" $i.SystemName "Service name" $i.Name $i.state "Service will not be Started" }
}
}
#Execute
exporttxt
changepw | out-null
restartsvc | out-null
|
PowerShellCorpus/PoshCode/chkhash_30.ps1
|
chkhash_30.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling
{ # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done
# before printing anything else, so that you are not printing into a long file name with extra characters from it visible.
if ($Host.Name -match 'ise')
{ write-host $writestr; return }
if ($global:lastlen -eq $null) {$global:lastlen=0}
$ctop=[console]::cursortop
[console]::cursorleft=0
$oldwritestrlen=$writestr.length
$spaces = ""
if ($global:lastlen -gt $writestr.length)
{
$spaces = " " * ($global:lastlen-$writestr.length)
}
$writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null)
$cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to.
if ($cwe -gt 0) {$ctop-=($cwe)}
write-host "$writestr" -nonewline
$global:oldctop=[console]::cursortop
if ([console]::cursorleft -ne 0) {$global:oldctop+=1}
write-host "$spaces" -nonewline
$global:lastlen = $oldwritestrlen
[console]::cursortop=$ctop
[console]::cursorleft=0
}
function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other
{ # and before printing something else
if ($Host.Name -match 'ise')
{ return }
if ($global:oldctop -ne $null)
{
[console]::cursortop=$global:oldctop
[console]::cursorleft=0
}
$global:oldctop=$null
$global:lastlen=$null
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
$n = $null
"ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, "
"in order to detect corrupt or hacked files."
""
".\\chkhash.ps1 -h for usage."
""
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files, minus directories and minus files in excluded paths
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
if ($files.count -eq 0) {"No files found. Exiting."; exit}
$files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
WriteFileNameEnd
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if (($xfiles.count -eq 0) -or ($files.count -eq 0)) {"No files in Database or no files specified. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles | %{get-item -ea 0 -literalpath $_.fullname}
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {WriteFileName "Needs to be added: `"$($f.fullname)`"";WriteFileNameEnd;continue} # if not updating, then continue
WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..."
$fc++ # File checked increment.
if (($upd -eq $false) -and ($f.length -ne $xfiles[$n].length))
{
$errs++
WriteFileName "Size mixmatch: `"$($f.fullname)`""; WriteFileNameEnd
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
# Check SHA512 and size for mixmatch.
if ($xfiles[$n].length -eq $f.length)
{
if ($xfiles[$n].SHA512 -eq $f.SHA512)
{
$fm++;continue # if matched, increment file matches and continue loop
}
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; WriteFileName "Updated `"$($f.fullname)`""; WriteFileNameEnd;continue}
WriteFileName "SHA-512 and/or size mixmatch found: `"$($f.fullname)`""; WriteFileNameEnd
}
WriteFileNameEnd # restore cursor position after last write string
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated Database: $hashespath"
"$nu file hash(es) added to Database."
"$errs file hash(es) updated in Database."
exit
}
"$errs SHA-512 or size mixmatch(es) found."
"$fm file(s) SHA512 and size matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Test-Prompt_3.ps1
|
Test-Prompt_3.ps1
|
$choices = [System.Management.Automation.Host.ChoiceDescription[]](
(New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Choose me!"),
(New-Object System.Management.Automation.Host.ChoiceDescription "&No","Pick me!"))
$Answer = $host.ui.PromptForChoice('Caption',"Message",$choices,(1))
Write-Output $Answer
$fields = new-object System.Collections.ObjectModel.Collection``1[System.Management.Automation.Host.FieldDescription]
$f = New-Object System.Management.Automation.Host.FieldDescription "String Field"
$f.HelpMessage = "This is the help for the first field"
$f.DefaultValue = "Field1"
$f.Label = "&Any Text"
$fields.Add($f)
$f = New-Object System.Management.Automation.Host.FieldDescription "Secure String"
$f.SetparameterType( [System.Security.SecureString] )
$f.HelpMessage = "You will get a password input with **** instead of characters"
$f.DefaultValue = "Password"
$f.Label = "&Password"
$fields.Add($f)
$f = New-Object System.Management.Automation.Host.FieldDescription "Numeric Value"
$f.SetparameterType( [int] )
$f.DefaultValue = "42"
$f.HelpMessage = "You need to type a number, or it will re-prompt"
$f.Label = "&Number"
$fields.Add($f)
$results = $Host.UI.Prompt( "Caption", "Message", $fields )
Write-Output $results
|
PowerShellCorpus/PoshCode/push-module function .ps1
|
push-module function .ps1
|
function Push-Module {
param(
[parameter(position=0, mandatory=$true)]
[validatenotnullorempty()]
[string]$ModuleName
)
# find out what this module exports (and therefore what it overwrites)
$metadata = new-module -ascustomobject {
param([string]$ModuleName)
# import targeted module
$inner = import-module $ModuleName -PassThru
function GetExportedFunctions() {
$inner.ExportedFunctions.values
}
# prevent export of inner module's exports
Export-ModuleMember -Cmdlet "" -Function GetExportedFunctions
} -args $ModuleName
$clobbered = @{}
# grab copies of functions that would get clobbered
$metadata.GetExportedFunctions() | ? {
Test-Path "function:$($_.name)"
} | % {
$clobbered[$_.name] = gc -path "function:$($_.name)"
}
# import module
$m = import-module $ModuleName -PassThru
# hook up function restore
$m.onremove = {
$clobbered.keys | % {
si -path function:global:$_ $clobbered[$_] -force
}
}.getnewclosure()
}
|
PowerShellCorpus/PoshCode/Get-TranscriptFilePath.ps1
|
Get-TranscriptFilePath.ps1
|
#requires -version 2.0
function Get-TranscriptFilePath {
try {
$externalHost = $host.gettype().getproperty("ExternalHost",
[reflection.bindingflags]"nonpublic,instance").getvalue($host, @())
$externalhost.gettype().getfield("transcriptFileName", "nonpublic,instance").getvalue($externalhost)
} catch {
write-warning "This host does not support transcription."
}
}
|
PowerShellCorpus/PoshCode/Get-FSMORoleOwner.ps1
|
Get-FSMORoleOwner.ps1
|
Function Get-FSMORoleOwner {
<#
.SYNOPSIS
Retrieves the list of FSMO role owners of a forest and domain
.DESCRIPTION
Retrieves the list of FSMO role owners of a forest and domain
.NOTES
Name: Get-FSMORoleOwner
Author: Boe Prox
DateCreated: 06/9/2011
.EXAMPLE
Get-FSMORoleOwner
DomainNamingMaster : dc1.rivendell.com
Domain : rivendell.com
RIDOwner : dc1.rivendell.com
Forest : rivendell.com
InfrastructureOwner : dc1.rivendell.com
SchemaMaster : dc1.rivendell.com
PDCOwner : dc1.rivendell.com
Description
-----------
Retrieves the FSMO role owners each domain in a forest. Also lists the domain and forest.
#>
[cmdletbinding()]
Try {
$forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
ForEach ($domain in $forest.domains) {
$forestproperties = @{
Forest = $Forest.name
Domain = $domain.name
SchemaMaster = $forest.SchemaRoleOwner
DomainNamingMaster = $forest.NamingRoleOwner
RIDOwner = $Domain.RidRoleOwner
PDCOwner = $Domain.PdcRoleOwner
InfrastructureOwner = $Domain.InfrastructureRoleOwner
}
$newobject = New-Object PSObject -Property $forestproperties
$newobject.PSTypeNames.Insert(0,"ForestRoles")
$newobject
}
}
Catch {
Write-Warning "$($Error)"
}
}
|
PowerShellCorpus/PoshCode/Start-Timer.ps1
|
Start-Timer.ps1
|
## Start-Timer.ps1
## A kitchen timer script with visible countdown and customizable audio alert and messages
####################################################################################################
param( $seconds=0, $reason="The Timer", $SoundFile="$env:SystemRoot\\Media\\notify.wav",
$minutes=0, $hours=0, $timeout=0, [switch]$novoice, [string[]]$status="Cooking","Burning"
)
$start = [DateTime]::Now
write-progress -activity $reason -status "Running"
$seconds = [Math]::Abs($seconds) + [Math]::Abs($minutes*60) + [Math]::Abs($hours*60*60)
$end = $start.AddSeconds( $seconds )
## Take care of as much overhead as we can BEFORE we start counting
## So the sounds can play as cloase to the end as possible
$Voice = new-object -com SAPI.SpVoice
$Sound = new-Object System.Media.SoundPlayer
if(Test-Path $soundFile) {
$Sound.SoundLocation=$SoundFile
} else {
$soundFile = $Null
}
## The actual timing loop ...
do {
$remain = ($end - [DateTime]::Now).TotalSeconds
$percent = [Math]::Min(100, ((($seconds - $remain)/$seconds) * 100))
$sec = [Math]::Max(000, $remain)
write-progress -activity $reason -status $status[0] -percent $percent -seconds $sec
start-sleep -milli 100
} while( $remain -gt 0 )
## And a loop for beeping
$Host.UI.RawUI.FlushInputBuffer()
do {
if($SoundFile) {
$Sound.PlaySync()
} else {
[System.Media.SystemSounds]::Exclamation.Play()
}
if(!$novoice -and !$Host.UI.RawUI.KeyAvailable){
$null = $Voice.Speak( "$reason is $($status[1])!!", 0 )
}
write-progress -activity $reason -status $status[1] -percent ([Math]::Min(100,((($seconds - $remain)/$seconds) * 100))) -seconds ([Math]::Max(0,$remain))
$remain = ($end - [DateTime]::Now).TotalSeconds
} while( !$Host.UI.RawUI.KeyAvailable -and ($timeout -eq 0 -or $remain -gt -$timeout))
if($SoundFile) {
$Sound.Stop()
}
|
PowerShellCorpus/PoshCode/New-Zip_3.ps1
|
New-Zip_3.ps1
|
Function New-Zip
{
<#
.SYNOPSIS
Create a Zip File from any files piped in.
.DESCRIPTION
Requires that you have the SharpZipLib installed, which is available from
http://www.icsharpcode.net/OpenSource/SharpZipLib/
.NOTES
File Name : PowerZip.psm1
Author : Christophe CREMON (uxone) - http://powershell.codeplex.com
Requires : PowerShell V2
.PARAMETER Source
Set the name of the source to zip (file or directory)
.PARAMETER ZipFile
Set the name of the zip file to create
.PARAMETER Recurse
Browse the source recursively
.PARAMETER Include
Include only items you specify
.PARAMETER Exclude
Exclude items you specify
.PARAMETER AbsolutePaths
Preserve the absolute path name of each item in the zip container
.PARAMETER DeleteAfterZip
Delete source items after successful zip
.EXAMPLE
New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip
Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP
#>
param (
[ValidateNotNullOrEmpty()]
[Parameter(
Mandatory = $true)
]
[string] $Source,
[Parameter(
Mandatory = $true)
]
[string] $ZipFile,
[switch] $Recurse,
[array] $Include,
[array] $Exclude,
[switch] $AbsolutePaths,
[switch] $DeleteAfterZip )
$LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib")
if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" }
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path
if ( -not $RootPath ) { throw "! Source not found {$Source}" }
if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" }
if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" }
if ( $AbsolutePaths -eq $true ) { $AbsolutePathsArgument = "-AbsolutePaths" }
if ( $DeleteAfterZip -eq $true ) { $DeleteAfterZipArgument = "-DeleteAfterZip" }
if ( $Include )
{
$Include = $Include -join ","
$IncludeArgument = "-Include $Include"
$Source = $Source+"\\*"
}
if ( $Exclude )
{
$Exclude = $Exclude -join ","
$ExcludeArgument = "-Exclude $Exclude"
}
$GetCommand = "Get-ChildItem -Path '$Source' $RecurseArgument $IncludeArgument $ExcludeArgument -Force"
$ItemsToZip = Invoke-Expression -Command $GetCommand
$SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( -not $SizeBeforeZip )
{
Write-Output "NOTHING TO ZIP"
break
}
$StartTime = Get-Date
Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n"
Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n"
Write-Output "Initializing ZIP File {$ZipFile} ...`n"
$CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue
if ( -not $CreateZIPContainer ) { throw "! Unable to create ZIP container {$ZipFile}" }
$oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile))
[byte[]] $Buffer = New-Object Byte[] 4096
foreach ( $Item in $ItemsToZip )
{
if ( $Item.FullName -ne $ZipFile )
{
if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue )
{
$ZipEntry = $Item.FullName
if ( -not $AbsolutePaths )
{
$ReplacePath = [Regex]::Escape( $RootPath+"\\" )
$ZipEntry = $Item.FullName -replace $ReplacePath,""
}
if ( $Item.psIsContainer -eq $true )
{
if ( $Recurse -eq $true )
{
Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/")
$oZipOutputStream.PutNextEntry($oZipEntry)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}")
}
$ErrorActionPreference = $OldErrorActionPreference
}
}
else
{
Write-Output "Processing ZIP of File {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$FileStream = [IO.File]::OpenRead($Item.FullName)
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry")
$oZipOutputStream.PutNextEntry($oZipEntry)
[ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}")
}
$FileStream.Close()
}
}
}
}
$oZipOutputStream.Finish()
$oZipOutputStream.Close()
if ( $? -eq $true )
{
$ErrorActionPreference = $OldErrorActionPreference
if ( $DeleteAfterZip )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object {
if ( $_.psIsContainer -ne $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of File {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete File {$($_.FullName)}")
}
}
}
}
if ( $Recurse )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object {
if ( $_.psIsContainer -eq $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of Directory {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}")
}
}
}
}
}
}
Write-Output "`nZIP File Created {$ZipFile} ...`n"
}
else
{
$ErrorActionPreference = $OldErrorActionPreference
$ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n")
}
$EndTime = Get-Date
$ExecutionTime = ($EndTime-$StartTime)
Write-Output "`nExecution Time : $ExecutionTime`n"
Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n"
if ( $ErrorsArray )
{
Write-Output "`n[ ERRORS OCCURED ]"
$ErrorsArray
return $false
}
else
{
$SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n"
$Gain = ( $SizeBeforeZip - $SizeAfterZip )
$GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( $Gain -gt 0 )
{
$GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ }
Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n"
}
}
}
Export-ModuleMember -Function New-Zip
|
PowerShellCorpus/PoshCode/Write-Log_7.ps1
|
Write-Log_7.ps1
|
function Write-Log {
#.Synopsis
# Write to a rotating log file
#.Example
# Get-ChildItem C:\\ -Recurse | Select FullName, CreationTimeUtc, LastWriteTimeUtc | Write-Log Files.txt -Rotate 5mb
#
# Writes a file list to disc, breaking it into multiple files of approximately 5MB of data each
[CmdletBinding()]
param(
# The file path to log to
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=0)]
[Alias("PSPath")]
$FilePath,
[Parameter(Position=1)]
[ValidateSet('unknown','string','unicode','bigendianunicode','utf8','utf7','utf32','ascii','default','oem')]
[ValidateNotNullOrEmpty()]
[string]
${Encoding} = 'utf8',
[ValidateRange(2, 2147483647)]
[int]
${Width},
# A max file size at which to rotate the log file
[Parameter()]
[Alias("Rotate","Length")]
[int]$SizeLimit = 10MB,
# A max file size at which to rotate the log file
[Parameter()]
[Alias("Count")]
[int]$FileCountLimit = 5,
# The data to log
[Parameter(ValueFromPipeline=$true, Mandatory=$true)]
$InputObject
)
begin {
try {
if($PSBoundParameters.ContainsKey('OutBuffer')) {
$PSBoundParameters.Remove('OutBuffer')
}
if($PSBoundParameters.ContainsKey('SizeLimit')) {
$PSBoundParameters.Remove('SizeLimit')
}
if(!$PSBoundParameters.ContainsKey('Encoding')) {
$PSBoundParameters.Add('Encoding', $Encoding)
}
# Pipeline-bound parameters will be set on $PSBoundParameters later (in the process block)
# Since we have to (re)create the steppablePipeline, we need a copy of them as they are now
$Parameters = $PSBoundParameters.Clone()
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(
'Microsoft.PowerShell.Utility\\Out-File',
[System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @Parameters -Append }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process {
try {
$steppablePipeline.Process($_)
# If the file triggers rotation:
if(($file = Get-Item $FilePath) -and $file.Length -gt $SizeLimit) {
# Remove the last item if it would go over the limit
$steppablePipeline.End()
if(Test-Path "$FilePath.$FileCountLimit)") {
Write-Verbose "Removing $FilePath.$FileCountLimit)"
Remove-Item "$FilePath.$FileCountLimit)"
}
foreach($i in ($FileCountLimit)..1) {
if(test-path "$FilePath.$($i-1)") {
Move-Item "$FilePath.$($i-1)" "$FilePath.$i"
}
}
Move-Item $FilePath "$FilePath.$i"
$null = New-Item $FilePath -Type File
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
}
## Bonus: the log rotation logic as a stand alone function...
function Rotate-Log {
#.Synopsis
# Rotate a log file if it's gotten too big
[CmdletBinding()]
param(
# The file of the path to test and rotate
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=0)]
[Alias("PSPath")]
$FilePath,
# When a log file goes over this size, rotate it
$SizeLimit = 10MB,
# How many backup logs (besides the primary log file) to keep
$LogLimit = 5
)
process {
foreach($LogFile in Resolve-Path $FilePath) {
# If the file triggers rotation:
if(($file = Get-Item $LogFile) -and $file.Length -gt $SizeLimit) {
# Remove the last item if it would go over the limit
if(Test-Path "$LogFile.$LogLimit") { Remove-Item "$LogFile.$LogLimit" }
foreach($i in $LogLimit..1) {
if(test-path "$LogFile.$($i-1)") {
Move-Item "$LogFile.$($i-1)" "$LogFile.$i"
}
}
Move-Item $LogFile "$LogFile.$i"
$null = New-Item $LogFile -Type File
}
}
}
}
|
PowerShellCorpus/PoshCode/Invoke-WindowsUpdate.ps1
|
Invoke-WindowsUpdate.ps1
|
###########################################################################"
#
# NAME: Invoke-WindowsUpdate.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: Script to download and install updates from Windows Update/WSUS. Reporting and rebooting may be customized.
# For more details, see the following blog-post:
# http://blog.powershell.no/2010/06/25/manage-windows-update-installations-using-windows-powershell
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 25.06.2010 - Initial release
#
###########################################################################"
#Requires -Version 2.0
#Variables to customize
$EmailReport = $true
$FileReport = $true
$To = "it-reports@domain.com"
$From = "powershell@domain.com"
$SMTPServer = "smtp.domain.local"
$FileReportPath = "\\\\domain.local\\IT\\Windows Update Reports\\"
$AutoRestart = $true
$AutoRestartIfPending = $true
$Path = $FileReportPath + "$env:ComputerName" + "_" + (Get-Date -Format dd-MM-yyyy_HH-mm).ToString() + ".html"
#Testing if there are any pending reboots from earlier Windows Update sessions
if (Test-Path "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired"){
#Report to e-mail if enabled
if ($EmailReport -eq $true) {
$pendingboot = @{$false="was pending for a restart from an earlier Windows Update session. Due to the reboot preferences in the script, a reboot was not initiated."; $true="was restarted due to a pending restart from an earlier Windows Update session."}
$status = $pendingboot[$AutoRestartIfPending]
$messageParameters = @{
Subject = "Windows Update report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
Body = "Invoke-WindowsUpdate was run on $env:ComputerName, and the server $status `nPlease run Invoke-WindowsUpdate again when the server is rebooted."
from = $From
To = $To
SmtpServer = $SMTPServer
}
Send-MailMessage @messageParameters -BodyAsHtml
#Report to file if enabled
if ($FileReport -eq $true) {
"Invoke-WindowsUpdate was run on $env:ComputerName, and the server $status `nPlease run Invoke-WindowsUpdate again when the server is rebooted." | Out-File -FilePath $path
}
#Reboot if autorestart for pending updates is enabled
if ($AutoRestartIfPending) {shutdown.exe /t 0 /r } }
exit
}
#Checking for available updates
$updateSession = new-object -com "Microsoft.Update.Session"
write-progress -Activity "Updating" -Status "Checking available updates"
$updates=$updateSession.CreateupdateSearcher().Search($criteria).Updates
$downloader = $updateSession.CreateUpdateDownloader()
$downloader.Updates = $Updates
#If no updates available, do nothing
if ($downloader.Updates.Count -eq "0") {
#Report to e-mail if enabled
if ($EmailReport -eq $true) {
$messageParameters = @{
Subject = "Windows Update report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
Body = "Invoke-WindowsUpdate was run on $env:ComputerName, but no new updates were found. Please try again later."
from = $From
To = $To
SmtpServer = $SMTPServer
}
Send-MailMessage @messageParameters -BodyAsHtml
}
#Report to file if enabled
if ($FileReport -eq $true) {
"Invoke-WindowsUpdate was run on $env:ComputerName, but no new updates were found. Please try again later." | Out-File -FilePath $Path
}
}
else
{
#If updates are available, download and install
write-progress -Activity 'Updating' -Status "Downloading $($downloader.Updates.count) updates"
$Criteria="IsInstalled=0 and Type='Software'"
$resultcode= @{0="Not Started"; 1="In Progress"; 2="Succeeded"; 3="Succeeded With Errors"; 4="Failed" ; 5="Aborted" }
$Result= $downloader.Download()
if (($Result.Hresult -eq 0) –and (($result.resultCode –eq 2) -or ($result.resultCode –eq 3)) ) {
$updatesToInstall = New-object -com "Microsoft.Update.UpdateColl"
$Updates | where {$_.isdownloaded} | foreach-Object {$updatesToInstall.Add($_) | out-null
}
$installer = $updateSession.CreateUpdateInstaller()
$installer.Updates = $updatesToInstall
write-progress -Activity 'Updating' -Status "Installing $($Installer.Updates.count) updates"
$installationResult = $installer.Install()
$Global:counter=-1
$Report = $installer.updates |
Select-Object -property Title,EulaAccepted,@{Name='Result';expression={$ResultCode[$installationResult.GetUpdateResult($Global:Counter++).resultCode ] }},@{Name='Reboot required';expression={$installationResult.GetUpdateResult($Global:Counter++).RebootRequired }} |
ConvertTo-Html
#Report to e-mail if enabled
if ($EmailReport -eq $true) {
$messageParameters = @{
Subject = "Windows Update report for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
Body = $Report | Out-String
from = $From
To = $To
SmtpServer = $SMTPServer
}
Send-MailMessage @messageParameters -BodyAsHtml
}
#Report to file if enabled
if ($FileReport -eq $true) {
$Report | Out-File -FilePath $path
}
#Reboot if autorestart is enabled and one or more updates are requiring a reboot
if ($autoRestart -and $installationResult.rebootRequired) { shutdown.exe /t 0 /r }
}
}
|
PowerShellCorpus/PoshCode/group-byobject_1.ps1
|
group-byobject_1.ps1
|
#groups by a set of properties, but returns then rather than as a string, as seperate properties on an object with _count , and _group for the original
#ones returned from group object
function group-byobject {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
$InputObject
,
[Parameter(Position=0)]
[object[]]$property
,
[switch]$includeGroup
,
[switch]$includeCount
)
begin {
$InputItems = @()
$select = $property
if ($includeCount){ $select += @{ n="_count"; e={$group.count} } }
if ($includeGroup){ $select += @{ n="_group"; e={$group.group} } }
}
process { $InputItems += $InputObject }
end {
foreach($group in $InputItems | group-object $property) {
$group.Group[0] | Select $select
}
}
}
set-alias groupby group-byobject
set-alias grby group-byobject
|
PowerShellCorpus/PoshCode/SharpSsh 5.ps1
|
SharpSsh 5.ps1
|
#requires -version 2.0
## A simple SSH Scripting module for PowerShell
## Retrieved from
## History:
## v1 - Initial Script
## v2 - Capture default prompt in New-SshSession
## v3 - Update to advanced functions, require 2.0, and add basic help
## v4(modification by Tao Klerks) - Update to reference modified SharpSSH library, configurable connection port, Port Forwarding feature, relative path to binaries
## v5(modification by Tao Klerks) - Update to validate known fingerprint for host, fix to key-based auth support, and allow user-interactive decisions around host key handling/key passphrase entry using another modified SharpSSH library
## USING the SharpSSH.dll binary from:
## https://bitbucket.org/TaoK/sharpssh/downloads / https://bitbucket.org/mattgwagner/sharpssh/downloads
## in the same folder as this script
$ScriptFullPath = $MyInvocation.MyCommand.Path
$ScriptFolder = (New-Object System.IO.FileInfo($ScriptFullPath)).Directory.FullName;
[void][reflection.assembly]::LoadFrom("$ScriptFolder\\SharpSSH.dll")
Function ConvertTo-SecureString {
#.Synopsis
# Helper function which converts a string to a SecureString
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
Function ConvertFrom-SecureString {
#.Synopsis
# Helper function which converts a SecureString to a string
Param([security.securestring]$secure)
$marshal = [Runtime.InteropServices.Marshal]
return $marshal::PtrToStringAuto( $marshal::SecureStringToBSTR($secure) )
}
Function ConvertTo-PSCredential {
#.Synopsis
# Helper function which converts a NetworkCredential to a PSCredential
Param([System.Net.NetworkCredential]$Credential)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
New-Object System.Management.Automation.PSCredential "$($Credential.UserName)@$($Credential.Domain)", (ConvertTo-SecureString $Credential.Password)
}
Function BooleanRead-Host {
#.Synopsis
# Uses built-in "PromptForChoice" mechanism to ask the user for a yes/no answer
Param([string]$caption, [string]$message)
$yes = new-Object System.Management.Automation.Host.ChoiceDescription "&Yes","help";
$no = new-Object System.Management.Automation.Host.ChoiceDescription "&No","help";
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no);
$answer = $host.ui.PromptForChoice($caption,$message,$choices,0)
switch ($answer){
0 {$true}
1 {$false}
}
}
## NOTE: These are still bare minimum functions, and only cover ssh, not sftp or scp (see here: http://poshcode.org/1034)
## IMPORTANT: if you "expect" something that does NOT get output, you'll be completely stuck and unable to 'break'
##
## As a suggestion, the best way to handle the output is to "expect" your prompt, and then do
## select-string matching on the output that was captured before the prompt.
function New-SshSession {
<#
.Synopsis
Create an SSH session to a remote server
.Description
Connect to a specific SSH server with the specified credentials. Supports RSA KeyFile connections.
.Parameter HostName
The server to SSH into
.Parameter UserName
The user name to use for login
.Parameter Password
The Password for login (Note: you really should pass this as a System.Security.SecureString, but it will accept a string instead)
.Parameter KeyFile
An RSA keyfile for ssh secret key authentication (INSTEAD of username/password authentication).
.Parameter Credentials
A PSCredential object containing all the information needed to log in. The login name should be in the form user@host
.Parameter Passthru
If passthru is specified, the new SshShell is returned.
.Parameter Port
The TCP port to connect to the SSH server on (default is 22)
.Parameter ExpectedHostKeyFingerprint
Have the host key be checked to match the provided fingerprint
.Parameter AllowSecurityPrompts
Allow for interactive user prompts for password, passphrase, host key checking decisions, etc
.Example
New-SshSession Microsoft.com BillG Micr050ft
Description
-----------
Creates a new ssh session with the ssh server at Microsoft.com using the 'BillG' as the login name and 'Micr050ft' as the password (please don't bother trying that).
.Example
New-SshSession Microsoft.com -Keyfile BillGates.ppk
Description
-----------
Creates a new ssh session with the ssh server at Microsoft.com using the credentials supplied in the BillGates.ppk private key file.
.Example
$MSCred = Get-Credential BillG@Microsoft.com # prompts for password
New-SshSession $MSCred
Description
-----------
Creates a new ssh session based on the supplied credentials. Uses the output of $MsCred.GetNetworkCredential() for the server to log into (domain) and the username and password.
#>
[CmdletBinding(DefaultParameterSetName='NamePass')]
Param(
[Parameter(Position=0,Mandatory=$true,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)]
[Parameter(Position=0,Mandatory=$true,ParameterSetName="RSAKeyFileOrInteractive",ValueFromPipelineByPropertyName=$true)]
[string]$HostName
,
[Parameter(Position=1,Mandatory=$false,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)]
[Parameter(Position=1,Mandatory=$true,ParameterSetName="RSAKeyFileOrInteractive",ValueFromPipelineByPropertyName=$true)]
[string]$UserName
,
[Parameter(Position=2,Mandatory=$false,ParameterSetName="NamePass",ValueFromPipelineByPropertyName=$true)]
$Password
,
[Parameter(Position=2,Mandatory=$false,ParameterSetName="RSAKeyFileOrInteractive",ValueFromPipelineByPropertyName=$true)]
[string]$KeyFile
,
[Parameter(Position=3,Mandatory=$false,ParameterSetName="RSAKeyFileOrInteractive",ValueFromPipelineByPropertyName=$true)]
[switch]$KeyboardInteractive
,
[Parameter(Position=0,Mandatory=$true,ParameterSetName="PSCredential",ValueFromPipeline=$true)]
[System.Management.Automation.PSCredential]$Credentials
,
[switch]$Passthru,
[int]$Port,
[string]$ExpectedHostKeyFingerprint = ""
)
process {
switch($PSCmdlet.ParameterSetName) {
'RSAKeyFileOrInteractive' {
$global:LastSshSession = new-object Tamir.SharpSsh.SshShell $HostName, $UserName
if ($KeyFile) { $global:LastSshSession.AddIdentityFile( (Convert-Path (Resolve-Path $KeyFile)) ) }
}
'NamePass' {
if(!$UserName -or !$Password) {
$Credentials = $Host.UI.PromptForCredential("SSH Login Credentials",
"Please specify credentials in user@host format",
"$UserName@$HostName","")
} else {
if($Password -isnot [System.Security.SecureString]) {
$Password = ConvertTo-SecureString $Password
}
$Credentials = New-Object System.Management.Automation.PSCredential "$UserName@$HostName", $Password
}
}
}
if($Credentials) {
$HostName = $Credentials.GetNetworkCredential().Domain
$global:LastSshSession = new-object Tamir.SharpSsh.SshShell `
$HostName,
$Credentials.GetNetworkCredential().UserName,
$Credentials.GetNetworkCredential().Password
}
else {
#Keyboard-interactive auth
$userInfo = new-object Tamir.SharpSsh.DelegatingKeyboardInteractiveUserInfo `
{ param($m); $s = Read-Host -AsSecureString $m; ConvertFrom-SecureString $s; }, `
{ param($m); $s = Read-Host -AsSecureString $m; ConvertFrom-SecureString $s; }, `
{ param($m); BooleanRead-Host -caption $m; }, `
{ param($m); Write-Host $m; }, `
{ param($d, $n, $i, $p, $e);
Write-Host "Keyboard-Interactive Authentication:";
Write-Host "Destination: $d, Name: $n, Instruction: $i";
if ($p -and $p.Length > 0) {
Write-Host "Prompt: ";
Write-Host $p
}
$s = Read-Host -AsSecureString;
$is = ConvertFrom-SecureString $s;
return @($is);
}
$global:LastSshSession.SetUserInfo($userInfo);
if (-not $ExpectedHostKeyFingerprint) {
$global:LastSshSession.SetHostKeyCheckingRule([Tamir.SharpSsh.HostKeyCheckType]::"AskUser");
$global:LastSshSession.SetHostKeyFileName("known_hosts");
}
}
if ($ExpectedHostKeyFingerprint) {
$global:LastSshSession.SetKnownHostFingerprint($ExpectedHostKeyFingerprint)
}
if ($Port) {
$global:LastSshSession.Connect($Port)
}
else {
$global:LastSshSession.Connect()
}
$global:LastSshSession.RemoveTerminalEmulationCharacters = $true
if($Passthru) { return $global:LastSshSession }
$global:LastSshSession.WriteLine("")
sleep -milli 500
$global:defaultSshPrompt = [regex]::Escape( $global:LastSshSession.Expect().Split("`n")[-1] )
}
}
function New-SshLocalPortForward {
<#
.Synopsis
Add remote port forwarding to an existing open SSH session.
.Description
Add tunnel to a remote port (on a specified remote host) from a port on localhost, through an existing open SSH Shell session. Local listening port will be auto-assigned if not specified. Ports forwards will be cleaned up when shell is closed.
.Parameter SshShell
The existing open SSH shell session to add the port forwarding to (defaults to the last one opened).
.Parameter RemotePort
The TCP port to forward to on the remote host.
.Parameter RemoteHostName
The hostname to tunnel to on the SSH host - often/usually "localhost" (if the resource you want to tunnel to is on the SSH server itself)
.Parameter LocalPort
The local TCP port that SSH should listen on. Will be auto-assigned if not specified.
.Parameter Passthru
Have the shell session be output instead of outputting the local port number the forward is configured to. This can be used for piping the shell through multiple port forwards.
.Example
$listeningPortNumber = New-SshSession (Get-Credential BillG@Microsoft.com) -Passthru | New-SshLocalPortForward -RemoteHostName localhost -RemotePort 5900
#>
Param(
[Parameter(Position=0,Mandatory=$true)]
[int]$RemotePort,
[Parameter(Position=1,Mandatory=$false)]
[string]$RemoteHostName="localhost",
[Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$true)]
[Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession,
[Parameter(Position=3,Mandatory=$false)]
[int]$LocalPort,
[Parameter(Position=4,Mandatory=$false)]
[switch]$Passthru
)
process {
if ($LocalPort) {
$SshShell.ForwardLocalPortToRemote($LocalPort, $RemoteHostName, $RemotePort)
}
else {
$LocalPort = $SshShell.ForwardLocalPortToRemote($RemoteHostName, $RemotePort)
}
if ($Passthru) {
return $SshShell
}
else {
return $LocalPort
}
}
}
function Remove-SshSession {
<#
.Synopsis
Exits an open SshSession (the last open opened, by default)
#>
Param([Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession)
$SshShell.WriteLine( "exit" )
sleep -milli 500
if($SshShell.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." }
$SshShell.Close()
$SshShell = $null
}
function Invoke-Ssh {
<#
.Synopsis
Executes an SSH command and Receives output
.Description
Invoke-Ssh is basically the same as a Send-Ssh followed by a Receive-Ssh, except that Expect defaults to $defaultSshPrompt (which is read in New-SshSession)
.Parameter Command
The command to send
.Parameter Expect
A regular expression for expect. The ssh session will wait for a line that matches this regular expression to be output before returning, and will return all the text up to AND INCLUDING the line that matches.
Defaults
.Parameter SshShell
The shell to invoke against. Defaults to the LastSshSession
#>
Param(
[string]$Command
, [regex]$Expect = $global:defaultSshPrompt ## there ought to be a non-regex parameter set...
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
$SshShell.WriteLine( $command )
if($expect) {
$SshShell.Expect( $expect ).Split("`n")
}
else {
sleep -milli 500
$SshShell.Expect().Split("`n")
}
}
else { throw "The ssh shell isn't open!" }
}
function Send-Ssh {
<#
.Synopsis
Executes an SSH command without receiving input
.Description
Sends a command to an ssh session
.Parameter Command
The command to send
.Parameter SshShell
The shell to send to. Defaults to the LastSshSession
#>
Param(
[string]$command
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
$SshShell.WriteLine( $command )
}
else { throw "The ssh shell isn't open!" }
}
function Receive-Ssh {
<#
.Synopsis
Receives output from an SSH session
.Description
Retrieves output from an SSH session until the text matches the Expect pattern
.Parameter Expect
A regular expression for expect. The ssh session will wait for a line that matches this regular expression to be output before returning, and will return all the text up to AND INCLUDING the line that matches.
.Parameter SshShell
The shell to wait for. Defaults to the LastSshSession
#>
Param(
[RegEx]$expect ## there ought to be a non-regex parameter set...
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
if($expect) {
$SshShell.Expect( $expect ).Split("`n")
}
else {
sleep -milli 500
$SshShell.Expect().Split("`n")
}
}
else { throw "The ssh shell isn't open!" }
}
|
PowerShellCorpus/PoshCode/Help Differ 10000 v0.01.ps1
|
Help Differ 10000 v0.01.ps1
|
# These functions are meant to help generate a table that shows differences between
# cmdlets among different versions of a module.
# You will need a MoinMoin wiki to render the output.
# If you don't have a MoinMoin wiki you might be able to use the sandbox at http://moinmo.in/WikiSandBox
# Extracts some data from a module's help for use with Diff-HelpXml
function Get-HelpXml {
param ($module)
get-vicommand -module $module | % {
$allParams = $_.parametersets | % { $_.parameters | select -unique Name }
$obj = new-object psobject
$obj | add-member -type noteproperty -name name -value $_.Name
$obj | add-member -type noteproperty -name parameters -value $allParams
# Pull some things out of help.
$h = $_ | get-help
$obj | add-member -type noteproperty -name description -value $h.Description
$obj | add-member -type noteproperty -name paramDescriptions -value $h.parameters
$obj
}
}
# Diff a help XML and output the results in Moinmoin wiki format.
# You can then copy to a MoinMoin wiki to do HTML rendering.
function Diff-HelpXml {
param ($beforeFile, $afterFile)
# The XML files should be generated with makexml.ps1
$before = import-clixml $beforeFile
$after = import-clixml $afterFile
$titleColor = "<bgcolor=`"#72AEC0`">"
$color1 = "<bgcolor=`"#C2DEF0`">"
$color2 = "<bgcolor=`"#ffffff`">"
echo "= New cmdlets in this release ="
echo " ||$titleColor Name ||$titleColor Description ||"
foreach ($a in $after) {
$match = $before | where { $_.Name -eq $a.Name }
if ($match -eq $null) {
$name = $a.Name
$desc = $a.Description[0].Text
echo " || $name || $desc ||"
}
}
echo ""
echo "= New cmdlet parameters in this release ="
$color = $color1
echo " ||$titleColor Cmdlet Name ||$titleColor Parameter Name ||$titleColor Description ||"
foreach ($a in $after) {
$match = $before | where { $_.Name -eq $a.Name }
if ($match) {
$noMatches = $true
foreach ($p in $a.parameters) {
$matchPar = $match.parameters | where { $_.Name -eq $p.Name }
if ($matchPar -eq $null) {
$cmdletName = ""
$pName = $p.Name
if ($noMatches) {
$cmdletName = $a.Name
$noMatches = $false
if ($color -eq $color1) {
$color = $color2
} else {
$color = $color1
}
}
# Find the help for this switch.
$matchDesc = $a.paramDescriptions.parameter | where { $_.Name -eq $pName }
$pDesc = $matchDesc.description[0].text
$pDesc = $pDesc -replace "[^A-Za-z1-9\\.`"``, ]", " "
echo " ||$color $cmdletName ||$color $pName ||$color $pDesc ||"
}
}
}
}
}
# Sample usage:
## Install VI Toolkit 1.0
# Get-HelpXml -module vmware.vimautomation.core | export-clixml before.xml
## Install VI Toolkit 1.5
# Get-HelpXml -module vmware.vimautomation.core | export-clixml after.xml
# Diff-HelpXml -before before.xml -after after.xml | set-content diffsInMoinMoin.txt
|
PowerShellCorpus/PoshCode/get-DiskVolumeInfo.ps1
|
get-DiskVolumeInfo.ps1
|
function get-DiskVolumeInfo
{
<#
.SYNOPSIS
Returns information about disk volumes including freespace
.DESCRIPTION
Returns information about disk volumes including freespace
.EXAMPLE
show-InnerException ExceptionObject
Shows the inner exception object of the error object that is passed to the
function.
.Notes
ChangeLog :
Date Initials Short Description
02/18/2009 RLV New
.Link
http://msdn.microsoft.com/en-us/library/aa394239(v=VS.85).aspx
.Link
http://msdn.microsoft.com/en-us/library/aa394515(VS.85).aspx
.Link
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$ComputerName,
[Parameter(Mandatory=$false)][switch]$Raw
)
trap
{
show-InnerException -ex $_
continue
}
write-log "$($MyInvocation.InvocationName) - Begin function"
foreach($Key in $PSBoundParameters.Keys){ write-log "$($MyInvocation.InvocationName) PARAM: -$Key - $($PSBoundParameters[$Key])" }
# Create an empty array to hold the property bags that will be created later
$VolArray = @()
# Windows 2003 supports mount points
if($(gwmi win32_operatingSystem -comp $ComputerName).version -ge '5.2')
{
# #region Persistent fold region
$VolArray = gwmi win32_volume -Computer $ComputerName | Select-Object `
@{Name='Computer';Expression={$ComputerName}}, `
@{Name='VolumeName';Expression={if($_.Name -like "\\\\?\\Volume*"){'\\\\?\\Volume'}else{$_.Name}}}, `
@{Name='Capacity_GB';Expression={[math]::Round($_.Capacity/1GB)}}, `
@{Name='FreeSpace_GB';Expression={[math]::Round($_.FreeSpace/1GB)}}, `
@{Name='Pct_Free';Expression={if($_.Capacity -gt 0){[math]::Round(($_.FreeSpace/$_.Capacity)*100)}else{0}}}, `
@{Name='BlockSize_KB';Expression={[math]::Round($_.Blocksize/1KB)}}
# #endregion
}
else
# Windows 2000 and Windows XP no mount point support
{
# #region Persistent fold region
$VolArray = gwmi win32_LogicalDisk -Computer $ComputerName | Select-Object `
@{Name='Computer';Expression={$ComputerName}}, `
@{Name='VolumeName';Expression={$_.Name}}, `
@{Name='Capacity_GB';Expression={[math]::Round($_.Size/1GB)}}, `
@{Name='FreeSpace_GB';Expression={[math]::Round($_.FreeSpace/1GB)}}, `
@{Name='Pct_Free';Expression={if($_.Size -gt 0){[math]::Round(($_.FreeSpace/$_.Size)*100)}else{0}}}
# #endregion
}
if($Raw){ $VolArray }
else{ $VolArray | ft -auto }
write-log "$($MyInvocation.InvocationName) - End function"
}
|
PowerShellCorpus/PoshCode/New-XVM_5.ps1
|
New-XVM_5.ps1
|
#Examples
<#
New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD
New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx'
New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD
New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB
New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic
New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx'
New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"}
#>
Function New-XVM
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$false,Position=1)]
[string]$ComputerName=$env:COMPUTERNAME,
[Parameter(Mandatory=$true,Position=2)]
[string]$Name,
[Parameter(Mandatory=$true,Position=3)]
[string]$SwitchName,
[Parameter(Mandatory=$true,Position=4)]
[ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")]
[string]$VhdType,
[Parameter(Mandatory=$false,Position=5)]
[hashtable]$Configuration
)
DynamicParam
{
Switch ($VhdType) {
"ExistingVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("VhdPath",$vhdPath)
return $paramDictionary
break
}
"NewVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("DiskType",$diskType)
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection)
$paramDictionary.Add("DiskSize",$diskSize)
return $paramDictionary
break
}
"Differencing" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("ParentVhdPath",$parentVhdPath)
return $paramDictionary
}
}
}
Begin
{
Try
{
$vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop
}
Catch
{
$PSCmdlet.ThrowTerminatingError($Error[0])
}
$defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath
}
Process
{
$validConfigNames = "MemoryStartupBytes","BootDevice"
$configParams = @()
Switch ($VhdType) {
"NoVHD" {
$newVhdPath = $null
}
"ExistingVHD" {
$newVhdPath = $vhdPath.Value
}
"NewVhd" {
if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"}
if (-not $diskSize.IsSet) {$diskSize.Value = 127GB}
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
Switch ($diskType.Value) {
"Fixed" {
$vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
"Dynamic" {
$vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
}
}
"Differencing" {
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
$vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop
}
}
if ($vhdFile -ne $null) {
Try
{
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'"
}
Catch
{
$PSCmdlet.WriteError($Error[0])
Remove-Item -Path $vhdFile.Path
}
} else {
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD"
}
if ($Configuration -ne $null) {
foreach ($configName in $Configuration.Keys.GetEnumerator()) {
if ($validConfigNames -contains $configName) {
$configParams += "-$configName" + " " + $Configuration[$configName]
}
}
$configParams = $configParams -join " "
}
if ($configParams.Count -eq 0) {
$command += " -ErrorAction Stop"
} else {
$command += " $configParams -ErrorAction Stop"
}
Invoke-Expression -Command $command
}
End {}
}
|
PowerShellCorpus/PoshCode/134032f9-0687-4d0a-b267-6a42e5c116df.ps1
|
134032f9-0687-4d0a-b267-6a42e5c116df.ps1
|
#'***********************************************************************
#'* File: Check-Directory.ps1
#'* Creation Date: 2008/05/30
#'* Author: Jacob Hodges (Technology Effect)
#'* Purpose: Checks to see if an INF File is already in the MDT Workbench.
#'* Usage: .\\Create-DistributionShare.ps1 D:\\Drivers
#'* Reference:
#'*
#'* Revisions: 0.1 JBH Initial Version
#'***********************************************************************
Param
(
[string]$Location =$(throw "You must specify a directory containing drivers")
)
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
#Get some code Gens
. "$myDir\\LibraryCodeGen.ps1"
#Initialize MDT
[System.Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft Deployment Toolkit\\Bin\\Microsoft.BDD.ConfigManager.dll") | Out-Null
$manager = [Microsoft.BDD.ConfigManager.Manager]
#Get driver manager
$driverManager=$manager::DriverManager
function Compile-Csharp ([string] $code, $FrameworkVersion="v2.0.50727",[Array]$References)
{
## Obtains an ICodeCompiler from a CodeDomProvider class.
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
## Get the location for System.Management.Automation DLL
$dllName = [PsObject].Assembly.Location
## Configure the compiler parameters
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
#Path to Framework Directory
$framework = Join-Path $env:windir "Microsoft.NET\\Framework\\$FrameWorkVersion"
$assemblies = new-object Collections.ArrayList
$assemblies.AddRange( @("${framework}\\System.dll",
"${framework}\\system.windows.forms.dll",
"${framework}\\System.data.dll",
"${framework}\\System.Drawing.dll",
"${framework}\\System.Xml.dll", $dllName))
if ($references.Count -ge 1)
{
$assemblies.AddRange($References)
}
$compilerParameters.ReferencedAssemblies.AddRange($assemblies)
$compilerParameters.IncludeDebugInformation = $true
$compilerParameters.GenerateInMemory = $true
## Invokes compilation.
$compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code)
## Write any errors if generated.
if($compilerResults.Errors.Count -gt 0)
{
$errorLines = ""
foreach($error in $compilerResults.Errors)
{
$errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText
}
Write-Error $errorLines
}
}
#Compile some C# to get .inf info
$txtCode = @'
//***************************************************************************
// ***** Script Header *****
//
// Solution: Solution Accelerator for Business Desktop Deployment
// File: InfInfo.cs
//
// Purpose: Gets information from a driver INF file
//
// Usage: (See constructor below)
//
// Microsoft Solution Version: 3.0.76
// Microsoft Script Version: 3.0.76
// Customer Build Version: 1.0.0
// Customer Script Version: 1.0.0
//
// Microsoft History:
// 3.0.76 MTN 09/22/2006 Added comment block.
//
// Customer History:
//
// ***** End Header *****
//***************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MDTCustom
{
public class InfInfo
{
private const uint INF_STYLE_WIN4 = 2;
private const uint MAX_INF_STRING_LENGTH = 4096;
private const string INFSTR_SECT_VERSION = "Version";
private const string INFSTR_SECT_MFG = "Manufacturer";
private const string INFSTR_KEY_PROVIDER = "Provider";
private const string INFSTR_KEY_HARDWARE_CLASS = "Class";
private const string INFSTR_KEY_HARDWARE_CLASSGUID = "ClassGUID";
private const string INFSTR_DRIVERVERSION_SECTION = "DriverVer";
public String Provider;
public String ClassGUID;
public String ClassName;
public String Date;
public String Version;
public List<String> Platforms;
public List<String> OSVersions;
public List<String> PNPIds;
struct INFCONTEXT
{
IntPtr Inf;
IntPtr CurrentInf;
uint Section;
uint Line;
}
public InfInfo(String infPath)
{
IntPtr theInf;
uint errorLine;
INFCONTEXT context;
StringBuilder infData = new StringBuilder(Convert.ToInt16(MAX_INF_STRING_LENGTH));
uint requiredSize;
Guid theGuid;
Boolean found;
String deviceSection = "";
List<String> suffixList = new List<String>();
Platforms = new List<String>();
OSVersions = new List<String>();
PNPIds = new List<String>();
// Open the INF file
theInf = SetupOpenInfFile(infPath, 0, INF_STYLE_WIN4, out errorLine);
// Get the platform and OS version information
if (SetupFindFirstLine(theInf, INFSTR_SECT_VERSION, INFSTR_KEY_PROVIDER, out context))
{
SetupGetStringField(ref context, 1, infData, MAX_INF_STRING_LENGTH, out requiredSize);
Provider = infData.ToString();
if (SetupFindFirstLine(theInf, INFSTR_SECT_MFG, null, out context))
{
// Get the name of the section that will have the PNP ID info in it
SetupGetStringField(ref context, 1, infData, MAX_INF_STRING_LENGTH, out requiredSize);
deviceSection = infData.ToString();
// Get the platform and version information
uint fieldCount = SetupGetFieldCount(ref context);
if (fieldCount == 1)
{
Platforms.Add("x86");
}
else
{
for (uint i = 2; i <= fieldCount; i++)
{
// Get the platform string and figure out what it is
SetupGetStringField(ref context, i, infData, MAX_INF_STRING_LENGTH, out requiredSize);
if (!suffixList.Contains(infData.ToString()))
suffixList.Add(infData.ToString());
if (infData.ToString().IndexOf(".") > 0)
{
if (!suffixList.Contains(infData.ToString().Substring(0, infData.ToString().IndexOf("."))))
suffixList.Add(infData.ToString().Substring(0, infData.ToString().IndexOf(".")));
}
string platformToAdd = "";
if (infData.ToString().IndexOf("NTx86", StringComparison.OrdinalIgnoreCase) >= 0)
platformToAdd = "x86";
else if (infData.ToString().IndexOf("NTamd64", StringComparison.OrdinalIgnoreCase) >= 0)
platformToAdd = "x64";
else if (infData.ToString().IndexOf("NTia64", StringComparison.OrdinalIgnoreCase) >= 0)
platformToAdd = "ia64";
else if (infData.ToString().IndexOf("NT", StringComparison.OrdinalIgnoreCase) >= 0)
platformToAdd = "x86"; // Since specifying just "NT" is valid
// Make sure the platform isn't already in the list, then add it.
found = false;
foreach (String p in Platforms)
if (p == platformToAdd)
found = true;
if (!found)
Platforms.Add(platformToAdd);
// See if there is a version suffix
if (infData.ToString().IndexOf(".") > 0)
{
OSVersions.Add(infData.ToString().Substring(infData.ToString().IndexOf(".") + 1));
}
}
}
}
}
// Get the class name
ClassName = null;
if (SetupFindFirstLine(theInf, INFSTR_SECT_VERSION, INFSTR_KEY_HARDWARE_CLASSGUID, out context))
{
SetupGetStringField(ref context, 1, infData, MAX_INF_STRING_LENGTH, out requiredSize);
ClassGUID = infData.ToString();
theGuid = new Guid(infData.ToString());
if (SetupDiClassNameFromGuid(ref theGuid, infData, MAX_INF_STRING_LENGTH, out requiredSize))
{
ClassName = infData.ToString();
}
}
if (ClassName == null)
{
if (SetupFindFirstLine(theInf, INFSTR_SECT_VERSION, INFSTR_KEY_HARDWARE_CLASS, out context))
{
SetupGetStringField(ref context, 1, infData, MAX_INF_STRING_LENGTH, out requiredSize);
ClassName = infData.ToString();
}
}
if (ClassName == null)
{
if (ClassGUID != null)
ClassName = ClassGUID;
else
ClassName = "Unknown";
}
// Get the date and version
if (SetupFindFirstLine(theInf, INFSTR_SECT_VERSION, INFSTR_DRIVERVERSION_SECTION, out context))
{
SetupGetStringField(ref context, 1, infData, MAX_INF_STRING_LENGTH, out requiredSize);
Date = infData.ToString();
SetupGetStringField(ref context, 2, infData, MAX_INF_STRING_LENGTH, out requiredSize);
Version = infData.ToString();
}
else
{
Date = "01/01/1990";
Version = "0.0";
}
// Get the PnP ID information, first for an undecorated section
if (SetupFindFirstLine(theInf, deviceSection, null, out context))
{
// If platforms doesn't include x86, add it since this section only would exist if x86 is supported.
found = false;
foreach (String p in Platforms)
if (p == "x86")
found = true;
if (!found)
{
Platforms.Add("x86");
}
// Get the PnP IDs
do
{
uint fieldCount = SetupGetFieldCount(ref context);
for (uint i = 2; i <= fieldCount; i++)
{
SetupGetStringField(ref context, i, infData, MAX_INF_STRING_LENGTH, out requiredSize);
if (!PNPIds.Contains(infData.ToString()))
PNPIds.Add(infData.ToString());
}
}
while (SetupFindNextLine(ref context, out context));
}
// Now try the suffixes
foreach (String suffix in suffixList)
{
if (SetupFindFirstLine(theInf, deviceSection + "." + suffix, null, out context))
{
// Get the PnP IDs
do
{
uint fieldCount = SetupGetFieldCount(ref context);
for (uint i = 2; i <= fieldCount; i++)
{
SetupGetStringField(ref context, i, infData, MAX_INF_STRING_LENGTH, out requiredSize);
if (!PNPIds.Contains(infData.ToString()))
PNPIds.Add(infData.ToString());
}
}
while (SetupFindNextLine(ref context, out context));
}
}
// Finished, clean up
SetupCloseInfFile(theInf);
}
[DllImport("setupapi.dll", EntryPoint = "SetupOpenInfFileW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr SetupOpenInfFile(
string infFile, uint infClass, uint infStyle, out uint errorLine);
[DllImport("setupapi.dll", EntryPoint = "SetupCloseInfFile", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern void SetupCloseInfFile(
IntPtr hInf);
[DllImport("setupapi.dll", EntryPoint = "SetupFindFirstLineW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupFindFirstLine(
IntPtr hInf, string section, string key, out INFCONTEXT context);
[DllImport("setupapi.dll", EntryPoint = "SetupFindNextLine", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupFindNextLine(
ref INFCONTEXT inContext, out INFCONTEXT outContext);
[DllImport("setupapi.dll", EntryPoint = "SetupGetStringFieldW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupGetStringField(
ref INFCONTEXT context, uint index, StringBuilder returnBuffer, uint returnBufferSize, out uint requiredSize);
[DllImport("setupapi.dll", EntryPoint = "SetupDiClassNameFromGuidW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool SetupDiClassNameFromGuid(
ref Guid theGuid, StringBuilder returnBuffer, uint returnBufferSize, out uint requiredSize);
[DllImport("setupapi.dll", EntryPoint = "SetupGetFieldCount", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint SetupGetFieldCount(
ref INFCONTEXT context);
}
}
'@
#########################################################
# Here I leverage one of my favorite features (here-strings) to define
# the C# code I want to run. Remember - if you use single quotes - the
# string is taken literally but if you use double-quotes, we'll do variable
# expansion. This can be VERY useful.
#########################################################
$code = @'
using System;
using System.Runtime.InteropServices;
namespace test
{
public class Testclass
{
[DllImport("msvcrt.dll")]
public static extern int puts(string c);
[DllImport("msvcrt.dll")]
internal static extern int _flushall();
public static void Run(string message)
{
puts(message);
_flushall();
}
}
}
'@
########################################################
# So now we compile the code and use .NET object access to run it.
########################################################
#Write-Host "asfdaf"
#compile-CSharp $code
#[Test.TestClass]::Run("Monad ROCKS!")
##compile the code
Compile-Csharp $txtCode
$infInfo = [MDTCustom]::InfInfo("D:\\Drivers\\DC7100\\Modem\\LTDFNT.INF")
$infInfo.PNPIds
#Function CheckDirectory($directoryPath)
#{
# #get all the inf files in this directory
# $files = Get-ChildItem $directoryPath *.inf
#
# #see if we already know about this one and if now create one
# foreach($currentFile in $files)
# {
# $newRow = $false
# $theItem = Find($currentFile)
# }
#
#}
#
#
#Function FindInfFile($infFile)
#{
#
#}
#
|
PowerShellCorpus/PoshCode/GPRS Online log_1.ps1
|
GPRS Online log_1.ps1
|
################################################################################
# Get-GprsTime.ps1(V 1008)
# Check the total connect time of any GPRS devices from a specified date.
# Use the -Verbose switch for some extra information if desired. A default value
# can be set with the -Monthly switch but can be temporarily overridden with any
# -Start value and deleted by entering an invalid date. Now uses .NET Parse to
# use any culture date input. Switches -M and -S cannot be used together.
# A Balloon prompt will be issued in the Notification area for the 5 days
# before the nominal month end, and a suitable Icon (exclamation.ico) file needs
# to be available in the $PWD directory for this to work.
# NOTE: this can effectively be suppressed by using a value higher than the SIM
# card term, ie something like -Account 90 for a 30 day card which will override
# the default setting. Use -Today to check only today's usage.
# Use 'Set-Alias Get-GprsTime -Account 30' to set value permanently to 30 days.
# Examples:
# .\\Get-GprsTime.ps1 -Monthly 4/8/2009
# .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose
# .\\Get-GprsTime.ps1 -m 5/9/2009
# .\\Get-GprsTime.ps1 10/4/2009 -v
# .\\Get-GprsTime.ps1 -v
# .\\Get-GprsTime.ps1 -Today
# .\\Get-GprsTime.ps1
#
# The author can be contacted at www.SeaStarDevelopment.Bravehost.com and the
# 'exclamation.ico' file is included in the Gprs100x.zip download there.
################################################################################
Param ([String] $start,
[String] $monthly,
[Int] $account = 0, #Start warning prompt 5 days before month end.
[Switch] $today,
[Switch] $verbose,
[Switch] $debug)
Trap [System.Management.Automation.MethodInvocationException] {
[Int]$line = $error[0].InvocationInfo.ScriptLineNumber
[System.Media.SystemSounds]::Hand.Play()
If ($line -eq 165) {
Write-Warning "[$name] Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
Else {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
}
Exit 1
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly can only be used separately."
If ($debug) {
$DebugPreference = 'Continue'
}
If ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
Exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
If ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
If ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$ErrorActionPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $default = $print = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00.
$insert = "since"
If ($verbose) {
$VerbosePreference = 'Continue'
}
Function CreditMsg ($value, $value2) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
[DateTime] $creditDT = $value2
$creditDT = $creditDT.AddDays($value) #Add the -Account days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below we
#can sometimes get a value of 1 returned instead 2, hence the above lines.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
Return $prefix
}
Function Interval ([String] $value) {
Switch($value) {
{ $_ -match '^00:00:\\d+(.*)$' } {$suffix = "seconds"; break}
{ $_ -match '^00:\\d+:\\d+(.*)$'} {$suffix = "minutes"; break}
Default {$suffix = " hours"}
}
Return $suffix
}
Function CheckSetting ($value) {
If ($value) {
$print = $default.ToShortDateString() #Correct for local culture.
}
Else {
$print = "(Value not set)"
}
Return $print
}
#The Script effectively starts here.............................................
$getGprs = [Environment]::GetEnvironmentVariable("GPRS","User")
#First check for GPRS variable and change from US date format to current locale.
If ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid.
$default = "{0:d}" -f [datetime]$getGprs
$default = [DateTime]::Parse($default)
$checkYear = "{0:yyyy}" -f $default
$checkMonth = "{0:%M}" -f $default
$dayCount = [DateTime]::DaysInMonth($checkYear,$checkMonth) #Range 28-31.
If($account -eq 0) {
$account = $dayCount
$summary = "$($dayCount.ToString()) days"
}
Else {
$summary = "$($account.Tostring()) days"
}
$text = CreditMsg $account $getGprs #Check if within 5 days of expiry date.
If (($text -ne "CURRENT") -and (Test-Path "$pwd\\exclamation.ico") ) {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = "$pwd\\exclamation.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
}
Else {
$summary = "(Days not set)"
If ((!$today) -and (!$monthly) -and (!$start)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning("Monthly date is either invalid or not set.")
Exit 1
}
}
If ($start) {
$start = [DateTime]::Parse($start) #Trigger TRAP if invalid!
[DateTime]$limit = $start
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
If ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
$print = $limit.ToShortDateString()
$summary = "(Days undetermined)" #Will show next time around.
}
If ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
$print = CheckSetting $default
}
If ((!$today) -and (!$monthly) -and (!$start)) {
If ($default) {
$monthly = $default
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print"
$lines = Get-EventLog system | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq 20159 -or $_.EventID -eq 20158)}
If ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
Else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
$source = $_.Source
If ($_.EventID -eq 20159) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
Else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
If ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $diff $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
If (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
Write-Output "Total online usage $insert $convert is $total $($period.Trim())."
Write-Output ""
|
PowerShellCorpus/PoshCode/Set-IPAddress_2.ps1
|
Set-IPAddress_2.ps1
|
function Set-IPAddress {
param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"),
[string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"),
[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"),
[string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"),
[string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"),
[string]$dns2,
[string]$registerDns = "TRUE"
)
$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.EnableStatic($ip, $subnetmask)
$NetInterface.SetGateways($gateway)
$NetInterface.SetDNSServerSearchOrder($dns)
$NetInterface.SetDynamicDNSRegistration($registerDns)
}
|
PowerShellCorpus/PoshCode/ExceptionHandling.ps1
|
ExceptionHandling.ps1
|
## ExceptionHandling.ps1
##############################################################################################################
## .Net style exception handling
##############################################################################################################
## Usage:
## . .\\ExceptionHandling.ps1
##############################################################################################################
## v 1.0 - First release
##############################################################################################################
if (-not ($MyInvocation.line -match '^\\. .')) {
Write-Error 'No Functions were loaded - you need to invoke with . scriptname'
return
}
# .SYNOPSIS
# Facilitates exception handling as used to under C# or Java
#
# .PARAMETER Command
# Contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
# .INPUTS
# None. You cannot pipe objects to try().
#
# .EXAMPLE
# function simpleException() {
# try {
# "Guarded code"
# throw New-Object [System.Exception]
# } -catch {
# "Catched " + $_.Exception
# } -finally {
# "All done with trying and catching"
# }
# }
#
# .EXAMPLE
# function multiDivByZeroSpecified() {
# try {
# [int32]1/[int32]0
# } -catch @{[System.DivideByZeroException] = {
# "Catched DivideByZeroException"
# }} -catch1 @{[System.Exception] = {
# "Catched Exception"
# }} -finally {
# "All done with trying and catching"
# }
# }
#
# .EXAMPLE
# function multiDivByZero() {
# try {
# [int32]1/[int32]0
# } -catch @{[System.DivideByZeroException] = {
# "Catched DivideByZeroException"
# }} -catch1 {
# "Catched Exception"
# } -finally {
# "All done with trying and catching"
# }
# }
#
# .LINK
# trap
# .LINK
# http://huddledmasses.org/trap-exception-in-powershell/
# .LINK
# http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx
function try {
param (
[ScriptBlock] $command = $( throw "The parameter -Command is required." ),
[Object] $catch,
[Object] $catch1,
[Object] $catch2,
[Object] $catch3,
[Object] $catch4,
[Object] $catch5,
[Object] $catch6,
[Object] $catch7,
[Object] $catch8,
[Object] $catch9,
[ScriptBlock] $finally = {}
)
# merge all catches to one single hashtable
$catches = @{}
($catch,$catch1,$catch2,$catch3,$catch4,$catch5,$catch6,$catch7,$catch8,$catch9) | ? { $_ -ne $null } | % {
if ($_ -is [System.Collections.Hashtable]) {
$catches += $_
} elseif ($_ -is [ScriptBlock]) {
if ($catches.Contains([System.Exception])) {
$catches.set_Item([System.Exception], $_)
} else {
$catches.Add([System.Exception], $_)
}
} else {
throw New-Object Exception("Unknown catch argument type'" + $_.GetType() + "'")
}
}
& {
$local:ErrorActionPreference = "SilentlyContinue"
trap {
trap {
& {
trap { throw $_ }
&$finally
}
throw $_
}
$exType = $_.Exception.GetType()
$catch = $null
do {
$catches.GetEnumerator() | ? { $exType -eq $_.Key } | % { $catch = $_.Value }
if ($catch -ne $null) {
break
}
$exType = $exType.BaseType
} while ($exType -ne $null)
if ($catch -eq $null) { throw $_ }
$_ | & { &$catch }
}
&$command
}
& {
trap { throw $_ }
&$finally
}
}
|
PowerShellCorpus/PoshCode/802afd05-1132-4f41-9443-b27fbe20dfd8.ps1
|
802afd05-1132-4f41-9443-b27fbe20dfd8.ps1
|
function Get-Pecoff
{
<#
.SYNOPSIS
Takes file-name and outputs fileobject with two more properties
poff_characteristic and poff_machinetype
.DESCRIPTION
This function creates file objects with PE properties for characteristic and machinetype
.EXAMPLE
For output from get-childitem or any other cmdlet that produces file objects from Win7 x64 machine.
Get-ChildItem "C:\\Windows\\System32"|where {$_.Extension -like ".dll" -or $_.Extension -like ".exe"}|Get-Pecoff|select poff_machinetype,poff_characteristic,fullname|format-table -autosize
poff_machinetype poff_characteristic FullName
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\aaclient.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\accessibilitycpl.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ACCTRES.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acledit.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\aclui.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acppage.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acproxy.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionCenter.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionCenterCPL.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionQueue.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\activeds.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\actxprxy.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\AdapterTroubleshooter.exe
o
o
I386 EXECUTABLE,LINE_NUMS_STRIPPED,32BIT_MACHINE,LOCAL_SYMS_STRIPPED C:\\Windows\\System32\\TsWpfWrp.exe
o
AMD64 NET_RUN_FROM_SWAP,EXECUTABLE,REMOVABLE_RUN_FROM_SWAP,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xmllite.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xmlprovi.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xolehlp.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsFilt.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsGdiConverter.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsPrint.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsRasterService.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpsrchvw.exe
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpsservices.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XPSSHHDR.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpssvcs.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwizard.exe
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwizards.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwreg.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwtpdui.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwtpw32.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\zgmprxy.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\zipfldr.dll
Where AMD64 means 64 bit app.
Where I386 means 32 bit app.
There are other archetectures than AMD64, I384: AM33 AMD64 ARM ARMV7 EBC IA64 M32R MIPS16 MIPSFPU MIPSFPU16
POWERPC POWERPCFP R4000 SH3 SH3DSP SH4 SH5 THUMB WCEMIPSV2
Where NoPE means file did not use PE standard
NoPE NoPE C:\\Windows\\SysWOW64\\typelib.dll
Where:
RELOCS_STRIPPED = 0x1,
Relocation info stripped from file.
EXECUTABLE = 0x2,
File is executable (i.e. no unresolved external references).
LINE_NUMS_STRIPPED = 0x4,
Line numbers stripped from file.
LOCAL_SYMS_STRIPPED = 0x8,
Local symbols stripped from file.
AGGRESSIVE_WS_TRIM = 0x10,
Aggressively trim working set
LARGE_ADDRESS_AWARE = 0x20,
For x86 applications:
on x86 OS
With special effort can allow access to 3Gb
on x64 OS
application can access 4GB
For x64 applications
on x64 OS
application can access 64 bits.
BYTES_REVERSED_LO = 0x80,
Bytes of machine word are reversed.
32BIT_MACHINE = 0x100,
32 bit word machine.
DEBUG_STRIPPED = 0x200,
Debugging info stripped from file in .DBG file
REMOVABLE_RUN_FROM_SWAP = 0x400,
If Image is on removable media, copy and run from the swap file.
Not Sure Why system32 files would have this but they are on my 64bit win 7
NET_RUN_FROM_SWAP = 0x800,
If Image is on Net, copy and run from the swap file.
Not Sure Why system32 files would have this but they are on my 64bit win 7
SYSTEM = 0x1000,
System File.
DLL = 0x2000,
File is a DLL.
UP_SYSTEM_ONLY = 0x4000,
File should only be run on a UP machine
BYTES_REVERSED_HI = 0x8000
Bytes of machine word are reversed.
If get-pecoff cannot determine the file characteristic it will display the hex instead.
This has been useful in debugging the table.
.EXAMPLE
For a single file:
Get-Pecoff -filename "C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\x64\\MdbgCore.dll"|select poff_machinetype,poff_characteristic,fullname|format-table -autosize
.PARAMETER filename
The full path of file to query.
Get-Pecoff can take the output of getchilditem
Creates file object output that has pe characteristic and pe machinetype properties added
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[Alias('fullname')]
[string]$filename=""
)
process {
#"filename " + $filename
$characteristics = @{}
# these entries were prefixed with IMAGE_FILE_ such as IMAGE_FILE_EXECUTABLE
$characteristics["RELOCS_STRIPPED"] = 0x0001
$characteristics["EXECUTABLE"] = 0x0002
$characteristics["LINE_NUMS_STRIPPED"] = 0x0004
$characteristics["LOCAL_SYMS_STRIPPED"] = 0x0008
$characteristics["AGGRESSIVE_WS_TRIM"] = 0x0010
$characteristics["LARGE_ADDRESS_AWARE"] = 0x0020
$characteristics["RESERVED"] = 0x0040
$characteristics["BYTES_REVERSED_LO"] = 0x0080
$characteristics["32BIT_MACHINE"] = 0x0100
$characteristics["DEBUG_STRIPPED"] = 0x0200
$characteristics["REMOVABLE_RUN_FROM_SWAP"] = 0x0400
$characteristics["NET_RUN_FROM_SWAP"] = 0x0800
$characteristics["SYSTEM"] = 0x1000
$characteristics["DLL"] = 0x2000
$characteristics["UP_SYSTEM_ONLY"] = 0x4000
$characteristics["BYTES_REVERSED_HI"] = 0x8000
#$fileBytes = Get-Content $filename -ReadCount 0 -Encoding byte
$stream=[System.IO.File]::OpenRead($filename)
$fileBytes = New-Object byte[] 1024
$bytesRead = $stream.Read($fileBytes,0,1024)
$signatureOffset = 256*$fileBytes[0x3d]+$fileBytes[0x3c]
#$signatureoffset
$signature = [char[]] $fileBytes[$signatureOffset..($signatureOffset + 3)]
if([String]::Join('', $signature) -ieq "PE`0`0")
{
$coffHeader = $signatureOffset + 4
$characteristicsData = [BitConverter]::ToInt32($fileBytes, $coffHeader + 18)
$poff_characteristic=""
foreach($key in $characteristics.Keys)
{
$flag = $characteristics[$key]
if(($characteristicsData -band $flag) -eq $flag)
{
if ($poff_characteristic -eq "") {$poff_characteristic=$key} else {$poff_characteristic=$poff_characteristic+","+$key}
}
}
$machineDatabin=[BitConverter]::ToInt32($fileBytes, $coffHeader)
$machineDatabin=$machineDatabin -band 0xFFFF # only need lower 2 bytes
$machineData="0x"+[STRING]::Format("{0:X}",$machineDatabin) #.substring(1)
#$machineData
$machineTypes=@{}
# These items used to be prefixed with IMAGE_FILE_MACHINE_ such as IMAGE_FILE_MACHINE_AMD64
$machineTypes["0x"] = "UNKNOWN"
$machineTypes["0x1d3"] = "AM33"
$machineTypes["0x8664"] = "AMD64"
$machineTypes["0x1c0"] = "ARM"
$machineTypes["0x1c4"] = "ARMV7"
$machineTypes["0xebc"] = "EBC"
$machineTypes["0x14c"] = "I386"
$machineTypes["0x200"] = "IA64"
$machineTypes["0x9041"] = "M32R"
$machineTypes["0x266"] = "MIPS16"
$machineTypes["0x366"] = "MIPSFPU"
$machineTypes["0x466"] = "MIPSFPU16"
$machineTypes["0x1f0"] = "POWERPC"
$machineTypes["0x1f1"] = "POWERPCFP"
$machineTypes["0x166"] = "R4000"
$machineTypes["0x1a2"] = "SH3"
$machineTypes["0x1a3"] = "SH3DSP"
$machineTypes["0x1a6"] = "SH4"
$machineTypes["0x1a8"] = "SH5"
$machineTypes["0x1c2"] = "THUMB"
$machineTypes["0x169"] = "WCEMIPSV2"
$poff_machinetype=$machineTypes[$machineData]
if ($poff_machinetype -eq "" -or $poff_machinetype -eq $null) {$poff_machinetype=$machineData}
}
else
{
$poff_characteristic="NoPE"
$poff_machinetype="NoPE"
}
$obj=get-childitem $filename
$obj|Add-Member -MemberType NoteProperty "poff_characteristic" $poff_characteristic
$obj|Add-Member -MemberType NoteProperty "poff_machinetype" $poff_machinetype
#$obj|gm
Write-Output $obj
}
}
|
PowerShellCorpus/PoshCode/AddTo-HostsFile.ps1
|
AddTo-HostsFile.ps1
|
function AddTo-HostsFile{
<#
.DESCRIPTION
This function checks to see if an entry exists in the hosts file.
If it does not, it attempts to add it and verifies the entry.
.EXAMPLE
Networkign.AddTo-Hosts -IPAddress 192.168.0.1 -HostName MyMachine
.EXTERNALHELP
None.
.FORWARDHELPTARGETNAME
None.
.INPUTS
System.String.
.LINK
None.
.NOTES
None.
.OUTPUTS
System.String.
.PARAMETER IPAddress
A string representing an IP address.
.PARAMETER HostName
A string representing a host name.
.SYNOPSIS
Add entries to the hosts file.
#>
param(
[parameter(Mandatory=$true,position=0)]
[string]
$IPAddress,
[parameter(Mandatory=$true,position=1)]
[string]
$HostName
)
$HostsLocation = "$env:windir\\System32\\drivers\\etc\\hosts";
$NewHostEntry = "`t$IPAddress`t$HostName";
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Utility.Time-Stamp): The hosts file already contains the entry: $NewHostEntry. File not updated.";
}
else
{
Write-Host "$(Utility.Time-Stamp): The hosts file does not contain the entry: $NewHostEntry. Attempting to update.";
Add-Content -Path $HostsLocation -Value $NewHostEntry;
}
# Validate entry
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Utility.Time-Stamp): New entry, $NewHostEntry, added to $HostsLocation.";
}
else
{
Write-Host "$(Utility.Time-Stamp): The new entry, $NewHostEntry, was not added to $HostsLocation.";
}
}
|
PowerShellCorpus/PoshCode/Show-Sample_1.ps1
|
Show-Sample_1.ps1
|
if(!(Get-Command New-System.Windows.Input.CommandBinding -ErrorAction SilentlyContinue)) {
Add-UIFunction -Type System.Windows.Input.CommandBinding
}
Show -Width 300 -Height 150 {
DockPanel {
Menu -DockPanel-Dock Top -Height 20 {
MenuItem -Header "_File" {
## Hook up the "New" menuitem to the New command ...
MenuItem -Header "_New" -Command ([system.windows.input.applicationcommands]::new)
MenuItem -Header "_Open"
MenuItem -Header "_Save"
MenuItem -Header "Save _As"
Separator
MenuItem -Header "_Print"
Separator
MenuItem -Header "E_xit"
}
MenuItem -Header "_Edit" {
MenuItem -Header "_Undo"
Separator
MenuItem -Header "Cu_t"
MenuItem -Header "_Copy"
MenuItem -Header "_Paste"
MenuItem -Header "De_lete"
Separator
MenuItem -Header "_Find"
MenuItem -Header "Find _Next"
MenuItem -Header "_Replace"
MenuItem -Header "_Go To"
Separator
MenuItem -Header "Select _All"
MenuItem -Header "Time/_Date"
}
MenuItem -Header "F_ormat" {
MenuItem -Header "_Word Wrap"
MenuItem -Header "_Font"
}
MenuItem -Header "_View" {
MenuItem -Header "_Status Bar"
}
MenuItem -Header "_Help" {
MenuItem -Header "_About"
}
}
TextBox -Name "Content"
}
## Down here you can hook up command bindings as usual...
$this.CommandBindings.Add( (
CommandBinding -Command ([system.windows.input.applicationcommands]::new) `
-On_CanExecute { param($sender, $e) $e.CanExecute = $true } `
-On_Executed { (Select-UIElement $this Content).Text = ""; }
) ) | Out-Null
}
|
PowerShellCorpus/PoshCode/New-CommandWrapper.ps1
|
New-CommandWrapper.ps1
|
##############################################################################\n##\n## New-CommandWrapper\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nAdds parameters and functionality to existing cmdlets and functions.\n\n.EXAMPLE\n\nNew-CommandWrapper Get-Process `\n -AddParameter @{\n SortBy = {\n $newPipeline = {\n __ORIGINAL_COMMAND__ | Sort-Object -Property $SortBy\n }\n }\n }\n\nThis example adds a 'SortBy' parameter to Get-Process. It accomplishes\nthis by adding a Sort-Object command to the pipeline.\n\n.EXAMPLE\n\n$parameterAttributes = @'\n [Parameter(Mandatory = $true)]\n [ValidateRange(50,75)]\n [Int]\n'@\n\nNew-CommandWrapper Clear-Host `\n -AddParameter @{\n @{\n Name = 'MyMandatoryInt';\n Attributes = $parameterAttributes\n } = {\n Write-Host $MyMandatoryInt\n Read-Host "Press ENTER"\n }\n }\n\nThis example adds a new mandatory 'MyMandatoryInt' parameter to\nClear-Host. This parameter is also validated to fall within the range\nof 50 to 75. It doesn't alter the pipeline, but does display some\ninformation on the screen before processing the original pipeline.\n\n#>\n\nparam(\n ## The name of the command to extend\n [Parameter(Mandatory = $true)]\n $Name,\n\n ## Script to invoke before the command begins\n [ScriptBlock] $Begin,\n\n ## Script to invoke for each input element\n [ScriptBlock] $Process,\n\n ## Script to invoke at the end of the command\n [ScriptBlock] $End,\n\n ## Parameters to add, and their functionality.\n ##\n ## The Key of the hashtable can be either a simple parameter name,\n ## or a more advanced parameter description.\n ##\n ## If you want to add additional parameter validation (such as a\n ## parameter type,) then the key can itself be a hashtable with the keys\n ## 'Name' and 'Attributes'. 'Attributes' is the text you would use when\n ## defining this parameter as part of a function.\n ##\n ## The Value of each hashtable entry is a scriptblock to invoke\n ## when this parameter is selected. To customize the pipeline,\n ## assign a new scriptblock to the $newPipeline variable. Use the\n ## special text, __ORIGINAL_COMMAND__, to represent the original\n ## command. The $targetParameters variable represents a hashtable\n ## containing the parameters that will be passed to the original\n ## command.\n [HashTable] $AddParameter\n)\n\nSet-StrictMode -Version Latest\n\n## Store the target command we are wrapping, and its command type\n$target = $Name\n$commandType = "Cmdlet"\n\n## If a function already exists with this name (perhaps it's already been\n## wrapped,) rename the other function and chain to its new name.\nif(Test-Path function:\\$Name)\n{\n $target = "$Name" + "-" + [Guid]::NewGuid().ToString().Replace("-","")\n Rename-Item function:\\GLOBAL:$Name GLOBAL:$target\n $commandType = "Function"\n}\n\n## The template we use for generating a command proxy\n$proxy = @'\n\n__CMDLET_BINDING_ATTRIBUTE__\nparam(\n__PARAMETERS__\n)\nbegin\n{\n try {\n __CUSTOM_BEGIN__\n\n ## Access the REAL Foreach-Object command, so that command\n ## wrappers do not interfere with this script\n $foreachObject = $executionContext.InvokeCommand.GetCmdlet(\n "Microsoft.PowerShell.Core\\Foreach-Object")\n\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(\n '__COMMAND_NAME__',\n [System.Management.Automation.CommandTypes]::__COMMAND_TYPE__)\n\n ## TargetParameters represents the hashtable of parameters that\n ## we will pass along to the wrapped command\n $targetParameters = @{}\n $PSBoundParameters.GetEnumerator() |\n & $foreachObject {\n if($command.Parameters.ContainsKey($_.Key))\n {\n $targetParameters.Add($_.Key, $_.Value)\n }\n }\n\n ## finalPipeline represents the pipeline we wil ultimately run\n $newPipeline = { & $wrappedCmd @targetParameters }\n $finalPipeline = $newPipeline.ToString()\n\n __CUSTOM_PARAMETER_PROCESSING__\n\n $steppablePipeline = [ScriptBlock]::Create(\n $finalPipeline).GetSteppablePipeline()\n $steppablePipeline.Begin($PSCmdlet)\n } catch {\n throw\n }\n}\n\nprocess\n{\n try {\n __CUSTOM_PROCESS__\n $steppablePipeline.Process($_)\n } catch {\n throw\n }\n}\n\nend\n{\n try {\n __CUSTOM_END__\n $steppablePipeline.End()\n } catch {\n throw\n }\n}\n\ndynamicparam\n{\n ## Access the REAL Get-Command, Foreach-Object, and Where-Object\n ## commands, so that command wrappers do not interfere with this script\n $getCommand = $executionContext.InvokeCommand.GetCmdlet(\n "Microsoft.PowerShell.Core\\Get-Command")\n $foreachObject = $executionContext.InvokeCommand.GetCmdlet(\n "Microsoft.PowerShell.Core\\Foreach-Object")\n $whereObject = $executionContext.InvokeCommand.GetCmdlet(\n "Microsoft.PowerShell.Core\\Where-Object")\n\n ## Find the parameters of the original command, and remove everything\n ## else from the bound parameter list so we hide parameters the wrapped\n ## command does not recognize.\n $command = & $getCommand __COMMAND_NAME__ -Type __COMMAND_TYPE__\n $targetParameters = @{}\n $PSBoundParameters.GetEnumerator() |\n & $foreachObject {\n if($command.Parameters.ContainsKey($_.Key))\n {\n $targetParameters.Add($_.Key, $_.Value)\n }\n }\n\n ## Get the argumment list as it would be passed to the target command\n $argList = @($targetParameters.GetEnumerator() |\n Foreach-Object { "-$($_.Key)"; $_.Value })\n\n ## Get the dynamic parameters of the wrapped command, based on the\n ## arguments to this command\n $command = $null\n try\n {\n $command = & $getCommand __COMMAND_NAME__ -Type __COMMAND_TYPE__ `\n -ArgumentList $argList\n }\n catch\n {\n\n }\n\n $dynamicParams = @($command.Parameters.GetEnumerator() |\n & $whereObject { $_.Value.IsDynamic })\n\n ## For each of the dynamic parameters, add them to the dynamic\n ## parameters that we return.\n if ($dynamicParams.Length -gt 0)\n {\n $paramDictionary = `\n New-Object Management.Automation.RuntimeDefinedParameterDictionary\n foreach ($param in $dynamicParams)\n {\n $param = $param.Value\n $arguments = $param.Name, $param.ParameterType, $param.Attributes\n $newParameter = `\n New-Object Management.Automation.RuntimeDefinedParameter `\n $arguments\n $paramDictionary.Add($param.Name, $newParameter)\n }\n return $paramDictionary\n }\n}\n\n<#\n\n.ForwardHelpTargetName __COMMAND_NAME__\n.ForwardHelpCategory __COMMAND_TYPE__\n\n#>\n\n'@\n\n## Get the information about the original command\n$originalCommand = Get-Command $target\n$metaData = New-Object System.Management.Automation.CommandMetaData `\n $originalCommand\n$proxyCommandType = [System.Management.Automation.ProxyCommand]\n\n## Generate the cmdlet binding attribute, and replace information\n## about the target\n$proxy = $proxy.Replace("__CMDLET_BINDING_ATTRIBUTE__",\n $proxyCommandType::GetCmdletBindingAttribute($metaData))\n$proxy = $proxy.Replace("__COMMAND_NAME__", $target)\n$proxy = $proxy.Replace("__COMMAND_TYPE__", $commandType)\n\n## Stores new text we'll be putting in the param() block\n$newParamBlockCode = ""\n\n## Stores new text we'll be putting in the begin block\n## (mostly due to parameter processing)\n$beginAdditions = ""\n\n## If the user wants to add a parameter\n$currentParameter = $originalCommand.Parameters.Count\nif($AddParameter)\n{\n foreach($parameter in $AddParameter.Keys)\n {\n ## Get the code associated with this parameter\n $parameterCode = $AddParameter[$parameter]\n\n ## If it's an advanced parameter declaration, the hashtable\n ## holds the validation and / or type restrictions\n if($parameter -is [Hashtable])\n {\n ## Add their attributes and other information to\n ## the variable holding the parameter block additions\n if($currentParameter -gt 0)\n {\n $newParamBlockCode += ","\n }\n\n $newParamBlockCode += "`n`n " +\n $parameter.Attributes + "`n" +\n ' $' + $parameter.Name\n\n $parameter = $parameter.Name\n }\n else\n {\n ## If this is a simple parameter name, add it to the list of\n ## parameters. The proxy generation APIs will take care of\n ## adding it to the param() block.\n $newParameter =\n New-Object System.Management.Automation.ParameterMetadata `\n $parameter\n $metaData.Parameters.Add($parameter, $newParameter)\n }\n\n $parameterCode = $parameterCode.ToString()\n\n ## Create the template code that invokes their parameter code if\n ## the parameter is selected.\n $templateCode = @"\n\n if(`$PSBoundParameters['$parameter'])\n {\n $parameterCode\n\n ## Replace the __ORIGINAL_COMMAND__ tag with the code\n ## that represents the original command\n `$alteredPipeline = `$newPipeline.ToString()\n `$finalPipeline = `$alteredPipeline.Replace(\n '__ORIGINAL_COMMAND__', `$finalPipeline)\n }\n"@\n\n ## Add the template code to the list of changes we're making\n ## to the begin() section.\n $beginAdditions += $templateCode\n $currentParameter++\n }\n}\n\n## Generate the param() block\n$parameters = $proxyCommandType::GetParamBlock($metaData)\nif($newParamBlockCode) { $parameters += $newParamBlockCode }\n$proxy = $proxy.Replace('__PARAMETERS__', $parameters)\n\n## Update the begin, process, and end sections\n$proxy = $proxy.Replace('__CUSTOM_BEGIN__', $Begin)\n$proxy = $proxy.Replace('__CUSTOM_PARAMETER_PROCESSING__', $beginAdditions)\n$proxy = $proxy.Replace('__CUSTOM_PROCESS__', $Process)\n$proxy = $proxy.Replace('__CUSTOM_END__', $End)\n\n## Save the function wrapper\nWrite-Verbose $proxy\nSet-Content function:\\GLOBAL:$NAME $proxy\n\n## If we were wrapping a cmdlet, hide it so that it doesn't conflict with\n## Get-Help and Get-Command\nif($commandType -eq "Cmdlet")\n{\n $originalCommand.Visibility = "Private"\n}
|
PowerShellCorpus/PoshCode/elevate-process (sudo)_1.ps1
|
elevate-process (sudo)_1.ps1
|
function elevate-process
{
$file, [string]$arguments = $args;
$psi = new-object System.Diagnostics.ProcessStartInfo $file;
$psi.Arguments = $arguments;
$psi.Verb = "runas";
$psi.WorkingDirectory = get-location;
[System.Diagnostics.Process]::Start($psi);
}
set-alias sudo elevate-process;
|
PowerShellCorpus/PoshCode/Xml Module 6.5.ps1
|
Xml Module 6.5.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
# Version 6.1 Update for PowerShell 3.0
# Version 6.2 Minor tweak in exception handling for CliXml
# Version 6.3 Added Remove-XmlElement to allow removing nodes or attributes
# This is something I specifically needed to remove "ignorable" namespaces
# Specifically, the ones created by the Visual Studio Workflow designer (and perhaps other visual designers like Blend)
# Which I don't want to check into source control, because it makes diffing nearly impossible
# Version 6.4 Fixed a bug on New-XElement for Rudy Shockaert (nice bug report, thanks!)
# Version 6.5 Added -Parameters @{} parameter to New-XDocument to allow local variables to be passed into the module scope. *grumble*
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( $a, $Type)
} else {
$null = $xlr8r::Remove( $a )
$xlr8r::Add( $a, $Type)
}
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
&{
$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] } | Add-Accelerator
Add-Accelerator "Dictionary" "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Add-Accelerator "PSParser" "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
function Get-XmlContent {
#.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") {
Write-Verbose $file.ProviderPath
$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 Import-Xml Get-XmlContent
Set-Alias ipxml Get-XmlContent
Set-Alias ipx Get-XmlContent
Set-Alias Get-Xml Get-XmlContent
Set-Alias gxml Get-XmlContent
Set-Alias gx Get-XmlContent
function Set-XmlContent {
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 Export-Xml Set-XmlContent
Set-Alias epxml Set-XmlContent
Set-Alias epx Set-XmlContent
Set-Alias Set-Xml Set-XmlContent
Set-Alias sxml Set-XmlContent
Set-Alias sx Set-XmlContent
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, 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 be 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
function Remove-XmlElement {
#.Synopsis
# Removes specified elements (tags or attributes) or all elements from a specified namespace from an Xml document
#.Description
# Runs an xml document through an XSL Transformation to remove tag 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 be one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=0,ParameterSetName="Xml")] #,Mandatory=$true
#[ValidateNotNullOrEmpty()]
[XNamespace[]]$Namespace
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
BEGIN {
foreach($Node in @($Xml)) {
$Allspaces += Get-Namespace -Xml $Node
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Allspaces.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
# If no namespaces are passed in, use the "ignorable" ones from XAML if there are any
if(!$Namespace) {
$root = $Node.DocumentElement
# $nsManager = new-object System.Xml.XmlNamespaceManager $Node.NameTable
$nsManager.AddNamespace("compat", "http://schemas.openxmlformats.org/markup-compatibility/2006")
if($ignorable = $root.SelectSingleNode("@compat:Ignorable",$nsManager)) {
foreach($prefix in $ignorable.get_InnerText().Split(" ")) {
$Namespace += $root.GetNamespaceOfPrefix($prefix)
}
}
}
}
Write-Verbose "$Namespace"
$i = 0
$NSString = $(foreach($n in $Namespace) { "xmlns:n$i='$n'"; $i+=1 }) -Join " "
$EmptyTransforms = $(for($i =0; $i -lt $Namespace.Count;$i++) {
"<xsl:template match='n${i}:*'>
</xsl:template>
<xsl:template match='@n${i}:*'>
</xsl:template>"
})
$XSLT = @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" $NSString>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
$EmptyTransforms
</xsl:stylesheet>
"@
Write-Verbose $XSLT
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $XSLT))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$Xml | Convert-Node $StyleSheet
}
}
#Set-Alias rmns Remove-XmlNamespace -EA 0
#Set-Alias rmxns Remove-XmlNamespace -EA 0
function Get-Namespace {
param(
[Parameter(Position=0)]
[String[]]$Prefix = "*"
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
foreach($Node in @($Xml)) {
$results = @{}
if($Node -is [Xml.XmlDocument]) {
$Node = $Node.DocumentElement
}
foreach($ns in $Node.CreateNavigator().GetNamespacesInScope("All").GetEnumerator()) {
foreach($p in $Prefix) {
if($ns.Key -like $p) {
$results.Add($ns.Key, $ns.Value)
break;
}
}
}
$results
}
}
######## 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 = [psobject].assembly.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 $xmlString"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [psobject].assembly.gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null)
$sw = new-object System.IO.StringWriter
$xw = new-object System.Xml.XmlTextWriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
}
process {
try {
[void]$method.invoke($serializer, $InputObject)
} catch {
write-warning "Could not serialize $($InputObject.gettype()): $InputObject"
}
}
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
#.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(
# The root node name
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
# Optional: the XML version. Defaults to 1.0
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
# Optional: the Encoding. Defaults to UTF-8
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
# A Hashtable of parameters which should be available as local variables to the scriptblock in args
[Parameter(Mandatory = $false)]
[hashtable]$Parameters
,
# this is where all the dsl magic happens. Please see the Examples. :)
[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 {
if($Parameters) {
foreach($key in $Parameters.Keys) {
Set-Variable $key $Parameters.$key -Scope Script
}
}
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
Write-Verbose "Reparsed DSL: $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
Write-Verbose "New-XElement $tag $($args -join ',')"
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]) {
Write-Verbose "New XAttribute xmlns: $($attrib.TrimStart("-").TrimEnd(':')) = $value"
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) {
Write-Verbose "New XAttribute $($attrib.TrimStart("-").TrimEnd(':')) = $value"
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) }
if($duds) {
[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, Remove-XmlElement, Get-Namespace, Get-XmlContent, Set-XmlContent, ConvertTo-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIZEwYJKoZIhvcNAQcCoIIZBDCCGQACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUSzpk+TjIGQhlVoEBJG9eVnhA
# vr+gghTRMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B
# AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp
# BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw
# NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xNDAyBgNVBAMTK1N5bWFudGVjIFRpbWUg
# U3RhbXBpbmcgU2VydmljZXMgU2lnbmVyIC0gRzMwgZ8wDQYJKoZIhvcNAQEBBQAD
# gY0AMIGJAoGBAKlZZnTaPYp9etj89YBEe/5HahRVTlBHC+zT7c72OPdPabmx8LZ4
# ggqMdhZn4gKttw2livYD/GbT/AgtzLVzWXuJ3DNuZlpeUje0YtGSWTUUi0WsWbJN
# JKKYlGhCcp86aOJri54iLfSYTprGr7PkoKs8KL8j4ddypPIQU2eud69RAgMBAAGj
# geMwgeAwDAYDVR0TAQH/BAIwADAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js
# LnZlcmlzaWduLmNvbS90c3MtY2EuY3JsMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI
# MDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AudmVyaXNp
# Z24uY29tMA4GA1UdDwEB/wQEAwIHgDAeBgNVHREEFzAVpBMwETEPMA0GA1UEAxMG
# VFNBMS0zMB0GA1UdDgQWBBS0t/GJSSZg52Xqc67c0zjNv1eSbzANBgkqhkiG9w0B
# AQUFAAOCAQEAHpiqJ7d4tQi1yXJtt9/ADpimNcSIydL2bfFLGvvV+S2ZAJ7R55uL
# 4T+9OYAMZs0HvFyYVKaUuhDRTour9W9lzGcJooB8UugOA9ZresYFGOzIrEJ8Byyn
# PQhm3ADt/ZQdc/JymJOxEdaP747qrPSWUQzQjd8xUk9er32nSnXmTs4rnykr589d
# nwN+bid7I61iKWavkugszr2cf9zNFzxDwgk/dUXHnuTXYH+XxuSqx2n1/M10rCyw
# SMFQTnBWHrU1046+se2svf4M7IV91buFZkQZXZ+T64K6Y57TfGH/yBvZI1h/MKNm
# oTkmXpLDPMs3Mvr1o43c1bCj6SU2VdeB+jCCA8QwggMtoAMCAQICEEe/GZXfjVJG
# Q/fbbUgNMaQwDQYJKoZIhvcNAQEFBQAwgYsxCzAJBgNVBAYTAlpBMRUwEwYDVQQI
# EwxXZXN0ZXJuIENhcGUxFDASBgNVBAcTC0R1cmJhbnZpbGxlMQ8wDQYDVQQKEwZU
# aGF3dGUxHTAbBgNVBAsTFFRoYXd0ZSBDZXJ0aWZpY2F0aW9uMR8wHQYDVQQDExZU
# aGF3dGUgVGltZXN0YW1waW5nIENBMB4XDTAzMTIwNDAwMDAwMFoXDTEzMTIwMzIz
# NTk1OVowUzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMSsw
# KQYDVQQDEyJWZXJpU2lnbiBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIENBMIIBIjAN
# BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqcqypMzNIK8KfYmsh3XwtE7x38EP
# v2dhvaNkHNq7+cozq4QwiVh+jNtr3TaeD7/R7Hjyd6Z+bzy/k68Numj0bJTKvVIt
# q0g99bbVXV8bAp/6L2sepPejmqYayALhf0xS4w5g7EAcfrkN3j/HtN+HvV96ajEu
# A5mBE6hHIM4xcw1XLc14NDOVEpkSud5oL6rm48KKjCrDiyGHZr2DWFdvdb88qiaH
# XcoQFTyfhOpUwQpuxP7FSt25BxGXInzbPifRHnjsnzHJ8eYiGdvEs0dDmhpfoB6Q
# 5F717nzxfatiAY/1TQve0CJWqJXNroh2ru66DfPkTdmg+2igrhQ7s4fBuwIDAQAB
# o4HbMIHYMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3Au
# dmVyaXNpZ24uY29tMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYDVR0fBDowODA2oDSg
# MoYwaHR0cDovL2NybC52ZXJpc2lnbi5jb20vVGhhd3RlVGltZXN0YW1waW5nQ0Eu
# Y3JsMBMGA1UdJQQMMAoGCCsGAQUFBwMIMA4GA1UdDwEB/wQEAwIBBjAkBgNVHREE
# HTAbpBkwFzEVMBMGA1UEAxMMVFNBMjA0OC0xLTUzMA0GCSqGSIb3DQEBBQUAA4GB
# AEpr+epYwkQcMYl5mSuWv4KsAdYcTM2wilhu3wgpo17IypMT5wRSDe9HJy8AOLDk
# yZNOmtQiYhX3PzchT3AxgPGLOIez6OiXAP7PVZZOJNKpJ056rrdhQfMqzufJ2V7d
# uyuFPrWdtdnhV/++tMV+9c8MnvCX/ivTO1IbGzgn9z9KMIIGnzCCBYegAwIBAgIQ
# DmkGmMIUyHq1tgS5FjzRkDANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJVUzEV
# MBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29t
# MTIwMAYDVQQDEylEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBDb2RlIFNpZ25pbmcg
# Q0EtMTAeFw0xMjAzMjAwMDAwMDBaFw0xMzAzMjIxMjAwMDBaMG0xCzAJBgNVBAYT
# AlVTMREwDwYDVQQIEwhOZXcgWW9yazEXMBUGA1UEBxMOV2VzdCBIZW5yaWV0dGEx
# GDAWBgNVBAoTD0pvZWwgSC4gQmVubmV0dDEYMBYGA1UEAxMPSm9lbCBILiBCZW5u
# ZXR0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2ogGAG89d1jMfRJv
# 2d3U1lCsW8ok7GkjnLYDn0zC1ALq11rWN5NVwVbn133i+KV0O8kM5vd2M7xE8CnV
# AgybjkrvRD2IqMtp4SrwQuiGiVGsNVWO3vSLHcWsS/I7N0UIpS5PhTuFB4PcOy/M
# HR4F2g6JLMrAtkpYWxauAFZfFwuEfm6vqWobHTDt5wG+zqOTxMSi1UvL5fEMDoej
# GqqriIx5mKDzrvUb/ALNKZ1rGPWlT7O0/UHrV5VuOfgij4XVKBAdcg9JLxkyAEIJ
# +VvVQ2Jn3lVONCCHbfu5IVhddMru81U/v5Wrj80Zrwh2TH25qlclUKr6eXRLtP+x
# Fm23CwIDAQABo4IDMzCCAy8wHwYDVR0jBBgwFoAUl0gD6xUIa7myWCPMlC7xxmXS
# ZI4wHQYDVR0OBBYEFJicRKq/XsBWRuKzU6eTUCBCCU65MA4GA1UdDwEB/wQEAwIH
# gDATBgNVHSUEDDAKBggrBgEFBQcDAzBpBgNVHR8EYjBgMC6gLKAqhihodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMC6gLKAqhihodHRwOi8v
# Y3JsNC5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMIIBxAYDVR0gBIIBuzCC
# AbcwggGzBglghkgBhv1sAwEwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3LmRp
# Z2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUHAgIw
# ggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQA
# aQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUA
# cAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMA
# UAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEA
# cgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkA
# dAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8A
# cgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIA
# ZQBuAGMAZQAuMIGGBggrBgEFBQcBAQR6MHgwJAYIKwYBBQUHMAGGGGh0dHA6Ly9v
# Y3NwLmRpZ2ljZXJ0LmNvbTBQBggrBgEFBQcwAoZEaHR0cDovL2NhY2VydHMuZGln
# aWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUNvZGVTaWduaW5nQ0EtMS5j
# cnQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQUFAAOCAQEAHIfeYpO0Jtdi/Tpc
# I6eWQIYU2ALO847Q91jLE6WiU6u8wN6tkHqgeOls070SDUK+C1rVoXKKZ0Jec2k1
# dYukKPkyf3qURPyh/aC3hJ0Wwbje7fK79Lt9ZHwJORpesJrwa8T63l3qLLLlPaIY
# o/bqiMpNZRfOclukKg2hO67yMaQl8DEL/D5UP1XZShF2zbauH627zEC5KXGZY2yU
# bmWG2N0oHxr+q4Gyfd0MPtU5avWOILB0ZsN+br+SCVVK6nKzauXMk4HXmKHaX7cy
# sqpmQiFb7/J7tPQ037KQKHCY/Z+fl0arRCiHih/Q/5owv51WSKPiaUrkBvdJ0mKV
# K+McHzCCBr8wggWnoAMCAQICEAgcV+5dcOuboLFSDHKcGwkwDQYJKoZIhvcNAQEF
# BQAwbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UE
# CxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1
# cmFuY2UgRVYgUm9vdCBDQTAeFw0xMTAyMTAxMjAwMDBaFw0yNjAyMTAxMjAwMDBa
# MHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsT
# EHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNzdXJh
# bmNlIENvZGUgU2lnbmluZyBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
# CgKCAQEAxfkj5pQnxIAUpIAyX0CjjW9wwOU2cXE6daSqGpKUiV6sI3HLTmd9QT+q
# 40u3e76dwag4j2kvOiTpd1kSx2YEQ8INJoKJQBnyLOrnTOd8BRq4/4gJTyY37zqk
# +iJsiMlKG2HyrhBeb7zReZtZGGDl7im1AyqkzvGDGU9pBXMoCfsiEJMioJAZGkwx
# 8tMr2IRDrzxj/5jbINIJK1TB6v1qg+cQoxJx9dbX4RJ61eBWWs7qAVtoZVvBP1hS
# M6k1YU4iy4HKNqMSywbWzxtNGH65krkSz0Am2Jo2hbMVqkeThGsHu7zVs94lABGJ
# AGjBKTzqPi3uUKvXHDAGeDylECNnkQIDAQABo4IDVDCCA1AwDgYDVR0PAQH/BAQD
# AgEGMBMGA1UdJQQMMAoGCCsGAQUFBwMDMIIBwwYDVR0gBIIBujCCAbYwggGyBghg
# hkgBhv1sAzCCAaQwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29t
# L3NzbC1jcHMtcmVwb3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEA
# bgB5ACAAdQBzAGUAIABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEA
# dABlACAAYwBvAG4AcwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMA
# ZQAgAG8AZgAgAHQAaABlACAARABpAGcAaQBDAGUAcgB0ACAARQBWACAAQwBQAFMA
# IABhAG4AZAAgAHQAaABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEA
# ZwByAGUAZQBtAGUAbgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEA
# YgBpAGwAaQB0AHkAIABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEA
# dABlAGQAIABoAGUAcgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4w
# DwYDVR0TAQH/BAUwAwEB/zB/BggrBgEFBQcBAQRzMHEwJAYIKwYBBQUHMAGGGGh0
# dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcwAoY9aHR0cDovL2NhY2Vy
# dHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNy
# dDCBjwYDVR0fBIGHMIGEMECgPqA8hjpodHRwOi8vY3JsMy5kaWdpY2VydC5jb20v
# RGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290Q0EuY3JsMECgPqA8hjpodHRwOi8v
# Y3JsNC5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290Q0Eu
# Y3JsMB0GA1UdDgQWBBSXSAPrFQhrubJYI8yULvHGZdJkjjAfBgNVHSMEGDAWgBSx
# PsNpA/i/RwHUmCYaCALvY2QrwzANBgkqhkiG9w0BAQUFAAOCAQEAggXpha+nTL+v
# zj2y6mCxaN5nwtLLJuDDL5u1aw5TkIX2m+A1Av/6aYOqtHQyFDwuEEwomwqtCAn5
# 84QRk4/LYEBW6XcvabKDmVWrRySWy39LsBC0l7/EpZkG/o7sFFAeXleXy0e5NNn8
# OqL/UCnCCmIE7t6WOm+gwoUPb/wI5DJ704SuaWAJRiac6PD//4bZyAk6ZsOnNo8Y
# T+ixlpIuTr4LpzOQrrxuT/F+jbRGDmT5WQYiIWQAS+J6CAPnvImQnkJPAcC2Fn91
# 6kaypVQvjJPNETY0aihXzJQ/6XzIGAMDBH5D2vmXoVlH2hKq4G04AF01K8UihssG
# yrx6TT0mRjGCA6wwggOoAgEBMIGHMHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxE
# aWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMT
# KURpZ2lDZXJ0IEhpZ2ggQXNzdXJhbmNlIENvZGUgU2lnbmluZyBDQS0xAhAOaQaY
# whTIerW2BLkWPNGQMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3AgEMMQowCKACgACh
# AoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAM
# BgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBRl7Z8Ka4sa/4B0YuthUiWk0DOI
# hTANBgkqhkiG9w0BAQEFAASCAQCb7PNuJWsmOxRPLG4o70iH1/kheuSC45XIj9Rj
# 3QHKqH7UReswMWNnpEBwM3w0kXMSHeLvuztx4hHtCDXVaf8sugtvZz/i7xjEdU3Q
# QF1DSDEPYcth/zk1qeGP2FpBnR/hGF/wup53XR93yIyXgJfxJjYFBsUL7A6b9Vdg
# 4/h14aOTv4IQPe8LLsr14QXaXRrcBScAFVqcVCoR5zu003A++RNaiv4yrI6chp2A
# ImKWwa9wBtny0WFaltAnlAAnh+yccn/a77GEVNZgTNzmdOQv6Fh+ZNqCSTfAQRd6
# bC7FDlIqvt1DWl8hADWmswz6RR8CR2dijPg27yWNm6HLmM/doYIBfzCCAXsGCSqG
# SIb3DQEJBjGCAWwwggFoAgEBMGcwUzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZl
# cmlTaWduLCBJbmMuMSswKQYDVQQDEyJWZXJpU2lnbiBUaW1lIFN0YW1waW5nIFNl
# cnZpY2VzIENBAhB5oqWF+dEVQhPZuD72to3tMAkGBSsOAwIaBQCgXTAYBgkqhkiG
# 9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMjA4MDIxNTA3MjRa
# MCMGCSqGSIb3DQEJBDEWBBRPzjZ9FFQI4JywxRW/O/s/eWMzPjANBgkqhkiG9w0B
# AQEFAASBgJkIUKOPt7BfL9hooks1U6ZY1ft9lNnIB1/iOYsD4QqWK+FSv6w4oM0T
# 4S7mwPnbTB3WuWXxnt55+JpSkshiGyKmBJ9biwh0a4h4ZqA+VfTLmbY+szaloWCx
# 9ordICKOsJ1S+7SpXNImGxvR7mOcNCpxVcn6OYzfBr8aNR4y+iJN
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Write-DataTable_5.ps1
|
Write-DataTable_5.ps1
|
#######################
<#
.SYNOPSIS
Writes data only to SQL Server tables.
.DESCRIPTION
Writes data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.
.INPUTS
None
You cannot pipe objects to Write-DataTable
.OUTPUTS
None
Produces no output
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"
Write-DataTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -Data $dt
This example loads a variable dt of type DataTable from query and write the datatable to another database
.NOTES
Write-DataTable uses the SqlBulkCopy class see links for additional information on this class.
Version History
v1.0 - Chad Miller - Initial release
v1.1 - Chad Miller - Fixed error message
v1.2 - B. Holliger - Adds column mapping according to source table, allows insertion of data if destination column count differs
.LINK
http://msdn.microsoft.com/en-us/library/30c3y597%28v=VS.90%29.aspx
#>
function Write-DataTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [string]$TableName,
[Parameter(Position=3, Mandatory=$true)] $Data,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000,
[Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0,
[Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15
)
$conn=new-object System.Data.SqlClient.SQLConnection
if ($Username)
{ $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
else
{ $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout }
$conn.ConnectionString=$ConnectionString
try
{
$conn.Open()
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = $tableName
# Set mappings according source table
$data | Get-Member -MemberType Property | Select-Object -ExpandProperty Name | ForEach-Object {
[void]$bulkCopy.ColumnMappings.Add($_, $_)
}
$bulkCopy.BatchSize = $BatchSize
$bulkCopy.BulkCopyTimeout = $QueryTimeOut
$bulkCopy.WriteToServer($Data)
$conn.Close()
}
catch
{
$ex = $_.Exception
Write-Error "$ex.Message"
continue
}
} #Write-DataTable
|
PowerShellCorpus/PoshCode/AsyncCallbacks in .NET.ps1
|
AsyncCallbacks in .NET.ps1
|
#requires -version 2.0
function New-ScriptBlockCallback {
param(
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[scriptblock]$Callback
)
<#
.SYNOPSIS
Allows running ScriptBlocks via .NET async callbacks.
.DESCRIPTION
Allows running ScriptBlocks via .NET async callbacks. Internally this is
managed by converting .NET async callbacks into .NET events. This enables
PowerShell 2.0 to run ScriptBlocks indirectly through Register-ObjectEvent.
.PARAMETER Callback
Specify a ScriptBlock to be executed in response to the callback.
Because the ScriptBlock is executed by the eventing subsystem, it only has
access to global scope. Any additional arguments to this function will be
passed as event MessageData.
.EXAMPLE
You wish to run a scriptblock in reponse to a callback. Here is the .NET
method signature:
void Bar(AsyncCallback handler, int blah)
ps> [foo]::bar((New-ScriptBlockCallback { ... }), 42)
.OUTPUTS
A System.AsyncCallback delegate.
#>
# is this type already defined?
if (-not ("CallbackEventBridge" -as [type])) {
Add-Type @"
using System;
public sealed class CallbackEventBridge
{
public event AsyncCallback CallbackComplete = delegate { };
private CallbackEventBridge() {}
private void CallbackInternal(IAsyncResult result)
{
CallbackComplete(result);
}
public AsyncCallback Callback
{
get { return new AsyncCallback(CallbackInternal); }
}
public static CallbackEventBridge Create()
{
return new CallbackEventBridge();
}
}
"@
}
$bridge = [callbackeventbridge]::create()
Register-ObjectEvent -input $bridge -EventName callbackcomplete -action $callback -messagedata $args > $null
$bridge.callback
}
|
PowerShellCorpus/PoshCode/Get-HPAgentVersion.ps1
|
Get-HPAgentVersion.ps1
|
#######################
<#
.SYNOPSIS
Gets HP PSP/SPP Agent Version
.DESCRIPTION
The Get-HPAgentVersion function gets the HP PSP/SPP version.
.EXAMPLE
Get-HPAgentVersion "Z002"
This command gets information for computername Z002.
.EXAMPLE
Get-Content ./servers.txt | Get-HPAgentVersion
This command gets information for a list of servers stored in servers.txt.
.EXAMPLE
Get-HPAgentVersion (get-content ./servers.txt)
This command gets information for a list of servers stored in servers.txt.
.NOTES
Version History
v1.0 - Chad Miller - Initial release
#>
function Get-HPAgentVersion
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullorEmpty()]
[string[]]$ComputerName
)
BEGIN {}
PROCESS {
foreach ($computer in $computername) {
Get-WMIObject -ComputerName $computer -Query "SELECT * FROM CIM_DataFile WHERE Drive ='C:' AND Path='\\\\WINDOWS\\\\system32\\\\CpqMgmt\\\\' AND FileName='agentver' AND Extension='dll'" |
Select CSName, Version, @{n='OS';e={(gwmi win32_operatingsystem -ComputerName $_.CSName).Version}}
}
}
END {}
}
|
PowerShellCorpus/PoshCode/Get-Constructor_1.ps1
|
Get-Constructor_1.ps1
|
function Get-Constructor {
PARAM( [Type]$type )
$type.GetConstructors() |
Format-Table @{
l="$($type.Name) Constructors"
e={ ($_.GetParameters() | % { $_.ToString() }) -Join ", " }
}
}
Set-Alias gctor Get-Constructor
|
PowerShellCorpus/PoshCode/Modify Excel.ps1
|
Modify Excel.ps1
|
# -----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
# -----------------------------------------------------
$objExcel = new-object -comobject excel.application
$objExcel.Visible = $True
$objWorkbook = $objExcel.Workbooks.Open("C:\\Users\\username\\Desktop\\scripts\\groupmaps.xlsx")
# write into cell B2 (column 2, line 2):
#$objWorkbook.ActiveSheet.Cells.Item(2,2)= "Test a Write"
# read cell content
#$content = $objWorkbook.ActiveSheet.Cells.Item(3,1).Text
#"Cell B2 content: $content"
$RowNum = 2
While ($objWorkbook.ActiveSheet.Cells.Item($RowNum, 1).Text -ne "") {
$lusername = $objWorkbook.ActiveSheet.Cells.Item($RowNum,2).Text
Import-Csv C:\\Users\\username\\Desktop\\scripts\\usermaps.csv | foreach {
if ($lusername -eq $_.ousername){
#Write-Host Match $lusername $_.ousername $_.nusername
$objWorkbook.ActiveSheet.Cells.Item($RowNum,4)= $_.nusername
$objWorkbook.ActiveSheet.Cells.Item($RowNum,5)= $_.DisplayName
}
}
$RowNum++
}
#close
$a = Release-Ref($objWorkbook)
$a = Release-Ref($objExcel)
|
PowerShellCorpus/PoshCode/Download DefragTools _2.ps1
|
Download DefragTools _2.ps1
|
#requires -version 2.0
<#
.Synopsis
Downloads Channel 9 Defrag Tool Episode Video
.DESCRIPTION
Downloads Channel 9 Defrag Tool Episode Video in the format selected and to a given path.
.EXAMPLE
Downloads all shows in WMV format to the default Downloads Folder for the user.
Get-DefragToolsShow -All -VideoType wmv
.EXAMPLE
Downloads only the last show of the series in MP4 format
Get-DefragToolsShow -Last -VideoType MP4
.NOTES
Author: Carlos Perez carlos_perez[at]darkoperator.com
#>
function Get-DefragToolsShow
{
[CmdletBinding()]
Param
(
# Path to download the episodes.
[Parameter(Mandatory=$false,
Position=0)]
$Path = "$($env:USERPROFILE)\\downloads",
# Download all the episodes.
[Parameter(Mandatory=$false,
ParameterSetName="All")]
[switch]$All = $true,
# Download only the last episode.
[Parameter(Mandatory=$false,
ParameterSetName="Last")]
[switch]$Last = $true,
# The type of video to download.
[Parameter(Mandatory=$false)]
[ValidateSet("MP4HD","MP4","WMVHD","WMV")]
[string]$VideoType = "MP4HD",
# Will create the folder if not present.
[Parameter(Mandatory=$false,
ParameterSetName="Last")]
[switch]$Force = $true
)
Begin
{
$WebClient = New-Object System.Net.WebClient
$Global:downloadComplete = $false
# Make sure there are no previously registered events.
Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged -ErrorAction SilentlyContinue
Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete -ErrorAction SilentlyContinue
# Register events for showing progress
Write-Verbose "Registering event for when tracking when download finishes."
$eventDataComplete = Register-ObjectEvent $WebClient DownloadFileCompleted `
-SourceIdentifier WebClient.DownloadFileComplete `
-Action {$Global:downloadComplete = $true}
Write-Verbose "Registering event for when tracking when download progress."
$eventDataProgress = Register-ObjectEvent $WebClient DownloadProgressChanged `
-SourceIdentifier WebClient.DownloadProgressChanged `
-Action { $Global:DPCEventArgs = $EventArgs }
# Lets change to the proper path
if (Test-Path $Path)
{
Set-Location (Resolve-Path $Path).Path
}
else
{
if ($Force)
{
New-Item -ItemType directory -Path $Path | out-null
Set-Location (Resolve-Path $Path).Path
}
else
{
Write-Error "Specified path does not exist"
return
}
}
}
Process
{
switch ($PsCmdlet.ParameterSetName)
{
"All"{$all = $true}
"Last"{$all = $false}
}
switch ($VideoType)
{
"MP4HD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4high"}
"MP4" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4"}
"WMVHD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmvhigh"}
"WMV" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmv"}
}
$feed = [xml]$WebClient.DownloadString($feedURL)
if ($All)
{
foreach ($episode in $feed.rss.channel.Item)
{
# Create a proper URI for parsing
$episodeURL = [System.Uri]$episode.enclosure.url
# Get the episode file name
$file = $episodeURL.Segments[-1]
#Check if the file exists if it does skip it
if (!(Test-Path "$((Resolve-Path $Path).Path)\\$($file)"))
{
Write-Progress -Activity 'Downloading file' -Status $file
$WebClient.DownloadFileAsync($episodeURL, "$((Resolve-Path $Path).Path)\\$($file)")
while (!($Global:downloadComplete))
{
$pc = $Global:DPCEventArgs.ProgressPercentage
if ($pc -ne $null)
{
Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc
}
}
$Global:downloadComplete = $false
}
}
}
else
{
$episodeURL = [System.Uri]$feed.rss.channel.Item[0].enclosure.url
# Get the episode file name
$file = $episodeURL.Segments[-1]
#Check if the file exists if it does skip it
if (!(Test-Path $file))
{
Write-Progress -Activity 'Downloading file' -Status $file
$WebClient.DownloadFileAsync($episodeURL, "$((Resolve-Path $Path).Path)\\$($file)")
# Lets wait for it to finish
while (!($Global:downloadComplete))
{
$pc = $Global:DPCEventArgs.ProgressPercentage
if ($pc -ne $null)
{
Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc
}
}
}
}
}
End
{
Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged
Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete
$Global:downloadComplete = $null
$Global:DPCEventArgs = $null
[GC]::Collect()
}
}
|
PowerShellCorpus/PoshCode/Get-WordOutline.ps1
|
Get-WordOutline.ps1
|
function Get-WordOutline ( $Path, [int]$MaxDepth = 9 ) {
if ( $Path -is [System.IO.FileInfo] ) { $Path = $_.FullName }
$word = New-Object -comObject word.application
$document = $wordd.documents.open( $path )
$outline = $document.paragraphs | Where-Object {
$_.outlineLevel -le $MaxDepth
} | ForEach-Object {
$n = ($_.outlineLevel - 1) * 2
' ' * $n + ($_.range.text -replace '\\u000d$')
}
Write-Output $outline
$document.close( [ref]$false )
$word.quit()
}
|
PowerShellCorpus/PoshCode/chkhash_16.ps1
|
chkhash_16.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"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 $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 "SHA-512 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|?{noequal $_.directoryname $exclude}) # Load database
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$fc++ # File checked increment.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{$fm++;continue} # if matched, increment file matches and continue loop
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fm file(s) SHA512 matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Convert-BounceToX_1.ps1
|
Convert-BounceToX_1.ps1
|
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $
# $Revision: 610 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
#.Example
# "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress
)
BEGIN
{
Add-Type -AssemblyName System.Web|Out-Null
}
PROCESS
{
if($_) {$bounceAddress = $_}
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
}
|
PowerShellCorpus/PoshCode/VMware Daily Report_1.ps1
|
VMware Daily Report_1.ps1
|
# vCheck - Daily Error Report
#
# Changes:
# Version 1.11 - Simplified mail function.
# Version 1.10 - Added How many days old the snapshots are
# Version 1.9 - Added ability to change user account which makes the WMI calls
# Version 1.8 - Added Real name resolution via AD and sorted disk space by PerfFree
# Version 1.7 - Added Event Logs for VMware warnings and errors for past day
# Version 1.6 - Add details to service state to see if it is expected or not
# Version 1.5 - Check for objects to see if they exist before sending the email + add VMs with No VMTools
param( [string] $VISRV)
# You can change the following defaults by altering the below settings:
#
#
# Set the SMTP Server address
#
$SMTPSRV = "myexchangeserver.mydomain.comk"
#
# Set the Email address to recieve from
#
$EmailFrom = "reports@mydomain.com"
#
# Set the Email address to send the email to
#
$EmailTo = "myemail@mydomain.com"
#### Detail Settings ####
# Set the username of the account with permissions to access the VI Server
# for event logs and service details - you will be asked for the same username and password
# only the first time this runs after setting the below username.
# If it is left blank it will use the credentials of the user who runs the script
$SetUsername = ""
# Set the location to store the credentials in a secure manner
$CredFile = ".\\mycred.crd"
# Set the warning threshold for Datastore % Free Space
$DatastoreSpace = "5"
# Set the warning threshold for snapshots in days old
$SnapshotAge = 14
# Set the number of days to show VMs created & removed for
$VMsNewRemovedAge = 5
# Set the number of days of VC Events to check for errors
$VCEventAge = 1
# Set tge bumber of days of VC Event Logs to check for warnings and errors
$VCEvntlgAge = 1
#######################################
# Start of script
if ($VISRV -eq ""){
Write-Host
Write-Host "Please specify a VI Server name eg...."
Write-Host " powershell.exe DailyReport.ps1 MYVISERVER"
Write-Host
Write-Host
exit
}
function Send-SMTPmail($to, $from, $subject, $smtpserver, $body) {
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
}
Function Get-CustomHTML ($Header){
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>$($Header)</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<meta name="save" content="history">
<style type="text/css">
DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 10pt; RIGHT: 8px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}
TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}
*{margin:0}
.dspcont { BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 95%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9}
.filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative}
.save{behavior:url(#default#savehistory);}
.dspcont1{ display:none}
a.dsphead0 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #cc0000}
a.dsphead1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #7BA7C7}
a.dsphead2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #A5A5A5}
a.dsphead1 span.dspchar{font-family:monospace;font-weight:normal;}
td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}
th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}
BODY {margin-left: 4pt}
BODY {margin-right: 4pt}
BODY {margin-top: 6pt}
</style>
</head>
<body>
<b><font face="Arial" size="5">$($Header)</font></b><hr size="8" color="#cc0000">
<font face="Arial" size="1"><b>Generated on $($ENV:Computername)</b></font><br>
<font face="Arial" size="1">Report created on $(Get-Date)</font>
<div class="filler"></div>
<div class="filler"></div>
<div class="filler"></div>
<div class="save">
"@
Return $Report
}
Function Get-CustomHeader0 ($Title){
$Report = @"
<h1><a class="dsphead0">$($Title)</a></h1>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader ($Num, $Title){
$Report = @"
<h2><a class="dsphead$($Num)">
$($Title)</a></h2>
<div class="dspcont">
"@
Return $Report
}
Function Get-CustomHeaderClose{
$Report = @"
</DIV>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader0Close{
$Report = @"
</DIV>
"@
Return $Report
}
Function Get-CustomHTMLClose{
$Report = @"
</div>
</body>
</html>
"@
Return $Report
}
Function Get-HTMLTable {
param([array]$Content)
$HTMLTable = $Content | ConvertTo-Html
$HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
Return $HTMLTable
}
Function Get-HTMLDetail ($Heading, $Detail){
$Report = @"
<TABLE>
<tr>
<th width='25%'><b>$Heading</b></font></th>
<td width='75%'>$($Detail)</td>
</tr>
</TABLE>
"@
Return $Report
}
function Find-Username ($username){
if ($username -ne $null)
{
$root = [ADSI]""
$filter = ("(&(objectCategory=user)(samAccountName=$Username))")
$ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter)
$ds.PageSize = 1000
$ds.FindOne()
}
}
function Get-VIServices
{
If ($SetUsername -ne ""){
$Services = get-wmiobject win32_service -Credential $creds -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" }
} Else {
$Services = get-wmiobject win32_service -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" }
}
$myCol = @()
Foreach ($service in $Services){
$MyDetails = "" | select-Object Name, State, StartMode, Health
If ($service.StartMode -eq "Auto")
{
if ($service.State -eq "Stopped")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "Unexpected State"
}
}
If ($service.StartMode -eq "Auto")
{
if ($service.State -eq "Running")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "OK"
}
}
If ($service.StartMode -eq "Disabled")
{
If ($service.State -eq "Running")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "Unexpected State"
}
}
If ($service.StartMode -eq "Disabled")
{
if ($service.State -eq "Stopped")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "OK"
}
}
$myCol += $MyDetails
}
Write-Output $myCol
}
function Get-DatastoreSummary {
param(
$InputObject = $null
)
begin {
}
process {
if ($InputObject -and $_) {
throw 'The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.'
return
}
$processObject = $(if ($InputObject) {$InputObject} else {$_})
if ($processObject) {
$myCol = @()
foreach ($ds in $_)
{
$MyDetails = "" | select-Object Name, Type, CapacityMB, FreeSpaceMB, PercFreeSpace
$MyDetails.Name = $ds.Name
$MyDetails.Type = $ds.Type
$MyDetails.CapacityMB = $ds.CapacityMB
$MyDetails.FreeSpaceMB = $ds.FreeSpaceMB
$MyDetails.PercFreeSpace = [math]::Round(((100 * ($ds.FreeSpaceMB)) / ($ds.CapacityMB)),0)
$myCol += $MyDetails
}
$myCol | Where { $_.PercFreeSpace -lt $DatastoreSpace }
}
}
end {
}
}
function Get-SnapshotSummary {
param(
$InputObject = $null
)
BEGIN {
}
PROCESS {
if ($InputObject -and $_) {
throw 'ParameterBinderStrings\\AmbiguousParameterSet'
break
} elseif ($InputObject) {
$InputObject
} elseif ($_) {
$mySnaps = @()
foreach ($snap in $_){
$SnapshotInfo = Get-SnapshotExtra $snap
$mySnaps += $SnapshotInfo
}
$mySnaps | Select VM, Name, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, @{N="Creator";E={(Find-Username (($_.Creator.split("\\"))[1])).Properties.displayname}}, Created, Description | Sort DaysOld
} else {
throw 'ParameterBinderStrings\\InputObjectNotBound'
}
}
END {
}
}
function Get-SnapshotTree{
param($tree, $target)
$found = $null
foreach($elem in $tree){
if($elem.Snapshot.Value -eq $target.Value){
$found = $elem
continue
}
}
if($found -eq $null -and $elem.ChildSnapshotList -ne $null){
$found = Get-SnapshotTree $elem.ChildSnapshotList $target
}
return $found
}
function Get-SnapshotExtra ($snap){
$guestName = $snap.VM # The name of the guest
$tasknumber = 999 # Windowsize of the Task collector
$taskMgr = Get-View TaskManager
# Create hash table. Each entry is a create snapshot task
$report = @{}
$filter = New-Object VMware.Vim.TaskFilterSpec
$filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
$filter.Time.beginTime = (($snap.Created).AddDays(-5))
$filter.Time.timeType = "startedTime"
$collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter))
$dummy = $collectionImpl.RewindCollector
$collection = $collectionImpl.ReadNextTasks($tasknumber)
while($collection -ne $null){
$collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{
$row = New-Object PsObject
$row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName
$vm = Get-View $_.Entity
if($vm -ne $null){
$snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result
if($snapshot -ne $null){
$key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString())
$report[$key] = $row
}
}
}
$collection = $collectionImpl.ReadNextTasks($tasknumber)
}
$collectionImpl.DestroyCollector()
# Get the guest's snapshots and add the user
$snapshotsExtra = $snap | % {
$key = $_.vm.Name + "&" + ($_.Created.ToString())
if($report.ContainsKey($key)){
$_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User
}
$_
}
$snapshotsExtra
}
Function Set-Cred ($File) {
$Credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content $File
}
Function Get-Cred ($User,$File) {
$password = Get-Content $File | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($user,$password)
$credential
}
If ($SetUsername -ne ""){
if ((Test-Path -Path $CredFile) -eq $false) {
Set-Cred $CredFile
}
$creds = Get-Cred $SetUsername $CredFile
}
$VIServer = Connect-VIServer $VISRV
If ($VIServer.IsConnected -ne $true){
# Fix for scheduled tasks not running.
$USER = $env:username
$APPPATH = "C:\\Documents and Settings\\" + $USER + "\\Application Data"
#SET THE APPDATA ENVIRONMENT WHEN NEEDED
if ($env:appdata -eq $null -or $env:appdata -eq 0)
{
$env:appdata = $APPPATH
}
$VIServer = Connect-VIServer $VISRV
If ($VIServer.IsConnected -ne $true){
send-SMTPmail -to $EmailTo -from $EmailFrom -subject "ERROR: $VISRV Daily Report" -smtpserver $SMTPSRV -body "The Connect-VISERVER Cmdlet did not work, please check you VI Server."
exit
}
}
$VM = Get-VM
$VMH = Get-VMHost
$Clusters = Get-Cluster
$Datastores = Get-Datastore
$FullVM = Get-View -ViewType VirtualMachine
$MyReport = Get-CustomHTML "$VIServer Daily Report"
$MyReport += Get-CustomHeader0 ($VIServer.Name)
# ---- General Summary Info ----
$MyReport += Get-CustomHeader "1" "General Details"
$MyReport += Get-HTMLDetail "Number of Hosts:" (($VMH).Count)
$MyReport += Get-HTMLDetail "Number of VMs:" (($VM).Count)
$MyReport += Get-HTMLDetail "Number of Clusters:" (($Clusters).Count)
$MyReport += Get-HTMLDetail "Number of Datastores:" (($Datastores).Count)
$MyReport += Get-CustomHeaderClose
# ---- Snapshot Information ----
$Snapshots = $VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-$SnapshotAge))} | Get-SnapshotSummary
If (($Snapshots | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "Snapshots (Over $SnapshotAge Days Old)"
$MyReport += Get-HTMLTable $Snapshots
$MyReport += Get-CustomHeaderClose
}
# ---- Datastore Information ----
$OutputDatastores = $Datastores | Get-DatastoreSummary | Sort PercFreeSpace
If (($OutputDatastores | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "Datastores (Less than $DatastoreSpace% Free)"
$MyReport += Get-HTMLTable $OutputDatastores
$MyReport += Get-CustomHeaderClose
}
# ---- VMs created or Cloned ----
$VIEvent = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VMsNewRemovedAge)
$OutputCreatedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmBeingClonedEvent" -or $_.Gettype().Name -eq "VmBeingDeployedEvent"} | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage
If (($OutputCreatedVMs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "VMs Created or Cloned (Last $VMsNewRemovedAge Day(s))"
$MyReport += Get-HTMLTable $OutputCreatedVMs
$MyReport += Get-CustomHeaderClose
}
# ---- VMs Removed ----
$OutputRemovedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmRemovedEvent"}| Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage
If (($OutputRemovedVMs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "VMs Removed (Last $VMsNewRemovedAge Day(s))"
$MyReport += Get-HTMLTable $OutputRemovedVMs
$MyReport += Get-CustomHeaderClose
}
# ---- VC Errors ----
$OutputErrors = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VCEventAge ) -Type Error | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage
If (($OutputErrors | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "Error Events (Last $VCEventAge Day(s))"
$MyReport += Get-HTMLTable $OutputErrors
$MyReport += Get-CustomHeaderClose
}
# ---- No VM Tools ----
$NoTools = $FullVM | Where { $_.Runtime.PowerState -eq "poweredOn" } | Select Name, @{N="ToolsVersion"; E={$_.Config.tools.toolsVersion}} | Where { $_.ToolsVersion -eq 0} | Select Name
If (($NoTools | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "No VMTools"
$MyReport += Get-HTMLTable $NoTools
$MyReport += Get-CustomHeaderClose
}
# ---- CD-Roms Connected ----
$CDConn = $VM | Where { $_ | Get-CDDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host
If (($CDConn | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "VM: CD-ROM Connected - VMotion Violation"
$MyReport += Get-HTMLTable $CDConn
$MyReport += Get-CustomHeaderClose
}
# ---- Floppys Connected ----
$Floppy = $VM | Where { $_ | Get-FloppyDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host
If (($Floppy | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "VM:Floppy Drive Connected - VMotion Violation"
$MyReport += Get-HTMLTable $Floppy
$MyReport += Get-CustomHeaderClose
}
# ---- Virtual Center Details ----
$MyReport += Get-CustomHeader "1" "$VIServer Service Details"
$MyReport += Get-HTMLTable (Get-VIServices)
$MyReport += Get-CustomHeaderClose
# ---- Virtual Center Event Logs - Error ----
$ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-$VCEvntlgAge))
If ($SetUsername -ne ""){
$ErrLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message
} Else {
$ErrLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message
}
If (($ErrLogs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Error"
$MyReport += Get-HTMLTable ($ErrLogs)
$MyReport += Get-CustomHeaderClose
}
# ---- Virtual Center Event Logs - Warning ----
$ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-1))
If ($SetUsername -ne ""){
$WarnLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message
} Else {
$WarnLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message
}
If (($WarnLogs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Warning"
$MyReport += Get-HTMLTable ($WarnLogs)
$MyReport += Get-CustomHeaderClose
}
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
#Uncomment the following lines to save the htm file in a central location
#$Date = Get-Date
#$Filename = "C:\\Temp\\" + $VIServer + "DailyReport" + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
#$MyReport | out-file -encoding ASCII -filepath $Filename
#Invoke-Item $Filename
send-SMTPmail $EmailTo $EmailFrom "$VISRV Daily Report" $SMTPSRV $MyReport
$VIServer | Disconnect-VIServer -Confirm:$false
|
PowerShellCorpus/PoshCode/HEX string to SID string_1.ps1
|
HEX string to SID string_1.ps1
|
Function EndianReverse ($strHex)
{
$intCounter=$strHex.length-1
do
{
$reverse=$reverse+$strHex.substring($intCounter-1, 2)
$intCounter=$intCounter-2
}
until ($intCounter -eq -1)
return $reverse
}
Function hex2sid ($strHex)
{
$intSidVersionLength = 2
$intSubAuthorityCountLength = 2
$intAuthorityIdentifierLength = 12
$intSubAuthorityLength = 8
$intStringPosition = 0
$bytSidVersion = [byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSidVersionLength),16)
$intStringPosition = $intStringPosition + $intSidVersionLength
$bytSubAuthorityCount=[byte][convert]::ToInt32($strHex.substring($intStringPosition, $intSubAuthorityCountLength),16)
$intStringPosition = $intStringPosition + $intSubAuthorityCountLength
$lngAuthorityIdentifier=[long][convert]::ToInt32($strHex.substring($intStringPosition, $intAuthorityIdentifierLength),16)
$intStringPosition = $intStringPosition + $intAuthorityIdentifierLength
[string]$ConvertHexStringToSidString = "S-" + $bytSidVersion + "-" + $lngAuthorityIdentifier
Do
{
$lngTempSubAuthority = EndianReverse($strHex.substring($intStringPosition, $intSubAuthorityLength))
$lngTempSubAuthority = [long][convert]::ToInt32($lngTempSubAuthority,16)
$intStringPosition = $intStringPosition + $intSubAuthorityLength
if ($lngTempSubAuthority -lt 0)
{
$lngTempSubAuthority = $lngTempSubAuthority + 4294967296
}
$ConvertHexStringToSidString = $ConvertHexStringToSidString+"-"+$lngTempSubAuthority
$bytSubAuthorityCount = $bytSubAuthorityCount - 1
}
until ($bytSubAuthorityCount -eq 0)
return $ConvertHexStringToSidString
}
|
PowerShellCorpus/PoshCode/MoveMailboxBySize.ps1
|
MoveMailboxBySize.ps1
|
### VARIABLES ###
#Stop the script if an error ever occurs
$ErrorActionPreference = "stop"
#Base Directory
$BaseDir="C:\\Scripts"
#Place for Migration Reports
$ReportFileDir="C:\\Scripts\\Logs"
#Exclusion List of Mailboxes to Not Move. This should be a return-separated list of mailbox display names to avoid.
$ExclusionListFile="$BaseDir\\ExcludedMailboxes.txt"
#Special Mailboxes. These are mailboxes that should be completely exempt, including errorChecking to see if they exist, such as non-standard system mailboxes or others that may cause problems with migration.
$SpecialMailboxes="$BaseDir\\SpecialMailboxes.txt"
#Excluded 2003 Hosts not to Scan for Mailboxes
$ExcludedHosts="$BaseDir\\ExcludedHosts.txt"
#Number of Mailboxes to Move in this Batch
$MailboxCount = 10000
#Output if a user is excluded by the Exclusion List
$ShowExclusions=$true
#Migrate for real. Only do a "what-if" evaluation if false.
$MigrateMailboxes = $false
### Functions ###
#Select-MigrateMailboxDatabase
#***READ ME*** REPLACE THE REGEX AND Mailbox Database Names as appropriate.
function Select-TargetDatabase ($NameToMatch) {
$TargetMailboxDatabaseName = switch -regex ($NameToMatch) {
"^[0-9].*" {"1 - Mailbox Store A - D"}
"^[a-d].*" {"1 - Mailbox Store A - D"}
"^[e-h].*" {"2 - Mailbox Store E - H"}
"^[i-l].*" {"3 - Mailbox Store I - L"}
"^[m-p].*" {"4 - Mailbox Store M - P"}
"^[q-t].*" {"5 - Mailbox Store Q - T"}
"^[u-z].*" {"6 - Mailbox Store U - Z"}
default {throw "No Datastore was matched by Select-MigrateMailboxDatabase for $MailboxDisplayName. Check that the user's name will be matched by the select-targetdatabase matching criteria"}
}
return $TargetMailboxDatabaseName
}
### INITIALIZE ###
#Load Exchange Snapins if not present
if (!(get-pssnapin Microsoft.Exchange.Management.Powershell.Admin -erroraction SilentlyContinue)) {
write-host -fore cyan "Loading Exchange Powershell Snapins..."
get-pssnapin -registered | where {$_.name -match "Microsoft.Exchange"} | add-pssnapin
}
#Load 2003 Statistics Formatting Module
if (!(get-module Format-2003MailboxStatistics)) {import-module "$BaseDir\\Format-2003MailboxStatistics.psm1"}
### END INITIALIZE ###
### SCRIPT ###
write-host -fore darkcyan "===Mailbox Move Script START==="
#Trim any leading/trailing whitespace from the exclusion list
$ExclusionList = (get-content $ExclusionListFile) | foreach {$_.trim()}
#Validate Exclude List. Ensure every item in the exclusion list has a corresponding mailbox. This way we can be sure we don't accidentally miss someone because their name was misspelled.
write-host -fore darkcyan "= Validating Exclusion List..." -nonewline
$ExclusionList | where {(get-content $SpecialMailboxes) -notcontains $_} | foreach {
if (!(get-mailbox "$_" -errorAction SilentlyContinue)) {throw "Validating the Exclusion List failed. There is no Exchange Mailbox with the display name $_. Verify that the name in the Exclusion List is correct and try again."}
}
write-host -fore green "SUCCESS"
###Collect mailbox statistics on all legacy mailboxes (aka not migrated to 2007) in the organization.
#First Get a list of all Exchange 2003 Servers in the organization
write-host -fore darkcyan "= Collecting Exchange 2003 Server Information..." -nonewline
$EX2003Servers = get-exchangeserver | where {$_.AdminDisplayVersion -match "6.5"}
write-host -fore green "SUCCESS"
#Collect Mailbox Statistics for Each Server
$2003MailboxStats = @()
$EX2003Servers | where {(get-content $ExcludedHosts) -notcontains $_.Name} | foreach {
$ServerName = $_.Name
write-host -fore darkcyan "= Collecting Exchange 2003 Mailbox Statistics on $ServerName..." -nonewline
$MailboxWMIInfo = Get-WMIObject -ComputerName $ServerName `
-Namespace "root/MicrosoftExchangeV2" -Class "Exchange_Mailbox"
$2003MailboxStats += $MailboxWMIInfo | Format-2003MailboxStatistics
write-host -fore green "SUCCESS"
}
#Check if each Mailbox is on the exclusion list, and filter it out if it is. We do this before mailbox selection in case the top X results are all excluded people, so we don't have to run the script a second time.
write-host -fore darkcyan "= Excluding Mailboxes on the Exclusion, System, and Keyword Lists..."
$MailboxMoveCandidates = $2003MailboxStats | `
where {(get-content $SpecialMailboxes) -notcontains "$($_.MailboxDisplayName)"} | `
where {
#@@BUGFIX - This logic is not 100% sound, several implications are made. Works fine but could be cleaner.
#Set some variables for ease-of-use later
$candidate = $_
$candidateName = $candidate.MailboxDisplayName.Trim()
#Filter Out System Mailboxes
if ($candidateName -match 'SMTP ' ) {return $false}
elseif ($candidateName -match 'SystemMailbox'){return $false}
#Filter Out Disabled Users
elseif ($candidate.DateDiscoveredAbsentInDS) {
if ($showExclusions) {write-host -fore yellow "= * Skipping $candidateName because the mailbox has no corresponding Active Directory Object."}
return $false;
}
#Verify user has a corresponding AD object
elseif (!(get-mailbox $candidate.Identity -erroraction silentlyContinue)) {
if ($showExclusions) {write-host -fore red "= * Skipping $candidateName because could not get mailbox info. Verify that the user has an Active Directory Account."}
return $false;
}
#Verify a user is not on the exclusion List.
elseif ($ExclusionList -notcontains "$candidateName") {
return $true;
}
#Exclude everything else as a safety check if it doesn't meet the above rules.
else {
if ($showExclusions) {write-host -fore yellow "= * $candidateName was excluded"}
return $false;
}
}
write-host -fore green "= Excluding Mailboxes SUCCESS"
#Select Top X Users
$MailboxesToMove = $MailboxMoveCandidates | sort size | select -first $MailboxCount
#Display Mailboxes that will be moved and where they will be moved to. We do this by creating new objects with Select that have a new targetDatastore parameter, and run the detection program to find the correct datastore and populate.
$MBDisplay = $MailboxesToMove | select MailboxDisplayName,@{Name='Size (KB)';Expression={$_.size}},serverName,NameToMatch,targetDatabase | foreach {
$_.nameToMatch = $_.MailboxDisplayName.split() | select -last 1
$_.targetDatabase = Select-TargetDatabase "$($_.nameToMatch)";$_
}
#Separated this out so that it will process all objects BEFORE showing the out-gridview in case of any errors.
$MBDisplay | out-gridview -title "List of Mailboxes to Migrate in This Batch"
if ((read-host "Do you wish to move these $MailboxCount users? Type MIGRATE to perform the migration or anything else to exit.") -notlike "MIGRATE") {throw "Migration Cancelled at User Request";exit 10}
#Perform the Migration.
$MailboxesToMove | foreach {
$mailboxToMove = get-mailbox $_.Identity
#@@BUGFIX - This is sloppy, would be better to query the AD last name. Is fine for 99% of users.
$NameToMatch = $_.MailboxDisplayName.split() | select -last 1
$targetDatabaseName = Select-TargetDatabase $NameToMatch
#@@BUGFIX - This is also sloppy, but we would need all kinds of logic to get the database server and storage group first and this works just as well for 99% of cases as long as target datastore names are unique (they have to be in EX2010).
$targetDatabase = get-mailboxdatabase | where {$_.name -like "$targetDatabaseName"}
$reportFileName = "$ReportFileDir\\$($mailboxToMove.Alias)-$(get-date -format "yyyy-MMM-dd-HHmmss").xml"
#Just do a whatif unless MigrateMailboxes is set to true
if ($MigrateMailboxes) {move-mailbox $mailboxToMove -targetdatabase $targetDatabase -reportfile $reportFileName -Confirm $false}
else {move-mailbox $mailboxToMove -targetdatabase $targetDatabase -reportfile $reportFileName -whatif}
}
#Free Up Memory by deleting variable we don't need anymore.
#remove-variable -name MailboxMoveCandidates
###TODO: Rewrite 2003Stats as a pipeline function, get stats, sort by name and filter, exclude, and then kick off move mailbox with -whatif unless MigrateMailboxes is set.
|
PowerShellCorpus/PoshCode/Get-PerformanceHistory 2.ps1
|
Get-PerformanceHistory 2.ps1
|
#requires -version 2.0
## Get-PerformanceHistory.ps1
##############################################################################################################
## Lets you see the amount of time recent commands in your history have taken
## History:
## v2 - adds a ton of parsing to make the output pretty
## - added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
param( [int]$count=1, [int]$id=((Get-History -count 1| Select Id).Id) )
$Parser = [System.Management.Automation.PsParser]
function FormatTimeSpan($ts) {
if($ts.Minutes) {
if($ts.Hours) {
if($ts.Days) {
return "{0:##}d {1:00}:{2:00}:{3:00}.{4:00000}" -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}:{2:00}.{3:00000}" -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}.{2:00000}" -f $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:#0}.{1:00000}" -f $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
Get-History -count $count -id $id |
ForEach {
$msr = $null
$cmd = $_
$len = 8
$com = @( $Parser::Tokenize( $cmd.CommandLine, [ref]$null ) |
where {$_.Type -eq "Command"} |
foreach { get-command $_.Content } |
where { $_.CommandType -eq "ExternalScript" } |
foreach { $_.Path } )
# If we actually got a script, measure it out
if($com.Count -gt 0){
$msr = Get-Content -path $com | Measure-Object -L -W -C
} else {
$msr = Measure-Object -in $cmd.CommandLine -L -W -C
}
"" | Select @{n="Id"; e={$cmd.Id}},
@{n="Duration"; e={FormatTimeSpan ($cmd.EndExecutionTime - $cmd.StartExecutionTime)}},
@{n="Lines"; e={$msr.Lines}},
@{n="Words"; e={$msr.Words}},
@{n="Chars"; e={$msr.Characters}},
@{n="Type"; e={if($com.Count -gt 0){"Script"}else{"Command"}}},
@{n="Commmand"; e={$cmd.CommandLine}}
} |
# I have to figure out what the longest time string is to make it look its best
Foreach { $len = [Math]::Max($len,$_.Duration.Length); $_ } | Sort Id |
Format-Table @{l="Duration";e={"{0,$len}" -f $_.Duration}},Lines,Words,Chars,Type,Commmand -auto
|
PowerShellCorpus/PoshCode/Get-ADGroupMembers_2.ps1
|
Get-ADGroupMembers_2.ps1
|
Function Get-ADGroupMembers
{
<#
.SYNOPSIS
Return a collection of users in an ActiveDirectory group.
.DESCRIPTION
This function returns an object that contains all the properties of a user object. This function
works for small groups as well as groups in excess of 1000.
.PARAMETER UserGroup
The name of the group to get membership from.
.PARAMETER UserDomain
The LDAP URL of the domain that the group resides in.
.EXAMPLE
Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn
name distinguishedName cn
---- ----------------- --
{Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts}
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533...
{Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple}
...
Description
-----------
This example shows passing in a group name, but leaving the default domain name in place.
.NOTES
The context under which this script is run must have rights to pull infromation from ActiveDirectory.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers
#>
Param
(
$UserGroup = "Domain Users",
$UserDomain = ([ADSI]"LDAP://DC=company,DC=com")
)
Begin
{
$DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path)
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))"
$DirectorySearcher.SearchRoot = $DirectoryEntry
$DirectorySearcher.PageSize = 1000
$DirectorySearcher.Filter = $LDAPFilter
$DirectorySearcher.SearchScope = "Subtree"
$SearchResult = $DirectorySearcher.FindAll()
$UserAccounts = @()
}
Process
{
foreach ($Item in $SearchResult)
{
$Group = $Item.GetDirectoryEntry()
$Members = $Group.member
If ($Members -ne $Null)
{
foreach ($User in $Members)
{
$UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)")
If ($UserObject.objectCategory.Value.Contains("Group"))
{
}
Else
{
$ThisUser = New-Object -TypeName PSObject -Property @{
cn = $UserObject.cn
distinguishedName = $UserObject.distinguishedName
name = $UserObject.name
nTSecurityDescriptor = $UserObject.nTSecurityDescriptor
objectCategory = $UserObject.objectCategory
objectClass = $UserObject.objectClass
objectGUID = $UserObject.objectGUID
objectSID = $UserObject.objectSID
showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly
}
}
$UserAccounts += $ThisUser
}
}
}
}
End
{
Return $UserAccounts
}
}
|
PowerShellCorpus/PoshCode/CSV Validator Framework.ps1
|
CSV Validator Framework.ps1
|
# --- begin test-csv.ps1 ---
param(
[string]$Path = $(throw "require CSV path!"),
[string]$RulesetPath = $(throw "require Ruleset path!")
)
$csvFiles = Resolve-Path -Path $Path
# load rules
if ((Test-Path (Resolve-Path $RulesetPath))) {
# ruleset is found, execute and assign result to variable (should be hashtable)
$ruleset = (& $RulesetPath)
write-host "Ruleset has $($ruleset.firstrow.keys.count) first row rule(s)"
write-host "Ruleset has $($ruleset.allrows.keys.count) all rows rule(s)"
if (-not ($ruleset.firstrow)) {
write-warning "ruleset $rulesetpath has no rules for first row (list/table validation)"
}
if (-not ($ruleset.allrows)) {
throw "ruleset $rulesetpath has no rules for allrows (row validation)"
}
} else {
throw "Could not find ruleset $rulesetpath"
}
write-verbose "Found $($csvfiles.length) file(s)"
$csvFiles | where-object {
# only pass on CSV files
[io.path]::GetExtension( $_.providerpath ) -eq ".csv"
} | foreach-object {
write-host "processing CSV $_"
# import csv files
$firstRow = $true
$rowcount = 0
import-csv $_.path <#| select -first 20#> | foreach-object {
write-host "row $rowcount"
$currentRow = $_
# process "first row only" rules, only on first row
if ($firstRow) {
$ruleset.FirstRow.Keys | % {
write-host -nonewline "Processing rule $_ ... "
# execute the scriptblock with the current row as an argument
# the scriptblock is the value of the imported hashtable
if ((& $ruleset.firstrow[$_] $currentRow)) {
write-host -fore green "passed"
} else {
# displays green in ISE (lol)
write-host -fore red "failed"
}
}
$firstRow = $false
}
# process "all rows" rules
$ruleset.AllRows.Keys | % {
write-host -nonewline "Processing rule $_ ... "
# execute the scriptblock with the current row as an argument
# the scriptblock is the value of the imported hashtable
if ((& $ruleset.AllRows[$_] $currentRow)) {
write-host -fore green "passed"
} else {
# displays green in ISE (lol)
write-host -fore red "failed"
}
}
$rowcount++
}
}
# --- end test-csv.ps1 ---
# --- begin ruleset-sample.ps1 ---
@{
FirstRow = @{
ruleVerifyColumns = {
param($row)
$columns = @("u_logon_name",
"u_user_security_password",
"g_user_id_changed_by",
"i_account_status",
"d_date_registered",
"d_date_last_changed",
"d_date_created")
$count = 0
$columns | ForEach-Object <# alias = % #> {
if ($row.psobject.members.Match($_)) { $count++ }
}
$count -eq $columns.length
};
};
AllRows = @{
ruleLogonNameLengthGreaterThan8 = {
param($row)
$row.u_logon_name -gt 8
};
ruleChangedByIsValidGuid = {
param($row)
try {
# try cast to guid and swallow result if successful
[guid]$row.g_user_id_changed_by > $null
$true
} catch { $false }
};
}
}
# --- end ruleset-sample.ps1 ---
|
PowerShellCorpus/PoshCode/SMS_1.psm1.ps1
|
SMS_1.psm1.ps1
|
<#
.Synopsis
Functions for managing SMS and SCCM.
.Notes
NAME: SMS.psm1
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
#>
#Requires -version 2.0
[string]$default_wmi_provider_server = 'myserver'
[string]$default_site = 'S00'
function Get-SmsWmi {
<#
.Synopsis
A function for accessing the SMS WMI classes from the SMS Provider.
.Description
This function wraps Get-WmiObject in order to provide an easy way to access
the SMS Provider and the classes it provides. This function keeps you from
having to keep entering in the long namespace and the name of the provider
server every time you want to query the provider.
To change the provider server, you can either use the -computername and -site
parameters or set $default_wmi_provider_server and $default_site before
calling the function.
.Parameter class
The class or class nickname to be returned.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Get all server clients
PS> Get-SmsWmi sys 'OperatingSystemNameAndVersion like "%serv%" and client = 1'
.Example
# Get the PackageID for all packages on Distribution Point Server1
PS> Get-SmsWmi dist 'ServerNALPath like "%Server1%"' | select PackageID
.Example
# Get the ResourceID for all systems with a HW Scan after 2009-03-31
PS> Get-SmsWmi work 'LastHardwareScan > "2009-03-31"' | select ResourceID
.ReturnValue
System.Management.ManagementObject objects of the corresponding class.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Get-SmsWmi
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([Parameter(Position = 0)]
[string]$class = $(Throw @"
`t
ERROR: You must enter a class name or nickname.
`t
Valid nicknames are:
`t
Nickname WMI Class
==============================================================================
AddRemovePrograms => SMS_G_System_ADD_REMOVE_PROGRAMS
AdStatus => SMS_ClientAdvertisementStatus
Advertisement => SMS_Advertisement
Collection => SMS_Collection
ComputerSystem => SMS_G_System_COMPUTER_SYSTEM
DistributionPoint => SMS_DistributionPoint
LogicalDisk => SMS_G_System_LOGICAL_DISK
MembershipRule => SMS_CollectionMembershipRule
NetworkAdapter => SMS_G_System_NETWORK_ADAPTER
NetworkAdapterConfiguration => SMS_G_System_NETWORK_ADAPTER_CONFIGURATION
OperatingSystem => SMS_G_System_OPERATING_SYSTEM
Package => SMS_Package
PkgStatus => SMS_PackageStatus
Program => SMS_Program
Query => SMS_Query
Server => SMS_SystemResourceList
Service => SMS_G_System_SERVICE
Site => SMS_Site
StatusMessage => SMS_StatusMessage
System => SMS_R_System
WorkstationStatus => SMS_G_System_WORKSTATION_STATUS
User => SMS_R_User
`t
Note: You only need to type as many characters as needed to be unambiguous.
`t
"@),
[Parameter(Position = 1)]
[string]$filter = $null,
[Parameter(Position = 2)]
[string]$computername = $default_wmi_provider_server,
[Parameter(Position = 3)]
[string]$site = $default_site)
$classes = @{'collection' = 'SMS_Collection';
'package' = 'SMS_Package';
'program' = 'SMS_Program';
'system' = 'SMS_R_System';
'server' = 'SMS_SystemResourceList';
'advertisement' = 'SMS_Advertisement';
'query' = 'SMS_Query';
'membershiprule' = 'SMS_CollectionMembershipRule';
'statusmessage' = 'SMS_StatusMessage';
'site' = 'SMS_Site';
'user' = 'SMS_R_User';
'pkgstatus' = 'SMS_PackageStatus';
'addremoveprograms' = 'SMS_G_System_ADD_REMOVE_PROGRAMS';
'computersystem' = 'SMS_G_System_COMPUTER_SYSTEM';
'operatingsystem' = 'SMS_G_System_OPERATING_SYSTEM';
'service' = 'SMS_G_System_SERVICE';
'workstationstatus' = 'SMS_G_System_WORKSTATION_STATUS';
'networkadapter' = 'SMS_G_System_NETWORK_ADAPTER';
'networkadapterconfiguration' = ('SMS_G_System_NETWORK_' +
'ADAPTER_CONFIGURATION');
'logicaldisk' = 'SMS_G_System_LOGICAL_DISK';
'distributionpoint' = 'SMS_DistributionPoint';
'adstatus' = 'SMS_ClientAdvertisementStatus'}
$matches = @();
foreach ($class_name in @($classes.Keys | sort)) {
if ($class_name.StartsWith($class.ToLower())) {
$matches += $classes.($class_name)
}
}
if ($matches.Count -gt 1) {
Write-Error @"
`t
Warning: Class provided matches more than one nickname.
`t
Type 'Get-SMSWmi' with no parameters to see a list of nicknames.
`t
"@
$class = $matches[0]
} elseif ($matches.Count -eq 1) {
$class = $matches[0]
}
$query = "Select * from $class"
if ($filter) {
$query += " Where $filter"
}
# Now that we have our parameters, let's execute the command.
$namespace = 'root\\sms\\site_' + $site
gwmi -ComputerName $computerName -Namespace $namespace -Query $query
}
function Find-SmsID {
<#
.Synopsis
Look up SMS WMI objects from the SMS Provider by SMS ID.
.Description
This function makes it easy to look up a System Resource, Advertisement,
Package, or Collection by ID. The SMS Provider is queried, and the WMI object
that matches the ID is returned.
.Parameter AdvertisementID
A switch indicating that the $ID is an AdvertisementID.
.Parameter CollectionID
A switch indicating that the $ID is a CollectionID.
.Parameter PackageID
A switch indicating that the $ID is a PackageID.
.Parameter ResourceID
A switch indicating that the $ID is a ResourceID.
.Parameter ID
A string with the ID to look up.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Look up PackageID S000003D
PS> Find-SmsID -PackageID S000003D
.ReturnValue
A System.Management.ManagementObject object of the corresponding class.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Find-SmsID
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([switch]$AdvertisementID,
[switch]$CollectionID,
[switch]$ResourceID,
[switch]$PackageID,
[string]$ID,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
$class = ''
$Type = ''
if ($AdvertisementID) {
$Type = 'AdvertisementID'
$class = 'SMS_Advertisement'
} elseif ($CollectionID) {
$Type = 'CollectionID'
$class = 'SMS_Collection'
} elseif ($PackageID) {
$Type = 'PackageID'
$class = 'SMS_Package'
} elseif ($ResourceID) {
$Type = 'ResourceID'
$class = 'SMS_R_System'
} else {
Throw @"
`t
You must specify an ID type. Valid switches are:
`t
`t-AdvertisementID
`t-CollectionID
`t-PackageID
`t-ResourceID
`t
USAGE: Find-SmsID <Type> <ID> [-computername <computer>] [-site <site>]
`t
"@
}
if ($ResourceID) {
trap [System.Exception] {
Write-Output "`nERROR: Invalid Input for ResourceID!`n"
break
}
$Type = 'ResourceID'
$class = 'System'
[int]$ID = $ID
} else{
if ($ID -notmatch '^[a-zA-Z0-9]{8}$') {
Throw "`n`t`nERROR: Invalid ID format.`n`t`n"
}
}
Get-SmsWmi -class $class -filter "$Type = `"$ID`"" `
-computername $computername `
-site $site
}
function Get-SmsCollectionTree {
<#
.Synopsis
Inspired by tree.com from DOS, it creates a tree of all collections in SMS.
.Description
This function iterates recursively through all collections, showing which
collections are under which other collections, and what their CollectionIDs
are.
.Parameter root
The CollectionID of the collection to start with (default COLLROOT).
.Parameter indent
The indent level of the current interation.
.Parameter computername
The hostname of the server with the SMS Provider
.Parameter site
The site code of the target SMS site.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Get-SmsCollectionTree
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([string]$root = 'COLLROOT',
[int]$indent = 0,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
Get-SmsWmi -class SMS_CollectToSubCollect `
-filter "parentCollectionID = '$root'" `
-computername $computername `
-site $site |
% {$name = (Find-SmsID -c $_.subCollectionID).Name
Add-Member -InputObject $_ -Name 'sub_name' NoteProperty $name
$_} |
sort sub_name |
% {Write-Host ((' ' * $indent) +
"+ $($_.sub_name) : $($_.subCollectionID)")
Get-SmsCollectionTree -root $_.subCollectionID `
-indent ($indent + 1) `
-computername $computername `
-site $site}
}
function Approve-Client {
<#
.Synopsis
Approves a list of resources or all clients in a collection.
.Description
Marks one or more clients as Approved in the SCCM DB. A list of resources
or a CollectionID may be passed.
.Parameter resource_list
A list of ResourceIDs to be approved.
.Parameter collection_id
A CollectionID whose members will be approved.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Approve two systems by ResourceID
PS> Approve-Client -resource_list 33217, 4522
.Example
# Approve all members of collection S000023C
PS> Approve-Client -collection_id S000023C
.ReturnValue
An integer with the number of clients approved.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Approve-Client
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([string[]]$resource_list,
[string]$collection_id,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
$clients = @()
$coll_class = [wmiclass]('\\\\{0}\\root\\sms\\site_{1}:SMS_Collection' `
-f $computername, $site)
if ($resource_list.Count) {
$clients = $resource_list
}elseif ($collection_id){
$clients = @(Get-SmsWmi SMS_CollectionMember_a `
-filter "CollectionID = '$($collection_id)'" |
%{$_.ResourceID})
}
if ($clients.Count -eq 0) {
Write-Error ('Error: You must supply at least one client.`n' +
' (Did you enter an empty or invalid collection?)')
break
}
return ($coll_class.ApproveClients($clients)).ReturnValue
}
|
PowerShellCorpus/PoshCode/RoboGUI.ps1
|
RoboGUI.ps1
|
# a helper GUI to create RoboCopy commands
# uses FormsLib.ps1
#
# /\\/\\o\\/\\/
# http://thePowerShellGuy.com
# load windows.forms assembly and FormsLib.ps1
[system.reflection.assembly]::LoadWithPartialName('system.windows.forms')
. .\\FormsLib.ps1
#############################################################################################
## Make RoboCopy Help Object
#############################################################################################
$RoboHelp = robocopy /? | Select-String '::'
$r = [regex]'(.*)::(.*)'
$RoboHelpObject = $RoboHelp | select `
@{Name='Parameter';Expression={ $r.Match( $_).groups[1].value.trim()}},
@{Name='Description';Expression={ $r.Match( $_).groups[2].value.trim()}}
$RoboHelpObject = $RoboHelpObject |% {$Cat = 'General'} {
if ($_.parameter -eq '') { if ($_.Description -ne ''){
$cat = $_.description -Replace 'options :',''}
} else {
$_ | select @{Name='Category';Expression={$cat}},parameter,description
}
}
# Form
##################################
$frmRobocopy = new-Object System.Windows.Forms.form
set-controlFormat $frmRobocopy `
-Location '{X=46,Y=46}'`
-Size '{Width=1223, Height=850}'`
-Text 'RoboCopy PowerShell GUI'`
# SwitchOptions
$dtSwitches = new-object Data.datatable
$Col = new-object Data.DataColumn
$col.DataType = [bool]
$Col.ColumnName = "Enabled"
$dtSwitches.Columns.Add($Col)
"Category","Name","Description" |
Foreach {
$Col = new-object Data.DataColumn
$Col.ColumnName = $_
$dtSwitches.Columns.Add($Col)
}
$RoboHelpObject |? { $_.Parameter -match '/[a-z]*$' } |
Foreach {
$row = $dtswitches.NewRow()
$row.Category = $_.Category
$row.Name = $_.Parameter
$row.Description = $_.Description
$dtSwitches.Rows.Add($row)
}
# ParameterOptions
$dtParameters = new-object Data.datatable
$Col = new-object Data.DataColumn
$col.DataType = [bool]
$Col.ColumnName = "Enabled"
$dtParameters.Columns.Add($Col)
"Category","Name","Value","Description" |
Foreach {
$Col = new-object Data.DataColumn
$Col.ColumnName = $_
$dtParameters.Columns.Add($Col)
}
$RoboHelpObject |? { $_.Parameter -match '/[a-z]*:' } |
Foreach {
$row = $dtParameters.NewRow()
$row.Category = $_.Category
$row.Name = $_.Parameter
$row.Description = $_.Description
$dtParameters.Rows.Add($row)
}
# Main Parameters
"Source",
"Destination",
"Files",
"Options",
"CommandLine" |% {$Y = 30}{
$label = New-Object System.Windows.Forms.Label
Set-ControlFormat $label `
-Anchor 'Top, Left'`
-Dock 'None'`
-Location "{X=50,Y=$y}"`
-Name "lbl$_"`
-Size '{Width=100, Height=23}'`
-Text $_
$TextBox = New-Object System.Windows.Forms.TextBox
Set-ControlFormat $textBox `
-Anchor 'Top, Left'`
-Dock 'None'`
-Location "{X=150,Y=$Y}"`
-Name "txt$_"`
-Size '{Width=400, Height=21}'
$FrmRobocopy.Controls.Add($label)
$FrmRobocopy.Controls.Add($TextBox)
$Y += 25
}
$command = "RoboCopy"
$FrmRobocopy.Controls['txtCommandLine'].Enabled = $false
$FrmRobocopy.Controls['txtOptions'].Enabled = $false
$FrmRobocopy.Controls['txtCommandLine'].Text = $command
$dgSwitches = new-object windows.forms.DataGridView
Set-ControlFormat $dgSwitches `
-Dock 'Fill'`
-Name 'dgOptions'`
-DataSource $dtSwitches.psObject.baseobject
$dgOptions = new-object windows.forms.DataGridView
Set-ControlFormat $dgOptions `
-Dock 'Fill'`
-Name 'dgOptions'`
-DataSource $dtParameters.psObject.baseobject
$scOptions = new-object System.Windows.Forms.SplitContainer
Set-ControlFormat $scOptions `
-Name 'scOptions' `
-Location '{X=20,Y=170}'`
-Size '{Width=1170, Height=615}'`
-SplitterDistance '534'`
-Anchor "Top, Bottom, Left, Right"
$scOptions.Panel1.Controls.Add( $DGswitches )
$scOptions.Panel2.Controls.Add( $dgOptions )
$FrmRobocopy.Controls.Add($scOptions)
$Switches = "$($dtSwitches |? {$_.Enabled -eq $True} |% {$_.name})"
function Update-Commandline {
$Switches = "$($dtSwitches |? {$_.Enabled -eq $True} |% {$_.name})"
$Options = "$($dtParameters |? {$_.Enabled -eq $True} |% {$_.name.split(':')[0] + "":$($_.Value)""})"
$FrmRobocopy.Controls['txtOptions'].Text = "$options $Switches"
$Command = '$robocopy ' `
+ $FrmRobocopy.Controls['txtSource'].Text `
+ ' ' + $FrmRobocopy.Controls['txtDestination'].Text `
+ " " + $FrmRobocopy.Controls['txtFiles'].Text `
+ ' ' + $FrmRobocopy.Controls['txtOptions'].Text
$FrmRobocopy.Controls['txtCommandLine'].Text = $command
}
$btnUpdate = new-Object System.Windows.Forms.Button
set-controlFormat $btnUpdate `
-Anchor 'Top, Left'`
-Dock 'None'`
-Location '{X=560,Y=30}'`
-Size '{Width=75, Height=23}'`
-Text 'Update'
$btnUpdate.add_Click({Update-Commandline})
$FrmRobocopy.Controls.Add($btnUpdate)
#Edit-Form $FrmRobocopy
#get-FormControls $FrmRobocopy
$FrmRobocopy.Add_Shown({$frmRoboCopy.Activate()
$dgSwitches.AutoResizeColumns()
$dgOptions.AutoResizeColumns()
})
$FrmRobocopy.ShowDialog()
|
PowerShellCorpus/PoshCode/BinaryClock V2.0.ps1
|
BinaryClock V2.0.ps1
|
Function Start-BinaryClock {
<#
.SYNOPSIS
This is a binary clock that lists the time in hours, minutes and seconds
.DESCRIPTION
This is a binary clock that lists the time in hours, minutes and seconds.
Key Input Tips:
r: Toggles the resize mode of the clock so you can adjust the size.
d: Toggles the date to hide/show
o: Toggles whether the clock remains on top of windows or not.
+: Increases the opacity of the clock so it is less transparent.
-: Decreases the opacity of the clock so it appears more transparent.
Right-Click to close.
Use left mouse button to drag clock.
.PARAMETER OnColor
Define the color used for the active time (1).
.PARAMETER OffColor
Define the color used for the inactive time (0).
.PARAMETER RandomColor
Default parameter if manual colors are not used. Picks a random color for On and Off colors.
.NOTES
Name: BinaryClock.ps1
Author: Boe Prox
DateCreated: 07/05/2011
Version 2.0
.EXAMPLE
Start-BinaryClock
Description
-----------
Starts the binary clock using randomly generated colors
.EXAMPLE
Start-BinaryClock -OnColor Red -OffColor Gold -DateColor Black
Description
-----------
Starts the binary clock using using specified colors.
#>
[cmdletbinding(
DefaultParameterSetName = 'RandomColor'
)]
Param (
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[system.windows.media.brush] $OnColor,
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[system.windows.media.brush] $OffColor,
[parameter(ParameterSetName = 'RandomColor')]
[Switch]$RandomColor,
[parameter(Mandatory = 'True',ParameterSetName = 'SetColor')]
[system.windows.media.brush] $DateColor
)
If ($PSCmdlet.ParameterSetName -eq 'RandomColor') {
[switch]$RandomColor = $True
}
$Global:rs = [RunspaceFactory]::CreateRunspace()
$rs.ApartmentState = “STA”
$rs.ThreadOptions = “ReuseThread”
$rs.Open()
$psCmd = {Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase}.GetPowerShell()
$rs.SessionStateProxy.SetVariable('OnColor',$OnColor)
$rs.SessionStateProxy.SetVariable('OffColor',$OffColor)
$rs.SessionStateProxy.SetVariable('RandomColor',$RandomColor)
$rs.SessionStateProxy.SetVariable('DateColor',$DateColor)
$psCmd.Runspace = $rs
$psCmd.Invoke()
$psCmd.Commands.Clear()
$psCmd.AddScript({
#Load Required Assemblies
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
##Colors
If ($RandomColor) {
#On Color
$OnColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$OnColor | Out-Null
}
Catch {
$OnColor = "White"
}
#Off Color
$OffColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$OffColor | Out-Null
}
Catch {
$OffColor = "Black"
}
#DateColor Color
$DateColor = "#{0:X}" -f (Get-Random -min 1 -max 16777215)
Try {
[system.windows.media.brush]$DateColor | Out-Null
}
Catch {
$DateColor = "Black"
}
}
[xml]$xaml = @"
<Window
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
x:Name='Window' WindowStyle = 'None' WindowStartupLocation = 'CenterScreen' Width = '170' Height = '101' ShowInTaskbar = 'True'
ResizeMode = 'NoResize' Title = 'Clock' AllowsTransparency = 'True' Background = 'Transparent' Opacity = '1' Topmost = 'True'>
<Grid x:Name = 'Grid' HorizontalAlignment="Stretch" ShowGridLines='false' Background = 'Transparent'>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition Width="*" x:Name = 'DayColumn'/>
<ColumnDefinition Width="*" x:Name = 'MonthColumn'/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition Height = '*'/>
<RowDefinition Height = '2'/>
<RowDefinition x:Name = 'timerow' Height = '0'/>
</Grid.RowDefinitions>
<Ellipse Grid.Row = '0' Grid.Column = '0' Fill = 'Transparent'/>
<Ellipse Grid.Row = '2' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourA0' Grid.Row = '6' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourA1' Grid.Row = '4' Grid.Column = '0' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB0' Grid.Row = '6' Grid.Column = '2' Fill = 'Transparent'/>
<Ellipse x:Name = 'HourB1' Grid.Row = '4' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB2' Grid.Row = '2' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse x:Name = 'HourB3' Grid.Row = '0' Grid.Column = '2' Fill = 'Transparent' />
<Ellipse Grid.Row = '0' Grid.Column = '4' Fill = 'Transparent'/>
<Ellipse x:Name = 'MinuteA0' Grid.Row = '6' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteA1' Grid.Row = '4' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteA2' Grid.Row = '2' Grid.Column = '4' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB0' Grid.Row = '6' Grid.Column = '6' Fill = 'Transparent'/>
<Ellipse x:Name = 'MinuteB1' Grid.Row = '4' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB2' Grid.Row = '2' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse x:Name = 'MinuteB3' Grid.Row = '0' Grid.Column = '6' Fill = 'Transparent' />
<Ellipse Grid.Row = '0' Grid.Column = '8' Fill = 'Transparent'/>
<Ellipse x:Name = 'SecondA0' Grid.Row = '6' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondA1' Grid.Row = '4' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondA2' Grid.Row = '2' Grid.Column = '8' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB0' Grid.Row = '6' Grid.Column = '10' Fill = 'Transparent'/>
<Ellipse x:Name = 'SecondB1' Grid.Row = '4' Grid.Column = '10' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB2' Grid.Row = '2' Grid.Column = '10' Fill = 'Transparent' />
<Ellipse x:Name = 'SecondB3' Grid.Row = '0' Grid.Column = '10' Fill = 'Transparent' />
<Viewbox VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch' Grid.Column = '12' Grid.RowSpan = '7'
StretchDirection = 'Both' Stretch = 'Fill'>
<TextBlock x:Name = 'DayLabel' VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch'
FontWeight = 'Bold'>
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Viewbox>
<Viewbox VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch' Grid.Column = '13' Grid.RowSpan = '7'
StretchDirection = 'Both' Stretch = 'Fill'>
<TextBlock x:Name = 'MonthLabel' VerticalAlignment = 'Stretch' HorizontalAlignment = 'Stretch'
FontWeight = 'Bold'>
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Viewbox>
</Grid>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Global:Window=[Windows.Markup.XamlReader]::Load( $reader )
$Global:DayLabel = $Global:window.FindName("DayLabel")
$Global:MonthLabel = $Global:window.FindName("MonthLabel")
$Global:DayColumn = $Global:window.FindName("DayColumn")
$Global:MonthColumn = $Global:window.FindName("MonthColumn")
$Global:TimeRow = $Global:window.FindName("TimeRow")
$Global:Grid = $Global:window.FindName("Grid")
##Events
#Key Events
$Global:Window.Add_KeyDown({
Switch ($_.Key) {
{'Add','OemPlus' -contains $_} {
If ($Window.Opacity -lt 1) {
$Window.Opacity = $Window.Opacity + .1
$Window.UpdateLayout()
}
}
{'Subtract','OemMinus' -contains $_} {
If ($Window.Opacity -gt .2) {
$Window.Opacity = $Window.Opacity - .1
$Window.UpdateLayout()
}
}
"r" {
If ($Window.ResizeMode -eq 'NoResize') {
$Window.ResizeMode = 'CanResizeWithGrip'
}
Else {
$Window.ResizeMode = 'NoResize'
}
}
"d" {
Switch ($MonthLabel.visibility) {
'Collapsed' {$MonthLabel.visibility = 'Visible';$DayLabel.Visibility = 'Visible'}
'Visible' {$MonthLabel.visibility = 'Collapsed ';$DayLabel.Visibility = 'Collapsed '}
}
}
"o" {
If ($Window.TopMost) {
$Window.TopMost = $False
}
Else {
$Window.TopMost = $True
}
}
}
})
$Window.Add_MouseRightButtonUp({
$This.close()
})
$Window.Add_MouseLeftButtonDown({
$This.DragMove()
})
$update = {
$DayLabel.Text = "$(((Get-Date).ToLongDateString() -split ',')[0] -split '')"
$DayLabel.Foreground = $DateColor
$MonthLabel.Text = Get-Date -u "%B %d %G"
$MonthLabel.Foreground = $DateColor
$hourA,$hourB = [string](Get-Date -f HH) -split "" | Where {$_}
$minuteA,$minuteB = [string](Get-Date -f mm) -split "" | Where {$_}
$secondA,$secondB = [string](Get-Date -f ss) -split "" | Where {$_}
$hourAdock = $grid.children | Where {$_.Name -like "hourA*"}
$minuteAdock = $grid.children | Where {$_.Name -like "minuteA*"}
$secondAdock = $grid.children | Where {$_.Name -like "secondA*"}
$hourBdock = $grid.children | Where {$_.Name -like "hourB*"}
$minuteBdock = $grid.children | Where {$_.Name -like "minuteB*"}
$secondBdock = $grid.children | Where {$_.Name -like "secondB*"}
#hourA
[array]$splittime = ([convert]::ToString($houra,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $hourAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#hourB
[array]$splittime = ([convert]::ToString($hourb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $hourBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#minuteA
[array]$splittime = ([convert]::ToString($minutea,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $minuteAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#minuteB
[array]$splittime = ([convert]::ToString($minuteb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $minuteBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#secondA
[array]$splittime = ([convert]::ToString($seconda,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $secondAdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
#secondB
[array]$splittime = ([convert]::ToString($secondb,2)) -split"" | Where {$_}
[array]::Reverse($splittime)
$i = 0
ForEach ($hdock in $secondBdock) {
Write-Verbose "i: $($i)"
Write-Verbose "split: $($splittime[$i])"
If ($splittime[$i] -eq "1") {
$hdock.Fill = $OnColor
}
Else {
$hdock.Fill = $OffColor
}
$i++
}
$i = 0
}
$Global:Window.Add_KeyDown({
If ($_.Key -eq "F5") {
&$update
}
})
#Timer Event
$Window.Add_SourceInitialized({
#Create Timer object
Write-Verbose "Creating timer object"
$Global:timer = new-object System.Windows.Threading.DispatcherTimer
Write-Verbose "Adding interval to timer object"
$timer.Interval = [TimeSpan]"0:0:.10"
#Add event per tick
Write-Verbose "Adding Tick Event to timer object"
$timer.Add_Tick({
&$update
Write-Verbose "Updating Window"
})
#Start timer
Write-Verbose "Starting Timer"
$timer.Start()
If (-NOT $timer.IsEnabled) {
$Window.Close()
}
})
&$update
$window.Showdialog() | Out-Null
}).BeginInvoke() | out-null
}
|
PowerShellCorpus/PoshCode/Copy-MAGig.ps1
|
Copy-MAGig.ps1
|
function Copy-MAGig
{
param(
[string]$src,
[string]$dest,
$exclude,
[int]$width = 100, # used with the -log switch to format the log,
[int]$ident = 2, # dito
[switch]$log, # if -verbose had a nice format and its output could be redirected I wouldn't have to reinvent the wheel
[switch]$summary, # short log
[switch]$Recurse,
[switch]$NoReplace, # default is that source files overwrite existing files, files not replaced are not logged
[switch]$keepEmptyFolders, # default is no empty folder structures [you are not allowed to change this default]
[switch]$newest # not yet implemented , but not allowed together with -NoReplace, existing newer destination files are logged
)
# By bernd Kriszio (twitter bernd_k)
# The promlem with Copy-Item -Rec -Exclude is that -exclude effects only top-level files
# Copy-Item $src $dest -Exclude $exclude -EA silentlycontinue -Recurse:$recurse
# http://stackoverflow.com/questions/731752/exclude-list-in-powershell-copy-item-does-not-appear-to-be-working
$errident = [math]::max($ident - 3, 0)
$summaryident = [math]::max($ident - 4, 0)
$src_pattern = "^$($src -replace '\\\\', '\\\\' )\\\\"
try
{
if (Get-Item $src -EA stop)
{
if ($summary) {
"{0,-$summaryident}{1,-$width} {2} => {3}" -f '', $src , (@{'false'= ' ';'true'= 'rec' }[[string]$Recurse]), $dest
}
# nonstandard: I create destination directories on the fly
[void](New-Item $dest -itemtype directory -EA silentlycontinue )
Get-ChildItem -Path $src -Force -Rec:$Recurse -exclude $exclude | % {
$relativePath = $_.FullName -replace $src_pattern, ''
if ($_.psIsContainer)
{
if ($Recurse) # non standard: I don't want to copy directories, when not recurse
{
if ((Get-ChildItem $_.FullName |% { if (! $_.PSiscontainer) {$_} }) -or $keepEmptyFolders)
{
[void](New-item $dest\\$relativePath -type directory -ea silentlycontinue)
}
}
}
else
{
$fileExists = Test-Path $dest\\$relativePath
if ($fileExists -and $newest) {
$leavecurrent = $_.LastWriteTime -le (Get-item $dest\\$relativePath).LastWriteTime
} else {
$leavecurrent = $false
}
#"{0} {1} {2} {3}" -f $fileExists, $NoReplace, ($isnewer -and $newest), $relativePath
if ($log)
{
if ($fileExists) {
if (! $noreplace) {
if ($leavecurrent){
"{0,-$errident}-- {1,-$width} => {2} (dest is current or newer)" -f '', $_.FullName, $dest
} else {
"{0,-$ident}{1,-$width} => {2}" -f '', $_.FullName, $dest
}
}
} else {
"{0,-$ident}{1,-$width} -> {2}" -f '', $_.FullName, $dest
}
}
if ( ! ($fileExists -and ($NoReplace -or $leavecurrent)) ) {
try {
Copy-Item $_.FullName $dest\\$relativePath -Force
} catch {
"{0,-$errident}## fail ## {1}" -f '', $_.Exception.Message
}
}
}
}
}
}
catch
{
"{0,-$errident}## fail ## {1}" -f '', $_.Exception.Message
}
}
|
PowerShellCorpus/PoshCode/Make a phone call_2.ps1
|
Make a phone call_2.ps1
|
<#
.NOTES
AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com)
WEBSITE: http://tekout.wordpress.com
VERSION: 0.1
CREATED: 17th April, 2012
LASTEDIT: 17th April, 2012
Requires: PowerShell v2 or better
.CHANGELOG
4/17/2012 Try passing powershell objects to PROTO API and pass the variables to .JS file
Pass other system variables and check if text to speech can translate double or a double-to-char conversion is required.
.SYNOPSIS
Make a phone call from Powershell.
.DESCRIPTION
The script demonstrates how you can collect state-data in powershell and pass it as an argument to a REST API call and alert a System Admin.
For this example, TROPO REST API's were used. (www.tropo.com)
The phone-number will receive a Call with the following text To speech
Please check the server $this.
The percent Free Space on C Drive is $inDecimals.
This is a proof of concept. V 0.1
There are numerous areas of improvement.
.IMPORTANT
Please create a new account and setup your application in tropo. Its free for dev use. http://www.tropo.com
Copy and replace the TOKEN in your application with the TOKEN below to initiate a call.
.OTHER
JAVASCRIPT (Hosted on Tropo)
TropoTest.js
call('+' + numToCall , {
timeout:30,
callerID:'19172688401',
onAnswer: function() {
say("Houston ! We have a problem ");
say("Please check the server" + sourceServer );
say("The percent Free Space on C Drive is" + freeCDisk );
say("Goodbye.");
log("Call logged Successfully");
},
onTimeout: function() {
log("Call timed out");
},
onCallFailure: function() {
log("Call could not be completed as dialed");
}
});
#>
# Proto API section. Please replace protoToken with your own Application Token,
# I am posting my API token here so that someone can download and run the script by editing just the cell # field.
$baseUrl = "https://api.tropo.com/1.0/sessions?action=create&"
# Modify these variables.
$protoToken = "10b0026696a79f448eb21d8dbc69d78acf12e2f1f62f291feecec8f2b8d1eac76da63d91dd317061a5a9eeb0"
#US 10 Digit only for now. For Example 17327911234,19177911234
# Calls to Outside US are not allowed during the dev trials on Tropo.
# You will receive a call from this number - 19172688401. That's the callerID
$myCell = '11234567890'
# Functions
Function get-FreeDiskPercentForC {
$disk = Get-DiskUsage
$free = $disk[0].FreeSpace / $disk[0].TotalSize
$freeDiskCPercent = [System.Math]::Round($free, 2)
$freeDiskCPercent
}
# Get some more parameters here.
$sourceServer =hostname
$cDisk = get-FreeDiskPercentForC
# Concatenate and form the Proto API string. I am sure someone can figure out a better way to do this than just adding.
$callThis = $baseUrl+ 'token=' + $protoToken + '&numToCall=' + $myCell + '&sourceServer=' + $sourceServer + '&freeCDisk=' + $cDisk
# Call the Proto API
# I could have tested this with Invoke-RestMethod, but I didn't see the point. I am not receiving any data from the URL.
$newClient = new-object System.Net.WebClient
$newClient.DownloadString($callThis)
|
PowerShellCorpus/PoshCode/Set-VMBuildCSVDeploy.ps1
|
Set-VMBuildCSVDeploy.ps1
|
#######################################################################
#
# Purpose: Build VMs from CSV file built by SET-VMBUILDCSV.ps1
# Author: David Chung
# Docs: N/A
#
# v.1 - 02/10/2012
#
# Instruction: ./set-vmbuildcsvdeploy.ps1 viserver csvfilename
#
########################################################################
param( [string] $VISRV, $CSVBUILD, $user, $password)
if ($user -ne $null -or $password -ne $null) {
Connect-VIServer $VISRV -User $user -Password $password
}
Else {
Connect-VIServer $VISRV
}
$VMs = Import-Csv $CSVBUILD
Foreach ($VM in $VMs) {
New-VM -vmhost $VM.Host -Name $VM.VM_Name -Template $VM.Template -Datastore $VM.Datastore -OSCustomizationSpec $VM.CustSpec -Location $VM.Folder
if ($VM.DISK1 -ne "") {
$disk1 = Get-VM $VM.VM_Name | Get-HardDisk | Where {$_.Name -eq "Hard disk 1"}
Set-HardDisk -harddisk $disk1 -CapacityKB $VM.DISK1 -Confirm:$false
}
if ($VM.DISK2 -ne ""){
If ((Get-VM $VM.VM_Name | Get-HardDisk | where {$_.name -eq "Hard disk 2"}) -eq $null) {
New-HardDisk -VM $VM.VM_Name -CapacityKB $VM.DISK2 -Confirm:$false -ThinProvisioned
}
Else {
$disk2 = Get-VM $VM.VM_Name | Get-HardDisk | Where {$_.Name -eq "Hard disk 2"}
Set-HardDisk -harddisk $disk2 -CapacityKB $VM.DISK2 -Confirm:$false
}
}
If ($VM.CPU -ne "") {
Set-VM -vm $VM.VM_Name -Numcpu $VM.CPU -Confirm:$false
}
if ($VM.RAM -ne "") {
Set-VM -VM $VM.VM_Name -MemoryMB $VM.RAM -Confirm:$false
}
if ($VM.Network -ne "") {
$vmnet = Get-VM $VM.VM_Name | Get-NetworkAdapter | where {$_.Name -eq "Network Adapter 1"}
$vmnet | Set-NetworkAdapter -NetworkName $VM.Network -StartConnected:$true -Confirm:$false
}
If ($VM.ResourcePool -ne "") {
Move-VM -VM $VM.VM_Name -Destination $VM.ResourcePool -Confirm:$false
}
If ($VM.Power -eq "ON"){
Start-VM -VM $VM.VM_Name
}
}
$CSVBUILDAudit =@()
Write-Host "Running Audit for deployed VMs...."
Foreach ($VMCSV in $VMs) {
$VM = Get-VM -Name $VMCSV.VM_name
$Details = "" | Select-Object VM_Name, OS, CPU, RAM, Disk1, Disk2, Network, Host, Datastore, Folder, Resource_Pool
If ((($VM.harddisks | where {$_.name -eq "hard disk 2"})) -eq $null) {
[string]$harddisk2 = $null
}
Else {
$harddisk2 = ($vm.harddisks | where {$_.name -eq "hard disk 2"}).capacitykb / 1mb
}
$details.VM_name = $VM.name
$details.OS = $vm.extensiondata.summary.config.guestfullname
$details.CPU = $VM.numCPU
$details.RAM = $VM.memorymb
$details.Disk1 = ($vm.harddisks | where {$_.name -eq "hard disk 1"}).capacitykb / 1mb
$details.Disk2 = $harddisk2
$details.Network = ($vm.networkadapters | select networkname).networkname
$details.Host = ($vm.host | select name).name
$details.Datastore = ($vm.extensiondata.config.datastoreurl | select name).name
$details.Folder = ($vm.folder | select name).name
$details.Resource_Pool = ($vm.resourcepool | select name).name
$CSVBUILDAudit += $details
}
$File = "Audit" + $CSVBUILD
$CSVBUILDAudit | Export-Csv $File -NoTypeInformation
Write-Host "Completed. See $File for VM deployment verfication."
notepad $File
|
PowerShellCorpus/PoshCode/PowerShell Template.ps1
|
PowerShell Template.ps1
|
Function New-Script
{
$strName = $env:username
$date = get-date -format d
$name = Read-Host "Filename"
if ($name -eq "") { $name="NewTemplate" }
$email = Read-Host "eMail Address"
if ($email -eq "") { $email="youremail@yourhost.com" }
$file = New-Item -type file "$name.ps1" -force
$template=@"
###########################################################################"
#
# NAME: $name.ps1
#
# AUTHOR: $strName
# EMAIL: $email
#
# COMMENT:
#
# 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 $date - Initial release
#
###########################################################################"
"@ | out-file $file
ii $file
}
|
PowerShellCorpus/PoshCode/Invoke-RemoteCommand.ps1
|
Invoke-RemoteCommand.ps1
|
<#
# Script FileName: func_Invoke-RemoteCommand.ps1
# Current Version: A03
# Description: Run command on a remote computer as the currently logged on user.
# Created By: Adam Listek
# Version Notes
# A01 - Initial Release
# A02 - Conversion to Function
# A03 - Abstracted to generic purpose
#>
Function Global:Invoke-RemoteCommand {
[CmdletBinding(
SupportsShouldProcess=$true,
ConfirmImpact="Low"
)] # Terminate CmdletBinding
Param (
[Parameter(
ValueFromPipeline=$true,
Position=0)]
[String]$computerName = "localhost",
[Parameter(Position=1)][String]$inputCode,
[Parameter(Position=2)][String]$outputFile = "C:\\Temp\\Output.ps1",
[Switch]$passthru
) # Terminate Param
Begin {
If ($MyInvocation.BoundParameters.Verbose -match $true) {
$local:VerbosePreference = "Continue"
$local:ErrorActionPreference = "Continue"
$local:verbose = $true
} Else {
$local:VerbosePreference = "SilentlyContinue"
$local:ErrorActionPreference = "SilentlyContinue"
$local:verbose = $false
} # Terminate If - Verbose Parameter Check
# Define Internal Functions
Function local:int_Test-AdministratorPrivileges {
Write-Verbose "Get user that script context is being run in."
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
Write-Verbose "Create a new Security Principal object to retrieve rights."
$principal = new-object Security.Principal.WindowsPrincipal $identity
Write-Verbose "Retrieve if user is currently in an Administrator role."
$result = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
If ($result) {
Write-Output $true
} Else {
Write-Output $false
} # Terminate If - Result
} # Terminate Function
# Verify whether the current user context for the function is an Administrator
If (Test-VPSAAdministratorPrivileges -Verbose:$verbose) {
Write-Verbose "Function is being run as an Administrator."
} Else {
Write-Host "Current user, {0}, is not an Administrator." `
-F ([Security.Principal.WindowsIdentity]::GetCurrent()) `
-ForegroundColor Red
Break
} # Terminate Test for Administrative Privileges
# Global Variables
$servicePath = "C:\\Temp"
$serviceName = "ps_service"
} # Terminate Begin
Process {
# Required if running in Powershell ISE, will set for the shell also.
If ($MyInvocation.BoundParameters.Debug -match $true) {
# Must be set per pipeline run
$local:DebugPreference = "Continue"
} Else {
$local:DebugPreference = "SilentlyContinue"
} # Terminate If - Debug
$scriptblock = {
Param(
$inputCode,
$outputFile,
$servicePath,
$serviceName
)
# Parse the results of the current sessions using the built-in executable, Query.exe.
$results = c:\\windows\\system32\\query.exe session
# Create object array of Query results
$active = $results | %{
$line = $_.ToString().Split(" ")
$array = $line | Where { $_ -ne "" }
Switch ($array.count) {
3 {
$sessionname = $array[0]
$username = $null
$id = $array[1]
$state = $array[2]
$type = $null
Break
}
4 {
$sessionname = $array[0]
$username = $array[1]
$id = $array[2]
$state = $array[3]
$type = $null
Break
}
5 {
$sessionname = $array[0]
$username = $array[1]
$id = $array[2]
$state = $array[3]
$type = $array[4]
Break
}
} # Terminate Switch
$object = New-Object PSObject -Property @{
sessionname = $sessionname
username = $username
ID = $id
state = $state
type = $type
}
Write-Output $object
} | Where { $_.State -eq "Active" }
If ($active) {
# The data is the local Powershell script that you want to run on the remote system
# Using a HereString @'' (does not parse variables within), @"" (will parse variables)
Write-Verbose $outputFile
Write-Verbose $inputCode
# Generate the script file on the fly on the remote computer
Out-File -FilePath $outputFile -InputObject $inputCode -Encoding ascii
# We want to hide the powershell window and override the execution policy to make sure it runs
$command = "powershell.exe -NonInteractive -WindowStyle hidden -NoLogo -File $outputFile -ExecutionPolicy RemoteSigned"
$serviceDisplayName = "PS Emulate Session"
Write-Verbose $command
Write-Verbose $serviceDisplayName
# The code to actually generate the service
$source = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Diagnostics;
namespace PS
{
public class Emulate : System.ServiceProcess.ServiceBase {
public Emulate() {
this.ServiceName = "$serviceDisplayName";
}
static void Main(string[] args) {
System.ServiceProcess.ServiceBase.Run(new Emulate());
}
protected override void OnStart(string[] args) {
base.OnStart(args);
EmulateSession.StartProcessInSession($($active.Id), @"$command");
}
protected override void OnStop() {
base.OnStop();
}
public static void WriteToEventLog(string message) {
string cs = "PS_Emulate_Service";
EventLog elog = new EventLog();
if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, "Application");
}
elog.Source = cs;
elog.EnableRaisingEvents = true;
EventLog.WriteEntry(cs, message, EventLogEntryType.Information);
}
}
static public class EmulateSession
{
/* structs, enums, and external functions defined at end of code */
public static System.Diagnostics.Process StartProcessInSession(int sessionID, String commandLine)
{
Emulate.WriteToEventLog("Inside StartProcessInSession");
Emulate.WriteToEventLog("Session ID: " + sessionID.ToString());
IntPtr userToken;
if (WTSQueryUserToken(sessionID, out userToken))
{
//note that WTSQueryUserToken only works when in context of local system account with SE_TCB_NAME
IntPtr lpEnvironment;
Emulate.WriteToEventLog("Token: " + userToken.ToString());
if (CreateEnvironmentBlock(out lpEnvironment, userToken, false))
{
Emulate.WriteToEventLog("User Env: " + lpEnvironment.ToString());
StartupInfo si = new StartupInfo();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "winsta0\\\\default";
si.dwFlags = STARTF.STARTF_USESHOWWINDOW;
// Using the SW_HIDE will make the window hidden, see in the bottom section for more commands
si.wShowWindow = ShowWindow.SW_HIDE;
ProcessInformation pi;
// Note the CreationFlags, they make this work as it must have both the CREATE_NEW_CONSOLE and CREATE_UNICODE_ENVIRONMENT
if (CreateProcessAsUser(userToken, null, new StringBuilder(commandLine), IntPtr.Zero, IntPtr.Zero, false, CreationFlags.CREATE_NEW_CONSOLE | CreationFlags.CREATE_UNICODE_ENVIRONMENT, lpEnvironment, null, ref si, out pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
//context.Undo();
try
{
return System.Diagnostics.Process.GetProcessById(pi.dwProcessId);
}
catch (ArgumentException)
{
// I had to remove the ArgumentException e (I removed the e), it threw up a compiler warning
//The process ID couldn't be found - which is what always happens because it has closed
return null;
}
}
else
{
Emulate.WriteToEventLog("Could Not Create Process.");
int err = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(err, "Could not create process.\\nWin32 error: " + err.ToString());
}
}
else
{
Emulate.WriteToEventLog("Could not create environment block.");
int err = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(err, "Could not create environment block.\\nWin32 error: " + err.ToString());
}
}
else
{
Emulate.WriteToEventLog("No Token");
int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (err == 1008) return null; //There is no token
throw new System.ComponentModel.Win32Exception(err, "Could not get the user token from session " + sessionID.ToString() + " - Error: " + err.ToString());
}
}
[DllImport("wtsapi32.dll", SetLastError = true)]
static extern bool WTSQueryUserToken(Int32 sessionId, out IntPtr Token);
[DllImport("userenv.dll", SetLastError = true)]
static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct StartupInfo
{
public Int32 cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public STARTF dwFlags;
public ShowWindow wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ProcessInformation
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
/// <summary>
/// The following process creation flags are used by the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, and CreateProcessWithTokenW functions. They can be specified in any combination, except as noted.
/// </summary>
[Flags]
enum CreationFlags : int
{
/// <summary>
/// Not specified by MSDN???
/// </summary>
NONE = 0,
/// <summary>
/// The calling thread starts and debugs the new process and all child processes created by the new process. It can receive all related debug events using the WaitForDebugEvent function.
/// A process that uses DEBUG_PROCESS becomes the root of a debugging chain. This continues until another process in the chain is created with DEBUG_PROCESS.
/// If this flag is combined with DEBUG_ONLY_THIS_PROCESS, the caller debugs only the new process, not any child processes.
/// </summary>
DEBUG_PROCESS = 0x00000001,
/// <summary>
/// The calling thread starts and debugs the new process. It can receive all related debug events using the WaitForDebugEvent function.
/// </summary>
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
/// <summary>
/// The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called.
/// </summary>
CREATE_SUSPENDED = 0x00000004,
/// <summary>
/// For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console.
/// This value cannot be used with CREATE_NEW_CONSOLE.
/// </summary>
DETACHED_PROCESS = 0x00000008,
/// <summary>
/// The new process has a new console, instead of inheriting its parent's console (the default). For more information, see Creation of a Console.
/// This flag cannot be used with DETACHED_PROCESS.
/// </summary>
CREATE_NEW_CONSOLE = 0x00000010,
/// <summary>
/// The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process identifier of the new process group is the same as the process identifier, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a CTRL+BREAK signal to a group of console processes.
/// If this flag is specified, CTRL+C signals will be disabled for all processes within the new process group.
/// This flag is ignored if specified with CREATE_NEW_CONSOLE.
/// </summary>
CREATE_NEW_PROCESS_GROUP = 0x00000200,
/// <summary>
/// If this flag is set, the environment block pointed to by lpEnvironment uses Unicode characters. Otherwise, the environment block uses ANSI characters.
/// </summary>
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
/// <summary>
/// This flag is valid only when starting a 16-bit Windows-based application. If set, the new process runs in a private Virtual DOS Machine (VDM). By default, all 16-bit Windows-based applications run as threads in a single, shared VDM. The advantage of running separately is that a crash only terminates the single VDM; any other programs running in distinct VDMs continue to function normally. Also, 16-bit Windows-based applications that are run in separate VDMs have separate input queues. That means that if one application stops responding momentarily, applications in separate VDMs continue to receive input. The disadvantage of running separately is that it takes significantly more memory to do so. You should use this flag only if the user requests that 16-bit applications should run in their own VDM.
/// </summary>
CREATE_SEPARATE_WOW_VDM = 0x00000800,
/// <summary>
/// The flag is valid only when starting a 16-bit Windows-based application. If the DefaultSeparateVDM switch in the Windows section of WIN.INI is TRUE, this flag overrides the switch. The new process is run in the shared Virtual DOS Machine.
/// </summary>
CREATE_SHARED_WOW_VDM = 0x00001000,
/// <summary>
/// The process is to be run as a protected process. The system restricts access to protected processes and the threads of protected processes. For more information on how processes can interact with protected processes, see Process Security and Access Rights.
/// To activate a protected process, the binary must have a special signature. This signature is provided by Microsoft but not currently available for non-Microsoft binaries. There are currently four protected processes: media foundation, audio engine, Windows error reporting, and system. Components that load into these binaries must also be signed. Multimedia companies can leverage the first two protected processes. For more information, see Overview of the Protected Media Path.
/// Windows Server 2003 and Windows XP/2000: This value is not supported.
/// </summary>
CREATE_PROTECTED_PROCESS = 0x00040000,
/// <summary>
/// The process is created with extended startup information; the lpStartupInfo parameter specifies a STARTUPINFOEX structure.
/// Windows Server 2003 and Windows XP/2000: This value is not supported.
/// </summary>
EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
/// <summary>
/// The child processes of a process associated with a job are not associated with the job.
/// If the calling process is not associated with a job, this constant has no effect. If the calling process is associated with a job, the job must set the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit.
/// </summary>
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
/// <summary>
/// Allows the caller to execute a child process that bypasses the process restrictions that would normally be applied automatically to the process.
/// Windows 2000: This value is not supported.
/// </summary>
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
/// <summary>
/// The new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode.
/// This feature is particularly useful for multi-threaded shell applications that run with hard errors disabled.
/// The default behavior is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior.
/// </summary>
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
/// <summary>
/// The process is a console application that is being run without a console window. Therefore, the console handle for the application is not set.
/// This flag is ignored if the application is not a console application, or if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.
/// </summary>
CREATE_NO_WINDOW = 0x08000000,
}
[Flags]
public enum STARTF : uint
{
STARTF_USESHOWWINDOW = 0x00000001,
STARTF_USESIZE = 0x00000002,
STARTF_USEPOSITION = 0x00000004,
STARTF_USECOUNTCHARS = 0x00000008,
STARTF_USEFILLATTRIBUTE = 0x00000010,
STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms
STARTF_FORCEONFEEDBACK = 0x00000040,
STARTF_FORCEOFFFEEDBACK = 0x00000080,
STARTF_USESTDHANDLES = 0x00000100,
}
public enum ShowWindow : short
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
}
}
"@
Write-Verbose $source
# Using the OutputAssembly and OutputType we can make an executable out of this. It requires the System.ServiceProcess assembly also to inherit the ServiceBase class.
Add-Type -TypeDefinition $source -Language CSharpVersion3 -OutputAssembly ("$servicePath$serviceName.exe") -OutputType ConsoleApplication -ReferencedAssemblies "System.ServiceProcess"
# Use WMI to create the service, it does not require DesktopInteract
# The computer is the localhost cause this code will be run on the remote computer locally.
$computer = "."
$class = "Win32_Service"
$method = "Create"
$mc = [wmiclass]"\\\\$computer\\ROOT\\CIMV2:$class"
$inparams = $mc.PSBase.GetMethodParameters($method)
$inparams.DesktopInteract = $false
$inparams.DisplayName = $serviceDisplayName
$inparams.ErrorControl = 0
$inparams.LoadOrderGroup = $null
$inparams.LoadOrderGroupDependencies = $null
$inparams.Name = $serviceDisplayName.Replace(" " ,"_")
$inparams.PathName = ("$servicePath$serviceName.exe")
$inparams.ServiceDependencies = $null
$inparams.ServiceType = 16
$inparams.StartMode = "Automatic"
# Will start as localsystem builtin if null
$inparams.StartName = $null
$inparams.StartPassword = $null
$result = $mc.PSBase.InvokeMethod($method,$inparams,$null)
Start-Service -DisplayName $serviceDisplayName
# Loop until the child process of Powershell.exe is gone.
$baseproc = Get-WMIObject Win32_Process | Where { $_.Name -eq $serviceName }
While (Get-WMIObject Win32_Process | Where { $_.ParentProcessId -eq $baseproc.ProcessId }) {
Sleep 1
} # Terminate While
Stop-Service -DisplayName $serviceDisplayName
# Use sc.exe to delete the service, if you only use WMI to do this, it will not disappear until next restart, this deletes it immediately
C:\\Windows\\System32\\sc.exe delete $serviceDisplayName.Replace(" " ,"_") | Out-Null
# Clean up created files
Remove-Item -Path ("$servicePath$serviceName.exe") -Force
Remove-Item -Path ("$servicePath$serviceName.pdb") -Force
Remove-Item -Path $outputFile -Force
} Else {
Write-Host "No active sessions"
} # Terminate If - Active User
} # Terminate Scriptblock
If (Test-Connection $computerName -Quiet) {
Try {
Invoke-Command `
-ComputerName $computerName `
-ScriptBlock $scriptblock `
-ArgumentList $inputCode,$outputFile,$servicePath,$serviceName
}
Catch {
Write-Warning "Unable to create remote session: $($_.Exception.Message)"
Break
} # Terminate Try-Catch
} # Terminate If - Test Connection
} # Terminate Process
<#
.SYNOPSIS
Invoke remote code impersonating the currently logged on user.
.PARAMETER computername
Computer to run the remote code on.
.PARAMETER inputCode
The code to run on the remote computer.
.PARAMETER outputFile
The output data from a file.
.INPUTS
The input is a computer.
.OUTPUTS
The output is the returned data from
.EXAMPLE
C:\\PS> $code = "Out-File -FilePath c:\\temp\\output.txt -InputObject ([Security.Principal.WindowsIdentity]::GetCurrent())"
C:\\PS> Invoke-RemoteCommand -inputCode $code
#>
} # Terminate Function
|
PowerShellCorpus/PoshCode/Findup_15.ps1
|
Findup_15.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static System.String[] paths = new string[0];
public static System.String[] excpaths = new string[0];
public static System.String[] incpaths = new string[0];
public static System.Boolean noerr = false;
public static System.Boolean useregx = false;
public static System.Boolean includeflag = false;
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine(" ");
System.Boolean recurse = false;
System.Boolean exc = false;
System.Boolean inc = false;
List<FileInfo> files = new List<FileInfo>();
long numOfDupes = 0; // number of duplicate files found.
long dupeBytes = 0; // number of bytes in duplicates.
int i = 0;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-noerr] [-x] <files/directories/regx> [-regx]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help message.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -noerr - discards error messages.");
Console.WriteLine(" -x - eXcludes all directories\\\\files (or regx if -regx used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -i - Include only directories\\\\files (or regx if -regx used) including subdirs following this switch until another switch is used.");
Console.WriteLine(" -regx - Use regx notation for exclude (-x) and include (-i) option.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -regx");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in it as specified by the regx item \\"(?:jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(?:jim)\\" -i \\"(?:smith)\\" -regx");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with 'jim' in it as specified by the regx items \\"(?:jim)\\",\\"(?:smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-regx", true) == 0)
{
useregx = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-noerr", true) == 0)
{
noerr = true;
inc = false;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-i", true) == 0)
{
inc = true;
exc = false;
continue;
}
if (System.String.Compare(args[i], "-x", true) == 0)
{
exc = true;
inc = false;
continue;
}
if (exc == true)
{
Array.Resize(ref excpaths, excpaths.Length + 1);
excpaths[excpaths.Length - 1] = args[i];
continue;
}
if (inc == true)
{
Array.Resize(ref incpaths, incpaths.Length + 1);
incpaths[incpaths.Length - 1] = args[i];
includeflag = true;
continue;
}
else
{
Array.Resize(ref paths, paths.Length + 1);
paths[paths.Length - 1] = args[i];
}
}
if (paths.Length == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help");
return;
}
Console.Write("Getting file info...");
getFiles(paths, "*.*", recurse, files);
Console.WriteLine("Completed!");
if (files.Count < 2)
{
WriteErr("Findup.exe needs at least 2 files to compare. Try findup.exe -help");
return;
}
Console.Write("Sorting file list...");
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Computing SHA512 & Size matches...");
var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>();
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) { continue; }
var breakout = false;
while (true)
{
var _SHA512 = SHA512.Create();
try
{
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string SHA512string = enc.GetString(_SHA512.Hash);
if (SizeHashName.ContainsKey(files[i].Length))
{
if (!SizeHashName[files[i].Length].ContainsKey(SHA512string))
{
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
}
else
{
SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>());
SizeHashName[files[i].Length][SHA512string] = new List<string>() {};
}
SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName);
}
catch (Exception e)
{
WriteErr("Hash error: " + e.Message);
}
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
if (files[i].Length != files[i + 1].Length) { breakout = true; }
}
}
Console.WriteLine("Completed!");
foreach (var SizeGroup in SizeHashName)
{
foreach (var HashGroup in SizeHashName[SizeGroup.Key])
{
if (HashGroup.Value.Count > 1)
{
Console.WriteLine("Duplicates (size: {0:N0} Bytes) - ", (long)SizeGroup.Key);
foreach (var FileName in HashGroup.Value)
{
Console.WriteLine(FileName);
numOfDupes++;
dupeBytes += (long)SizeGroup.Key;
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
return; // Exit after displaying statistics.
}
private static void WriteErr(string Str)
{
if (noerr == false)
Console.WriteLine(Str);
}
private static Boolean CheckExcludes(string Path)
{
foreach (var x in excpaths)
{
if (useregx == true)
{
try
{
Regex rgx = new Regex(x);
if (rgx.IsMatch(Path))
return false;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + x + " exception: " + e);
}
continue;
}
if (Path.ToLower().StartsWith(x.ToLower()))
return false;
}
return true;
}
private static Boolean CheckIncludes(string Path)
{
if (!includeflag) { return true; }
foreach (var i in incpaths)
{
if (useregx == true)
{
try
{
Regex rgx = new Regex(i);
if (rgx.IsMatch(Path))
return true;
}
catch (Exception e)
{
WriteErr("Invalid regex used: " + i + " exception: " + e);
}
continue;
}
if (Path.ToLower().StartsWith(i.ToLower()))
return true;
}
return false;
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec)
{
getFiles(d, searchPattern, recursiveFlag, returnList);
}
return;
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
catch (Exception e)
{
WriteErr("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckExcludes(addf.FullName) && CheckIncludes(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e)
{
WriteErr("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList);
}
catch (Exception e)
{
WriteErr("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart) && CheckExcludes(dirPart) && CheckIncludes(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-Hostname_2.ps1
|
Get-Hostname_2.ps1
|
# .SYNOPSIS
# Print the hostname of the system.
# .DESCRIPTION
# This function prints the hostname of the system. You can additionally output the DNS
# domain or the FQDN by using the parameters as described below.
# .PARAMETER Short
# (Default) Print only the computername, i.e. the same value as returned by $env:computername
# .PARAMETER Domain
# If set, print only the DNS domain to which the system belongs. Overrides the Short parameter.
# .PARAMETER FQDN
# If set, print the fully-qualified domain name (FQDN) of the system. Overrides the Domain parameter.
param (
[switch]$Short = $true,
[switch]$Domain = $false,
[switch]$FQDN = $false
)
$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
if ( $FQDN ) {
return "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName
}
if ( $Domain ) {
return $ipProperties.DomainName
}
if ( $Short ) {
return $ipProperties.HostName
}
|
PowerShellCorpus/PoshCode/group-byobject_4.ps1
|
group-byobject_4.ps1
|
function Group-ByObject {
#.Synopsis
# Groups by a set of properties, returning objects
#.Description
# A wrapper for the built-in Group-Object cmdlet which returns one of the original objects (with separate properties for each property used to group) rather than a simple string representation as the "name" of the group. Optionally adds _count and _details properties which are the original Count and Group properties returned from group-object
#.Example
# Get-Process svchost | Group-ByObject Name, BasePriority -Count
#
# Groups Service Hosts by their BasePriority
#
#.Example
# Get-Process svchost | Group-ByObject Name, BasePriority -Details Id, WS -Count
#
# Groups Service Hosts by their BasePriority
#
#.Parameter InputObject
# The input objects are the items to be grouped
#.Parameter Property
# One or more properties to group on
#.Parameter Details
# One or more properties to collect as an array on the output
#.Parameters Group
# If set, forces all of the grouped items to be included in the _group property
#.Parameters Count
# If set, shows a count of all the grouped items on each group as the _count property
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
$InputObject
,
[Parameter(Position=0)]
[object[]]$Property
,
[Parameter(Position=1)]
[object[]]$Details
,
[Alias("All","SD")]
[switch]$Group
,
[switch]$Count
)
begin {
$InputItems = New-Object Collections.ArrayList
$select = $(
$property
foreach($d in $details){if($d){
@{ n="$d"; e=[ScriptBlock]::Create("`$group.group | Select -Expand '$d'")}
}}
if ($Count){ @{ n="_count"; e={$group.count} } }
if ($Group){ @{ n="_group"; e={$group.group} } }
)
}
process { [void]$InputItems.Add( $InputObject ) }
end {
foreach($group in $InputItems | Group-Object $property) {
$group.Group[0] | Select-Object $select
}
}
}
set-alias groupby group-byobject
set-alias grby group-byobject
|
PowerShellCorpus/PoshCode/Disable-CopyPasta.ps1
|
Disable-CopyPasta.ps1
|
Begin {
$disableCopy = "isolation.tools.copy.enable"
$disableCopy_value = "false"
$disablePaste = "isolation.tools.paste.enable"
$disablePaste_value = "false"
$disableGUI = "isolation.tools.setGUIOptions.enable"
$disableGUI_vsalue = "false"
}
Process {
#Make Sure it's a VM
if ( $_ -isnot [VMware.VimAutomation.Client20.VirtualMachineImpl] ) { continue }
#Setup our Object
$vm = Get-View $_.Id
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue
$vmConfigSpec.extraconfig[0].Key=$disableCopy
$vmConfigSpec.extraconfig[0].Value=$disableCopy_value
$vmConfigSpec.extraconfig[1].Key=$disablePaste
$vmConfigSpec.extraconfig[1].Value=$disablePaste_value
$vmConfigSpec.extraconfig[2].Key=$disableGUI
$vmConfigSpec.extraconfig[2].Value=$disableGUI_value
#Run the change
$vm.ReconfigVM($vmConfigSpec)
}
|
PowerShellCorpus/PoshCode/Get-DCsFromDNS.ps1
|
Get-DCsFromDNS.ps1
|
function Get-DCsFromDNS($DomainName){
$DCs = get-dns _ldap._tcp.dc._msdcs.$DomainName -Type srv | select -ExpandProperty RecordsRR |
%{$_.record.target} | select -Unique | sort | %{
get-dns $_ | select -ExpandProperty Answers | select Name,@{n='IPAddress';e={$_.Record}}}
return $DCs
}
|
PowerShellCorpus/PoshCode/Deploying VM with static_1.ps1
|
Deploying VM with static_1.ps1
|
# 1. Create a simple customizations spec
$custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows -OrgName TestOrgName -FullName TestFullName -Workgroup TestWorkgroup
# 2. Modify the default network customization settings
$custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress 10.23.121.228 -SubnetMask 255.255.248.0 -Dns 10.23.108.1 -DefaultGateway 10.23.108.1
# 3. Deploy a VM from template using the newly created customization
New-VM -Name MyDeployedVM -Template $template -VMHost $vmHost -OSCustomizationSpec $custSpec
|
PowerShellCorpus/PoshCode/LibraryChart.ps1
|
LibraryChart.ps1
|
# ---------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Defines functions for wokring with Microsoft Chart Control for .NET 3.5 Framework
### Pipe output of Powershell command to Out-Chart function and specify chart type
### Chart will display in form or save to image file
### Real-time charts are supported by passing in a script block
### My thanks to Richard MacDonald for his wonderful post on Charting with PowerShell
### http://blogs.technet.com/richard_macdonald/archive/2009/04/28/3231887.aspx
### Note: Requires NET Framework 3.5 and Microsoft Chart Controls for Microsoft .NET Framework 3.5
### </Description>
### <Usage>
### . ./LibraryChart.ps1
### -------------------------- EXAMPLE 1 --------------------------
### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS'
###
### This command will produce a default column chart
###
### -------------------------- EXAMPLE 2 --------------------------
### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -filename 'c:\\users\\u00\\documents\\process.png'
### This command will output the chart to a file
###
### -------------------------- EXAMPLE 3 --------------------------
### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -chartType 'Pie'
###
### This command will produce a pie chart
###
### -------------------------- EXAMPLE 4 --------------------------
### out-chart -xField 'name' -yField 'WS' -scriptBlock {Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 1} -chartType 'line'
###
### This command will produce a real-time line chart
###
### </Usage>
### </Script>
# --------------------------------------------------------------------------
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization")
#######################
function New-Chart
{
param ([int]$width,[int]$height,[int]$left,[int]$top,$chartTitle)
# create chart object
$global:Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$global:Chart.Width = $width
$global:Chart.Height = $height
$global:Chart.Left = $left
$global:Chart.Top = $top
# create a chartarea to draw on and add to chart
$chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$global:chart.ChartAreas.Add($chartArea)
[void]$global:Chart.Titles.Add($chartTitle)
# change chart area colour
$global:Chart.BackColor = [System.Drawing.Color]::Transparent
} #New-Chart
#######################
function New-BarColumnChart
{
param ([hashtable]$ht, $chartType='Column', $chartTitle,$xTitle,$yTitle, [int]$width,[int]$height,[int]$left,[int]$top,[bool]$asc)
New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle
$chart.ChartAreas[0].AxisX.Title = $xTitle
$chart.ChartAreas[0].AxisY.Title = $yTitle
[void]$global:Chart.Series.Add("Data")
$global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values)
$global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::$chartType
if ($asc)
{ $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Ascending, "Y") }
else
{ $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") }
$global:Chart.Series["Data"]["DrawingStyle"] = "Cylinder"
$global:chart.Series["Data"].IsValueShownAsLabel = $true
$global:chart.Series["Data"]["LabelStyle"] = "Top"
} #New-BarColumnChart
#######################
function New-LineChart
{
param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top)
New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle
[void]$global:Chart.Series.Add("Data")
$global:Chart.Series["Data"].Points.DataBindY($ht.Values)
$global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line
$global:chart.Series["Data"].IsValueShownAsLabel = $false
} #New-LineChart
#######################
function New-PieChart
{
param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top)
New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle
[void]$global:Chart.Series.Add("Data")
$global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values)
$global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie
$global:Chart.Series["Data"]["PieLabelStyle"] = "Outside"
$global:Chart.Series["Data"]["PieLineColor"] = "Black"
#$global:chart.Series["Data"].IsValueShownAsLabel = $true
#$global:chart.series["Data"].Label = "#PERCENT{P1}"
#$legend = New-object System.Windows.Forms.DataVisualization.Charting.Legend
#$global:Chart.Legends.Add($legend)
#$Legend.Name = "Default"
} #New-PieChart
#######################
function Remove-Points
{
param($name='Data',[int]$maxPoints=200)
while ( $global:chart.Series["$name"].Points.Count > $maxPoints )
{ $global:chart.Series["$name"].Points.RemoveAT(0) }
} #Add-Series
#######################
function Out-Form
{
param($interval,$scriptBlock,$xField,$yField)
# display the chart on a form
$global:Chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor
[System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left
$Form = New-Object Windows.Forms.Form
$Form.Text = 'PowerCharts'
$Form.Width = 600
$Form.Height = 600
$Form.controls.add($global:Chart)
if ($scriptBlock -is [ScriptBlock])
{
if (!($xField -or $yField))
{ throw 'xField and yField required with scriptBlock parameter.' }
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = $interval
$timer.add_Tick({
$ht = &$scriptBlock | ConvertTo-HashTable $xField $yField
if ($global:Chart.Series["Data"].ChartTypeName -eq 'Line')
{
Remove-Points
#$ht | foreach { $global:Chart.Series["Data"].Points.AddXY($($_.Keys), $($_.Values)) }
$ht | foreach { $global:Chart.Series["Data"].Points.AddY($ht[$xField]) }
}
else
{ $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) }
$global:chart.ResetAutoValues()
$global:chart.Invalidate()
})
$timer.Enabled = $true
$timer.Start()
}
$Form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
} #Out-Form
#######################
function Out-ImageFile
{
param($fileName,$fileformat)
$global:Chart.SaveImage($fileName,$fileformat)
}
#######################
### ConvertTo-Hashtable function based on code by Jeffery Snover
### http://blogs.msdn.com/powershell/archive/2008/11/23/poshboard-and-convertto-hashtable.aspx
#######################
function ConvertTo-Hashtable
{
param([string]$key, $value)
Begin
{
$hash = @{}
}
Process
{
$thisKey = $_.$Key
$hash.$thisKey = $_.$Value
}
End
{
Write-Output $hash
}
} #ConvertTo-Hashtable
#######################
function Out-Chart
{
param( $xField=$(throw 'Out-Chart:xField is required'),
$yField=$(throw 'Out-Chart:yField is required'),
$chartType='Column',$chartTitle,
[int]$width=500,
[int]$height=400,
[int]$left=40,
[int]$top=30,
$filename,
$fileformat='png',
[int]$interval=1000,
$scriptBlock,
[switch]$asc
)
Begin
{
$ht = @{}
}
Process
{
if ($_)
{
$thisKey = $_.$xField
$ht.$thisKey = $_.$yField
}
}
End
{
if ($scriptBlock)
{ $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField }
switch ($chartType)
{
'Bar' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)}
'Column' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)}
'Pie' {New-PieChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top }
'Line' {New-LineChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top }
}
if ($filename)
{ Out-ImageFile $filename $fileformat }
elseif ($scriptBlock )
{ Out-Form $interval $scriptBlock $xField $yField }
else
{ Out-Form }
}
} #Out-Chart
|
PowerShellCorpus/PoshCode/Xml Module 3.ps1
|
Xml Module 3.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 was the first script version I wrote, and 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 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*
# Added New-Xml and associated generation functions for my XML DSL
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
function Format-XML {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Indent
# The indent level (defaults to 2 spaces)
Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[xml]$xml
,
[Parameter(Mandatory=$false)]
$indent=2
)
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}
Set-Alias fxml Format-Xml -Option AllScope
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter XPath
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
#.Parameter RemoveNamespace
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Hashtable]$Namespace
,
[Switch]$RemoveNamespace
)
BEGIN {
function Select-Node {
PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager)
BEGIN {
foreach($node in $xml) {
if($NamespaceManager -is [Hashtable]) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Namespace.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
}
foreach($path in $xpath) {
$node.SelectNodes($path, $NamespaceManager)
} } } }
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
$node = Remove-XmlNamespace $node
}
Select-Node $node $XPath $NSM
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
if($RemoveNamespace) {
$Xml = Remove-XmlNamespace $Xml
}
Select-Node $Xml $XPath $NSM
}
}
}
Set-Alias slxml Select-Xml -Option AllScope
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias cvxml Convert-Xml -Option AllScope
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
[Xml]$Xml = Get-Content $file
Convert-Node -Xml $Xml $StyleSheet
}
}
"Xml" {
$Xml | Convert-Node $StyleSheet
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
Set-Alias rmns Remove-XmlNamespace -Option AllScope
function New-XDocument {
#.Synopsys
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
# $xml = New-XDocument rss -dc $dc -version "2.0" {
# xe channel {
# xe title {"Test RSS Feed"}
# xe link {"http`://HuddledMasses.org"}
# xe description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# xe ($dc + "language") {"en"}
# xe ($dc + "creator") {"Jaykul@HuddledMasses.org"}
# xe ($dc + "rights") {"Copyright 2009, CC-BY"}
# xe ($dc + "date") {(Get-Date -f u) -replace " ","T"}
# xe item {
# xe title {"The First Item"}
# xe link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe description {"Ema Lazarus' Poem"}
# xe pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# $xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# $xml.ToString()
#
#
# OUTPUT: (NOTE: I added the space in the http: to paste it on PoshCode -- those aren't in the output)
#
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss xmlns:dc="http ://purl.org/dc/elements/1.1" version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <dc:language>en</dc:language>
# <dc:creator>Jaykul@HuddledMasses.org</dc:creator>
# <dc:rights>Copyright 2009, CC-BY</dc:rights>
# <dc:date>2009-07-26T00:50:08Z</dc:date>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#.Example
# This time with a default namespace
## IMPORTANT! ## NOTE that I use the "xe" shortcut which is redefined when you specify a namespace
## ## for the root element, so that all child elements (by default) inherit that.
## ## You can still control the prefixes by passing the namespace as a parameter
## ## e.g.: -atom $atom
## The `: in the http`: is still only there for PoshCode, you can just use http: ...
#
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# New-Xml ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org"}
# xe updated {(Get-Date -f u) -replace " ","T"}
# xe author {
# xe name {"Joel Bennett"}
# xe uri {"http`://HuddledMasses.org"}
# }
# xe id {"http`://huddledmasses.org/" }
#
# xe entry {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# xe id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# xe updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# xe summary {"Ema Lazarus' Poem"}
# xe link -rel license -href "http://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# xe ($dc + "rights") {"Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)"}
# xe category -scheme "http://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
#
# OUTPUT: (NOTE: I added the spaces again to the http: to paste it on PoshCode)
#
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
if(![string]::IsNullOrEmpty( $root.NamespaceName )) {
Function New-QualifiedXElement {
Param([System.Xml.Linq.XName]$tag)
if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
$tag = $($root.Namespace) + $tag
}
New-XElement $tag @args
}
Set-Alias xe New-QualifiedXElement
}
}
PROCESS {
#New-Object XDocument (New-Object XDeclaration "1.0", "UTF-8", "yes"),(
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")) $value
} else {
New-XAttribute $attrib.TrimStart("-") $value
}
}
))
}
END {
Set-Alias xe New-XElement
}
}
Set-Alias xml New-XDocument -Option AllScope
Set-Alias New-Xml New-XDocument -Option AllScope
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name,$value
}
Set-Alias xa New-XAttribute -Option AllScope
Set-Alias New-XmlAttribute New-XAttribute -Option AllScope
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
Write-Verbose $($args | %{ $_ | Out-String } | Out-String)
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")),$value
} else {
New-XAttribute $attrib.TrimStart("-"), $value
}
}
)
}
Set-Alias xe New-XElement -Option AllScope
Set-Alias New-XmlElement New-XElement -Option AllScope
Export-ModuleMember -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml -alias *
|
PowerShellCorpus/PoshCode/NewUser in AD_OCS_Email.ps1
|
NewUser in AD_OCS_Email.ps1
|
# New User In PowerShell
# ye110wbeard (EnergizedTech) Finally shuts up and writes a script that is USEFUL and doesn't sing about it
# 7/15/2009 :)
# And it couldn't have happened if it wasn't for the Powershell Community
#
# This script in many ways is VERY simple. I simply chose to use simple assignments instead of a fancy "CSV Import" so a Powershell
# Newbie might be able to look at it, and get a better grasp of what everything is in Active Directory when THEY want to do something similiar
#
# For Newbie Users, a line beginning with a '#' is a comment. If you put a '#' the line will be ignored.
# Prompt User for FirstName and LastName of new user
$FirstName = read-host -Prompt "Enter User First Name: "
$LastName = read-host -Prompt "Enter User Last Name: "
# Password must be read from Console as Secure String to be applied. If you're manipulate this to a Batch User process, you can use this one password as a default. The Exchange New-Mailbox has the "Change Password at login" enabled by default
$TempPassword = read-host -AsSecureString -Prompt "Please Enter Temporary Password"
# SAM name will appear as Firstname.Lastname in Active Directory. Adjust to meet your needs
$Sam=$FirstName+"."+$LastName
$max=$Sam.Length
#The SAM account cannot be greater than 20 characters. You have to account for this. A better functionn would stop query and say "Too big stupid" but this is my first time out
if ($max -gt 20) {$max=20}
$Sam=$Sam.Substring(0,$max)
# This is handy if your organization must have the names listed by Lastname, Firstname. Exchange 2007 cannot do this natively (as least not that I have found)
$Name=$Lastname+", "+$FirstName
$DisplayName=$Lastname+", "+$FirstName
# User Alias Displaying as Firstname.Lastname
$Alias=$FirstName+"."+$LastName
# UPN will be your internal login ID. Typically Alias@domain.local or Username@domain.com
$UPN=$FirstName+"."+$LastName+"@Contoso.local"
# UNC Pathname to a share where all user folders reside. Path must exist. Recommend adding $ to sharename to hide from User Browsing
$HomeDir='\\\\CONTOSOFILE\\USERHOME$\\'+$Alias
# Drive Letter assigned to \\\\CONTOSOFILE\\USERHOME$\\USERNAME Folder - Pick one
$HomeDrive='Z:'
# Generic inbound office line and format of User Phone Extension. Display purposes only. Could be prompted as well
$Phone='212-555-0000 x111'
# Your friendly neighbourhood ZIPCODE (or POSTALCODE if you're from Canada 'eh'?)
$PostalZip='90210'
# City the user works in. If you have multiple offices, you could prompt this as well
$City='Toronto'
# Your State (no not Confusion, the one you live in) or Province for those 'Canadians' Again
$StateProv='Ontario'
# Address you work at
$Address='123 Sesame Street'
# Default web site
$Web='www.contosorocks.com'
# Company where you work at, or won't work at if your boss catches you spending too much time drooling over Powershell
$Company='Contoso Rocks Ltd'
# What location in the building? typically floor X, Division Y, the back room behind the boxes
$Office='In the Basement with my stapler'
# A generic description for the user
$Description='New User'
# Job Description. Carpet burner, box stacker, cable monkey
$JobTitle='New User Hired'
# What department. Where you hiding? Network Admins, Secretaries?
$Department='New Department Hire'
# Office Fax Number
$Fax='212-555-1234'
# The ending part of the domain @wherever.com @fabrikam.com etc etc
$ourdomain='@contoso.local'
# This first line is done within the Microsoft Exchange Management Shell from Exchange 2007. I add it's ability to my Powershell with the command
# ADD-PSSNAPIN -name Microsoft.Exchange.Management.Powershell.Admin IF you have the Microsoft Exchange console on the computer running this script. And you have Microsoft Exchange Server 2007 in the environment
New-Mailbox -Name $Name -Alias $Alias -OrganizationalUnit 'Contoso.local/Users' -UserPrincipalName $UPN -SamAccountName $SAM -FirstName $FirstName -Initials '' -LastName $LastName -Password $TempPassword -ResetPasswordOnNextLogon $true -Database 'CONTOSOEXCHANGE\\First Storage Group\\Mailbox Database'
# This command l
set-qaduser -identity $alias -homedirectory $HomeDir -homedrive $Homedrive -city $City -company $Company -department $Department -fax $Fax -office $Office -phonenumber $Phone -postalcode $PostalZip -stateorprovince $StateProv -streetaddress $Address -webpage $web -displayname $displayname -title $JobTitle
#http://www.powergui.org/thread.jspa?messageID=14099 Source post for creating OCS user with Powershell! Thank you Powergui.ORG!
#
# Tips. If you do have Office Communications Server or Live Comm and looking for the Variables used, Check an enabled user in Active Directory while in ADVANCED mode
# and choose the "Attribute Editor" tab. You'll find them all down there. If it doesn't say "Enabled" or contain a value? Don't use it
$SIPHOMESERVER='CN=LC Services,CN=Microsoft,CN=CONTOSO-OCSSERVER,CN=Pools,CN=RTC Service,CN=Microsoft,CN=System,DC=CONTOSO,DC=local'
$oa = @{'msRTCSIP-OptionFlags'=384; 'msRTCSIP-PrimaryHomeServer'=$SIPHOMESERVER; 'msRTCSIP-PrimaryUserAddress'=("sip:"+$alias+$ourdomain); 'msRTCSIP-UserEnabled'=$true }
Set-QADUser $Alias -oa $oa
#http://blogs.msdn.com/johan/archive/2008/10/01/powershell-editing-permissions-on-a-file-or-folder.aspx - Great reference on SETTING NTFS permissions with SET-ACL! Thumbs up!
#Make User Home Folder and Apply NTFS permissions - This was taken almost VERBATIM from the Blogpost. I added in the $alias created from the FirstName Lastname to automatically populate a HomeFolder based upon the user name
$HomeFolderMasterDir='\\\\CONTOSOFILE\\USERHOME$\\'
new-item -path $HomeFolderMasterDir -name $Alias -type directory
$Foldername=$HomeFolderMasterDir+$Alias
$DomainUser='CONTOSO\\'+$Alias
$ACL=Get-acl $Foldername
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($DomainUser,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $Foldername $Acl
|
PowerShellCorpus/PoshCode/Colorize Subversion SVN_3.ps1
|
Colorize Subversion SVN_3.ps1
|
# draw output
function drawlines($colors, $lines) {
if (!$lines) { return }
foreach ($line in $lines) {
$color = $colors[[string]$line[0]]
if ($color) {
write-host $line -Fore $color
} else {
write-host $line
}
}
}
# svn stat
function ss {
drawlines @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } (svn stat)
}
# svn update
function su {
drawlines @{ "A"="Magenta"; "D"="Red"; "U"="Green"; "C"="Yellow"; "G"="Blue"; } (svn up)
}
# svn diff
function sd {
drawlines @{ "@"="Magenta"; "-"="Red"; "+"="Green"; "="="DarkGray"; } (svn diff)
}
|
PowerShellCorpus/PoshCode/VMWare Quick Migration_2.ps1
|
VMWare Quick Migration_2.ps1
|
#########################################
#Name: VMWare Quick Migration Function
#Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com>
#Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html
#Version: 0.1
#Last Revised: 31 July 2009
#
#Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM,
# moving it to a new host, and resuming it. This does not require vMotion licensing.
# it works by providing required VM objects via the pipeline or the second argument,
# and specifying the Destination host in the first argument.
# The commeand accepts both text strings and VMHost objects for the VMHost Parameter
#
#Prerequisites:
# Powershell v1
# VMWare PowerCLI 4.0 (May work with earlier version but not tested)
#
#Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1
# You can also include it in your PowerCLI profile to have it automatically included.
#Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2"
#########################################
function QuickMigrate-VM {
PARAM(
$NewVMHost = ""
, [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null
)
BEGIN {
if (!$NewVMHost){
Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`""
break
}
elseif ($VMsToMigrate) {
Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost
}
else {
#If NewVMHost was provided as a String, convert it into a VMHost Object.
if ($NewVMHost.GetType().Name -eq "String") {
set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1
}
#Make sure that we have a VMHost object to work with.
if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) {
write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host"
break
}
write-host -fore white "===Begin Quick Migration==="
}
}
PROCESS {
$step = 0
$skip = $false
#In the Event of an error, output the error, and skip the rest of the current item.
#This is a workaround for the fact that "continue" doesn't work in a function process loop.
trap {
write-host -fore yellow "`tSKIPPED: "$_.Exception.Message
set-variable -name skip -value ($true) -scope 1
continue
}
$vmToMigrate = $_
### Validation Checks
if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) {
write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..."
}
else {
throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl."
}
# Check for connected devices
if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected CD Drive. Please disconnect and try again."
}
if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected Floppy Drive. Please disconnect and try again."
}
# Make sure the current VM Host and the Destination Host are different.
$sourceVMHost = get-vmhost -vm $vmToMigrate
if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) {
throw "Source and Destination Hosts are the same."
}
###Validation Complete, begin Migration
if (! $skip) {
$step++
write-host -fore cyan "`t$($step. Suspending" $vmToMigrate.Name"..."
$suspend = Suspend-VM -VM $vmToMigrate -confirm:$false
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Moving" $vmToMigrate.Name "to" $destinationVMHost.Name"..."
$migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..."
$resume = Start-VM -VM $vmToMigrate
}
write-host -fore green "`tCOMPLETED"
}
END { write-host -fore white "===END Quick Migration===" }
}
|
PowerShellCorpus/PoshCode/Get-RebootTime.ps1
|
Get-RebootTime.ps1
|
$compres = Read-Host -message "Enter a computer name."
$date = Get-WmiObject Win32_OperatingSystem -ComputerName $compres | foreach{$_.LastBootUpTime}
$RebootTime = [System.DateTime]::ParseExact($date.split('.')[0],'yyyyMMddHHmmss',$null)
$RebootTime
|
PowerShellCorpus/PoshCode/Invoke-RickRoll.ps1
|
Invoke-RickRoll.ps1
|
function Invoke-RickRoll {
<#
.SYNOPSIS
Invoke-RickRoll
A RickRoll PowerShell Script :)
Authors: Chris Campbell (@obscuresec)
License: BSD 3-Clause
.DESCRIPTION
A script to call IE and send it to a URL.
.PARAMETER VideoURL
Specifies a URL to send IE to.
.EXAMPLE
PS C:\\>Invoke-RickRoll -VideoURL http://www.obscuresec.com
#>
[CmdletBinding()] Param(
[string] $VideoURL = 'http://www.youtube.com/watch?v=dQw4w9WgXcQ'
)
[string] $CmdString = "$env:SystemDrive\\PROGRA~1\\INTERN~1\\iexplore.exe $VideoURL"
Write-Verbose "I am now opening IE to $VideoUrl"
Invoke-Expression $CmdString
}
|
PowerShellCorpus/PoshCode/New-XVM_7.ps1
|
New-XVM_7.ps1
|
#Examples
<#
New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD
New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx'
New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD
New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB
New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic
New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx'
New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"}
#>
Function New-XVM
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$false,Position=1)]
[string]$ComputerName=$env:COMPUTERNAME,
[Parameter(Mandatory=$true,Position=2)]
[string]$Name,
[Parameter(Mandatory=$true,Position=3)]
[string]$SwitchName,
[Parameter(Mandatory=$true,Position=4)]
[ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")]
[string]$VhdType,
[Parameter(Mandatory=$false,Position=5)]
[hashtable]$Configuration
)
DynamicParam
{
Switch ($VhdType) {
"ExistingVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("VhdPath",$vhdPath)
return $paramDictionary
}
"NewVHD" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("DiskType",$diskType)
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $false
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection)
$paramDictionary.Add("DiskSize",$diskSize)
return $paramDictionary
}
"Differencing" {
$attributes = New-Object System.Management.Automation.ParameterAttribute
$attributes.ParameterSetName = "_AllParameterSets"
$attributes.Mandatory = $true
$attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection)
$paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add("ParentVhdPath",$parentVhdPath)
return $paramDictionary
}
}
}
Begin
{
Try
{
$vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop
}
Catch
{
$PSCmdlet.ThrowTerminatingError($Error[0])
}
$defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath
}
Process
{
$validConfigNames = "MemoryStartupBytes","BootDevice"
$configParams = @()
Switch ($VhdType) {
"NoVHD" {
$newVhdPath = $null
}
"ExistingVHD" {
$newVhdPath = $vhdPath.Value
}
"NewVhd" {
if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"}
if (-not $diskSize.IsSet) {$diskSize.Value = 127GB}
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
Switch ($diskType.Value) {
"Fixed" {
$vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
"Dynamic" {
$vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop
}
}
}
"Differencing" {
$newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx"
$vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop
}
}
if ($vhdFile -ne $null) {
Try
{
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'"
}
Catch
{
$PSCmdlet.WriteError($Error[0])
Remove-Item -Path $vhdFile.Path
}
} else {
$command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD"
}
if ($Configuration -ne $null) {
foreach ($configName in $Configuration.Keys.GetEnumerator()) {
if ($validConfigNames -contains $configName) {
$configParams += "-$configName" + " " + $Configuration[$configName]
}
}
$configParams = $configParams -join " "
}
if ($configParams.Count -eq 0) {
$command += " -ErrorAction Stop"
} else {
$command += " $configParams -ErrorAction Stop"
}
Invoke-Expression -Command $command
}
End {}
}
|
PowerShellCorpus/PoshCode/GPRS Online log_6.ps1
|
GPRS Online log_6.ps1
|
<#
.SYNOPSIS
Get-GprsTime (V4.0 Update for Windows 7 and allow time correction) Check the
total connect time of any GPRS devices from a specified date.
Use 'Get-Help .\\Get-GprsTime -full' to view Help for this script.
.DESCRIPTION
Display all the GPRS modem Event Log entries. While applications issued by the
mobile phone manufacturers will invariably monitor only their own usage, this
will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc.
Use the -Verbose switch for some extra information if desired. A default value
can be set with the -Monthly switch but can be temporarily overridden with any
-Start value and deleted by entering an invalid date. Now uses .NET Parse to
use any culture date input. Switches -M and -S cannot be used together.
A Balloon prompt will be issued in the Notification area for the 5 days
before the nominal month end.
NOTE: this can effectively be suppressed by using a value higher than the SIM
card term, ie something like -Account 90 for a 30 day card which will override
the default setting.
Define a function in $profile to set any permanent switches, for example to
remove 1hour 15 minutes from the total each time.
function GPRS {
Invoke-Expression ".\\Get-GprsTime -Adjust 1:15:00- $args"
}
.EXAMPLE
.\\Get-GprsTime.ps1 -Monthly 4/8/2011
This will set the default search date to start from 4/8/2011 and is used to
reset the start date each month for the average 30/31 day SIM card.
.EXAMPLE
.\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose
Search from 12/07/2011 and also show (Verbose) details for each session. The
Account switch will override any balloon prompt near the SIM expiry date.
.EXAMPLE
.\\Get-GprsTime.ps1 5/9/2011 -v
Search one day only and show session details.
.EXAMPLE
.\\Get-GprsTime.ps1 -Today
Show all sessions for today. This always defaults to verbose output.
.EXAMPLE
.\\Get-GprsTime.ps1 -Debug
This shows the first available Event Log record & confirms switch settings.
(Note that it will probably not be the first 'RemoteAccess' or 'RasClient'
record).
.EXAMPLE
.\\Get-GprsTime -Adjust 1:20:00
If the same SIM card is used on another computer then such times will have
to be added here manually (this should be put in a function in $profile so
that it will automatically be included - see example above).
To remove an amount of time, just put a '-' sign after the desired figure.
.NOTES
A shorter total time than that actually used will result if the Event Log
does not contain earlier dates; just increase the log size in such a case.
The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a
(binary compiled) Module version of this procedure is included in the file
Gprs3xxx.zip download there; the execution time of the module being about
10 times faster than this script.
Use '(measure-Command {.\\Get-GprsTime}).TotalSeconds' to confirm the times.
For the Event Log to record connect & disconnect events, the modem software
should be set to RAS rather than NDIS if possible.
#>
Param ([String] $start,
[alias("PERIOD")][string] $adjust,
[String] $monthly,
[Int] $account = 0,
[Switch] $today,
[Switch] $verbose,
[Switch] $debug)
Trap [System.Management.Automation.MethodInvocationException] {
[Int]$line = $error[0].InvocationInfo.ScriptLineNumber
[System.Media.SystemSounds]::Hand.Play()
if ($line -eq 205) {
Write-Warning "[$name] Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
else {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
}
exit 1
}
#Establish the Operating System...We only need to confirm XP here.
#The result will be written to the 'out' variable '$osv'.
function Get-OSVersion($computer,[ref]$osv) {
$os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer
Switch -regex ($os.Version) {
'^5\\.1\\.(\\d{1,4})$' { $osv.value = "xp" } #Find XP & variants.
default { $osv.value = "unknown" }
}
}
$osv = $null
Get-OSVersion -computer 'localhost' -osv ([ref]$osv)
if ($osv -eq 'xp') {
$logname = 'System'
$connEvent = 20158
$discEvent = 20159
$source = 'RemoteAccess'
}
else { #Treat As Vista or Windows 7.
$logname = 'Application'
$connEvent = 20225
$discEvent = 20226
$source = 'RasClient'
}
$entryType = 'Information'
$logEntry = $null
$oldest = Get-eventlog -LogName $logname | #Get the earliest Log record.
Sort-Object TimeGenerated |
Select-Object -first 1
if ($oldest.TimeGenerated) {
$logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())"
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly can only be used separately."
if ($debug) {
$DebugPreference = 'Continue'
}
if ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
if ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
if ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$ErrorActionPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $default = $print = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00.
$insert = "since"
if ($verbose) {
$VerbosePreference = 'Continue'
}
function CreditMsg ($value, $value2) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
[DateTime] $creditDT = $value2
$creditDT = $creditDT.AddDays($value) #Add the -Account days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below we
#can sometimes get a value of 1 returned instead 2, hence the above lines.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
return $prefix
}
function Interval ([String] $value) {
Switch -regex ($value) {
'^00?:00?:\\d+(.*)$' {$suffix = "seconds"; break}
'^00?:\\d+:\\d+(.*)$' {$suffix = "minutes"; break}
'^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break}
'^(\\d+)\\D(\\d+)(.*)$' {$suffix = " hours"
$pDays = $matches[1]
$pHours = $matches[2]
[string]$pMinSec = $matches[3]
[string]$tHours = (([int]$pDays) * 24)+[int]$pHours
$value = $tHours + $pminSec; break}
default {$suffix = " hours"} #Should never come here!
}
return "$value $suffix"
}
function CheckSetting ($value) {
if ($value) { #Correct for local culture.
$print = $default.ToShortDateString()
}
else {
$print = "(Value not set)"
}
return $print
}
#The Script effectively starts here.............................................
$getGprs = [Environment]::GetEnvironmentVariable("GPRS","User")
#First check for GPRS variable and change from US date format to current locale.
if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid.
$default = "{0:d}" -f [datetime]$getGprs
$default = [DateTime]::Parse($default)
$checkParts = "{0:yyyy},{0:%M}" -f $default
$times = $checkParts.Split(',')
$dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31.
if($account -eq 0) {
$account = $dayCount
$summary = "$($dayCount.ToString()) days"
}
else {
$summary = "$($account.Tostring()) days"
}
$text = CreditMsg $account $getGprs #Check if within 5 days of expiry date.
if ($text -ne "CURRENT") {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
}
else {
$summary = "(Days not set)"
if ((!$today) -and (!$monthly) -and (!$start)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning("Monthly date is either invalid or not set.")
exit 1
}
}
if ($start) {
$start = [DateTime]::Parse($start) #Trigger TRAP if invalid!
[DateTime]$limit = $start
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
if ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
$print = $limit.ToShortDateString()
$summary = "(Days undetermined)" #Will show next time around.
}
if ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
$print = CheckSetting $default
}
if ((!$today) -and (!$monthly) -and (!$start)) {
if ($default) {
$monthly = $default
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
}
$adjustment = $null #Otherwise 'Set-Strictmode -Version latest' will catch.
if ($adjust) {
$pattern = '^(\\d{1,3}):(\\d{1,2}):(\\d{1,2})-?$'
if ($adjust -notmatch $pattern ) {
Write-Warning "Invalid format - use <hours>:<minutes>:<seconds>"
return
} #Now create the 'adjustment' to add later.
$adjustment = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3]
$outString = $adjust.Replace('-','')
$outString = interval $outString
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print"
if ($logEntry) {
Write-Debug "$logEntry"
}
$lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)}
if ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
try {
$source = $_.Source
}
catch {
return
}
if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
if (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
function formatSpan ($timespan) { #Convert returns of '1.11:00:00'.
$addHours = $timespan.Days * 24
$addHours+= $timespan.Hours
$h = $addHours.ToString().PadLeft(2,'0') + ':'
$m = $timespan.Minutes.ToString().PadLeft(2,'0') + ':'
$s = $timespan.Seconds.ToString().PadLeft(2,'0')
return $h + $m + $s
}
if ($adjustment -and ($total -match $pattern)) {
$outDate = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3]
if (!$adjust.EndsWith('-')) {
$period = $outDate + $adjustment #The '-adjust' value added at start.
$show = formatSpan $period
$show = interval $show #Get hours,minutes suffix.
Write-Output "Total online usage $insert $convert is $show"
Write-Output "(Including $($outString.Replace(' ',' ')) adjustment time)"
}
else {
if ($outDate.TotalSeconds -gt $adjustment.TotalSeconds) {
$period = $outDate - $adjustment
$show = formatSpan $period
$show = interval $show
Write-Output "Total online usage $insert $convert is $show"
Write-Output "(Excluding $($outString.Replace(' ',' ')) adjustment time)"
}
else {
Write-Output "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))."
$adjust = $adjust.Replace('-','')
Write-Warning "Invalid amount entered ($adjust) - no adjustment performed"
}
}
}
else {
Write-OutPut "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))."
}
Write-Output ""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.