full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/GUI process explorer.ps1
|
GUI process explorer.ps1
|
function BuildProcessesList {
$arr = New-Object Collections.ArrayList
$script:col = ps | select Name, Id, BasePriority, Description, Company | sort Name
$arr.AddRange($col)
$dtgGrid.DataSource = $arr
$frmMain.Refresh()
}
function SelectedItemModules {
$ErrorActionPreference = "SilentlyContinue"
$lstView.Items.Clear()
$sbRules.Text = ""
$row = $dtgGrid.CurrentRowIndex
if ($itm = $script:col[$row].Id) {
trap { $sbRules.Text = $_.Exception.Message }
(ps | ? {$_.Id -eq $itm}).Modules | % {
$sel = $lstView.Items.Add($_.Size)
[void]$sel.Subitems.Add($_.ModuleName)
[void]$sel.Subitems.Add($_.FileName)
}
}
}
function AutoUpdate {
if (!($mnuAuto.Checked)) {
$mnuAuto.Checked = $true
$trTimer.Start()
$sbRules.Text = "Auto update has been enabled."
}
else {
$mnuAuto.Checked = $false
$trTimer.Stop()
$sbRules.Text = "Auto update has been disabled."
}
}
$frmMain_OnLoad= {
BuildProcessesList
}
function ShowMainWindow {
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[Windows.Forms.Application]::EnableVisualStyles()
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuAuto = New-Object Windows.Forms.MenuItem
$mnuRfrs = New-Object Windows.Forms.MenuItem
$mnuNull = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$scSplit = New-Object Windows.Forms.SplitContainer
$dtgGrid = New-Object Windows.Forms.DataGrid
$lstView = New-Object Windows.Forms.ListView
$chSizeK = New-Object Windows.Forms.ColumnHeader
$chFileM = New-Object Windows.Forms.ColumnHeader
$chFileP = New-Object Windows.Forms.ColumnHeader
$trTimer = New-Object Windows.Forms.Timer
$sbRules = New-Object Windows.Forms.StatusBar
#mnuMain
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuHelp))
#mnuFile
$mnuFile.MenuItems.AddRange(@($mnuAuto, $mnuRfrs, $mnuNull, $mnuExit))
$mnuFile.Text = "&File"
#mnuAuto
$mnuAuto.Shortcut = "CtrlA"
$mnuAuto.Text = "Auto &Update"
$mnuAuto.Add_Click( { AutoUpdate } )
#mnuRfrs
$mnuRfrs.Shortcut = "F5"
$mnuRfrs.Text = "&Refresh"
$mnuRfrs.Add_Click( { $sbRules.Text = ""; BuildProcessesList } )
#mnuNull
$mnuNull.text = "-"
#mnuExit
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click( { $frmMain.Close() })
#mnuHelp
[void]$mnuHelp.MenuItems.Add($mnuInfo)
$mnuHelp.Text = "&Help"
#mnuInfo
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click( { ShowAboutWindow } )
#scSplit
$scSplit.Dock = "Fill"
$scSplit.Orientation = "Horizontal"
$scSplit.Panel1.Controls.Add($dtgGrid)
$scSplit.Panel2.Controls.Add($lstView)
$scSplit.SplitterWidth = 1
#dtgGrid
$dtgGrid.CaptionVisible = $false
$dtgGrid.Dock = "Fill"
$dtgGrid.PreferredColumnWidth = 109
$dtgGrid.Add_Click( { SelectedItemModules } )
#lstView
$lstView.Columns.AddRange(@($chSizeK, $chFileM, $chFileP))
$lstView.Dock = "Fill"
$lstView.FullRowSelect = $true
$lstView.GridLines = $true
$lstView.Sorting = "Ascending"
$lstView.View = "Details"
#chSizeK
$chSizeK.Text = "Size (K)"
$chSizeK.Width = 70
#chFileM
$chFileM.Text = "Module Name"
$chFileM.Width = 130
#chFileP
$chFileP.Text = "Path"
$chFileP.Width = 380
#trTimer
$trTimer.Interval = 1000
$trTimer.Add_Tick( { BuildProcessesList } )
#sbRules
$sbRules.SizingGrip = $false
#frmMain
$frmMain.ClientSize = New-Object Drawing.Size(601, 480)
$frmMain.Controls.AddRange(@($scSplit, $sbRules))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "PExplore"
$frmMain.Add_Load($frmMain_OnLoad)
[void]$frmMain.ShowDialog()
}
function ShowAboutWindow {
$frmMain = New-Object Windows.Forms.Form
$lblThis = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#lblThis
$lblThis.Location = New-Object Drawing.Point(5, 29)
$lblThis.Size = New-Object Drawing.Size(330, 50)
$lblThis.Text = "(C) 2008 Grigori Zakharov `n
This is just an example that you can make better."
$lblThis.TextAlign = "MiddleCenter"
#btnExit
$btnExit.Location = New-Object Drawing.Point(132, 97)
$btnExit.Text = "Close"
$btnExit.Add_Click( { $frmMain.Close() } )
#frmMain
$frmMain.ClientSize = New-Object Drawing.Size(350, 137)
$frmMain.ControlBox = $false
$frmMain.Controls.AddRange(@($lblThis, $btnExit))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.ShowInTaskbar = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "About..."
[void]$frmMain.ShowDialog()
}
ShowMainWindow
|
PowerShellCorpus/PoshCode/New-HyperVVM.ps1
|
New-HyperVVM.ps1
|
function New-HyperVVM {
param (
[string]$Hypervhost = "localhost",
[string]$Vm = "VM Courtesy of PowerShell",
[string]$location = "C:\\MyVirtualMachines\\$vm"
)
$wmiClassString = "\\\\" + $Hypervhost + "\\root\\virtualization:Msvm_VirtualSystemGlobalSettingData"
$wmiclass = [WMIClass]$wmiClassString
$newVSGlobalSettingData = $wmiClass.CreateInstance()
$newVSGlobalSettingData.psbase.Properties.Item("ExternalDataRoot").value = $location
$newVSGlobalSettingData.psbase.Properties.Item("ElementName").value = $Vm
$VSManagementService = gwmi MSVM_VirtualSystemManagementService -namespace "root\\virtualization" -ComputerName $Hypervhost
$GlobalSettings = $newVSGlobalSettingData.psbase.GetText(1)
$VSManagementService.DefineVirtualSystem($GlobalSettings, $ResourceSettings)
}
|
PowerShellCorpus/PoshCode/Get-FileEncoding_4.ps1
|
Get-FileEncoding_4.ps1
|
<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
)
[byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
if ($byte.count -ge 0)
{
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ $encoding = 'UTF8' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ $encoding = 'BigEndianUnicode' }
elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe)
{ $encoding = 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ $encoding = 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ $encoding = 'UTF7'}
else
{ $encoding = 'ASCII' }
return $encoding
}
}
|
PowerShellCorpus/PoshCode/Autoload Module_1.ps1
|
Autoload Module_1.ps1
|
#Requires -Version 2.0
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## Provides significant memory benefits over pre-loading all your functions, and significant performance benefits over using plain scripts. Can also *inject* functions into Modules so they inherit the module scope instead of the current local scope.
## Please see the use example in the script below
## Version History
## v 1.1 - 2011.02.09
## Added support for autoloading scripts (files that don't have a "function" in them)
## v 1.0 - 2010.10.20
## Officially out of beta -- this is working for me without problems on a daily basis.
## Renamed functions to respect the Verb-Noun expectations, and added Export-ModuleMember
## beta 8 - 2010.09.20
## Finally fixed the problem with aliases that point at Invoke-Autoloaded functions!
## beta 7 - 2010.06.03
## Added some help, and a function to force loading "now"
## Added a function to load AND show the help...
## beta 6 - 2010.05.18
## Fixed a bug in output when multiple outputs happen in the END block
## beta 5 - 2010.05.10
## Fixed non-pipeline use using $MyInvocation.ExpectingInput
## beta 4 - 2010.05.10
## I made a few tweaks and bug fixes while testing it's use with PowerBoots.
## beta 3 - 2010.05.10
## fix for signed scripts (strip signature)
## beta 2 - 2010.05.09
## implement module support
## beta 1 - 2010.04.14
## Initial Release
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script (for our example: C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 )
## 3) Import the Autoload Module
## 5) Run this command (or add it to your profile):
<#
New-Autoload C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
function Invoke-Autoloaded {
#.Synopsis
# This function was autoloaded, but it has not been parsed yet.
# Use Get-AutoloadHelp to force parsing and get the correct help (or just invoke the function once).
#.Description
# You are seeing this help because the command you typed was imported via the New-Autoload command from the Autoload module. The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the Get-AutoloadHelp function.
#
# For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: Get-AutoloadHelp Get-PerformanceHistory
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
return LoadNow $CommandName
}#DynamicParam
begin {
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName -> $FunctionName"
#Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
$global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function )
Write-Verbose "Autoloaded Command: $($Command|Out-String)"
$scriptCmd = {& $command @PSBoundParameters | Write-Output }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($myInvocation.ExpectingInput)
}
process
{
Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)"
try {
if($_) {
$steppablePipeline.Process($_)
} else {
$steppablePipeline.Process()
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Invoke-Autoloaded End: $CommandName"
}
}#Invoke-Autoloaded
function Get-AutoloadHelp {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
$null = LoadNow $CommandName
Get-Help $CommandName
}
function LoadNow {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "LoadNow Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
Write-Verbose "LoadNow DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Autoloading:`nScriptName: $ScriptName `nModuleName: $ModuleName `nFunctionName: $FunctionName"
if(!$ScriptName){ $ScriptName = $CommandName }
if(!$FunctionName){ $FunctionName = $CommandName }
if($ModuleName) {
$Module = Get-Module $ModuleName
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
$function = $false
ForEach($token in $tokens) {
if($prev -and $token.Content -eq "# SIG # Begin signature block") {
$script = $script.SubString(0, $token.Start )
}
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) {
$script = $script.Insert( $prev.Start, "global:" )
$function = $true
Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')"
}
$prev = $token
}
if(!$function) {
$script = "function global:$Functionname { $script }"
}
if($Module) {
$script = Invoke-Expression "{ $Script }"
Write-Verbose "Importing Function into $($Module) module."
&$Module $Script | Out-Null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
} else {
Write-Verbose "Importing Function without module."
Invoke-Expression $script | out-null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
if($CommandName -eq $FunctionName) {
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)"
} else {
Set-Alias $CommandName $FunctionName -Scope Global
Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)"
}
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}
function New-Autoload {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName")]
$Alias = $Name
,
[Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
$Function = $Alias
,
[Parameter(Position=3,Mandatory=$false)]
[String]$Module
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
)
begin {
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
process {
for($i=0;$i -lt $Name.Count;$i++){
if($Alias -is [Scriptblock]) {
$a = $Name[$i] | &$Alias
} elseif($Alias -is [Array]) {
$a = $Alias[$i]
} else {
$a = $Alias
}
if($Function -is [Scriptblock]) {
$f = $Name[$i] | &$Function
} elseif($Function -is [Array]) {
$f = $Function[$i]
} else {
$f = $Function
}
Write-Verbose "Set-Alias $Module\\$a Invoke-Autoloaded -Scope $Scope"
Set-Alias $a Invoke-Autoloaded -Scope $Scope
$Script:AutoloadHash[$a] = $Name[$i],$Module,$f
Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
}
}
}
Set-Alias Autoload New-Autoload
$Script:AutoloadHash = @{}
Export-ModuleMember -Function New-Autoload, Invoke-Autoloaded, Get-AutoloadHelp -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUssOSqKkXdzRkKCA3J7jqfwad
# YC+gggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUoLiD3TXY
# htHM+1GkrG8rScPT4vEwDQYJKoZIhvcNAQEBBQAEggEAMLJBsTm5V6/9jyX1RrTz
# TgDFLvTTriT0ma6/2/nEEih4tjEDLM/4DO3HQR1f2r2DpuNwYeoKVLYCiohPm993
# VOqwzmxXgNBi3KC8hJ9/rq0prVCnlcQ9M5OveuAJITcR8KWxQpR9MRiYsvmjh3gv
# GwEuoPeAywdecbQFUNK1v0ZPl/U8DA0ekAXRHrmD1bvUK+Osa9tnXvYYMZ2QsPmJ
# XnetDsRFjEz968O30Ufrd5IlrGfvuUww5MtQPzSR9jW5RWSJa137ExNn1MifC6if
# kJMBhBBafbJmiSJARB3fIff8NVl0dlvOi2jHZ8zxQcpumzVtYBf4h5mvTnlB8Uef
# NA==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-RemoteRegistry_3.ps1
|
Get-RemoteRegistry_3.ps1
|
#.SYNOPSIS
# Query the registry on a remote machine
#.NOTE
# You have to have access, and the remote registry service has to be running
#
# Version History:
# 3.0
# + updated to PowerShell 2
# + support pipeline parameter for path
# 2.1
# + Fixed a pasting bug
# + I added the "Properties" parameter so you can select specific redgistry values
# ######################################################################################
#.EXAMPLE
# (Get-RemoteRegistry ${Env:ComputerName} HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\).Subkeys |
# Get-RemoteRegistry ${Env:ComputerName} `
# -Path { "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$_" } `
# -Properties DisplayName, DisplayVersion, Publisher, InstallDate, HelpLink, UninstallString
#.EXAMPLE
# Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"
# * Returns a list of subkeys (because this key has no properties)
#.EXAMPLE
# Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727"
# * Returns a list of subkeys and all the other "properties" of the key
#.EXAMPLE
# Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Version"
# * Returns JUST the full version of the .Net SP2 as a STRING (to preserve prior behavior)
#.EXAMPLE
# Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version
# * Returns a custom object with the property "Version" = "2.0.50727.3053" (your version)
#.EXAMPLE
# Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version,SP
# * Returns a custom object with "Version" and "SP" (Service Pack) properties
#
# For fun, get all .Net Framework versions (2.0 and greater)
# and return version + service pack with this one command line:
#
# Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" |
# Select -Expand Subkeys | ForEach-Object {
# Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\$_" Version,SP
# }
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$computer = $(Read-Host "Remote Computer Name")
,
[Parameter(Position=1, ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true, Mandatory=$true)]
[string]$Path = $(Read-Host "Remote Registry Path (must start with HKLM,HKCU,etc)")
,
[Parameter(Position=2)]
[string[]]$Properties
)
process {
$root, $last = $Path.Split("\\")
$last = $last[-1]
$Path = $Path.Substring($root.Length + 1,$Path.Length - ( $last.Length + $root.Length + 2))
$root = $root.TrimEnd(":")
#split the path to get a list of subkeys that we will need to access
# ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
switch($root) {
"HKCR" { $root = "ClassesRoot"}
"HKCU" { $root = "CurrentUser" }
"HKLM" { $root = "LocalMachine" }
"HKU" { $root = "Users" }
"HKPD" { $root = "PerformanceData"}
"HKCC" { $root = "CurrentConfig"}
"HKDD" { $root = "DynData"}
default { return "Path argument is not valid" }
}
#Access Remote Registry Key using the static OpenRemoteBaseKey method.
Write-Verbose "Accessing $root from $computer"
$rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($root,$computer)
if(-not $rootkey) { Write-Error "Can't open the remote $root registry hive" }
Write-Verbose "Opening $Path"
$key = $rootkey.OpenSubKey( $Path )
if(-not $key) { Write-Error "Can't open $($root + '\\' + $Path) on $computer" }
$subkey = $key.OpenSubKey( $last )
$output = new-object object
if($subkey -and $Properties -and $Properties.Count) {
foreach($property in $Properties) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
} elseif($subkey) {
Add-Member -InputObject $output -Type NoteProperty -Name "Subkeys" -Value @($subkey.GetSubKeyNames())
foreach($property in $subkey.GetValueNames()) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
}
else
{
$key.GetValue($last)
}
}
|
PowerShellCorpus/PoshCode/Get-LastReboot.ps1
|
Get-LastReboot.ps1
|
Param (
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[alias("Name","ComputerName")]$Computer=@($env:ComputerName),
[switch] $Output
)
process{
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet){
write-host "Getting Uptime for $Computer" -foregroundcolor green
$Result = GetUpTime $Computer
$Global:objOut += $Result
}
else {
Write-Output $("$($Computer) cannot be reached")
}
}
begin{
$Global:objOut = @()
Function GetUpTime ($HostName){
try{
$UpTime = [System.Management.ManagementDateTimeconverter]::ToDateTime((Get-WmiObject -Class Win32_OperatingSystem -Computer $HostName).LastBootUpTime)
$UpTimeSpan = New-TimeSpan -start $UpTime -end $(Get-Date -Hour 8 -Minute 0 -second 0)
$Filter = @{ProviderName= "USER32";LogName = "system"}
$Reason = (Get-WinEvent -ComputerName $HostName -FilterHashtable $Filter | where {$_.Id -eq 1074} | Select -First 1)
$Result = New-Object PSObject -Property @{
Date = $(Get-Date -Format d)
ComputerName = [string]$HostName
LastBoot = $UpTime
Reason = $Reason.Message
Days = $($UpTimeSpan.Days)
Hours = $($UpTimeSpan.Hours)
Minutes = $($UpTimeSpan.Minutes)
Seconds = $($UpTimeSpan.Seconds)
}
return $Result
}
catch{
write-error $error[0]
return $null
}
}
}
end{
if ($Output){
[string]$OutputLog = ([environment]::getfolderpath("mydocuments")) + "\\" + "Servers_Uptime.csv"
$Global:objOut | ConvertTo-Csv -Delimiter ";" -NoTypeInformation | out-file $OutputLog
}
else{
$Global:objOut | Select Date, Servername, Lastboot, Reason, Days, Hours, Minutes, Seconds | fl
}
}
|
PowerShellCorpus/PoshCode/Start-Encryption_2.ps1
|
Start-Encryption_2.ps1
|
## Start-Encryption
##################################################################################################
## Rijndael symmetric key encryption ... with no passes on the key. Very lazy.
## USAGE:
## $encrypted = Encrypt-String "Oisin Grehan is a genius" "P@ssw0rd"
## Decrypt-String $encrypted "P@ssw0rd"
##
## You can choose to return an array by passing -arrayOutput to Encrypt-String
## I chose to use Base64 encoded strings because they're easier to save ...
[Reflection.Assembly]::LoadWithPartialName("System.Security")
function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key", [switch]$arrayOutput)
{
$r = new-Object System.Security.Cryptography.RijndaelManaged
$pass = [Text.Encoding]::UTF8.GetBytes($Passphrase)
$salt = [Text.Encoding]::UTF8.GetBytes($salt)
$r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
$r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
$c = $r.CreateEncryptor()
$ms = new-Object IO.MemoryStream
$cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write"
$sw = new-Object IO.StreamWriter $cs
$sw.Write($String)
$sw.Close()
$cs.Close()
$ms.Close()
$r.Clear()
[byte[]]$result = $ms.ToArray()
if($arrayOutput) {
return $result
} else {
return [Convert]::ToBase64String($result)
}
}
function Decrypt-String($Encrypted, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key")
{
if($Encrypted -is [string]){
$Encrypted = [Convert]::FromBase64String($Encrypted)
}
$r = new-Object System.Security.Cryptography.RijndaelManaged
$pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase)
$salt = [System.Text.Encoding]::UTF8.GetBytes($salt)
$r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8
$r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15]
$d = $r.CreateDecryptor()
$ms = new-Object IO.MemoryStream @(,$Encrypted)
$cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read"
$sr = new-Object IO.StreamReader $cs
Write-Output $sr.ReadToEnd()
$sr.Close()
$cs.Close()
$ms.Close()
$r.Clear()
}
|
PowerShellCorpus/PoshCode/Search-StartMenu.ps1
|
Search-StartMenu.ps1
|
##############################################################################\n##\n## Search-StartMenu\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/blog)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nSearch the Start Menu for items that match the provided text. This script\nsearches both the name (as displayed on the Start Menu itself,) and the\ndestination of the link.\n\n.Example\n\nSearch-StartMenu "Character Map" | Invoke-Item\nSearches for the "Character Map" appication, and then runs it\n\nSearch-StartMenu PowerShell | Select-FilteredObject | Invoke-Item\nSearches for anything with "PowerShell" in the application name, lets you\npick which one to launch, and then launches it.\n\n#>\n\nparam(\n ## The pattern to match\n [Parameter(Mandatory = $true)]\n $Pattern\n)\n\nSet-StrictMode -Version Latest\n\n## Get the locations of the start menu paths\n$myStartMenu = [Environment]::GetFolderPath("StartMenu")\n$shell = New-Object -Com WScript.Shell\n$allStartMenu = $shell.SpecialFolders.Item("AllUsersStartMenu")\n\n## Escape their search term, so that any regular expression\n## characters don't affect the search\n$escapedMatch = [Regex]::Escape($pattern)\n\n## Search for text in the link name\ndir $myStartMenu *.lnk -rec | ? { $_.Name -match "$escapedMatch" }\ndir $allStartMenu *.lnk -rec | ? { $_.Name -match "$escapedMatch" }\n\n## Search for text in the link destination\ndir $myStartMenu *.lnk -rec |\n Where-Object { $_ | Select-String "\\\\[^\\\\]*$escapedMatch\\." -Quiet }\ndir $allStartMenu *.lnk -rec |\n Where-Object { $_ | Select-String "\\\\[^\\\\]*$escapedMatch\\." -Quiet }
|
PowerShellCorpus/PoshCode/Set-Computername_13.ps1
|
Set-Computername_13.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/CLR4 module.ps1
|
CLR4 module.ps1
|
function Start-CLR4 {
[CmdletBinding()]
param ( [string] $cmd )
if ($PSVersionTable.CLRVersion.Major -eq 4)
{
write-debug 'already running clr 4'
invoke-expression $cmd;
return
}
$RunActivationConfigPath = resolve-path ~ | Join-Path -ChildPath .CLR4PowerShell;
write-debug "clr4 config path: $runactivationconfigpath"
if( -not( test-path $runactivationconfigpath ))
{
New-Item -Path $RunActivationConfigPath -ItemType Container | Out-Null;
@"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
</configuration>
"@ | Set-Content -Path $RunActivationConfigPath\\powershell.exe.activation_config -Encoding UTF8;
}
$EnvVarName = 'COMPLUS_ApplicationMigrationRuntimeActivationConfigPath';
[Environment]::SetEnvironmentVariable($EnvVarName, $RunActivationConfigPath);
write-debug "current COMPLUS_ApplicationMigrationRuntimeActivationConfigPath: $env:COMPLUS_ApplicationMigrationRuntimeActivationConfigPath";
& powershell.exe -nologo -command "$cmd";
}
|
PowerShellCorpus/PoshCode/Get-WebSite_2.ps1
|
Get-WebSite_2.ps1
|
function Get-WebPage {
<#
.SYNOPSIS
Downloads web page from site.
.DESCRIPTION
Downloads web page from site and displays source code or displays total bytes of webpage downloaded
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER Credential
Provide alternate credentials
.PARAMETER ShowSize
Displays the size of the downloaded page in Kilobytes
.NOTES
Name: Get-WebPage
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebPage -url "http://www.bing.com"
Description
------------
Returns the source code from bing.com -showsize
.EXAMPLE
Get-WebPage -url "http://www.bing.com" -ShowSize
Description
------------
Returns the size of the webpage bing.com in bytes.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$ShowSize
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebClient object
Write-Verbose "Creating web client object"
$wc = New-Object Net.WebClient
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Determine if using Default Credentials
If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($PSBoundParameters.ContainsKey('Credentials')) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
}
Process {
Try {
If ($ShowSize) {
#Get the size of the webpage
Write-Verbose "Downloading web page and determining size"
"{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT]
}
Else {
#Get the contents of the webpage
Write-Verbose "Downloading web page and displaying source code"
$wc.DownloadString($url)
}
}
Catch {
Write-Warning "$($Error[0])"
}
}
}
|
PowerShellCorpus/PoshCode/Snippet Compiler_2.ps1
|
Snippet Compiler_2.ps1
|
#Required 2.0
$def = $(if ((gi .).FullName -eq (gi .).Root) {
([string](gi .).Root).TrimEnd("\\")
}
else { (gi .).FullName }
)
##################################################################################################
$mnuOpen_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$sr = New-Object IO.StreamReader $_.FileName
$txtEdit.Text = $sr.ReadToEnd()
$sr.Close()
}
}
}
$mnuFont_Click= {
(New-Object Windows.Forms.FontDialog) | % {
$_.Font = "Lucida Console"
$_.MinSize = 10
$_.MaxSize = 12
$_.ShowEffects = $false
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$txtEdit.Font = $_.Font
}
}
}
$mnuOpaF_Click= {
$frmMain.Opacity = 1
$cur.Checked = $false
$mnuOpaF.Checked = $true
$cur = $mnuOpaF
}
$mnuWrap_Click= {
$toggle =! $mnuWrap.Checked
$mnuWrap.Checked = $toggle
$txtEdit.WordWrap = $toggle
}
$tbTools_ButtonClick= {
switch ($_.Button.Tag) {
"Atom" { Invoke-Atom; break }
"Progress" { Show-Panel $mnuToS1 $scSplt1; break }
"Params" { Show-Panel $mnuToS2 $scSplt2; break }
"Build" { Invoke-Builder; break }
"BuildEx" { Start-AfterBuilding; break }
"Exit" { $frmMain.Close(); break }
}
}
$cboPlat_SelectedIndexChanged= {
switch ($cboPlat.SelectedIndex) {
"0" { $lboRefs.Items.Remove("`"System.Core.dll`""); break }
"1" { $lboRefs.Items.Add("`"System.Core.dll`""); break }
}
}
$chkExec_Click= {
switch ($chkExec.Checked) {
$true {
$txtIOut.Text = $def + '\\app.exe'
$chkWApp.Enabled = $true
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
$btnBnRA.Enabled = $true
break
}
$false {
$txtIOut.Text = $def + '\\lib.dll'
$chkWApp.Enabled = $false
$chkIMem.Enabled = $true
$mnuBnRA.Enabled = $false
$btnBnRA.Enabled = $false
break
}
}
}
$chkWApp_Click= {
switch ($chkWApp.Checked) {
$true {
$lboRefs.Items.AddRange(@("`"System.Drawing.dll`"", "`"System.Windows.Forms.dll`""))
break
}
$false {
$lboRefs.Items.Remove("`"System.Windows.Forms.dll`"")
$lboRefs.Items.Remove("`"System.Drawing.dll`"")
break
}
}
}
$mnuICnM_Click= {
$script:buff = $lboRefs.SelectedItem
$lboRefs.Items.Remove($lboRefs.SelectedItem)
}
$mnuIIns_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.Filter = "PE File (*.dll)|*.dll"
$_.InitialDirectory = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$lboRefs.Items.Add('"' + (Split-Path -leaf $_.FileName) + '"')
}
}
}
$frmMain_Load= {
$txtIOut.Text = $def + '\\app.exe'
$sbPnl_2.Text = "Str: 1, Col: 0"
$lboRefs.Items.Add("`"System.dll`"")
}
##################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$ico = [Drawing.Icon]::ExtractAssociatedIcon($($PSHome + '\\powershell_ise.exe'))
$cdcp = New-Object CodeDom.Compiler.CompilerParameters
$dict = New-Object "Collections.Generic.Dictionary[String, String]"
$dict.Add("CompilerVersion", "v3.5")
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuAtom = New-Object Windows.Forms.MenuItem
$mnuOpen = New-Object Windows.Forms.MenuItem
$mnuEmp1 = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuEdit = New-Object Windows.Forms.MenuItem
$mnuUndo = New-Object Windows.Forms.MenuItem
$mnuEmp2 = New-Object Windows.Forms.MenuItem
$mnuCopy = New-Object Windows.Forms.MenuItem
$mnuPast = New-Object Windows.Forms.MenuItem
$mnuICut = New-Object Windows.Forms.MenuItem
$mnuEmp3 = New-Object Windows.Forms.MenuItem
$mnuSAll = New-Object Windows.Forms.MenuItem
$mnuView = New-Object Windows.Forms.MenuItem
$mnuFont = New-Object Windows.Forms.MenuItem
$mnuEmp4 = New-Object Windows.Forms.MenuItem
$mnuOpac = New-Object Windows.Forms.MenuItem
$mnuOp50 = New-Object Windows.Forms.MenuItem
$mnuOp60 = New-Object Windows.Forms.MenuItem
$mnuOp70 = New-Object Windows.Forms.MenuItem
$mnuOp80 = New-Object Windows.Forms.MenuItem
$mnuOp90 = New-Object Windows.Forms.MenuItem
$mnuOpaF = New-Object Windows.Forms.MenuItem
$mnuTgls = New-Object Windows.Forms.MenuItem
$mnuWrap = New-Object Windows.Forms.MenuItem
$mnuToS1 = New-Object Windows.Forms.MenuItem
$mnuToS2 = New-Object Windows.Forms.MenuItem
$mnuMake = New-Object Windows.Forms.MenuItem
$mnuBAsm = New-Object Windows.Forms.MenuItem
$mnuBnRA = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$tbTools = New-Object Windows.Forms.ToolBar
$btnAtom = New-Object Windows.Forms.ToolBarButton
$btnToS1 = New-Object Windows.Forms.ToolBarButton
$btnMake = New-Object Windows.Forms.ToolBarButton
$btnBAsm = New-Object Windows.Forms.ToolBarButton
$btnBnRA = New-Object Windows.Forms.ToolBarButton
$btnExit = New-Object Windows.Forms.ToolBarButton
$scSplt1 = New-Object Windows.Forms.SplitContainer
$scSplt2 = New-Object Windows.Forms.SplitContainer
$lstView = New-Object Windows.Forms.ListView
$chPoint = New-Object Windows.Forms.ColumnHeader
$chError = New-Object Windows.Forms.ColumnHeader
$chCause = New-Object Windows.Forms.ColumnHeader
$txtEdit = New-Object Windows.Forms.RichTextBox
$gboMake = New-Object Windows.Forms.GroupBox
$lblLab1 = New-Object Windows.Forms.Label
$cboPlat = New-Object Windows.Forms.ComboBox
$chkExec = New-Object Windows.Forms.CheckBox
$chkWApp = New-Object Windows.Forms.CheckBox
$chkIDbg = New-Object Windows.Forms.CheckBox
$chkIMem = New-Object Windows.Forms.CheckBox
$lblLab2 = New-Object Windows.Forms.Label
$txtIOut = New-Object Windows.Forms.TextBox
$lblLab3 = New-Object Windows.Forms.Label
$lboRefs = New-Object Windows.Forms.ListBox
$sbPanel = New-Object Windows.Forms.StatusBar
$sbPnl_1 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_2 = New-Object Windows.Forms.StatusBarPanel
$imgList = New-Object Windows.Forms.ImageList
$mnuRefs = New-Object Windows.Forms.ContextMenu
$mnuIMov = New-Object Windows.Forms.MenuItem
$mnuICnM = New-Object Windows.Forms.MenuItem
$mnuIBuf = New-Object Windows.Forms.MenuItem
$mnuIIns = New-Object Windows.Forms.MenuItem
#
#mnuMain
#
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuEdit, $mnuView, $mnuMake, $mnuHelp))
#
#mnuFile
#
$mnuFile.MenuItems.AddRange(@($mnuAtom, $mnuOpen, $mnuEmp1, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuAtom
#
$mnuAtom.Shortcut = "F3"
$mnuAtom.Text = "Nu&Clear..."
$mnuAtom.Add_Click({Invoke-Atom})
#
#mnuOpen
#
$mnuOpen.Shortcut = "CtrlO"
$mnuOpen.Text = "&Open"
$mnuOpen.Add_Click($mnuOpen_Click)
#
#mnuEmp1
#
$mnuEmp1.Text = "-"
#
#mnuExit
#
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuEdit
#
$mnuEdit.menuItems.AddRange(@($mnuUndo, $mnuEmp2, $mnuCopy, $mnuPast, $mnuICut, `
$mnuEmp3, $mnuSAll))
$mnuEdit.Text = "&Edit"
#
#mnuUndo
#
$mnuUndo.Shortcut = "CtrlZ"
$mnuUndo.Text = "&Undo"
$mnuUndo.Add_Click({$txtEdit.Undo()})
#
#mnuEmp2
#
$mnuEmp2.Text = "-"
#
#mnuCopy
#
$mnuCopy.Shortcut = "CtrlC"
$mnuCopy.Text = "&Copy"
$mnuCopy.Add_Click({if ($txtEdit.SelectionLength -ge 0) {$txtEdit.Copy()}})
#
#mnuPast
#
$mnuPast.Shortcut = "CtrlV"
$mnuPast.Text = "&Paste"
$mnuPast.Add_Click({$txtEdit.Paste()})
#
#mnuICut
#
$mnuICut.Shortcut = "Del"
$mnuICut.Text = "Cut &Item"
$mnuICut.Add_Click({if ($txtEdit.SelectionLength -ge 0) {$txtEdit.Cut()}})
#
#mnuEmp3
#
$mnuEmp3.Text = "-"
#
#mnuSAll
#
$mnuSAll.Shortcut = "CtrlA"
$mnuSAll.Text = "Select &All"
$mnuSAll.Add_Click({$txtEdit.SelectAll()})
#
#mnuView
#
$mnuView.MenuItems.AddRange(@($mnuFont, $mnuEmp4, $mnuOpac, $mnuTgls))
$mnuView.Text = "&View"
#
#mnuFont
#
$mnuFont.Text = "&Font..."
$mnuFont.Add_Click($mnuFont_Click)
#
#mnuEmp4
#
$mnuEmp4.Text = "-"
#
#mnuOpac
#
$mnuOpac.MenuItems.AddRange(@($mnuOp50, $mnuOp60, $mnuOp70, $mnuOp80, $mnuOp90, $mnuOpaF))
$mnuOpac.Text = "&Opacity"
#
#mnuOp50
#
$mnuOp50.Text = "50%"
$mnuOp50.Add_Click({Set-Opacity $mnuOp50; $cur = $mnuOp50})
#
#mnuOp60
#
$mnuOp60.Text = "60%"
$mnuOp60.Add_Click({Set-Opacity $mnuOp60; $cur = $mnuOp60})
#
#mnuOp70
#
$mnuOp70.Text = "70%"
$mnuOp70.Add_Click({Set-Opacity $mnuOp70; $cur = $mnuOp70})
#
#mnuOp80
#
$mnuOp80.Text = "80%"
$mnuOp80.Add_Click({Set-Opacity $mnuOp80; $cur = $mnuOp80})
#
#mnuOp90
#
$mnuOp90.Text = "90%"
$mnuOp90.Add_Click({Set-Opacity $mnuOp90; $cur = $mnuOp90})
#
#mnuOpaF
#
$cur = $mnuOpaF #checked item by default
$mnuOpaF.Checked = $true
$mnuOpaF.Text = "Opaque"
$mnuOpaF.Add_Click($mnuOpaF_Click)
#
#mnuTgls
#
$mnuTgls.MenuItems.AddRange(@($mnuWrap, $mnuToS1, $mnuToS2))
$mnuTgls.Text = "&Toggles"
#
#mnuWrap
#
$mnuWrap.Checked = $true
$mnuWrap.Shortcut = "CtrlW"
$mnuWrap.Text = "&Wrap Mode"
$mnuWrap.Add_Click($mnuWrap_Click)
#
#mnuToS1
#
$mnuToS1.Checked = $true
$mnuToS1.Text = "Building &Progress"
$mnuToS1.Add_Click({Show-Panel $mnuToS1 $scSplt1})
#
#mnuToS2
#
$mnuToS2.Checked = $true
$mnuToS2.Shortcut = "F12"
$mnuToS2.Text = "Building P&roperties"
$mnuToS2.Add_Click({Show-Panel $mnuToS2 $scSplt2})
#
#mnuMake
#
$mnuMake.MenuItems.AddRange(@($mnuBAsm, $mnuBnRA))
$mnuMake.Text = "&Build"
#
#mnuBAsm
#
$mnuBAsm.Shortcut = "F5"
$mnuBAsm.Text = "&Compile"
$mnuBAsm.Add_Click({Invoke-Builder})
#
#mnuBnRA
#
$mnuBnRA.Shortcut = "F9"
$mnuBnRA.Text = "Compile And &Run"
$mnuBnRA.Add_Click({Start-AfterBuilding})
#
#mnuHelp
#
$mnuHelp.MenuItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#tbTools
#
$tbTools.Buttons.AddRange(@($btnAtom, $btnToS1, $btnMake, $btnBAsm, $btnBnRA, $btnExit))
$tbTools.ImageList = $imgList
$tbTools.Add_ButtonClick($tbTools_ButtonClick)
#
#btnAtom
#
$btnAtom.ImageIndex = 0
$btnAtom.Tag = "Atom"
$btnAtom.ToolTipText = "NuClear (F3)"
#
#btnToS1
#
$btnToS1.ImageIndex = 1
$btnToS1.Tag = "Progress"
$btnToS1.ToolTipText = "Building Progress Panel"
#
#btnMake
#
$btnMake.ImageIndex = 2
$btnMake.Tag = "Params"
$btnMake.ToolTipText = "Building Properties (F12)"
#
#btnBAsm
#
$btnBAsm.ImageIndex = 3
$btnBAsm.Tag = "Build"
$btnBAsm.ToolTipText = "Compile (F5)"
#
#btnBnRA
#
$btnBnRA.ImageIndex = 4
$btnBnRA.Tag = "BuildEx"
$btnBnRA.ToolTipText = "Compile And Run (F9)"
#
#btnExit
#
$btnExit.ImageIndex = 5
$btnExit.Tag = "Exit"
$btnExit.ToolTipText = "Exit (Ctrl+X)"
#
#scSplt1
#
$scSplt1.Anchor = "Left, Top, Right, Bottom"
$scSplt1.Location = New-Object Drawing.Point(0, 28)
$scSplt1.Orientation = "Horizontal"
$scSplt1.Panel1.Controls.Add($scSplt2)
$scSplt1.Panel2.Controls.Add($lstView)
$scSplt1.Size = New-Object Drawing.Size(790, 500)
$scSplt1.SplitterDistance = 410
$scSplt1.SplitterWidth = 1
#
#scSplt2
#
$scSplt2.Dock = "Fill"
$scSplt2.Panel1.Controls.Add($txtEdit)
$scSplt2.Panel2.Controls.Add($gboMake)
$scSplt2.SplitterDistance = 510
$scSplt2.SplitterWidth = 1
#
#lstView
#
$lstView.Columns.AddRange(@($chPoint, $chError, $chCause))
$lstView.Dock = "Fill"
$lstView.FullRowSelect = $true
$lstView.GridLines = $true
$lstView.MultiSelect = $false
$lstView.ShowItemToolTips = $true
$lstView.SmallImageList = $imgList
$lstView.View = "Details"
#
#chPoint
#
$chPoint.Text = "Line"
$chPoint.Width = 50
#
#chError
#
$chError.Text = "Error"
$chError.TextAlign = "Right"
$chError.Width = 65
#
#chCause
#
$chCause.Text = "Description"
$chCause.Width = 650
#
#txtEdit
#
$txtEdit.AcceptsTab = $true
$txtEdit.Dock = "Fill"
$txtEdit.Font = New-Object Drawing.Font("Courier New", 10)
$txtEdit.ScrollBars = "Both"
$txtEdit.Add_Click({Write-CursorPoint})
$txtEdit.Add_KeyUp({Write-CursorPoint})
$txtEdit.Add_TextChanged({Write-CursorPoint})
#
#gboMake
#
$gboMake.Controls.AddRange(@($lblLab1, $cboPlat, $chkExec, $chkWApp, $chkIDbg, `
$chkIMem, $lblLab2, $txtIOut, $lblLab3, $lboRefs))
$gboMake.Dock = "Fill"
$gboMake.Text = "Building Parameters"
#
#lblLab1
#
$lblLab1.Location = New-Object Drawing.Point(21, 33)
$lblLab1.Text = "Platform:"
$lblLab1.Width = 50
#
#cboPlat
#
$cboPlat.Anchor = "Left, Top, Right"
$cboPlat.Items.AddRange(@(".NET Framework 2.0", ".NET Framework 3.5"))
$cboPlat.Location = New-Object Drawing.Point(71, 30)
$cboPlat.SelectedItem = ".NET Framework 2.0"
$cboPlat.Width = 180
$cboPlat.Add_SelectedIndexChanged($cboPlat_SelectedIndexChanged)
#
#chkExec
#
$chkExec.Checked = $true
$chkExec.Location = New-Object Drawing.Point(23, 63)
$chkExec.Text = "Create Executable"
$chkExec.Width = 120
$chkExec.Add_Click($chkExec_Click)
#
#chkWApp
#
$chkWApp.Location = New-Object Drawing.Point(43, 83)
$chkWApp.Text = "Windows Application"
$chkWApp.Width = 130
$chkWApp.Add_Click($chkWApp_Click)
#
#chkIDbg
#
$chkIDbg.Checked = $true
$chkIDbg.Location = New-Object Drawing.Point(23, 103)
$chkIDbg.Text = "Include Debug Information"
$chkIDbg.Width = 157
#
#chkIMem
#
$chkIMem.Enabled = $false
$chkIMem.Location = New-Object Drawing.Point(23, 123)
$chkIMem.Text = "Building In Memory"
$chkIMem.Width = 130
#
#lblLab2
#
$lblLab2.Location = New-Object Drawing.Point(23, 163)
$lblLab2.Text = "Output:"
$lblLab2.Width = 45
#
#txtIOut
#
$txtIOut.Anchor = "Left, Top, Right"
$txtIOut.Location = New-Object Drawing.Point(71, 160)
$txtIOut.Width = 180
#
#lblLab3
#
$lblLab3.Location = New-Object Drawing.Point(23, 203)
$lblLab3.Size = New-Object Drawing.Size(70, 17)
$lblLab3.Text = "References:"
#
#lboRefs
#
$lboRefs.Anchor = "Left, Top, Right, Bottom"
$lboRefs.ContextMenu = $mnuRefs
$lboRefs.Location = New-Object Drawing.Point(23, 223)
$lboRefs.SelectionMode = "One"
$lboRefs.Size = New-Object Drawing.Size(229, 157)
#
#sbPanle
#
$sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2))
$sbPanel.ShowPanels = $true
$sbPanel.SizingGrip = $false
#
#sbPnl_1
#
$sbPnl_1.AutoSize = "Spring"
#
#sbPnl_2
#
$sbPnl_2.Alignment = "Center"
$sbPnl_2.AutoSize = "Contents"
#
#imgList
#
$i_1, $i_2, $i_3, $i_4, $i_5, $i_6, $i_7, $i_8 | % { $imgList.Images.Add((Get-Image $_)) }
#
#mnuRefs
#
$mnuRefs.MenuItems.AddRange(@($mnuIMov, $mnuICnM, $mnuIBuf, $mnuIIns))
#
#mnuIMov
#
$mnuIMov.Shortcut = "Del"
$mnuIMov.Text = "Remove Item"
$mnuIMov.Add_Click({$lboRefs.Items.Remove($lboRefs.SelectedItem)})
#
#mnuICnM
#
$mnuICnM.Shortcut = "CtrlM"
$mnuICnM.Text = "Copy And Remove"
$mnuICnM.Add_Click($mnuICnM_Click)
#
#mnuIBuf
#
$mnuIBuf.Text = "Insert Copied..."
$mnuIBuf.Add_Click({if ($script:buff -ne $null) {$lboRefs.Items.Add($script:buff)}})
#
#mnuIIns
#
$mnuIIns.Shortcut = "CtrlR"
$mnuIIns.Text = "Add Reference"
$mnuIIns.Add_Click($mnuIIns_Click)
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(790, 550)
$frmMain.Controls.AddRange(@($tbTools, $scSplt1, $sbPanel))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Snippet Compiler"
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
##################################################################################################
function frmInfo_Show {
$frmInfo = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Point(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "Snippet Compiler v2.54"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2012-2013 greg zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmInfo
#
$frmInfo.AcceptButton = $btnExit
$frmInfo.CancelButton = $btnExit
$frmInfo.ClientSize = New-Object Drawing.Size(350, 110)
$frmInfo.ControlBox = $false
$frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmInfo.ShowInTaskBar = $false
$frmInfo.StartPosition = "CenterScreen"
$frmInfo.Text = "About..."
$frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()})
[void]$frmInfo.ShowDialog()
}
##################################################################################################
function Invoke-Atom {
if ($txtEdit.Text -ne "") {
$res = [Windows.Forms.MessageBox]::Show("Do you want to save data before?", `
$frmMain.Text, [Windows.Forms.MessageBoxButtons]::YesNoCancel, `
[Windows.Forms.MessageBoxIcon]::Question)
switch ($res) {
'Yes' {
(New-Object Windows.Forms.SaveFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
Out-File $_.FileName -enc UTF8 -input $txtEdit.Text
}
}
break
}
'No' { $txtEdit.Clear(); break }
'Cancel' { return }
}
}#if
}
function Set-Opacity($obj) {
$cur.Checked = $false
$frmMain.Opacity = [float]('.' + $($obj.Text)[0])
$obj.Checked = $true
}
function Show-Panel($obj1, $obj2) {
switch ($obj1.Checked) {
$true {$obj1.Checked = $false; $obj2.Panel2Collapsed = $true; break }
$false {$obj1.Checked = $true; $obj2.Panel2Collapsed = $false; break }
}
}
function Get-CursorPoint {
$z = $txtEdit.SelectionStart
$y = $txtEdit.GetLineFromCharIndex($z) + 1
$x = $z - $txtEdit.GetFirstCharIndexOfCurrentLine()
return (New-Object Drawing.Point($x, $y))
}
function Write-CursorPoint {
$sbPnl_2.Text = 'Str: ' + (Get-CursorPoint).Y.ToString() + ', Col: ' + `
(Get-CursorPoint).X.ToString()
}
function Invoke-Builder {
$lstView.Items.Clear()
if ($txtEdit.Text -ne "") {
switch ($cboPlat.SelectedIndex) {
"0" { $cscp = New-Object Microsoft.CSharp.CSharpCodeProvider; break }
"1" { $cscp = New-Object Microsoft.CSharp.CSharpCodeProvider($dict); break}
}
$cdcp.GenerateExecutable = $chkExec.Checked
if ($chkWApp.Checked) { $cdcp.CompilerOptions = "/t:winexe" }
$cdcp.IncludeDebugInformation = $chkIDbg.Checked
$cdcp.GenerateInMemory = $chkIMem.Checked
if ($lboRefs.Items.Count -ne 0) {
for ($i = 0; $i -lt $lboRefs.Items.Count; $i++) {
$cdcp.ReferencedAssemblies.Add($lboRefs.Items[$i].ToString())
}
}
$cdcp.WarningLevel = 3
$cdcp.OutputAssembly = $txtIOut.Text
$script:make = $cscp.CompileAssemblyFromSource($cdcp, $txtEdit.Text)
$make.Errors | % {
if ($_.Line -ne 0 -and $_.Column -ne 0) {
$err = $_.Line.ToString() + ', ' + ($_.Column - 1).ToString()
}
elseif ($_.Line -ne 0 -and $_.Column -eq 0) {
$err = $_.Line.ToString() + ', 0'
}
elseif ($_.Line -eq 0 -and $_.Column -eq 0) {
$err = '*'
}
if (!($_.IsWarning)) {
$lstView.ForeColor = [Drawing.Color]::Crimson
$itm = $lstView.Items.Add($err, 6)
}
else {
$lstView.ForeColor = [Drawing.Color]::Gray
$itm = $lstView.Items.Add($err, 7)
}
$itm.SubItems.Add($_.ErrorNumber)
$itm.SubItems.Add($_.ErrorText)
}
}#if
}
function Start-AfterBuilding {
Invoke-Builder
if ($script:make.Errors.Count -eq 0) { Invoke-Item $txtIOut.Text }
}
function Get-Image($img) {
[Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = `
[Convert]::FromBase64String($img)), 0, $$.Length)))
}
##################################################################################################
#
#do not modify or remove this because these are images for toolbar and lower panel
#
$i_1 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAARCAIAAACNaGH2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAVFJREFUOE91kTGOgzAQRc2ZOA" + `
"s9lU+Uxj1lak7hMtJKVCjalSIZkpiEVbSN980Y2GijjEaDgTff3+PiNs/GmJQKKk+txuhboR9TsX7kCd22rXP" + `
"eeU/d7/eydr5pGuput6NO8yx5n810/4Z7vMT1kUjrCJod9G2h3XvaOp8ScqW1St8iTt5qW1dVVV3XpXXxHoVm" + `
"r3+0ejCDhveiTYPQcYqcbKN/wof+ddCkXyLhJE5XodFGjAaffIaeE21aVjqODCvTWYzd+75nXcqroATu4zSaG" + `
"Ee0IWjw3mbHzEE75UtusJwS+hIHxgkkB1KIPBwOyHddt/aIk8s1LDQc9KtpvWIJJij0+XzievOkqHi11ujdO7" + `
"Q336J9PgnNfW2j5ffz4NYJim+hx/EL7U0Dx8veG7hOcBw+heaU2GIvar7kvNYqiTATFDqE418Ox6A55AySz8A" + `
"v1EEhBG84RKcAAAAASUVORK5CYII="
$i_2 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAARCAIAAABfOGuuAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAOVJREFUOE+VkUEOgyAQRfFMnM" + `
"NrzJ3Yu3TtKTiEaVOTFgICXXQ3nQG1xjapkOEzII8vQ5OeSQiB1IVoysBZGZY5Yp4vi7QNBWFKoVJ6U8g5Kaw" + `
"qQUuFrMCaUlwxjeoQfBbBHFtCZxEWV0wDMd8mbMj71iiGGYvRE/A63SRAiI6xYRiIwnNNyoxRL27nKPpPCCFj" + `
"1W6MzabOTcIcDGN93+dX+h9aa7obY94/6iopwfs7Y13XVZRkwdxUdzcA527Cu6nWjTFrr3VuEqy9MEZuVB96R" + `
"9ZfSdu2n3XImDHjFtaM+9h/OuRvranSBDuoeeYAAAAASUVORK5CYII="
$i_3 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAIAAACUZLgLAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAWJJREFUOE+FkTFywjAQRcUROI" + `
"sqWnpKeirVHIFD0OwdqDnFnsANZiZFEguwncad8tYCm2Bmovksa3nffq08a38aN13psTXLyeM5/7MJ9kdtoyK" + `
"qBFbY7/fE3W4nIRyPR1EJGsxpiqUk2+02pWDSe1QNEjwtIA1r2muvS1ZZljQGoGJgLFGP2PTiKTPMOgiFmg9H" + `
"UWYWi0UPBFWv4pO4EaubyCyiSTUxTeL0wXOkzWaD53K5BOjlcPJIPIjjhw8M09MYhi5E8tVqxcG8d/P5nLher" + `
"/vXhri6/sKk67oYIzdBJKcNRZgAYEtBXX8iEh8MGTGqn9fhcOBURVHQCNuMAWS52816vDA81l0C0GQz40zZs0" + `
"bMvqYoQE6Yl0gO7EN4xa7Xj6lbtjI3bjglDkmZ6XKXG7DBLZsMhpBvsBjPb93G2Xq3SzyjGEtTdXZg3DsvmJv" + `
"4nOTHvF6xqjr9r+9TlfUo/gXNq15sSG6qYQAAAABJRU5ErkJggg=="
$i_4 = "iVBORw0KGgoAAAANSUhEUgAAABQAAAARCAIAAABSJhvpAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAARRJREFUOE9tklFuxCAMROH+J9" + `
"jTNU1VabUQAmT/qc3AwNJYoyQEPzwYbH5fthRTo1iLN4a26LD0oYyRhFkNga8rQ/JdlR8PUzSMfEA1M6kkrUt" + `
"+yaDRzKuw8sDmGJWuPGBWa1uoldXmPwvNpsL5zDmIWA01p2ezQF8pB2jAUmR2C8NYAlMIkgqndMQURFgY+8ST" + `
"/LLtqMghYINnz51p3eIW2PkBx+hifLFb7DDOic7nY0vpJRLKANavGkhiKrq92B7weT6p5WB6WWXZsI98Dmbny" + `
"zktV20UC+H3rGLP6B+GedXYf0EgQ1j4eW+8WMuGSSrs/c/h90W3Bb3fq7679ntY1loKyp8b2LltkXfbrGn2y7" + `
"lZ2x9XMW8UGH69+AAAAABJRU5ErkJggg=="
$i_5 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAIAAACUZLgLAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAhNJREFUOE9jfPPyBgMZAKgNju" + `
"o2nlWtXqVVtQpOAhnIKGDqbohiBmQ9fXuv77rzbsOdtxC08dY7NLTu0tvgaXtQtOk3rQcq7Tv5BEheePFx4rm" + `
"X7SefQ1DrcRC7+9TLxVdfuEzdiaIN6IAZpx/V7r0F1Pbr77/7H382HH9eeugpEBXvA6GmA89699/OX3ISRVve" + `
"irNAPambrhXvubPzwXugznOvvmYffJq0/SEQxa+/V7ntYeHasyh+q1x3unLzhYTV53wWnw1afSVpx929jz8Bd" + `
"a66+8Fu8W3TKZd0u85FzbvqO20fijagC4Ha3OccNZ9+zGTOOasll6P2PHjx9fenn39MZ1xTaTqjUnEideYls9" + `
"aNKNqAoQx0pFbHTo2+Q0BtufsfPv3yC+i92A13gfYA9egWHMxfchFdm23Xlri5B4DarOadAAYX0HnAgHFdegP" + `
"oPL3mM5oVx8zKjhStuARUg2Jb1Kx9QTP3WE/bBwx6oMMaD98LX3sdEmnAuAIit8ZjQOd0br+I0Na27ULB4iPu" + `
"E7YA42T5hYdBi0+Y9O/3n3fmwL13Jx992nH9HRAFdZ0On30YnjZAqQRodeXyg5b1yzTKFwERMHEBkXbtLuPmg" + `
"0BkUHkE6DFgeAA9gqINmF6m7blQtfJQ/sL9+YsPAW0GxikYXYSg0mVXJ+6+DQw2FG1ADlAnWqpF40KSIro2ZC" + `
"Fi2ACR3EDpQ7cspgAAAABJRU5ErkJggg=="
$i_6 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAANCAIAAAD5fKMWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAJxJREFUKFONjEEOwyAMBMn/P5" + `
"lD1FSCENt5QLpgcA1tpaI52LtjFrk42LvvMi59r9uwwn4jJOAqwAS2llAoMCegHUsq9LWFVVAG22odADm12hS" + `
"JGyb1s8ioICgcBxudP8A620RPz/T91IZPG4m/8UI4z92AVOcH8AeaoPppfzvYQ86bgs/ysQ3U0ED1l91+hJ3i" + `
"mlLjiCsoidJzG15Z2J4gUYDWoQAAAABJRU5ErkJggg=="
$i_7 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAsZJREFUOE9FkmtIk1EYx9/nvH" + `
"u3V+dUyltIIaI5DAsiyy5SlphmCprpirnp8MWaoEikXwzayrQgzTLtQ0hN0UIssyQv1AcnQnMaXlIzTDOsvG7" + `
"OnG7qTmdq+vBwLpzf/znP4fwBY0z9D6O+k6qpdlha5lOwsri4zDI2eSqz/4DQyWmLoYiAhNlg+JsQjzkOFxXh" + `
"ykpcUYELCnBGBo6Onj1xfH5iYgOzV9+gLafDcGoqVqlwYSHOzcUKBU5JsWd8PA4NnQvY211fty2Yi47CERE2i" + `
"eRDerotONjm7W1xdV11d1/192+NicFBQSaxWO/jM/Fz3H7DtE5nDgzEISHNKtXIzExTVtYUwC+A3wBPpFL96K" + `
"g2O9vg5TXg6VkadtIuGEpKMPj62vz8Rjhu1mIxLi015+aOATy7cvWP0UiIaaXyh0jU6eKicXXt7+ulevcFjnl" + `
"4kBqTLNsnkxms1sWVlX6t1mQ2E3qc477weH1CYZujY4ODw7VMJdW+c0ePs/N3F5dhgaAfoFuWvGyzEXQN428K" + `
"hQ5AzzA6gaCVz28QCKRxsVSrl6eWZT+zbA+f3wVQl5NjXSMwJqI2tbodoJ2mP/J4r2i6imEuno+img4famSYN" + `
"ob5hFCJXD41P0/oSY1mBeMFq/VldnYLQANCGoTu03RSQhzVVVJcw+O9BXisVE6uv7KP494BdHCcaXXVZLHU5+" + `
"VVkVOaTqbp/PyblMlorBYKNQCNEgmp2p2W9hrgDUJkbJHLib41MfEBwD2EgtzchgYH7D/dUV5WjlAZQK1Y/By" + `
"gmiRClQBPAaoCAu4C5CMUSdPy5Eub1iDTe7W6mHQJUAJQShoAeAhAtvkAKoBYhI4dPTK/3vCm+ciq/lHJDZHo" + `
"DkK3AW6tcyQzETrIspFnw41Gw7aXtpw4/HXwuuyyNFB8YZfXOU+PkD27w8+cqq19sbBg2mL+AY/qjcgixtNMA" + `
"AAAAElFTkSuQmCC"
$i_8 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAAABGdBTUEAALGPC/xhBQAAAglJREFUKFN1jktoE" + `
"1EUhufMTCbJNNNFS01xZ9GFCCIYhBYUF1XR7nygSxvRVSS6kbQoEoklYggUiuJj300NkRpsXdqNZhHRpp1ETW" + `
"LSdJJ08piZmFGbx3EmDdoUvfxc/vvf/3wcArtPsXir2bBUq+bZ2Vc7vrQnsT1S1ZKYB0Rbq8F5vSM8n9wx0NU" + `
"uCK6axCCy2ByURMbhmPlvW1XLxQy5keu96aAWFqxYZ+65j6XT69sH/rILmQlVNLjdrBn2HRiyYbO/+M3k8wX+" + `
"0VZrlQ2exp/c00cMRx4ZGz6E2NeSmTuu0UpF+TPQYeeTt6spAypsOgZDg+efePejQuMPq7DM+v3BrrZak3IRQ" + `
"73QgwKJMowcvLwU6kcBUB1orFOuGyclqYPX2YWEW4pSKFowDViGC2eGy3FK9zlTq9SXCfdMT7/cwhP6xmFjY4" + `
"3DFI0JwAyEnlkxC7r/Cvh9dzNJTzpPyW08kefvKhEasxzGAD+DEqPck8Z3QbNejQOmTCjuyi6x/jaeyL811WM" + `
"s8hSuAPLwYIKxGPeeOHwa10BPooD5gUaUctrHZFkhsm/gV4Ta/EBqqn8kl+eNo7aj4cDVehQ64Se69p5afL5n" + `
"5vFr4st878ocuToHW4oHQFiERBBWX3QSLcyESNe142fPTRGKrDiv++zjnivj93XZNeNp35pvJ7o8Fy89LJWk3" + `
"9PM0i5eafwSAAAAAElFTkSuQmCC"
##################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/New-Struct 3.ps1
|
New-Struct 3.ps1
|
function New-Struct {
#.Synopsis
# Creates Struct types from a list of types and properties
#.Description
# A wrapper for Add-Type to create struct types.
#.Example
# New-Struct Song {
# [string]$Artist
# [string]$Album
# [string]$Name
# [TimeSpan]$Length
# } -CreateConstructorFunction
#
# Description
# -----------
# Creates a "Song" type with strongly typed Artist, Album, Name, and Length properties, with a simple constructor and a constructor function
#.Example
# New-Struct @{
# >> Product = { [string]$Name; [double]$Price; }
# >> Order = { [Guid]$Id; [Product]$Product; [int]$Quantity }
# >> Customer = {
# >> [string]$FirstName
# >> [string]$LastName
# >> [int]$Age
# >> [Order[]]$OrderHistory
# >> }
# >> }
# >>
#
# Description
# -----------
# To create a series of related struct types (where one type is a property of another type), you need to use the -Types hashtable parameter set. That way, all of the types will compiled together at once, so the compiler will be able to find them all.
#
[CmdletBinding(DefaultParameterSetName="Multiple")]
param(
# The name of the TYPE you are creating. Must be unique per PowerShell session.
[ValidateScript({
if($_ -notmatch '^[a-z][a-z1-9_]*$') {
throw "'$_' is invalid. A valid name identifier must start with a letter, and contain only alpha-numeric or the underscore (_)."
}
return $true
})]
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")]
[string]$Name
,
# A Scriptblock full of "[Type]$Name" definitions to show what properties you want on your Struct type
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")]
[ScriptBlock]$Property
,
# A Hashtable in the form @{Name={Properties}} with multiple Names and Property Scriptblocks to define related structs (see example 2).
[Parameter(Position=0, Mandatory=$true, ParameterSetName = "Multiple")]
[HashTable]$Types
,
# Generate a New-StructName shortcut function for each New-Object StructName
[Alias("CTorFunction","ConstructorFunction")]
[Switch]$CreateConstructorFunction
,
# Output the defined type(s)
[Switch]$PassThru
)
begin {
if($PSCmdlet.ParameterSetName -eq "Multiple") {
$Structs = foreach($key in $Types.Keys) {
New-Object PSObject -Property @{Name=$key;Property=$Types.$key}
}
Write-Verbose ($Structs | Out-String)
$Structs | New-Struct -Passthru:$Passthru -CreateConstructorFunction:$CreateConstructorFunction
} else {
$code = "using System;`nusing System.Collections;`nusing System.Management.Automation;`n"
$function = ""
}
}
process {
if($PSCmdlet.ParameterSetName -ne "Multiple") {
$parserrors = $null
$tokens = [System.Management.Automation.PSParser]::Tokenize( $Property, [ref]$parserrors ) | Where-Object { "Newline","StatementSeparator" -notcontains $_.Type }
# CODE GENERATION MAGIKS!
$Name = $Name.ToUpper()[0] + $Name.SubString(1)
$ctor = @()
$setr = @()
$prop = @()
$parm = @()
$cast = @()
$hash = @()
$2Str = @()
$(while($tokens.Count -gt 0) {
$typeToken,$varToken,$tokens = $tokens
if($typeToken.Type -ne "Type") {
throw "Syntax error on line $($typeToken.StartLine) Column $($typeToken.Start). Missing Type. The Struct Properties block must contain only statements of the form: [Type]`$Name, see Get-Help New-Struct -Parameter Properties.`n$($typeToken | Out-String)"
} elseif($varToken.Type -ne "Variable") {
throw "Syntax error on line $($varToken.StartLine) Column $($varToken.Start). Missing Name. The Struct Properties block must contain only statements of the form: [Type]`$Name, see Get-Help New-Struct -Parameter Properties.`n$($typeToken | Out-String)"
}
$varName = $varToken.Content.ToUpper()[0] + $varToken.Content.SubString(1)
$varNameLower = $varName.ToLower()[0] + $varName.SubString(1)
try {
Write-Verbose "TypeToken: $($typeToken.Content) $varName"
if($PSVersionTable.PSVersion.Major -lt 3) {
$typeName = Invoke-Expression "[$($typeToken.Content)].FullName"
} else {
$typeName = Invoke-Expression "$($typeToken.Content).FullName"
}
} catch {
## It's probably a reference to another struct, so just put the name in
if($PSVersionTable.PSVersion.Major -lt 3) {
$typeName = $typeToken.Content
} else {
$typeName = $typeToken.Content -replace '\\[(.*)\\]','$1'
}
}
Write-Verbose "Type Name: $typeName $varName"
$prop += ' public {0} {1};' -f $typeName,$varName
$setr += ' {0} = {1};' -f $varName,$varNameLower
$ctor += '{0} {1}' -f $typeName,$varNameLower
$cast += ' if(input.Properties["{0}"] != null){{ output.{0} = ({1})input.Properties["{0}"].Value; }}' -f $varName,$typeName
$hash += ' if(hash.ContainsKey("{0}")){{ output.{0} = ({1})hash["{0}"]; }}' -f $varName,$typeName
$2Str += '"{0} = [{1}]\\"" + {0}.ToString() + "\\""' -f $varName, $typeName
if($CreateConstructorFunction) {
$parm += '[{0}]${1}' -f $typeName,$varName
}
})
$code += @"
public struct $Name {
$($prop -join "`n")
public $Name ($( $ctor -join ","))
{
$($setr -join "`n")
}
public static implicit operator $Name(Hashtable hash)
{
$Name output = new $Name();
$($hash -join "`n")
return output;
}
public static implicit operator $Name(PSObject input)
{
$Name output = new $Name();
$($cast -join "`n")
return output;
}
public override string ToString()
{
return "@{" + $($2Str -join ' + "; " + ') + "}";
}
}
"@
if($CreateConstructorFunction) {
$function += @"
Function global:New-$Name {
[CmdletBinding()]
param(
$( $parm -join ",`n" )
)
New-Object $Name -Property `$PSBoundParameters
}
"@
}
}}
end {
if($PSCmdlet.ParameterSetName -ne "Multiple") {
Write-Verbose "C# Code:`n$code"
Write-Verbose "PowerShell Code:`n$function"
Add-Type -TypeDefinition $code -PassThru:$Passthru -ErrorAction Stop
if($CreateConstructorFunction) {
Invoke-Expression $function
}
}}}
|
PowerShellCorpus/PoshCode/Test-IsAdmin.ps1
|
Test-IsAdmin.ps1
|
Function Test-IsAdmin
{
<#
.SYNOPSIS
Function used to detect if current user is an Administrator.
.DESCRIPTION
Function used to detect if current user is an Administrator. Presents a menu if not an Administrator
.NOTES
Name: Test-IsAdmin
Author: Boe Prox
DateCreated: 30April2011
.EXAMPLE
Test-IsAdmin
Description
-----------
Command will check the current user to see if an Administrator. If not, a menu is presented to the user to either
continue as the current user context or enter alternate credentials to use. If alternate credentials are used, then
the [System.Management.Automation.PSCredential] object is returned by the function.
#>
[cmdletbinding()]
Param()
Write-Verbose "Checking to see if current user context is Administrator"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You are not currently running this under an Administrator account! `nThere is potential that this command could fail if not running under an Administrator account."
Write-Verbose "Presenting option for user to pick whether to continue as current user or use alternate credentials"
#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription[]] @("Use &Alternate Credentials","&Continue with current Credentials")
#Determine Default Selection
[int]$default = 0
#Present choice option to user
$userchoice = $host.ui.PromptforChoice("Warning","Please select to use Alternate Credentials or current credentials to run command",$choice,$default)
Write-Debug "Selection: $userchoice"
#Determine action to take
Switch ($Userchoice)
{
0
{
#Prompt for alternate credentials
Write-Verbose "Prompting for Alternate Credentials"
$Credential = Get-Credential
Write-Output $Credential
}
1
{
#Continue using current credentials
Write-Verbose "Using current credentials"
Write-Output "CurrentUser"
}
}
}
Else
{
Write-Verbose "Passed Administrator check"
}
}
|
PowerShellCorpus/PoshCode/New-StoredProcFunction_3.ps1
|
New-StoredProcFunction_3.ps1
|
# New-StoredProcFunction.ps1
# Steven Murawski
# http://blog.usepowershell.com
# 04/08/2009
# Replaced the parsing of the stored procedure text and use Information_Schema.Parameters to get the parameter information
# Thanks to Chad Miller for the idea.
# Example: ./New-StoredProcFunction.ps1 'Data Source=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123' sp_createnewcustomer
# Example 'sp_createnewcustomer | ./New-StoredProcFunction.ps1 'Data Source=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123'
param($ConnectionString, [String[]]$StoredProc= $null)
BEGIN
{
if ($StoredProc.count -gt 0)
{
$StoredProc | ./New-StoredProcFunction $ConnectionString
}
function Invoke-SQLQuery()
{
param ($ConnectionString, $Query)
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand $query,$connection
$connection.Open()
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
[void] $adapter.Fill($dataSet)
$connection.Close()
$dataSet.Tables | ForEach-Object {$_.Rows}
}
function Get-FunctionParameter()
{
param($FunctionName, $ConnectionString)
$query = @"
SELECT parameter_Name, data_type, character_maximum_length, parameter_mode
FROM INFORMATION_SCHEMA.Parameters
WHERE specific_NAME LIKE '$FunctionName'
"@
$Rows = Invoke-SQLQuery $ConnectionString $Query
foreach ($Row in $Rows)
{
$Parameter = "" | Select-Object Name, DataType, Length, IsOutput
$Parameter.Name = $row.parameter_Name
$Parameter.DataType = $Row.data_type
$Parameter.Length = $Row.character_maximum_length
$Parameter.IsOutput = if ($Row.parameter_mode -eq 'INOUT'){$true} else {$false}
$Parameter
}
}
}
PROCESS
{
if ($_ -ne $null)
{
$FunctionName = $_
$Parameters = Get-FunctionParameter $FunctionName $ConnectionString
[String[]]$InputParamNames = $Parameters | where {-not $_.IsOutput} | ForEach-Object {$_.Name -replace '@' }
[String[]]$OutputParameterNames = $Parameters | Where-Object {$_.IsOutput} | ForEach-Object {$_.Name -replace '@'}
$ScriptText = ' '
if ($InputParamNames.count -gt 0)
{
$OFS = ', $'
$ScriptText += 'param (${0})' -f $InputParamNames
$ScriptText += "`n"
$OFS = ', '
}
$BodyTemplate = @'
$connection = New-Object System.Data.SqlClient.SqlConnection('{0}')
$command = New-Object System.Data.SqlClient.SqlCommand('{1}', $connection)
$command.CommandType = [System.Data.CommandType]::StoredProcedure
'@
$ScriptText += $BodyTemplate -f $ConnectionString, $FunctionName
if ( ($Parameters -ne $null) -or ($Parameters.count -gt 1) )
{
if ($OutputParameterNames.count -gt 0)
{
$ReturnText = ""
$CommandOutput = "" | select $OutputParameterNames
}
#Add the parameters
foreach ($param in $Parameters)
{
if ($param.length -isnot [DBNull])
{
$ParamTemplate = '$command.Parameters.Add("{0}", "{1}", {2}) | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $param.datatype, $param.length
}
else
{
$ParamTemplate = '$command.Parameters.Add("{0}", "{1}") | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $param.datatype
}
if ($param.IsOutput)
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["{0}"].Direction = [System.Data.ParameterDirection]::Output ' -f $param.Name
$ReturnText += "`n"
$ReturnText += '$CommandOutput.{1} = $command.Parameters["{0}"].Value' -f $param.name, ($param.name -replace '@')
}
else
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["{0}"].Value = ${1} ' -f $param.name, ($param.name -replace '@')
}
}
}
$ScriptText += "`n"
$ScriptText += @'
$connection.Open() | out-null
$command.ExecuteNonQuery() | out-null
'@
if ($OutputParameterNames.count -gt 0)
{
$ScriptText += $ReturnText
}
$ScriptText += @'
$connection.Close() | out-null
return $CommandOutput
'@
#$ScriptText
Set-Item -Path function:global:$FunctionName -Value $scripttext
}
}
|
PowerShellCorpus/PoshCode/Resolve-Aliases _1.7.ps1
|
Resolve-Aliases _1.7.ps1
|
#requires -version 2.0
## ResolveAliases Module v 1.6
########################################################################################################################
## Sample Use:
## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1
## ls *.ps1 | Resolve-Aliases -Inplace
########################################################################################################################
## Version History
## 1.0 - First Version. "It worked on my sample script"
## 1.1 - Now it parses the $(...) blocks inside strings
## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts)
## 1.3 - I went back to processing the whole script at once (instead of a line at a time)
## Processing a line at a time makes it impossible to handle Here-Strings...
## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it
## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is
## 1.4 - Now resolves parameters too
## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem)
## - Refactored the Resolve-Line filter right out of existence
## - Created a test script for validation, and
## 1.6 - Added resolving parameter ALIASES instead of just short-forms
## 1.7 - Minor tweak to make it work in CTP3
##
## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path
## * *TODO:* Add an option to put #requires statements at the top for each snapin used
########################################################################################################################
function which {
PARAM( [string]$command )
# aliases, functions, cmdlets, scripts, executables, normal files
$cmds = @(Get-Command $command -EA "SilentlyContinue")
if($cmds.Count -gt 1) {
$cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0]
} else {
$cmd = $cmds[0]
}
if(!$cmd) {
$cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0]
}
if( $cmd.CommandType -eq "Alias" ) {
$cmd = which $cmd.Definition
}
return $cmd
}
function Resolve-Aliases
{
[CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")]
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")]
[string]$Line
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")]
[Alias("FullName","PSChildName","PSPath")]
[IO.FileInfo]$File
,
[Parameter(Position=1, ParameterSetName="Files")]
[Switch]$InPlace
)
BEGIN {
Write-Debug $PSCmdlet.ParameterSetName
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "Files") {
if($File -is [System.IO.FileInfo]){
$Line = ((Get-Content $File) -join "`n")
} else {
throw "We can't resolve a whole folder at once yet"
}
}
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null)
for($t = $Tokens.Count; $t -ge 0; $t--) {
$token = $Tokens[$t]
# DEBUG $token | fl * | out-host
switch($token.Type) {
"Command" {
$cmd = which $token.Content
Write-Debug "Command $($token.Content) => $($cmd.Name)"
#if($cmd.CommandType -eq "Alias") {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name )
#}
}
"CommandParameter" {
Write-Debug "Parameter $($token.Content)"
for($c = $t; $c -ge 0; $c--) {
if( $Tokens[$c].Type -eq "Command" ) {
$cmd = which $Tokens[$c].Content
# if($cmd.CommandType -eq "Alias") {
# $cmd = @(which $cmd.Definition)[0]
# }
$short = $token.Content -replace "^-?","^"
Write-Debug "Parameter $short"
$parameters = $cmd.ParameterSets | Select -expand Parameters
$param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique)
if($param.Count -eq 1) {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" )
}
break
}
}
}
}
}
switch($PSCmdlet.ParameterSetName) {
"Text" {
$Line
}
"Files" {
switch($File.GetType()) {
"System.IO.FileInfo" {
if($InPlace) {
$Line | Set-Content $File
} else {
$Line
}
}
default { throw "We can't resolve a whole folder at once yet" }
}
}
default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" }
}
}
}
|
PowerShellCorpus/PoshCode/Remove-MyOldComputers.ps1
|
Remove-MyOldComputers.ps1
|
##
# Remove-MyOldComputers.ps1
#
# Makes certian assumptions about your computers naming scheme: mainly that all your
# computers are named as follows: {username}* I.E. bob1, bob-test, bob-server, etc
#
##
param (
[String] $Name=((whoami).Split('\\')[1]),
[Int32] $MaxDaysOld=20
)
$root = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(Name=$Name*)"
$computers = $searcher.findall()
$computers | % {
$Comp = [ADSI]$_.Path
$LastChange = [DateTime]::Now - [DateTime][String]$Comp.WhenChanged
if ($LastChange.TotalDays -gt $MaxDaysOld) {
Write-Host Deleting $Comp.Name [$LastChangeTimeSpan.TotalDays days old]
$Comp.psbase.DeleteTree()
}
}
|
PowerShellCorpus/PoshCode/Add new smtp_set prmary_2.ps1
|
Add new smtp_set prmary_2.ps1
|
#alias,addnewemailaddress
import-csv .\\source.csv | foreach {
$user = Get-Mailbox $_.alias
$user.emailAddresses+= $_.addnewemailaddress
$user.primarysmtpaddress = $_.addnewemailaddress
Set-Mailbox $user -emailAddresses $user.emailAddresses
set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress
}
|
PowerShellCorpus/PoshCode/Compare-Drive_1.ps1
|
Compare-Drive_1.ps1
|
param($ComputerName1,$ComputerName2)
$a = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName1 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}}
$b = gwmi win32_volume -filter "DriveType=3" -computername $ComputerName2 | where {@('Y:','Z:') -notcontains $_.DriveLetter} | select name, @{n='capacity'; e={[math]::truncate($_.Capacity/1GB)}}
Compare-Object -ReferenceObject $a -DifferenceObject $b -Property name,capacity -PassThru |
select-object name, @{n='ComputerName1';e={$ComputerName1}}, @{n='ComputerName2';e={$ComputerName2}},
@{n='Capacity1';e={$name = $_.name; $drive = $a | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }},
@{n='Capacity2';e={$name = $_.name; $drive = $b | ? { $_.name -eq $name }; if ($drive.capacity) {$drive.capacity} else {0} }} |
Sort-Object -Property name -Unique
#get-content .\\serverpairs.txt | %{$servers = $_ -split ','; .\\compare-drive.ps1 $servers[0] $servers[1] } | ogv
|
PowerShellCorpus/PoshCode/Send-Mapi.ps1
|
Send-Mapi.ps1
|
##############################################################################
#.AUTHOR
# Josh Einstein
# Einstein Technologies, LLC
##############################################################################
##############################################################################
#.SYNOPSIS
# Opens a new mail message window (without actually sending it) with the
# To/CC/BCC/Subject/Body pre-filled with optional values and optional file
# attachments added to the message.
#
#.DESCRIPTION
# This function uses your default email client to display a new message
# window with the specified file(s) attached and a pre-filled subject and
# message body.
#
#.PARAMETER Path
# Specifies the path to one or more attachments to add. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER To
# Specifies one or more recipients on the To line.
#
#.PARAMETER CC
# Specifies one or more recipients on the CC line.
#
#.PARAMETER BCC
# Specifies one or more recipients on the BCC line.
#
#.PARAMETER Subject
# The subject of the message.
#
#.PARAMETER Body
# The body of the message.
#
#.EXAMPLE
# Get-ChildItem C:\\temp\\*.txt | Send-MAPI -To josheinstein@hotmail.com
##############################################################################
function Send-MAPI {
[CmdletBinding(DefaultParameterSetName='Path')]
param(
[Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$Path,
[Alias("PSPath")]
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[String[]]$LiteralPath,
[Parameter()]
[String[]]$To,
[Parameter()]
[String[]]$CC,
[Parameter()]
[String[]]$BCC,
[Parameter()]
[String]$Subject,
[Parameter()]
[String]$Body
)
begin {
$Message = New-Object MAPI.Message
$Message.AddRecipient($To)
$Message.AddCC($CC)
$Message.AddBCC($BCC)
$Message.Subject = $Subject
$Message.Body = $Body
}
process {
switch ($PSCmdlet.ParameterSetName) {
Path { $ResolvedPaths = @(Resolve-Path -Path:$Path) }
LiteralPath { $ResolvedPaths = @(Resolve-Path -LiteralPath:$LiteralPath) }
}
foreach ($ResolvedPath in $ResolvedPaths) {
Write-Verbose "$($PSCmdlet.MyInvocation.MyCommand.Name) Processing $ResolvedPath"
$Message.Attachments.Add($ResolvedPath.ProviderPath)
}
}
end {
if ($Message.Attachments.Count) {
if (-not $Message.Subject) { $Message.Subject = "Emailing: $($Message.Attachments | %{ [IO.Path]::GetFileName($_) })" }
if (-not $Message.Body) {
$Message.Body = @"
Your message is ready to be sent with the following file or link attachments:
$(($Message.Attachments | %{ [IO.Path]::GetFileName($_) }) -join "`n" )
Note: To protect against computer viruses, e-mail programs may prevent sending or receiving certain types of file attachments. Check your e-mail security settings to determine how attachments are handled.
"@
}
}
$Message.Show()
}
}
Add-Type @"
// Credit goes to David M Brooks
// http://www.codeproject.com/KB/IP/SendFileToNET.aspx
using System;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Generic;
using System.Threading;
namespace MAPI
{
public sealed class Message
{
public Message() {
Attachments = new List<string>();
}
public string Subject;
public string Body;
public List<string> Attachments;
public void AddRecipient(string[] email)
{
if (email == null || email.Length == 0) return;
foreach ( string e in email) {
AddRecipient(e, HowTo.MAPI_TO);
}
}
public void AddCC(string[] email)
{
if (email == null || email.Length == 0) return;
foreach ( string e in email ) {
AddRecipient(e, HowTo.MAPI_TO);
}
}
public void AddBCC(string[] email)
{
if (email == null || email.Length == 0) return;
foreach ( string e in email ) {
AddRecipient(e, HowTo.MAPI_TO);
}
}
public void Show() {
Thread t = new Thread((ThreadStart)delegate {
SendMail(Subject, Body, MAPI_LOGON_UI | MAPI_DIALOG);
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void Send() {
Thread t = new Thread((ThreadStart)delegate {
SendMail(Subject, Body, MAPI_LOGON_UI);
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
[DllImport("MAPI32.DLL")]
static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
int SendMail(string strSubject, string strBody, int how)
{
MapiMessage msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);
if (m_lastError > 1)
throw new Exception("MAPISendMail failed! " + GetLastError());
Cleanup(ref msg);
return m_lastError;
}
bool AddRecipient(string email, HowTo howTo)
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.recipClass = (int)howTo;
recipient.name = email;
m_recipients.Add(recipient);
return true;
}
IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
int ptr = (int)intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (Attachments == null)
return IntPtr.Zero;
if ((Attachments.Count <= 0) || (Attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(Attachments.Count * size);
MapiFileDesc mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
int ptr = (int)intPtr;
foreach (string strAttachment in Attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
ptr += size;
}
fileCount = Attachments.Count;
return intPtr;
}
void Cleanup(ref MapiMessage msg)
{
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
int ptr = 0;
if (msg.recips != IntPtr.Zero)
{
ptr = (int)msg.recips;
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof(MapiFileDesc));
ptr = (int)msg.files;
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_lastError = 0;
}
public string GetLastError()
{
if (m_lastError <= 26)
return errors[ m_lastError ];
return "MAPI error [" + m_lastError.ToString() + "]";
}
readonly string[] errors = new string[] {
"OK [0]", "User abort [1]", "General MAPI failure [2]", "MAPI login failure [3]",
"Disk full [4]", "Insufficient memory [5]", "Access denied [6]", "-unknown- [7]",
"Too many sessions [8]", "Too many files were specified [9]", "Too many recipients were specified [10]", "A specified attachment was not found [11]",
"Attachment open failure [12]", "Attachment write failure [13]", "Unknown recipient [14]", "Bad recipient type [15]",
"No messages [16]", "Invalid message [17]", "Text too large [18]", "Invalid session [19]",
"Type not supported [20]", "A recipient was specified ambiguously [21]", "Message in use [22]", "Network failure [23]",
"Invalid edit fields [24]", "Invalid recipients [25]", "Not supported [26]"
};
List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
int m_lastError = 0;
const int MAPI_LOGON_UI = 0x00000001;
const int MAPI_DIALOG = 0x00000008;
const int maxAttachments = 20;
enum HowTo{MAPI_ORIG=0, MAPI_TO, MAPI_CC, MAPI_BCC};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private class MapiMessage
{
public int reserved;
public string subject;
public string noteText;
public string messageType;
public string dateReceived;
public string conversationID;
public int flags;
public IntPtr originator;
public int recipCount;
public IntPtr recips;
public int fileCount;
public IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private class MapiFileDesc
{
public int reserved;
public int flags;
public int position;
public string path;
public string name;
public IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
private class MapiRecipDesc
{
public int reserved;
public int recipClass;
public string name;
public string address;
public int eIDSize;
public IntPtr entryID;
}
}
}
"@
|
PowerShellCorpus/PoshCode/82bfeecc-3581-4dec-8684-4e98aef8a59a.ps1
|
82bfeecc-3581-4dec-8684-4e98aef8a59a.ps1
|
# Enumerate fan speeds on an ESX host that is running WSMAN.
# This doesn't take advantage of CTP3's WSMAN cmdlets.
# Needs winrm installed.
$serverName = "your.server"
$user = "root"
$password = "password"
$x = [xml](winrm enumerate `
http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor `
"-username:$user" "-password:$password" "-auth:basic" "-skipCAcheck" `
"-skipCNcheck" "-r:https://$serverName/wsman" "-format:pretty")
$pattern = "(?<ID>FAN .)"
$x.Results.OMC_NumericSensor
|
PowerShellCorpus/PoshCode/Format-Column 0.3.ps1
|
Format-Column 0.3.ps1
|
function global:Format-Column {
################################################################
#.Synopsis
# Formats incoming data to columns.
#.Description
# It works similarly as Format-Wide but it works vertically. Format-Wide outputs
# the data row by row, but Format-Columns outputs them column by column.
#.Parameter Property
# Name of property to get from the object.
# It may be
# -- string - name of property.
# -- scriptblock
# -- hashtable with keys 'Expression' (value is string=property name or scriptblock)
# and 'FormatString' (used in -f operator)
#.Parameter Column
# Number of columns to display.
#.Parameter Autosize
# Automatically calculate the number of columns to display.
#.Parameter MaxColumn
# Maximum number of columns to display if using Autosize.
#.Parameter Flow
# The direction of flow to display items.
#.Parameter InputObject
# Data to display.
#.Example
# PS> 1..150 | Format-Column -Autosize
#.Example
# PS> Format-Column -Col 3 -Input 1..130
#.Example
# PS> Get-Process | Format-Column -prop @{Expression='Handles'; FormatString='{0:00000}'} -auto
#.Example
# PS> Get-Process | Format-Column -prop {$_.Handles} -auto
#.Notes
# Name: Format-Column
# Author: stej, http://twitter.com/stejcz
# Version 0.1 - January 6, 2010 - stej
# Version 0.2 - January 14, 2010 - stej
# - ADDED parameter MaxColumn
# - FIXED displaying collection of 1 item was incorrect
# Version 0.3 - March 14, 2012 - By Jason Archer (This Version)
# - ADDED parameter Flow
################################################################
param(
[Parameter(Position=0)][Object]$Property,
[Parameter()][switch]$Autosize,
[Parameter()][int]$Column,
[Parameter()][int]$MaxColumn,
[Parameter()][ValidateSet("Horizontal","Vertical")][String]$Flow = "Horizontal",
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][Object[]]$InputObject
)
begin { [Object[]]$Values = @() }
process { $Values += $InputObject }
end {
function ProcessValues {
if ($Property -is [Hashtable]) {
$exp = $Property.Expression
if ($exp) {
if ($exp -is [string]) { $Values = $Values | % { $_.($exp) } }
elseif ($exp -is [scriptblock]) { $Values = $Values | % { & $exp $_} }
else { throw 'Invalid Expression value' }
}
if ($Property.FormatString) {
if ($Property.FormatString -is [string]) {
$Values = $Values | % { $Property.FormatString -f $_ }
} else {
throw 'Invalid format string'
}
}
}
elseif ($Property -is [scriptblock]) { $Values = $Values | % { & $Property $_} }
elseif ($Property -is [string]) { $Values = $Values | % { $_.$Property } }
elseif ($Property -ne $null) { throw 'Invalid -Property type' }
# in case there were some numbers, objects, etc., convert them to string
$Values | % { $_.ToString() }
}
function Base($i) { [Math]::Floor($i) }
function Max($i1, $i2) { [Math]::Max($i1, $i2) }
if (!$Column) { $Autosize = $true }
$Values = ProcessValues
$valuesCount = $values.Count
if ($valuesCount -eq 1) {
$Values | Out-Host
return
}
# For some reason the console host doesn't use the last column and writes to new line
$consoleWidth = $Host.UI.RawUI.MaxWindowSize.Width - 1
$spaceWidthBetweenCols = 2
# get length of the longest string
$Values | ForEach-Object -Begin { [int]$maxLength = -1 } -Process { $maxLength = Max $maxLength $_.Length }
# get count of columns if not provided
if ($Autosize) {
$Column = Max (Base ($consoleWidth/($maxLength+$spaceWidthBetweenCols))) 1
$remainingSpace = $consoleWidth - $Column*($maxLength+$spaceWidthBetweenCols);
if ($remainingSpace -ge $maxLength) {
$Column++
}
if ($MaxColumn -and $MaxColumn -lt $Column) {
Write-Debug "Columns corrected to $MaxColumn (original: $Column)"
$Column = $MaxColumn
}
}
$countOfRows = [Math]::Ceiling($valuesCount / $Column)
$maxPossibleLength = Base ($consoleWidth / $Column)
# cut too long values, considers count of columns and space between them
$Values = $Values | ForEach-Object {
if ($_.length -gt $maxPossibleLength) { $_.Remove($maxPossibleLength-2) + '..' }
else { $_ }
}
#add empty values so that the values fill rectangle (2 dim array) without space
if ($Column -gt 1) {
$Values += (@('') * ($countOfRows * $Column - $valuesCount))
}
<#
now we have values like this: 1, 2, 3, 4, 5, 6, 7, ''
#>
$formatString = (1..$Column | %{"{$($_-1),-$maxPossibleLength}"}) -join ''
1..$countOfRows | ForEach-Object {
$r = $_ - 1
if ($Flow -eq "Horizontal") {
<# Display them like this:
1 2 3 4
5 6 7 ''
#>
$line = @(1..$Column | % { $Values[($r * $Column) + ($_ - 1)]})
} else {
<# Display them like this:
1 3 5 7
2 4 6 ''
#>
$line = @(1..$Column | % { $Values[$r + ($_ - 1) * $countOfRows]})
}
$formatString -f $line | Out-Host
}
}
}
|
PowerShellCorpus/PoshCode/Script-Object.ps1
|
Script-Object.ps1
|
#Copyright (c) 2011 Justin Dearing
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
param(
[Parameter(Mandatory=$true, HelpMessage='The name of the stored procedure or user defined function to script')]
[string] $ProcedureName,
[string] $Path = "$($ProcedureName).sql",
[string] $ConnectionString = 'Data Source=.\\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;'
);
try {
[System.Data.SqlClient.SqlConnection] $cn = New-Object System.Data.SqlClient.SqlConnection (,$ConnectionString);
$cn.Open() > $null;
$cmd = $cn.CreateCommand();
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
$cmd.CommandText = 'sp_helptext';
$cmd.Parameters.AddWithValue('@objname', $ProcedureName) > $null;
[System.Data.IDataReader] $rdr = $cmd.ExecuteReader();
[string] $sproc_text = '';
while ($rdr.Read()) {
$sproc_text += $rdr[0];
}
$rdr.Close();
$sproc_text | Out-File -FilePath $Path;
}
finally {
if ($cmd -ne $null) { $cmd.Dispose(); }
if ($cn -ne $null) { $cn.Dispose(); }
}
|
PowerShellCorpus/PoshCode/ESXi Config BackupScript_1.ps1
|
ESXi Config BackupScript_1.ps1
|
###ESXi Configuration Backup Script
#DESCRIPION: This Script takes a CSV file with the hostname, username, and password of a list of ESXi servers, and backs up their configurations to a specified Destination
#USAGE: This script is meant to be run as a regular scheduled task or a pre-script for a backup job. There is no version control, so it is recommended to use an external backup program (Such as Backup Exec) to scan this.
#LAST MODIFIED: 15 Dec 2009 by JGrote <jgrote AT enpointe NOSPAMDOT-com>
#REQUIREMENTS:
#VMWare Remote CLI (Tested with 4.0U1)
### SETTINGS
#Location of the VMWare Remote CLI vicfg-cfgbackup.pl command (will be different for 32-bit systems)
$vSphereCLIPath = "C:\\Program Files (x86)\\VMware\\VMware vSphere CLI\\"
#Backup Destination Folder
$BackupDest = "E:\\Backup\\ESXi"
#Path to ESXi CSV File. APPLY STRICT PERMISSIONS TO THIS FILE SO THAT ONLY THE SCRIPTAND ADMINISTRATORS CAN READ IT!
#Format:
#1st Field - HOSTNAME - ESXi IP Address or Hostname
#2nd Field - USERNAME - Local Username (usually root)
#3rd Field - PASSWORD - Password
#
#Example:
#HOSTNAME,USERNAME,PASSWORD
#server1,root,password
#server2,root,password2
#It is recommended to create and edit this file using Excel (Save as CSV)
$ESXiCSV = "C:\\Scripts\\ESXiBackupList.csv"
### PREPARATION
#Create an ESXi Backup Event Source if it doesn't already exist
$eventsource = "Backup-ESXi"
$eventlog = "Application"
if (!(get-eventlog -logname $eventlog -source $eventsource)) {new-eventlog -logname $eventlog -source $eventsource}
#Write an error and exit the script if an exception is ever thrown
trap {write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Error" -Message "An Error occured during $($eventsource): $_ . Script run from $($MyInvocation.MyCommand.Definition)"; exit}
#Path Verification
#Verify that the following paths and files exist. If it is not there, it will throw an exception caught by the trap above that will exit the script.
#Verify:ESX Config File
$ESXiCSVIsPresentTest = Get-Item $ESXiCSV
#Verify:VMWare Remote CLI Path
$vSphereCLIISPresentTest = Get-Item $vSphereCLIPath
#Verify:Backup Destination Directory
$BackupDestIsPresentTest = Get-Item $BackupDest
### SCRIPT
#Read Each Host from the File and back up the config to the backup directory
import-csv $ESXiCSV | ForEach-Object {
$BackupResult = invoke-expression "& '$vSphereCLIPath\\perl\\bin\\perl.exe' '$vSphereCLIPath\\bin\\vicfg-cfgbackup.pl' --server $($_.HOSTNAME) --username $($_.USERNAME) --password $($_.PASSWORD) --save $($BackupDest)\\$($_.HOSTNAME)-cfgbackup.tgz"
if ($LastExitCode -ne 0) {throw "An Error occurred while executing $BackupBin for $($_.HOSTNAME): $BackupResult"}
}
#Compose and Write Success Event
$successText = "ESXi Configurations were successfully backed up to $BackupDest. Script run from $($MyInvocation.MyCommand.Definition)"
write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Information" -Message $successText
|
PowerShellCorpus/PoshCode/get-serials.ps1
|
get-serials.ps1
|
<#
.SYNOPSIS
Get the BIOS serial numbers from computers in the domain.
.DESCRIPTION
Return a list of computers with their serial numbers. For Dell computers the Win32_BIOS.SerialNumber property
is the service tag of the computer. This identifies the computer on the Dell support site, and with it you can
get the proper drivers/manuals and warranty information.
.PARAMETER ADSPath
The location within Active Directory to find computers.
.EXAMPLE
.\\get-serials.ps1 -ADSPath "LDAP://OU=workstations,DC=company,DC=com"
ComputerName ServiceTag
------------ ----------
Desktop-pc01 a1b2c3d
Desktop-pc02 b2c3d4e
Desktop-pc03 The RPC server is unavailable. (Exception from H ...
Desktop-pc04 f4g5h6i
Description
-----------
This example shows the output of the command.
.EXAMPLE
.\\get-serials.ps1 -ADSPath "LDAP://OU=workstations,DC=company,DC=com" `
| Export-Csv .\\sample.csv -NoTypeInformation
Description
-----------
This example shows piping the output to a csv file.
.NOTES
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/GetSerials
#>
Param
(
[Parameter(Mandatory=$true)]
$ADSPath
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
# Dotsource in the AD functions I need
. .\\includes\\ActiveDirectoryManagement.ps1
}
Process
{
$Workstations = Get-ADObjects -ADSPath $ADSPath
$Jobs = @()
foreach ($Workstation in $Workstations)
{
[string]$ThisWorkstation = $Workstation.Properties.name
$ThisJob = New-Object PSobject
if ($Workstation -eq $null){}
else
{
Try
{
$ErrorActionPreference = "Stop"
$Serial = Get-WmiObject -query "select SerialNumber from win32_bios" `
-computername $ThisWorkstation
$Return = $serial.serialnumber
}
Catch
{
[string]$ThisError = $Error[0].Exception
$ThisError = $ThisError.Substring($ThisError.IndexOf(":"))
$ThisError = $ThisError.Substring(1,$ThisError.IndexOf("`r"))
$return = $ThisError.Trim()
}
Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "ComputerName" `
-Value $ThisWorkstation
Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "ServiceTag" -Value $Return
}
$Jobs += $ThisJob
$ThisJob
}
$Message = [system.string]::Join("`n",($Jobs))
Write-EventLog -LogName $LogName -Source $ScriptName -EventId "101" -EntryType "Information" -Message $Message
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
}
|
PowerShellCorpus/PoshCode/bc7d5dc9-76a4-432e-ad15-2f3acae17658.ps1
|
bc7d5dc9-76a4-432e-ad15-2f3acae17658.ps1
|
param (
$UserName,
$FilePath,
[switch]$SaveCredential=$False,
[switch]$RdpSaveCredential=$False,
[switch]$DeleteCredential=$False,
[switch]$Help=$False
)
$ScriptFilenam = $MyInvocation.MyCommand.Name # ScriptFilename wo path.
$ScriptUnbArgs = $MyInvocation.UnboundArguments # UnNamed Arguments of the PowerShell Script ($Args)
$CredDir = $env:UserProfile # sotres credential files
$RdpFilenam = $env:UserProfile + "\\My Documents\\Default.rdp"
function Get-ScriptHelp {
Write-Host -ForegroundColor:White "
Usage:`t`t version 2009.10.07 ,karaszmiklos@gmail.com
$ScriptFilenam [-UserName:]UserName [[-FilePath:]program [arg1] ['arg 2'] [arg...]] [-SaveCredential] [-RdpSaveCredential] [-DeleteCredential] [-Help]
-UserName:
Required parameter! There is no default value.
1st position if parameter name is not defined.
Predefined user aliases:
SU Local Admin (SID ending with 500)
EMA Domain Admin (UserDomain\\uEMAsername)
Alias1 Default alias for context menus.
You can define aliases by runing: su AliasName -SaveCred
-FilePath:
Executable files. Default value:cmd.exe
2nd position if parameter name is not defined.
-SaveCredential
Switch parameter. Default value:$False
Force asking and saving credential into efs encrypted file.
-RdpSaveCredential
Switch parameter. Default value:$False
Force saving the specified credential into RDP profile:default.rdp
-DeleteCredential
Switch parameter. Default value:$False
Forcing deletion of the specified credential.
-Help
Switch parameter. Default value:$False
.\\ means current directory.
Use 'single quotes' for programs and arguments containing spaces.
Partial paramter names can be used while they are not ambiguous.
Examples:
su SU
su EMA
su EMA -Save
su EMA -Rdp
su EMA -Save -RdpSave
su Alias1 -SaveCred
su Alias1 -DeleteCred
su Domain\\Username cmd
powershell.exe $ScriptFilenam SU cmd.exe
su SU sc.exe stop ccmexec
powershell.exe $ScriptFilenam SU sc.exe stop ccmexec
su.bat SU 'c:\\Directory with spaces\\procexp.exe' /t /p:r -accepteula
"
}
function Export-PSCredential { #http://halr9000.com/article/531
param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" )
# Look at the object type of the $Credential parameter to determine how to handle it
switch ( $Credential.GetType().Name ) {
# It is a credential, so continue
PSCredential { continue }
# It is a string, so use that as the username and prompt for the password
String { $Credential = Get-Credential -credential:$Credential }
# In all other cases, throw an error and exit
default { Throw "You must specify a credential object to export to disk." }
}
$export = New-Object PSObject # Create temporary object to be serialized to disk
Add-Member -InputObject $export -Name:Username -Value:$Credential.Username -MemberType:NoteProperty
# Encrypt SecureString password using Data Protection API
$EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
Add-Member -InputObject:$export -Name:EncryptedPassword -Value:$EncryptedPassword -MemberType:NoteProperty
$export.PSObject.TypeNames.Insert(0,’ExportedPSCredential’) # Give object a type name which can be identified later
$export | Export-Clixml $Path # Export using the Export-Clixml cmdlet
Write-Host -foregroundcolor:Green "Credential saved to: "
Get-Item -Force $Path # Return FileInfo object referring to saved credentials
}
function Import-PSCredential { #http://halr9000.com/article/531
param ( [string]$Path = "credentials.enc.xml", [string]$CredentialVariable ) #to create a global credential with a specified name
$import = Import-Clixml $Path # Import credential file
# Test for valid import
if ( !$import.UserName -or !$import.EncryptedPassword ) {
Throw "Input is not a valid ExportedPSCredential object, exiting."
}
$Username = $import.Username
$SecurePass = $import.EncryptedPassword | ConvertTo-SecureString # Decrypt the password and store as a SecureString object for safekeeping
$PsCredential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass # Build the new credential object
if ($CredentialVariable) {
New-Variable -Name:$CredentialVariable -Scope:Global -Value:$PsCredential
} else {
return $PsCredential
}
}
if ( $Help ) {
Get-ScriptHelp
exit 0;
}
switch ($UserName) {
$null {
Write-Host -ForegroundColor:Red "UserName is not defined. Exiting..."
Get-ScriptHelp
exit 1;
}
"SU" {
$CredUsrExpr = '(Get-WmiObject -Query "SELECT * FROM Win32_Account WHERE LocalAccount = True AND SID LIKE ""S-1-5-21-%-500""").Caption'
$CredFilenam = Join-Path -Path:$CredDir -ChildPath:$($env:COMPUTERNAME+"_S-1-5-21--500")
}
"EMA" {
$CredUsrExpr = '$env:UserDomain + "\\" + $env:UserName[0] + "ema" + $env:UserName.Remove(0,1)'
$CredFilenam = Join-Path -Path:$CredDir -ChildPath:$($env:UserDomain+"_S-1-5-21--ema")
}
default {
$CredUsrExpr = '$UserName'
$CredFilenam = Join-Path -Path:$CredDir -ChildPath:$UserName.Replace("\\","_")
}
}
#Test Credential Directory
if ( -not(Test-Path $CredDir) ) {
New-Item "$CredDir" -Type:Directory -Force -Confirm -Verbose
if ( -not(Test-Path $CredDir) ) {
Write-Warning "Credential directory ""$CredDir"" doesn't exist. Exiting..."
exit 82; # 82 The directory or file cannot be created.
}
}
if ( $DeleteCredential ) {
if ( Test-Path $CredFilenam) {
Write-Host "Deleting credential:""$CredFilenam"" ..." -ForegroundColor:Yellow
Remove-Item -Path $CredFilenam -Force -Confirm -Verbose
if ( -not(Test-Path $CredFilenam) ) {
Write-Host -ForegroundColor:Green "$CredFilenam is deleted."
} else {
Write-Host -ForegroundColor:Yellow "$CredFilenam has not been deleted."
}
exit 0;
} else {
Write-Warning "Credential does not exist:$CredFilenam"
exit 2; # 2 The system cannot find the file specified.
}
}
if ( $SaveCredential -or !(Test-Path $CredFilenam) ) {
try {
$PsCred = Get-Credential -Credential:(Invoke-Expression $CredUsrExpr)
}
catch {
"$($Error[0])"
}
} else {
#Import Credential from encrypted file (if exists).
if (Test-Path $CredFilenam) {
$PsCred = Import-PSCredential -Path:"$CredFilenam"
}
}
if ( !$PsCred ) {
Write-Warning "Credential is not defined. Exiting..."
exit 1326; # 1326 Logon failure: unknown user name or bad password.
}
try {
#Setup arguments of Start-Process based on Script parameters
if ( $FilePath ) {
if ( $ScriptUnbArgs ) {
if ( ( ".exe",".com",".bat",".cmd" | Foreach-Object { $FilePath.EndsWith($_) } ) -contains $True ) {
Start-Process -LoadUserProfile -Credential:$PsCred -FilePath:$FilePath -ArgumentList:$ScriptUnbArgs
} else {
Start-Process -LoadUserProfile -Credential:$PsCred -FilePath:Cmd.exe -ArgumentList:"/C start ""PS_Process_Starter"" /B ""$FilePath"" $ScriptUnbArgs"
}
} else { # No args
if ( ( ".exe",".com",".bat",".cmd" | Foreach-Object { $FilePath.EndsWith($_) } ) -contains $True ) {
Start-Process -LoadUserProfile -Credential:$PsCred -FilePath:$FilePath
} else {
Start-Process -LoadUserProfile -Credential:$PsCred -FilePath:Cmd.exe -ArgumentList:"/C start ""PS_Process_Starter"" /B ""$FilePath"""
}
}
} else {
Start-Process -LoadUserProfile -Credential:$PsCred -FilePath:Cmd.exe -ArgumentList:"/K Title $($PsCred.UserName): $($MyInvocation.Line)"
}
}
catch {
#Error handling...
Write-Host -ForegroundColor:Red "runas:$($PsCred.UserName):`t $($MyInvocation.Line)"
"$($Error[0])"
#Password has been changed...
if ( ($Error[0] -match "Logon failure: unknown user name or bad password") -and !$SaveCredential ) {
if ( Test-Path $CredFilenam ) {
Write-Host -ForegroundColor:Yellow "Deleting invalid credential. Use -SaveCredential next time to save it again."
Remove-Item -Path $CredFilenam -Force -Confirm -Verbose
if ( -not(Test-Path $CredFilenam) ) {
Write-Host -ForegroundColor:Green "$CredFilenam is deleted. Exiting..."
} else {
Write-Host -ForegroundColor:Yellow "$CredFilenam has not been deleted."
}
exit 1326; # Logon failure: unknown user name or bad password.
}
} else {
exit 1;
}
}
if ( !$Error ) { # There were not errors:
Write-Host -ForegroundColor:Green "runas:$($PsCred.UserName):`t $($MyInvocation.Line)"
#Export credential:
if ( $SaveCredential ) {
Write-Host "Saving credential:""$CredFilenam"" ..."
Export-PSCredential -Credential $PsCred -Path "$CredFilenam"
try { (Get-Item -Force $CredFilenam).Encrypt() }
catch {
"$($Error[0])"
}
if ((Get-Item -Force $CredFilenam).Attributes -match "Encrypted") {
Write-Host -ForegroundColor:Green "$((Get-Item -Force $CredFilenam).Attributes)"
} else {
Write-Warning "$CredFilenam is not encrypted. Deleting..."
Remove-Item -Path "$CredFilenam" -Force -Confirm -Verbose
}
}
if ( $RdpSaveCredential ) {
if (Test-Path $RdpFilenam) {
Write-Host "Saving credential:""$RdpFilenam"" $((Get-Item -Force $RdpFilenam).Attributes) ..."
if ( (Get-Item -Force $RdpFilenam).Attributes -notmatch "Encrypted" ) { # ReadOnly, Archive, Encrypted
(Get-Item -Force $RdpFilenam).Attributes = "Archive"
try {
(Get-Item -Force $RdpFilenam).Encrypt()
}
catch {
"$($Error[0])"
}
} # if $RdpFilenam not Encrypted
(Get-Item -Force $RdpFilenam).Attributes = "ReadOnly, Archive, Encrypted"
if ( (Get-Item -Force $RdpFilenam).Attributes -notmatch "Encrypted" ) {
Write-Warning "$RdpFilenam is not encrypted!"
}
Write-Host "Creating backup:"
$RdpFileBak = $RdpFilenam + $(Get-Date -Format:_yyyyMMdd_HHmmss)
Copy-Item $RdpFilenam $RdpFileBak -Force -Confirm
if ( Test-Path $RdpFileBak ) {
if ( !$PsCred.GetNetworkCredential().Domain ) { $PsCred.GetNetworkCredential().Domain = $env:ComputerName }
$RdpFileLines = switch -regex -File:"$RdpFilenam" {
"username:s:*" { }
"domain:s:*" { }
"password 51:b:*" { }
default { $_ }
}
[array] $RdpFileLines += "username:s:" + $($PsCred.GetNetworkCredential().UserName)
$RdpFileLines += "domain:s:" + $($PsCred.GetNetworkCredential().Domain)
$RdpFileLines += "password 51:b:" + $($PsCred.Password | ConvertFrom-SecureString)
Set-Content -Value:$RdpFileLines -Path:$RdpFilenam -Force
Write-Host "Credential saved:""$RdpFilenam""`t $((Get-Item -Force $RdpFilenam).Attributes)" -ForegroundColor:Green
$RdpFileLines | Select-Object -Last:3
} # if ( Test-Path $RdpFileBak )
} else {
Write-Warning "File does not exist:""$RdpFilenam"". Generate an RDP profile first."
exit 2; # 2 The system cannot find the file specified.
} # if (Test-Path $RdpFilenam)
} # if ( $RdpSaveCredential )
Start-Sleep -Milliseconds 2000
} else {
exit 1;
} # if ( !$Error )
# su.ps1 runs on powershell 2.0 only! http://connect.microsoft.com/PowerShell
# Put su.ps1 and su.bat to a directory listed in PATH environment variables.
# content of su.bat: (without hashmarks of course :)
#
#@echo off
#PowerShell.exe -ExecutionPolicy RemoteSigned su.ps1 %*
#if NOT [%ErrorLevel%] == [0] (
# if [%ErrorLevel%] == [9009] (
# echo PowerShell.exe is not under %%Path%% or Poweshell 2.0 has not been installed.
# echo http://www.microsoft.com/powershell
# )
#
# if NOT [%1] == [] ( echo For usage type su -Help )
# pause
#)
|
PowerShellCorpus/PoshCode/ShowUI Text Converter.ps1
|
ShowUI Text Converter.ps1
|
#Import-Module showui
$Windowparam = @{
Width = 500
Height = 400
Title = 'Fun Text Converter'
Background = '#C4CBD8'
WindowStartupLocation = 'CenterScreen'
AsJob = $True
}
#Create Window
New-Window @Windowparam {
New-Grid -Rows *,Auto,*,Auto -Children {
New-TextBox -Row 0 -Name InputBox -TextWrapping Wrap -VerticalScrollBarVisibility Auto
New-Grid -Row 1 -Columns *,*,Auto,Auto,Auto,*,* -Children {
New-Button -Column 2 -Name ConvertButton -Width 65 -Height 25 -Content Translate -On_Click {
If ($ComboBox.Text -eq 'TextToBinary') {
$OutputBox.Text = Convert-TextToBinary $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'BinaryToText') {
$OutputBox.Text = Convert-BinaryToText $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'TextToHex') {
$OutputBox.Text = Convert-TextToHex $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'HexToText') {
$OutputBox.Text = Convert-HexToText $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'BinaryToHex') {
$OutputBox.Text = Convert-BinaryToHex $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'HexToBinary') {
$OutputBox.Text = Convert-HexToBinary $InputBox.Text
} ElseIf ($ComboBox.Text -eq 'ReverseInput') {
$OutputBox.Text = Convert-TextToReverseText $InputBox.Text
}
}
New-Label -Column 3
New-ComboBox -Name ComboBox -Column 4 -IsReadOnly:$True -SelectedIndex 0 -Items {
New-TextBlock -Text TextToBinary
New-TextBlock -Text BinaryToText
New-TextBlock -Text TextToHex
New-TextBlock -Text HexToText
New-TextBlock -Text BinaryToHex
New-TextBlock -Text HexToBinary
New-TextBlock -Text ReverseInput
}
}
New-TextBox -Row 2 -Name OutputBox -IsReadOnly:$True -TextWrapping Wrap `
-VerticalScrollBarVisibility Auto
New-StackPanel -Row 3 -Orientation Horizontal {
New-Button -Name CopyTextButton -Width 65 -Height 25 -HorizontalAlignment Left -Content CopyText -On_Click {
$OutputBox.text | clip
}
New-Label
New-Button -Name ClearTextButton -Width 65 -Height 25 -HorizontalAlignment Left -Content ClearText -On_Click {
$OutputBox.Text=$Null
}
}
}
} -On_Loaded {
Function Convert-TextToBinary {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Text
)
Begin {
#Create binary empty collection
[string[]]$BinaryArray = @()
}
Process {
#Convert text to array
$textarray = $text.ToCharArray()
#Convert each item to binary
ForEach ($a in $textarray) {
$BinaryArray += ([convert]::ToString([int][char]$a,2)).PadLeft(8,"0")
}
}
End {
#Write out binary string
[string]::Join(" ",$BinaryArray)
}
}
Function Convert-BinaryToText {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Binary
)
Begin {
#Create binary empty collection
[string[]]$TextArray = @()
}
Process {
#Split Binary string into array
$BinaryArray = $Binary -split "\\s"
#Convert each item to Char
ForEach ($a in $BinaryArray) {
$TextArray += [char]([convert]::ToInt64($a,2))
}
}
End {
#Write out text string
[string]::Join("",$TextArray)
}
}
Function Convert-TextToHex {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Text
)
Begin {
#Create hex empty collection
[string[]]$HexArray = @()
}
Process {
#Convert text to array
$textarr = $text.ToCharArray()
#Convert each item to binary
ForEach ($a in $textarr) {
$HexArray += "0x$(([convert]::ToString([int][char]$a,16)).PadLeft(8,'0'))"
}
}
End {
#Write out hex string
[string]::Join(" ",$HexArray)
}
}
Function Convert-HexToText {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Hex
)
Begin {
#Create text empty collection
[string[]]$textarr = @()
}
Process {
#Split Binary string into array
$HexArray = $Hex -split "\\s"
#Convert each item to Char
ForEach ($a in $HexArray) {
$textarr += [char]([convert]::ToInt64($a.TrimStart('x0'),16))
}
}
End {
#Write out text string
[string]::Join("",$textarr)
}
}
Function Convert-HexToBinary {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Hex
)
Begin {
#Create binary empty collection
[string[]]$binarr = @()
}
Process {
#Split Binary string into array
$HexArray = $Hex -split "\\s"
#Convert each item to Char
ForEach ($a in $HexArray) {
$a = ([char]([convert]::ToInt64($a.TrimStart('x0'),16)))
$binarr += ([convert]::ToString([int][char]$a,2)).PadLeft(8,"0")
}
}
End {
#Write out binary string
[string]::Join(" ",$binarr)
}
}
Function Convert-BinaryToHex {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$Binary
)
Begin {
#Create binary empty collection
[string[]]$TextArray = @()
}
Process {
#Split Binary string into array
$BinaryArray = $Binary -split "\\s"
#Convert each item to Char
ForEach ($a in $BinaryArray) {
$a = [char]([convert]::ToInt64($a,2))
$TextArray += "0x$(([convert]::ToString([int][char]$a,16)).PadLeft(8,'0'))"
}
}
End {
#Write out hex string
[string]::Join(" ",$TextArray)
}
}
Function Convert-TextToReverseText {
[cmdletbinding()]
Param (
[parameter(ValueFromPipeLine='True')]
[string]$InputString
)
Begin {
}
Process {
#Convert text to array
$inputarray = $InputString -split ""
#Reverse array
[array]::Reverse($inputarray)
}
End {
#Write out reverse string
[string]::Join("",$inputarray)
}
}
}
|
PowerShellCorpus/PoshCode/Get-App.ps1
|
Get-App.ps1
|
## Get-App
## Attempt to resolve the path to an executable using Get-Command and the AppPaths registry key
##################################################################################################
## Example Usage:
## Get-App Notepad
## Finds notepad.exe using Get-Command
## Get-App pbrush
## Finds mspaint.exe using the "App Paths" registry key
## &(Get-App WinWord)
## Finds, and launches, Word (if it's installed) using the "App Paths" registry key
##################################################################################################
## Revision History
## 1.0 - initial release
##################################################################################################
function Get-App {
param( [string]$cmd )
$eap = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
Get-Command $cmd
if(!$?) {
$AppPaths = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths"
if(!(Test-Path $AppPaths\\$cmd)) {
$cmd = [IO.Path]::GetFileNameWithoutExtension($cmd)
if(!(Test-Path $AppPaths\\$cmd)){
$cmd += ".exe"
}
}
if(Test-Path $AppPaths\\$cmd) {
Get-Command (Get-ItemProperty $AppPaths\\$cmd)."(default)"
}
}
}
|
PowerShellCorpus/PoshCode/Get-WebSite.ps1
|
Get-WebSite.ps1
|
function Get-WebSite {
<#
.SYNOPSIS
Retrieves information about a website.
.DESCRIPTION
Retrieves information about a website.
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER TimeOut
Timeout to connect to site, in milliseconds
.PARAMETER Credential
Provide alternate credentials
.NOTES
Name: Get-WebSite
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebSite -url "http://www.bing.com"
Description
------------
Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[Int]$Timeout,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebRequest object using the given url
Write-Verbose "Creating the web request object"
$webRequest = [net.WebRequest]::Create($url)
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Set timeout
If ($PSBoundParameters.ContainsKey('TimeOut')) {
#Setting the timeout on web request
Write-Verbose "Setting the timeout on web request"
$webRequest.Timeout = $timeout
}
#Determine if using Default Credentials
If ($UseDefaultCredentials) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($Credential) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
#Set TimeStamp prior to attempting connection
$then = get-date
}
Process {
Try {
#Make connection to gather response from site
$response = $webRequest.GetResponse()
#If successful, get the date for comparison
$now = get-date
#Generate report
Write-Verbose "Generating report from website connection and response"
$report = @{
URL = $url
StatusCode = $response.Statuscode -as [int]
StatusDescription = $response.StatusDescription
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
Catch {
#Get timestamp of failed attempt
$now = get-date
#Put the current error into a variable for later use
$errorstring = "$($error[0])"
#Generate report
$report = @{
URL = $url
StatusCode = ([regex]::Match($errorstring,"\\b\\d{3}\\b")).value
StatusDescription = (($errorstring.split('\\)')[2]).split('.\\')[0]).Trim()
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
}
End {
#Display Report
New-Object PSObject -property $report
}
}
|
PowerShellCorpus/PoshCode/PS2WCF_5.ps1
|
PS2WCF_5.ps1
|
<#
.SYNOPSIS
Functions to call WCF Services With PowerShell.
.NOTES
Version 1.2 11.02.2012
Requires Powershell v2 and .NET 3.5
Original version by Christian Glessner
Blog: http://www.iLoveSharePoint.com
Twitter: http://twitter.com/cglessner
Codeplex: http://codeplex.com/iLoveSharePoint
PowerShell v2.0 modification by Justin Dearing
Blog: http://justaprogrammer.net
Twitter: http://twitter.com/zippy1981
.LINK
Blog describing original version: http://www.ilovesharepoint.com/2008/12/call-wcf-services-with-powershell.html
Authoritative version of this fork: https://github.com/justaprogrammer/PowerShellWCF
Posted to PoshCode.org http://poshcode.org/?lang=&q=PS2WCF
#>
# load WCF assemblies
Add-Type -AssemblyName "System.ServiceModel"
Add-Type -AssemblyName "System.Runtime.Serialization"
<#
.SYNOPSIS
Get metadata of a service
.DESCRIPTION
Parses a wsdl or mex and generates a WsdlImporter object from it.
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc/mex'
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc' -HttpGet
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc?wsdl' -HttpGet
#>
function global:Get-WsdlImporter([CmdletBinding()][Parameter(Mandatory=$true, ValueFromPipeline=$true)][string]$WsdlUrl, [switch]$HttpGet)
{
if($HttpGet)
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet
}
else
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange
}
$mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient([Uri]$WsdlUrl, $mode);
$mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue
$metadataSet = $mexClient.GetMetadata()
$wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet)
return $wsdlImporter
}
<#
.SYNOPSIS
Generate wcf proxy types
.DESCRIPTION
Examines a web services meta data (wsdl or mex) and generates the types for the client proxy,
as well as request and response contracts.
.EXAMPLE
$proxyType = Get-WcfProxyType $wsdlImporter
$endpoints = $wsdlImporter.ImportAllEndpoints();
$proxy = New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address);
#>
function global:Get-WcfProxyType(
[CmdletBinding()]
[Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter,
[Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl,
[string] $proxyPath
) {
switch ($PsCmdlet.ParameterSetName)
{
"WsdlUrl" {
$WsdlImporter = Get-WsdlImporter $WsdlUrl
trap [Exception]
{
$WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet
continue
}
break
}
"WsdlImporter" { break }
}
$generator = new-object System.ServiceModel.Description.ServiceContractGenerator
foreach($contractDescription in $wsdlImporter.ImportAllContracts())
{
[void]$generator.GenerateServiceContractType($contractDescription)
}
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
if($proxyPath -eq $null)
{
$parameters.GenerateInMemory = $true
}
else
{
$parameters.OutputAssembly = $proxyPath
}
$providerOptions = New-Object "Collections.Generic.Dictionary[String,String]"
[void]$providerOptions.Add("CompilerVersion","v3.5")
$compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions)
$result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit);
if($result.Errors.Count -gt 0)
{
throw "Proxy generation failed"
}
return $result.CompiledAssembly.GetTypes() | Where-Object {$_.BaseType.IsGenericType -and $_.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" }
}
<#
.SYNOPSIS
Generate wcf proxy
.DESCRIPTION
Generate wcf proxy in a manner similar to a Get-WebServiceProxy
.EXAMPLE
$proxy = Get-WcfProxy 'http://localhost.fiddler:14232/EchoService.svc/mex'
$proxy.Echo("Justin Dearing");
#>
function global:Get-WcfProxy(
[CmdletBinding()]
[Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter,
[Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl,
[Parameter(Position=1, Mandatory=$false)][string] $EndpointAddress = $null,
[Parameter(Position=2, Mandatory=$false)][System.ServiceModel.Channels.Binding] $Binding = $null
) {
if ($Binding -ne $null -and [string]::IsNullOrEmpty($EndpointAddress)) {
throw New-Object ArgumentNullException '$EndPointAddress', 'You cannot set $Binding without setting $EndpointAddress.'
}
switch ($PsCmdlet.ParameterSetName)
{
"WsdlUrl" {
$WsdlImporter = Get-WsdlImporter $WsdlUrl
trap [Exception]
{
$WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet
continue
}
break
}
}
$proxyType = Get-WcfProxyType $wsdlImporter;
if ([string]::IsNullOrEmpty($EndpointAddress)) {
$endpoints = $WsdlImporter.ImportAllEndpoints();
$Binding = $endpoints[0].Binding;
$EndpointAddress = $endpoints[0].Address;
}
return New-Object $proxyType($Binding, $EndpointAddress);
}
|
PowerShellCorpus/PoshCode/Set Logfile lines.ps1
|
Set Logfile lines.ps1
|
################################################################################
# This script will maintain the PS Transcript file at a fixed length and can be
# used to prevent such files, etc, from becoming too large. It is best placed in
# the $profile. Defaults to 10000 lines. Parameters allow use for other files.
# The author can be contacted via www.SeaStarDevelopmet.Bravehost.com
################################################################################
Param ([int] $lines = 10000,
[String]$file = "$env:scripts\\Transcript.txt")
If ($file -notlike "*.txt") {
[System.Media.SystemSounds]::Hand.Play()
Write-Error "This script can only process .txt files"
Exit 1
}
If (!(Test-Path $file)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Error "File $file does not exist"
Exit 1
}
[int]$count = 0
$errorActionPreference = 'SilentlyContinue'
$content = (Get-Content $file)
$extra = ($content | Measure-Object -line)
[int]$extra = $extra.Lines - $lines #The number of lines to remove.
If ($extra -gt 0) {
$tempfile = [IO.Path]::GetTempFileName()
Write-Output "Starting maintenance on file $file"
$content | ForEach-Object {
$count += 1
If($count -gt $extra) { #Ignore the first $extra lines.
$_ | Out-File $tempfile -Append -Force #Create new Transcript file.
}
}
If (file -like "*transcript.txt") {
Stop-Transcript | Out-Null
}
Remove-Item $file
Move-Item $tempfile -Destination $file
$tag = "[$extra lines removed]."
If ($file -like "*transcript.txt") {
Start-Transcript -append -path $file -force | Out-Null
}
Write-Output "Maintenance of file completed $tag"
}
$ErrorActionPreference = 'Continue'
|
PowerShellCorpus/PoshCode/Split-TextToLines Demo_2.ps1
|
Split-TextToLines Demo_2.ps1
|
# Variables
$viserver = Read-Host "Enter VI server name"
$cluster = Read-Host "Enter Cluster name"
$vmhelper = Read-Host "Enter VM_HELPER name"
Write-Host "Connecting to $viserver..."
Connect-VIServer $viserver -WarningAction:SilentlyContinue
# Get VM Hosts
$vmhosts = Get-Cluster $cluster -ErrorAction:SilentlyContinue | Get-VMHost | where {$_.powerstate -eq "poweredon"} | sort name
If ($vmhosts -eq $null) {
Write-Host "Invalid cluster name"
break
}
$vmhosts | select name
Write-Host "Listed servers will be tested for virtual machine VLAN"
Write-Host "Verify that $cluster cluster is NOT A PRODUCTION cluster"
Write-Host "Press Any Key to Continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Write-Host
# Get VM IP
Write-Host "Getting VM IP(s) from $vmehlper virtual machine VLAN...."
$vm = Get-VM $vmhelper -ErrorAction:SilentlyContinue
if ($vm -eq $null) {
Write-Host "Invalid VM name"
break
}
$vm.guest.nics | select NetworkName, IPAddress
$answer = Read-host "Do you want to continue with current IP address? (yes/no)"
# Start VLAN Ping
if ($answer -eq "yes") {
$vm.guest.nics | foreach {
$vmnic = $_
$pingfile = "c:\\scripts\\"+ $vmnic.networkname + ".cmd"
$pingcmd = "ping -t " + $vmnic.IPAddress
Add-Content $pingfile $pingcmd
Start-Process $pingfile
}
# Prep Vmotion by moving VM to last host
Write-Host "Moving $vmhelper to " ($vmhosts| select -last 1) "..."
Move-VM -VM $vmhelper -Destination ($vmhosts | select -last 1) -Confirm:$false -ErrorAction:SilentlyContinue | Out-Null
# Start Vmotion on two pass-thru NIC
Foreach ($vmhost in $vmhosts) {
Write-Host "Moving $vmhelper to $vmhost... Check continuous ping"
Move-VM -VM $vmhelper -Destination $vmhost -Confirm:$false -ErrorAction:SilentlyContinue | Out-Null
if (($vmhost | Get-VM $vmhelper) -eq $nul) {
Write-Host "Vmotion to $vmhost failed. Check settings"
break
}
}
# Remove vmnic1 from vSiwtch0
Foreach ($vmhost in $vmhosts) {
$vSwitch = $vmhost | Get-VirtualSwitch | Where-Object {$_.Name -eq "vSwitch0"}
Write-Host "Removing vmnic1 from $vmhost..."
$vSwitch | Set-VirtualSwitch -Nic vmnic0 -Confirm:$false | Out-Null
}
sleep 10
# Start Vmotion on two pass-thru NIC
Foreach ($vmhost in $vmhosts) {
Write-Host "Moving $vmhelper to $vmhost... Check continuous ping"
Move-VM -VM $vmhelper -Destination $vmhost -Confirm:$false -ErrorAction:SilentlyContinue | Out-Null
if (($vmhost | Get-VM $vmhelper) -eq $null) {
Write-Host "Vmotion to $vmhost failed. Check settings"
break
}
}
# Remove vmnic0 from vSiwtch0
Foreach ($vmhost in $vmhosts) {
$vSwitch = $vmhost | Get-VirtualSwitch | Where-Object {$_.Name -eq "vSwitch0"}
Write-Host "Removing vmnic0 from $vmhost..."
$vSwitch | Set-VirtualSwitch -Nic vmnic1 -Confirm:$false | Out-Null
}
sleep 10
Foreach ($vmhost in $vmhosts) {
Write-Host "Moving $vmhelper to $vmhost... Check continuous ping"
Move-VM -VM $vmhelper -Destination $vmhost -Confirm:$false -ErrorAction:SilentlyContinue | Out-Null
}
# Add vmnic0 and vmnic1 back to vSwitch0
Write-Host "Re-Adding vmnic0 and vmnic1 to vSwitch0..."
Foreach ($vmhost in $vmhosts) {
$vSwitch = $vmhost | Get-VirtualSwitch | Where-Object {$_.Name -eq "vSwitch0"}
Write-Host "Adding vmnic0, vmnic1 on $vmhost..."
$vSwitch | Set-VirtualSwitch -Nic vmnic0,vmnic1 -Confirm:$false | Out-Null
}
$vm.guest.nics | foreach {
$vmnic = $_
$pingfile = "c:\\scripts\\"+ $vmnic.networkname + ".cmd"
del $pingfile
}
Write-Host "Test is completed."
}
|
PowerShellCorpus/PoshCode/Set vSphere CDP LinkDisc.ps1
|
Set vSphere CDP LinkDisc.ps1
|
function set-vSwitchLinkDiscovery {
Param (
#Switch to enable vSwitch Discovery On
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$vSwitchName
#Host on which the vSwitch Resides
,[Parameter(Mandatory=$true,HelpMessage="")][string]$VMBackupDestination,
) #Param
#Variables
$vSwitchName = "vSwitch0"
$linkProtocol = "cdp"
$linkOperation = "both"
$VMHost = "myhost"
#Get the specification for the vSwitch
$networkview = (get-vmhostnetwork -vmhost $VMHost | get-view)
$vSwitchSpec = ($networkView.NetworkConfig.vSwitch | Where {$_.Name -eq $vSwitchName}).Spec
#Set Protocol Type and Operation
$vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.protocol = $linkProtocol $vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.operation = $linkOperation
#Commit Changes
$networkview.updateVirtualSwitch($vSwitchName,$vSwitchSpec)
}
|
PowerShellCorpus/PoshCode/01dbc242-a783-4249-9862-3fbf3231f7b6.ps1
|
01dbc242-a783-4249-9862-3fbf3231f7b6.ps1
|
# Code to auto update the Address policy, GAL, OAB and storage groups and mailbox databases of an Exchange 2007 server by John McLear
# This code is good for hosting providers or people who wish to use lots of storage groups and mailbox databases.
#
# Thanks to Joel Bennett (Jaykul) for general scripting help and the friendly folks in #powershell - freenode
#
# I rewrote this and didnt test before publishing so there may be some syntax errors.
#
# Created 07/09/2008
#################################################################################################################################
param([string]$fullname, [string]$mail2, [string]$typeofcustomer)
# PRE REQ - Create a container in your address lists called "Generic Address Book" or something similar - this is where we will store address lists!
- Create a public folder database on your MB server - In $publicfolderDatabase our example is in storage group sg0 called Public Folder.
# We need to set some things manually too!
$yourinternaldomain = "domain.com" # ie contoso.com
$OABDistributionServer = "CASserver" # Your CAS server responsible for OAB distribution
$MailboxServer = "MBserver" # Shortname of your MailboxServer
$PublicFolderDatabase = $MailboxServer + '\\sg0\\Public Folder' # The Path to your public folder used for Address List distribution
$LogFilePath = "d:\\Program Files\\Microsoft\\Exchange Server\\Mailbox\\First Storage Group\\" # Where we will put the log files
$AdminName = "CN=Servers,CN=Exchange Administrative Group (TESTING23TESTY),CN=Administrative Groups,CN=Contoso,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" # This needs to be changed
echo "Fullname: $fullname" # full name of customer - this must be a unique value)
echo "Domain name: $mail2" # customers domain name ie fraggle.com
echo "Type of customer (1 is basic, 2 is standard, 3 is premium): $typeofcustomer" # Basically a premium customer will get their own mailboxdatabase - a basic or standard will share in one big database (know why before you use this!)
echo "Your internal domain: $yourinternaldomain" # The internal domain you set
# Lets go!
######################
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
# Loads exchange snap ins
new-AcceptedDomain -Name $mail2 -DomainName $mail2 -DomainType 'Authoritative'
# Creates an accepted domain
new-EmailAddressPolicy -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain
# Creates a new address policy giving - you may wish to modify this to suit
set-EmailAddressPolicy -Identity $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain
# Modifies the new address policy giving - you may wish to modify this to suit - Why modify? You may wish to update this at some point and its best practice to have a set command imho
new-GlobalAddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname
# Create a new GAL
new-AddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Container '\\Generic Address Book'
# Create a new address list in the Generic Address Book container - Modify your container to suit!
$fullname2 = '\\Generic Address book\\' + $fullname
# You may wish to modify the above to suit
$OABPoint = $OABdistributionServer + '\\OAB (Default Web Site)'
# You may wish to modify the above line to suit but I doubt it.
new-OfflineAddressBook -Name $fullname -Server $pinkyring -AddressLists $fullname2 -PublicFolderDistributionEnabled $false -VirtualDirectories $OABPoint
# Create a new Offline Address Book
Set-OfflineAddressBook -Identity $fullname -versions Version3, Version4 -PublicFolderDistributionEnabled $true -AddressLists $fullname2
# Set the OAB to V3, 4 and Public folder distribution.
Update-EmailAddressPolicy -Identity $fullname
# Update the Email Address Policy
Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase
# Set the Mailbox database of the customer to use the public folder database you created
$maildb = Get-MailboxDataBase | Select-String $fullname
echo $maildb
if ($maildb -match "sg")
# if there is a database for the fullname value then
{
echo "not making the DB"
}
# if there isnt a school name
else
{
if ($typeofcustomer -match "3")
# and if the type of customer is 3 (premium)
{
echo "making the DB" # this customer must be premium! good for them!!
$i = 1
for( $i=0; $i -lt 50; $i++ )
# for each count 1 to 50
{
$maildb = Get-MailboxDataBase | Select-String $fullname
echo $maildb
if ($maildb -match "sg")
# Check for a database
{ echo "database located" } # if database is found then do nothing
else
{
new-storagegroup sg$i
# creating 50 storage groups
new-mailboxdatabase -StorageGroup $MailboxServer\\sg$i -Name $fullname -EdbFilePath $LogFilePath + '\\' + $fullname.edb
# make a database on the server - we need to add incrementation on servername here..
mount-database -Identity "CN=$fullname,CN=sg$i,CN=InformationStore,CN=$MailboxServer,$AdminName"
# mount the database
$i++
# increase the storage group by 1
}
}
Set-MailboxDatabase -Identity $fullname -PublicFolderDatabase $PublicFolderDatabase
# set the public folder
}
else
{
echo "customer is a basic or standard customer so we are going to not create a DB"
Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase
}
}
|
PowerShellCorpus/PoshCode/Get-InstalledProgram_v_4.ps1
|
Get-InstalledProgram_v_4.ps1
|
function Get-InstalledProgram() {
param (
[String[]]$Computer,
$User
)
#############################################################################################
if ($User) {$Connection = Get-Credential -Credential $User}
#############################################################################################
if (!$Connection){
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-Table __SERVER,Name,Version,InstallDate
$Install_soft
}
}
else {
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-Table __SERVER,Name,Version,InstallDate
$Install_soft
}
}
}
|
PowerShellCorpus/PoshCode/Set-Domain_4.ps1
|
Set-Domain_4.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Crdential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-Domain -domain MyDomain -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/Get-Tail.ps1
|
Get-Tail.ps1
|
# Name: Get-Tail.ps1
# Author: William Stacey
# Created: 02/22/2007
# Description: Gets the last N lines of a file. Does scan from end-of-file so works on large files. Also has a loop flag that prompts for refresh.
function Get-Tail([string]$path = $(throw "Path name must be specified."), [int]$count = 10, [bool]$loop = $false)
{
if ( $count -lt 1 ) {$(throw "Count must be greater than 1.")}
function get-last
{
$lineCount = 0
$reader = new-object -typename System.IO.StreamReader -argumentlist $path, $true
[long]$pos = $reader.BaseStream.Length - 1
while($pos -gt 0)
{
$reader.BaseStream.Position = $pos
if ($reader.BaseStream.ReadByte() -eq 10)
{
if($pos -eq $reader.BaseStream.Length - 1)
{
$count++
}
$lineCount++
if ($lineCount -ge $count) { break }
}
$pos--
}
if ($lineCount -lt $count)
{
$reader.BaseStream.Position = 0
}
while($line = $reader.ReadLine())
{
$lines += ,$line
}
$reader.Close()
$lines
}
while(1)
{
get-last
if ( ! $loop ) { break }
$in = read-host -prompt "Hit [Enter] to tail again or Ctrl-C to exit"
}
}
|
PowerShellCorpus/PoshCode/Copy-MAGig_1.ps1
|
Copy-MAGig_1.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) 2012-10-21
# 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 '\\\\', '\\\\' )\\\\"
$src_obj = Get-item $src
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 ) ## ToDo: check subfolders to create
Get-ChildItem -Path $src -Force -Rec:$Recurse -exclude $exclude | % {
if ($src_obj.psIscontainer)
{
#'src is container'
$relativePath = $_.FullName -replace $src_pattern, ''
}
else
{
#'src is file'
$relativePath = Split-Path $src -leaf
}
#"relativePath: $relativePath"
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
{
$FileDestination = "$dest\\$relativePath"
try
{
$fileExists = Test-Path $FileDestination
}
catch
{
$fileExists = $false
}
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, $FileDestination
} else {
"{0,-$ident}{1,-$width} => {2}" -f '', $_.FullName, $FileDestination
}
}
} else {
"{0,-$ident}{1,-$width} -> {2}" -f '', $_.FullName, $FileDestination
}
}
if ( ! ($fileExists -and ($NoReplace -or $leavecurrent)) ) {
try {
Copy-Item $_.FullName $dest\\$relativePath -Force
} catch {
"{0,-$errident}## fail ## {1}`r`n {2} `r`n {3}" -f '', $_.Exception.Message, "copysource $($_.FullName)", "copydest $dest\\$relativePath"
}
}
}
}
}
}
catch
{
"{0,-$errident}## fail ## {1}" -f '', $_.Exception.Message
}
}
|
PowerShellCorpus/PoshCode/1931a71c-ecb0-4b18-85ba-635d4034e7a1.ps1
|
1931a71c-ecb0-4b18-85ba-635d4034e7a1.ps1
|
PARAM(
$location=$(throw "Make sure to specify a location for old machines to be imported")
)
$oldVM = Get-ChildItem "$location\\*.xml"
foreach($vm in $oldVM)
{
$vmGuid = [System.IO.Path]::GetFileNameWithoutExtension($vm.Name)
Invoke-Command -ScriptBlock {cmd /c "Mklink `"C:\\ProgramData\\Microsoft\\Windows\\Hyper-V\\Virtual Machines\\$vmGuid.xml`" `"D:\\VMConfig\\Virtual Machines\\$vmGuid.xml`""}
Invoke-Command -ScriptBlock {cmd /c "Icacls `"C:\\ProgramData\\Microsoft\\Windows\\Hyper-V\\Virtual Machines\\$vmGuid.xml`" /grant `"NT VIRTUAL MACHINE\\$vmGuid`":(F) /L"}
Invoke-Command -ScriptBlock {cmd /c "Icacls $location /T /grant `"NT VIRTUAL MACHINE\\$vmGuid`":(F)"}
}
|
PowerShellCorpus/PoshCode/Profile Function.ps1
|
Profile Function.ps1
|
########################################################
# This function will prompt the user asking if they want
# to start a transcript file. It will loop until the user
# types y or n. If the user selects y, the script will
# check to see if the transcript exists. If it doesn't
# it is created. If it does, the transcript file is created.
# The transcript started message, and folder creation
# message are all piped to null. Modified script from
# Shay's site http://blogs.microsoft.co.il/blogs/ScriptFanatic
########################################################
function Save-Transcript{
$global:TRANSCRIPT = "C:\\Scripts\\PowerShell\\Transcripts\\PSLOG_{0:dd-MM-yyyy}.txt" -f (Get-Date)
Start-Transcript -Append | out-null
}
do{$a = Read-Host "Do you want to start a transcript? y/n"}
Until($a -ne "")
If($a -eq "y")
{
if (Test-Path C:\\Scripts\\PowerShell\\Transcripts)
{
"C:\\Scripts\\PowerShell\\Transcripts"
}
else
{
New-Item C:\\Scripts\\PowerShell\\Transcripts -type directory | out-null
}
Save-Transcript
}
|
PowerShellCorpus/PoshCode/Update-VmFromTemplate.ps.ps1
|
Update-VmFromTemplate.ps.ps1
|
<#
.SYNOPSIS
Create a new VM from an imported template
.DESCRIPTION
This script will modify a VM on Hyper-V R2 that has been imported from an exported VM.
The current release of the HyperV module does not support the proper Import method, so
I don't implement that bit in this script.
.PARAMETER TargetVM
This is the name of the imported VM Template
.PARAMETER NewVMName
This is the name you wish to give your new VM
.EXAMPLE
.\\Update-VmFromTemplate.ps1 -TargetVM "2008 Core Server" -NewVMName "IIS Web Server"
Description
-----------
This is the only syntax for this script.
.NOTES
ScriptName: Update-VmFromTemplate.ps1
Created By: Jeff Patton
Date Coded: August 3, 2011
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
You will need the HyperV Module from Codeplex
http://pshyperv.codeplex.com/
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/Update-VmFromTemplate
.LINK
http://technet.microsoft.com/en-us/magazine/ff458346.aspx
.LINK
http://pshyperv.codeplex.com/
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$TargetVM,
[Parameter(Mandatory=$true)]
[string]$NewVMName
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
# Dotsource in the functions you need.
if ($modules.Name -contains "HyperV")
{}
else
{
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Loading HyperV Module"
Import-Module 'C:\\Program Files\\modules\\HyperV\\HyperV.psd1'
}
# Set the name of the VM we're working with
$VirtualMachine = Get-VM |Where-Object {$_.VMElementName -eq $TargetVM}
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Get the Working VM, $($VirtualMachine.VMElementName)"
# Get the disk information for the rename
$VMDiskPath = Get-VMDisk -VM $VirtualMachine.VMElementName |Where-Object {$_.DriveName -eq "Hard Drive"}
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Get the disk to work with, $($VMDiskPath.DiskImage)"
# Split the path up on slash
$NewDiskPath = $VMDiskPath.DiskImage.Split("\\")
# The last item in the array is the filename, so update it.
$NewDiskPath[$NewDiskPath.Count -1] = "$($NewVMName).vhd"
# Cat the string back together
$NewDiskPath = [string]::join("\\",$NewDiskPath)
}
Process
{
# Remove any disks that are attached to the newly imported VM
Get-VMDisk -VM $VirtualMachine.VMElementName | `
foreach {Remove-VMDrive -Diskonly -VM $_.VMElementName -ControllerID $_.ControllerID -LUN $_.DriveLUN}
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Removed all disks"
# Rename the existing imported disk, to the new VM name
Rename-Item $VMDiskPath.DiskImage $NewDiskPath
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Renamed disk to $($NewDiskPath)"
# Attach the newly renamed VHD back to the VM
Set-VMDisk -VM $TargetVM -Path $NewDiskPath
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Added new disk to VM"
# Change the name of the VM to the new name, and add a note about what happened
Set-VM -VM $TargetVM -Name $NewVMName -Notes "Imported $($TargetVM) to $($NewVMName) on $(Get-Date)"
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Changed the VM name to $($NewVMName) and wrote a note"
# Create an initial snapshot after the import
New-VMSnapshot -VM $NewVMName -Note "Creating initial snapshot after Import" -Force
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message "Creating initial snapshot after Import"
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
}
|
PowerShellCorpus/PoshCode/Two ways get random pass.ps1
|
Two ways get random pass.ps1
|
#ugly way
function Get-RandomPassword {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[int]$PasswordLength = "7"
)
$rnd = New-Object Random
$chr = @(33..125)
for ($i = 0; $i -lt $PasswordLength; $i++) {
$pas += [char]$chr[$rnd.Next(0, [int]$chr.Length)]
}
return $pas
}
#smart way
function Get-RandomPassword {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[int]$PasswordLength = "7"
)
return -join ([char[]]@(33..125) | Get-Random -count $PasswordLength)
}
|
PowerShellCorpus/PoshCode/SearchZIP.psm1 .ps1
|
SearchZIP.psm1 .ps1
|
function SearchZIPfiles {
<#
.SYNOPSIS
Search for (filename) strings inside compressed ZIP or RAR files.
.DESCRIPTION
In any directory containing a large number of ZIP/RAR compressed Web Page files
this procedure will search each individual file name for simple text strings,
listing both the source RAR/ZIP file and the individual file name containing
the string. The relevant RAR/ZIP can then be subsequently opened in the usual
way.
Using the '-Table' switch will show the results with the Out-GridView display.
.EXAMPLE
extract -find 'library' -path d:\\scripts
Searching for 'library' - please wait... (Use CTRL+C to quit)
[Editor.zip] File: Windows 7 Library Procedures.mht
[Editor.rar] File: My Library collection from 1974 Idi Amin.html
[Test2.rar] File: Playlists from library - Windows 7 Forums.mht
[Test3.rar] File: Module library functions UserGroup.pdf
A total of 4 matches for 'library' found in folder 'D:\\Scripts'.
.EXAMPLE
extract -find 'backup' -path desktop
Searching for 'backup' - please wait... (Use CTRL+C to quit)
[Web.zip] File: How To Backup User and System Files.mht
[Pages.rar] File: Create an Image Backup.pdf
A total of 2 matches for 'backup' found in folder 'C:\\Users\\Sam\\Desktop'.
.NOTES
The first step will find any lines containing the selected pattern (which can
be anywhere in the line). Each of these lines will then be split into 2
headings: Source and Filename.
Note that there may be the odd occasion where a 'non-readable' character in the
returned string slips through the net!
.LINK
Web Address Http://www.SeaStarDevelopment.BraveHost.com
#>
[CmdletBinding()]
param([string][string][Parameter(Mandatory=$true)]$Find,
[string][ValidateNotNullOrEmpty()]$path = $pwd,
[switch]$table)
[int]$count = 0
if ($path -like 'desk*') {
$path = Join-Path $home 'desktop\\*'
}
else {
$path = Join-Path $path '*'
}
if (!(Test-path $path)) {
Write-Warning "Path '$($path.Replace('\\*',''))' is invalid - resubmit"
return
}
$folder = $path.Replace('*','')
$lines = @{}
$regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*\\\\(?<file>.*\\.(mht|html?|pdf))(.*)$'
Get-ChildItem $path -include '*.rar','*.zip' |
Select-String -SimpleMatch -Pattern $find |
foreach-Object `
-begin { Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)" } `
-process {
$_ = $_ -replace '/','\\'
if ( $_ -match $regex ) {
$source = $matches.zip.Replace($folder,'')
$file = $matches.file
$file = $file -replace '\\s+',' ' #Single space words.
$file = $file -replace '\\p{S}',' ' #Remove some 'Dingbats'.
if ($table) {
$key = "{0:D4}" -f $count
$lines["$key $source"] = $file #Create a unique key.
}
else {
Write-Host "[$source] File: $file"
}
$count++
}
} `
-end {
$title = "A total of $($count) matches for '$find' found in host folder '$($path.Replace('\\*',''))'."
if ($table -and ($lines.count -gt 0)) {
$lines.GetEnumerator() |
Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}},
@{name = 'File' ;expression = {$_.Value}} |
Sort-Object File |
Out-GridView -Title $title
}
else {
Write-Host $title
}
}
} #End function.
New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR'
Export-ModuleMember -Function SearchZIPfiles -Alias Extract
|
PowerShellCorpus/PoshCode/UIAutomation 1.6.ps1
|
UIAutomation 1.6.ps1
|
## UI Automation v 1.6 -- REQUIRES the Reflection module (current version: http://poshcode.org/2480 )
##
# WASP 2.0 is getting closer, but this is just a preview:
# -- a lot of the commands have weird names still because they're being generated ignorantly
# -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke
# #
# Select-Window Notepad | Remove-Window -passthru #
# ## And later ... #
# Select-Window Notepad | Select-ChildWindow | Send-Keys "%N" #
# ## OR ## #
# Select-Window Notepad | Select-ChildWindow | #
# Select-Control -title "Do&n't Save" -recurse | Send-Click #
# #
# #
# PS notepad | Select-Window | Select-ChildWindow | %{ New-Object Huddled.Wasp.Window $_ } #
# #
# cp C:\\Users\\Joel\\Projects\\PowerShell\\Wasp\\trunk\\WASP\\bin\\Debug\\Wasp.dll .\\Modules\\WASP\\ #
# Import-Module WASP
#PS1 [Reflection.Assembly]::Load()
#PS1 [Reflection.Assembly]::Load()
Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
$SWA = "System.Windows.Automation"
# Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
# Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue
# Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue
# Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue
# Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
# Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
# This is what requires the Reflection module:
Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue
Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue
##### Conditions
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
##### IDentifiers
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
##### Patterns:
$patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern
#| Where { $_ -ne [System.Windows.Automation.InvokePattern] }
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Automation;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StaticFieldAttribute : ArgumentTransformationAttribute {
private Type _class;
public override string ToString() {
return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName);
}
public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) {
if(inputData is string && !string.IsNullOrEmpty(inputData as string)) {
System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public);
if(field != null) {
return field.GetValue(null);
}
}
return inputData;
}
public StaticFieldAttribute( Type ofClass ) {
OfClass = ofClass;
}
public Type OfClass {
get { return _class; }
set { _class = value; }
}
}
public class UIAutomationHelper {
public static AutomationElement RootElement {
get { return AutomationElement.RootElement; }
}
}
"@ -ReferencedAssemblies UIAutomationClient, UIAutomationTypes
## TODO: Write Get-SupportedPatterns or rather ...
## Get-SupportedFunctions (to return the names of the functions for the supported patterns)
## TODO: Support all the "Properties" too
## TODO: Figure out why Notepad doesn't support SetValue
## TODO: Figure out where the menus support went
ForEach($pattern in $patterns){
$pattern | Add-Accelerator
$PatternFullName = $pattern.FullName
$PatternName = $Pattern.Name -Replace "Pattern","."
$newline = "`n`t`t"
New-Item "Function:Get-UIAPattern$($PatternName.TrimEnd('.'))" -Value "
param(
[Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject
)
process {
trap { Write-Warning `"`$(`$_)`"; continue }
Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current
}"
$pattern.GetMethods() |
Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } |
ForEach {
$FunctionName = "Function:Invoke-$PatternName$($_.Name)"
$Position = 1
if (test-path $FunctionName) { remove-item $FunctionName }
$Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+
"$newline[Alias('Parent','Element','Root','AutomationElement')]"+
"$newline[AutomationElement]`$InputObject"
) +
@(
"[Parameter()]$newline[Switch]`$Passthru"
) +
@($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" })
$Parameters = $Parameters -Join "$newline,$newline"
$ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $')
$definition = @"
param(
$Parameters
)
process {
## trap { Write-Warning "`$(`$_)"; break }
`$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues }))
}
if(`$passthru) {
`$InputObject
}
}
"@
trap {
Write-Warning $_
Write-Host $definition -fore cyan
}
New-Item $FunctionName -value $definition
}
$pattern.GetProperties() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} |
ForEach {
$FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.')
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$pattern.'$($_.Name)'
}
}"
}
## So far this seems to be restricted to Text (DocumentRange) elements
$pattern.GetFields() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -like "*Attribute"} |
ForEach {
$FunctionName = "Function:Get-UIAAttribute$PatternName$($_.Name)"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name))
}"
}
$pattern.GetFields() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -like "*Event"} |
ForEach {
$Name = $_.Name -replace 'Event$','Handler'
$FunctionName = "Function:Add-$PatternName$Name"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
,
[System.Windows.Automation.TreeScope]`$TreeScope = 'Element'
,
[ScriptBlock]`$EventHandler
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
[Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler )
}"
}
}
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
$AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties()
Set-Alias Invoke-UIAElement Invoke-Invoke.Invoke
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Set-UIAText {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$valuePattern = $null
if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) {
Write-Verbose "Set via ValuePattern!"
$valuePattern.SetValue( $Text )
}
elseif($InputObject.Current.IsKeyboardFocusable)
{
$InputObject.SetFocus();
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
if($passthru) {
$InputObject
}
}
}
function Set-UIAFocus {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
$InputObject.SetFocus()
if($passthru) {
$InputObject
}
}
}
function Get-UIAClickablePoint {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
)
process {
$InputObject.GetClickablePoint()
}
}
function Send-UIAKeys {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Keys
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
,
[Parameter()]
[Switch]$Async
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$InputObject.SetFocus();
if($Async) {
[SendKeys]::Send( $Keys )
} else {
[SendKeys]::SendWait( $Keys )
}
if($passthru) {
$InputObject
}
}
}
function Select-UIElement {
[CmdletBinding(DefaultParameterSetName="FromParent")]
PARAM (
[Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)]
[Alias("MainWindowHandle","hWnd","Handle")]
[IntPtr[]]$WindowHandle=[IntPtr]::Zero
,
[Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)]
[System.Windows.Point[]]$Point
,
[Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)]
[System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement
,
[Parameter(ParameterSetName="FromParent", Position="0")]
[Alias("WindowName")]
[String[]]$Name
,
[Parameter(ParameterSetName="FromParent", Position="1")]
[System.Windows.Automation.ControlType]
[StaticField(([System.Windows.Automation.ControlType]))]$ControlType
,
## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle
[Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )]
[Alias("Id")]
[Int[]]$PID
,
[Parameter(ParameterSetName="FromParent")]
[String[]]$ProcessName
,
[Parameter(ParameterSetName="FromParent")]
[String[]]$ClassName
,
[switch]$Recurse
)
process {
Write-Debug "Parameters Found"
Write-Debug ($PSBoundParameters | Format-Table | Out-String)
$search = "Children"
if($Recurse) { $search = "Descendants" }
$condition = [System.Windows.Automation.Condition]::TrueCondition
Write-Verbose $PSCmdlet.ParameterSetName
switch -regex ($PSCmdlet.ParameterSetName) {
"FromWindowHandle" {
$Element = $(
foreach($hWnd in $WindowHandle) {
[System.Windows.Automation.AutomationElement]::FromHandle( $hWnd )
}
)
continue
}
"FromPoint" {
$Element = $(
foreach($pt in $Point) {
[System.Windows.Automation.AutomationElement]::FromPoint( $pt )
}
)
continue
}
"FromParent" {
## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition
[ScriptBlock[]]$filters = @()
if($PID) {
[System.Windows.Automation.Condition[]]$current += $(
foreach($p in $PID) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p #.id
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($ProcessName) {
if($ProcessName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current += $(
foreach($p in Get-Process -Name $ProcessName) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($Name) {
if($Name -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current += $(
foreach($n in $Name){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ClassName) {
if($ClassName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current += $(
foreach($c in $ClassName){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ControlType) {
if($ControlType -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current += $(
foreach($c in $ControlType){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($conditions.Length -gt 1) {
[System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions
} elseif($conditions) {
[System.Windows.Automation.Condition]$condition = $conditions[0]
} else {
Write-Host "Oh no! It's the TRUE condition." -fore red
[System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition
}
if($filters.Count -gt 0) {
Write-Host "There are Filters too though ... " -fore red
$Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item }
} else {
$Element = $Parent.FindAll( $search, $condition )
}
}
}
Write-Verbose "Element: $(@($Element).Count)"
if($Element) {
foreach($el in $Element) {
$e = New-Object PSObject $el
foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName)
{
## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property
$propName = [System.Windows.Automation.Automation]::PropertyName($prop)
Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0
}
foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName)
{
Add-Member -InputObject $e -Type ScriptProperty -Name $patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0
}
Write-Output $e
}
}
}
}
# [Cmdlet(VerbsCommon.Add, "UIAHandler")]
# public class AddUIAHandlerCommand : PSCmdlet
# {
# private AutomationElement _parent = AutomationElement.RootElement;
# private AutomationEvent _event = WindowPattern.WindowOpenedEvent;
# private TreeScope _scope = TreeScope.Children;
#
# [Parameter(ValueFromPipeline = true)]
# [Alias("Parent", "Element", "Root")]
# public AutomationElement InputObject { set { _parent = value; } get { return _parent; } }
#
# [Parameter()]
# public AutomationEvent Event { set { _event = value; } get { return _event; } }
#
# [Parameter()]
# public AutomationEventHandler ScriptBlock { set; get; }
#
# [Parameter()]
# public SwitchParameter Passthru { set; get; }
#
# [Parameter()]
# public TreeScope Scope { set { _scope = value; } get { return _scope; } }
#
# protected override void ProcessRecord()
# {
# Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock);
#
# if (Passthru.ToBool())
# {
# WriteObject(InputObject);
# }
#
# base.ProcessRecord();
# }
# }
Export-ModuleMember -cmdlet * -Function * -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU1J/dovQ2Sib/5ECSBjkJCtAP
# TKmgggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU4y8DgFgU
# E4gFrdVXpPcBOvsvx+QwDQYJKoZIhvcNAQEBBQAEggEADdDsHJdQxMh9saVCbqer
# SUk3ygs0LAiYF0IozBiHD1tY23CZokYGWAOCSfzF5gOJb9pa2p3oU8aH9PJWBSn7
# HQ1x5RTPqccDUQA03ucgZAN0WQ/V27Zoahox1h8Q597zqp76y4T9bvBjv1lJju9P
# 0tolEvS0uciAQhPgCvxbvRBdWmOKOK5TPSp6hEk3FsPPlgS9xp7twVNI4Kn619Ku
# cKzoZQoTeFwefKuGMSWMVwKugw2ZJKRkTsoPSl4hDjZ2d5cZM+1bbaGOqxmSBeVr
# wD3nfxZhZOGm54jbqu8WvObLB4znvGo1PBVi/vTb13ncdVFHBu10IQeW+STxLfpb
# LQ==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-Password.ps1
|
Get-Password.ps1
|
# ----------------------------------------------------------------------------------------------
# Get-Password PowerShell Script
#
# Author: John T Childers III
# Originally Written: 7/5/2011
# ***Important****
# Make sure to store this in a directory in that is a part of the path
# so that it you can call it directly from powershell by typing Get-Password
# ----------------------------------------------------------------------------------------------
<#
.SYNOPSIS
Generate a random password.
.DESCRIPTION
The Get-Password function generates a random password from a pre-generated array of characters based of the length and complexity paramters defined at run time. If no parameters are supplied the function defaults to a length of 9 characters and the high complexity character set which includes upper case letters, lower case letters, numbers and symbols. The output is written to the console and is not stored anywhere else.
.PARAMETER -PasswordLength
Defines the number of random characters to generate for the password. Also can be called by two alliases to provide for less typing which are -PassLen and -PL.
.PARAMETER -ComplexityLevel
Defines the complexity level of the password. The options to be used are H for high complexity, M for medium complexity and L for low complexity. Also can be called by the alias -CL.
.EXAMPLE
Generate a random password with the default settings of high complexity and 9 characters
Get-Password
.EXAMPLE
Generate a password with 20 characters and low complexity(i.e. only letters)
Get-Password -PasswordLength 20 -ComplexityLevel L
#>
#Parameter configuration
Param
(
#Defines the parameter for password length
[Alias("PL")]
[Alias("PassLen")]
[Int]$PasswordLength = 9,
#Defines the paramter for the complexity level of the password generated
[Alias("CL")]
[ValidateSet("H","M","L")]
[String]$ComplexityLevel = "H"
)
Process
{
# The array of characters below is used for the high complexity password generations
$arrCharH = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0","!","@","#","$","%","&","^","*","(",")","-","+","=","_","{","}","\\","/","?","<",">"
# The array of characters below is used for the medium complexity password generations
$arrCharM = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"
# The array of characters below is used for the low complexity password generations
$arrCharL = "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
#Define the counter to be used in the for loop below
$i = 1
#Switch configuration to generate the appropriate complexity level defined by the -ComplexityLevel paramter
Switch ($ComplexityLevel)
{
H {
For(; $i -le $PasswordLength; $i++)
{
$arrPass = Get-Random -Input $arrCharH
Write-Host $arrPass -NoNewLine
}
Write-Host "`n"
}
M {
For(; $i -le $PasswordLength; $i++)
{
$arrPass = Get-Random -Input $arrCharM
Write-Host $arrPass -NoNewLine
}
Write-Host "`n"
}
L {
For(; $i -le $PasswordLength; $i++)
{
$arrPass = Get-Random -Input $arrCharL
Write-Host $arrPass -NoNewLine
}
Write-Host "`n"
}
}
}
|
PowerShellCorpus/PoshCode/Roll-Dice_2.ps1
|
Roll-Dice_2.ps1
|
# Roll-Dice.ps1
# Cody Bunch
# ProfessionalVMware.com
Begin {
$rand = New-Object System.Random
$dice = $rand.next(1,4)
}
Process {
if ( $_ -isnot [VMware.VimAutomation.Types.Snapshot] ) { continue }
if ($dice -gt 1) {
$_ | Remove-Snapshot -Confirm:$false
Write-Host "OH NOES! Snapshot $_ Has been deleted!`n"
} else {
Write-Host "Snapshot $_ lives to fight again!`n"
}
}
|
PowerShellCorpus/PoshCode/IP Scan_Local User admin.ps1
|
IP Scan_Local User admin.ps1
|
# The trigger
$obj = New-Object system.Net.NetworkInformation.Ping
100..200 | % { $ip = "10.1.1.$_"
$ping = $obj.send($ip,100)
write-host "." -noNewLine
if ($ping.status -eq "Success"){
C:\\Powershell\\Finduser.ps1 $ping.address.ipaddresstostring
}}
#--------------------------------
# Finduser.ps1
param (
[string]$strcomputer,
[switch]$delete)
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$Users = $computer.psbase.children |where{$_.psbase.schemaclassname -eq "User"}
foreach ($member in $Users.psbase.syncroot){
if ($member.name -eq "username"){
write-host Found user! $computer.name
if ($delete){
write-host Deleting...
.\\set-localaccount.ps1 -UserName username -remove -computerName $computer.name
}
}
}
#--------------------------------
# set-localaccount.ps1
##################################################################################
#
# Script name: Set-LocalAccount.ps1
# Author: niklas.goude@zipper.se
# Homepage: www.powershell.nu
#
##################################################################################
param([string]$UserName, [string]$Password, [switch]$Add, [switch]$Remove, [switch]$ResetPassword, [switch]$help, [string]$computername)
function GetHelp() {
$HelpText = @"
DESCRIPTION:
NAME: Set-LocalAccount.ps1
Adds or Removes a Local Account
PARAMETERS:
-UserName Name of the User to Add or Remove (Required)
-Password Sets Users Password (optional)
-Add Adds Local User (Optional)
-Remove Removes Local User (Optional)
-ResetPassword Resets Local User Password (Optional)
-help Prints the HelpFile (Optional)
SYNTAX:
.\\Set-LocalAccount.ps1 -UserName nika -Password Password1 -Add
Adds Local User nika and sets Password to Password1
.\\Set-LocalAccount.ps1 -UserName nika -Remove
Removes Local User nika
.\\Set-LocalAccount.ps1 -UserName nika -Password Password1 -ResetPassword
Sets Local User nika's Password to Password1
.\\Set-LocalAdmin.ps1 -help
Displays the helptext
"@
$HelpText
}
function AddRemove-LocalAccount ([string]$UserName, [string]$Password, [switch]$Add, [switch]$Remove, [switch]$ResetPassword, [string]$computerName) {
if($Add) {
[string]$ConnectionString = "WinNT://$computerName"
$ADSI = [adsi]$ConnectionString
$User = $ADSI.Create("user",$UserName)
$User.SetPassword($Password)
$User.SetInfo()
}
if($Remove) {
[string]$ConnectionString = "WinNT://$computerName"
$ADSI = [adsi]$ConnectionString
$ADSI.Delete("user",$UserName)
}
if($ResetPassword) {
[string]$ConnectionString = "WinNT://" + $ComputerName + "/" + $UserName + ",user"
$Account = [adsi]$ConnectionString
$Account.psbase.invoke("SetPassword", $Password)
}
}
if($help) { GetHelp; Continue }
if($UserName -AND $Password -AND $Add -AND !$ResetPassword) { AddRemove-LocalAccount -UserName $UserName -Password $Password -Add -computerName $computerName}
if($UserName -AND $Password -AND $ResetPassword) { AddRemove-LocalAccount -UserName $UserName -Password $Password -ResetPassword -computerName $computerName}
if($UserName -AND $Remove) { AddRemove-LocalAccount -UserName $UserName -Remove -computerName $computerName}
|
PowerShellCorpus/PoshCode/25a74c84-07ab-45d9-a031-0aaf972b8522.ps1
|
25a74c84-07ab-45d9-a031-0aaf972b8522.ps1
|
select * from sys.dm_db_index_physical_stats(db_id('vCenter'),null,null,null,null)
order by avg_fragmentation_in_percent desc
|
PowerShellCorpus/PoshCode/Sendmail for PoSh V1.0.ps1
|
Sendmail for PoSh V1.0.ps1
|
#region vars
$global:maileditor = "C:\\Programme\\vim\\vim72\\vim.exe"
$global:encryption = "C:\\Programme\\GNU\\GnuPG\\gpg.exe"
$global:enckey = "s.patrick1982@gmail.com"
$global:tempmail = "C:\\temp\\psmail.txt"
$global:sigmail = "C:\\temp\\halten\\sig.txt"
$global:mailbody = ""
#endregion vars
#region initMail
function global:initHeader {
$global:mailTo = ($global:mailTo).Split(',') | % { $_.Trim() }
if (Test-Path $global:sigmail) {
(Get-Content $global:sigmail | Out-String) | Out-File $global:tempmail
}
& $global:maileditor $global:tempmail
}
function global:initMail {
$smtpserver = "yoursmtpserver"
$myuser = "user"
$mypass = "pass"
$myAddress = "Patrick<s.patrick1982@gmail.com>"
$global:mail = New-Object System.Net.Mail.MailMessage
$global:srv = New-Object System.Net.Mail.SmtpClient
$global:srv.Host = $smtpserver
$global:srv.Credentials = New-Object System.Net.NetworkCredential($myuser, $mypass)
$global:mail.from = $myAddress
foreach ($rcpt in $global:mailTo) {
if ($rcpt -ne "") {
$global:mail.To.Add($rcpt)
}
}
$global:mail.subject = $global:subject
}
function global:initMailol {
$global:outlook = New-Object -ComObject Outlook.Application
$global:srv = New-Object -ComObject Redemption.SafeMailItem
$global:omail = $outlook.CreateItem("olMailItem")
$global:srv.Item = $global:omail
#region check
#User Input
foreach ($rcpt in $global:mailTo) {
$global:srv.Recipients.Add($rcpt) | Out-Null
}
#check recipients
$check = $global:srv.Recipients.ResolveAll()
if ($check -eq $False) {
for ($i=0; $i -gt $global:sitem.Recipients.Count;$i++) {
$global:srv.Recipients.Remove($i)
exit(-1)
}
}
#endregion
$global:srv.item.Subject = $global:subject
if ($global:debug -eq $true) {
Write-Host "Mail an - " $global:sitem.Recipients
Write-Host "Betreff - " $global:subject
}
}
#endregion initMail
#region sendmail
function global:sendmail {
Param (
[string]$global:client,
[string]$global:mailTo,
[string]$global:subject,
[string]$global:mtype
)
#Parameter Check
if (!$global:client) {
$global:client = Read-Host -Prompt "Which Client (srv,ol): "
}
if (!$global:mailto) {
$global:mailTo = Read-Host -Prompt "E-Mail To: "
}
if (!$global:subject) {
$global:subject = Read-Host -Prompt "Subject: "
}
initheader($global:mailTo, $global:subject)
#region encrypt
switch ($global:mtype) {
s {
& $global:encryption -a -r $global:enckey --clearsign $global:tempmail
break;
}
e {
& $global:encryption -a -r $global:enckey --encrypt $global:tempmail
break;
}
}
#endregion encrypt
#body
if ($global:mtype -ne "") {
$global:mailbody = (Get-Content $global:tempmail".asc" | Out-String)
} else {
$global:mailbody = (Get-Content $global:tempmail | Out-String)
}
#cleaning
if (test-path $global:tempmail) { Remove-Item $global:tempmail -Confirm:$false }
if (test-path $global:tempmail".asc" ) { Remove-Item $global:tempmail".asc" -Confirm:$false }
switch ($global:client) {
srv {
initMail
$global:mail.Body = $global:mailbody
$global:srv.Send($global:mail)
break;
}
ol {
initMailol
$global:srv.Body = $global:mailbody
$global:srv.Send()
break;
}
}
}
|
PowerShellCorpus/PoshCode/Hack ESXi.ps1
|
Hack ESXi.ps1
|
$screen = " You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
"
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/Start-BootsTimer.ps1
|
Start-BootsTimer.ps1
|
function Start-BootsTimer {
#.Syntax
# Creates a stay-on-top countdown timer
#.Description
# A WPF borderless count-down timer, with audio/voice alarms and visual countdown + colored progress indication
#.Parameter EndMessage
# The message to be spoken by a voice when the time is up...
#.Parameter StartMessage
# A message to be spoken at start up (just to let you know, audibly, what's up).
#.Parameter Minutes
# Some minutes to add to the timer
#.Parameter Seconds
# Some seconds to add to the timer
#.Parameter Hours
# Some hours to add to the timer
#.Parameter SoundFile
# A .wav file to play as the alarm
#.Parameter FontSize
# The size of the timer text
#.Parameter SingleAlarm
# Only sound the alarm once
#.Example
# Start-BootsTimer 180 "The three minute egg is ready!"
#
# Starts a three minute timer with the specified voice alert at the end
#
#.Example
# Start-BootsTimer -End "The three minute egg is ready!" -Minute 3
#
# Starts a three minute timer with the specified voice alert at the end
#
#.Example
# Start-BootsTimer "Your turn is over!" -Minutes 10 -Single -FontSize 18
#
# Starts a 10 minute timer that only plays the alert once at the end, and has a small font, which would fit over the task bar or a window title bar...
[CmdletBinding(DefaultParameterSetName="Times")]
PARAM(
[Parameter(Position=2,ParameterSetName="Times",Mandatory=$false)]
[Parameter(Position=1,ParameterSetName="Reasons", Mandatory=$true)]
[string]$EndMessage
,
[Parameter(Position=2,ParameterSetName="Reasons", Mandatory=$false)]
[string]$StartMessage
,
[Parameter(Position=3,ParameterSetName="Reasons", Mandatory=$false)]
[int]$minutes = 0
,
[Parameter(Position=4,ParameterSetName="Reasons", Mandatory=$false)]
[Parameter(Position=1,ParameterSetName="Times", Mandatory=$true)]
[int]$seconds = 0
,
[Parameter()]
[int]$hours = 0
,
[Parameter()]
$SoundFile = "$env:SystemRoot\\Media\\notify.wav"
,
[Parameter()]
$FontSize = 125
,
[Parameter()]
[Switch]$SingleAlarm
)
Write-Host "ParameterSet: $($psCmdlet.ParameterSetName)"
Write-Host "StartMessage: $StartMessage"
Write-Host "EndMessage: $EndMessage"
# Default to 10 seconds ... without adding 5 seconds when people specify minutes
if(($seconds + $Minutes + $hours) -eq 0) { $seconds = 10 }
$start = [DateTime]::Now
## We have to store all this stuff, because the powerboots window lasts longer than the script
$TimerStuff = @{}
$TimerStuff["seconds"] = [Math]::Abs($seconds) + [Math]::Abs([int]($minutes*60)) + [Math]::Abs([int]($hours*60*60))
$TimerStuff["TimerEnd"] = $start.AddSeconds( $TimerStuff["seconds"] )
$TimerStuff["SingleAlarm"] = $SingleAlarm
## Take care of as much overhead as we can before we need it...
if(Test-Path $soundFile) {
$TimerStuff["Sound"] = new-Object System.Media.SoundPlayer
$TimerStuff["Sound"].SoundLocation=$SoundFile
}
if($EndMessage -or $StartMessage) {
$TimerStuff["Voice"] = new-object -com SAPI.SpVoice
}
## Create and store a scriptblock to figure out the remaining time and format it
$TimerStuff["NowFunction"] = {
$diff = $BootsTimer.Tag["TimerEnd"] - [DateTime]::Now;
$diff.TotalSeconds
if($diff.Ticks -ge 0) {
([DateTime]$diff.Ticks).ToString(" HH:mm.ss")
} else {
([DateTime][Math]::Abs($diff.Ticks)).ToString("-HH:mm.ss")
}
}
## Create and store a scriptblock to sound the alarm
$TimerStuff["AlarmFunction"] = {
if($BootsTimer.Tag["Sound"]) {
$BootsTimer.Tag["Sound"].Play()
} else {
[System.Media.SystemSounds]::Exclamation.Play()
}
if($BootsTimer.Tag["EndMessage"]) {
$null = $BootsTimer.Tag["Voice"].Speak( $BootsTimer.Tag["EndMessage"], 1 )
}
}
## Store the "EndMessage" message
if($EndMessage) {
$TimerStuff["EndMessage"] = $EndMessage
}
## If they provided a second status message, read it out loud
if($StartMessage) {
$null = $TimerStuff["Voice"].Speak( $StartMessage, 1 )
}
## Make the window ...
$Global:BootsTimer = boots -WindowStyle None -AllowsTransparency $true -Topmost $true {
TextBlock "" -FontSize $FontSize -FontFamily Impact -margin 20 `
-BitmapEffect $(OuterGlowBitmapEffect -GlowColor White -GlowSize 15) `
-Foreground $(LinearGradientBrush -Start "1,1" -End "0,1" {
GradientStop -Color Black -Offset 0.0
GradientStop -Color Black -Offset 0.95
GradientStop -Color Red -Offset 1.0
GradientStop -Color Red -Offset 1.0
}) # -TextDecorations ([System.Windows.TextDecorations]::Underline)
} -On_MouseDown {
if($_.ChangedButton -eq "Left") { $this.DragMove() }
} -On_Close {
$this.Tag["Timer"].Stop()
Remove-BootsWindow $this
} -Async -Popup -Passthru -Background Transparent -ShowInTaskbar $False -Tag $TimerStuff
## Now we need to call that scriptblock on a timer. That's easy, but it
## must be done on the window's thread, so we use Invoke-BootsWindow.
## Notice the first argument is the window we want to run the script in
Invoke-BootsWindow $BootsTimer {
## We'll create a timer
$BootsTimer.Tag["Timer"] = new-object System.Windows.Threading.DispatcherTimer
$BootsTimer.Tag["Timer"].Interval = [TimeSpan]"0:0:0.05"
## And will invoke the $updateBlock
$BootsTimer.Tag["Timer"].Add_Tick( {
trap {
write-host "Error: $_" -fore Red
write-host $($_.Exception.StackTrace | Out-String) -fore Red
}
$remain, $BootsTimer.Content.Text = & $BootsTimer.Tag["NowFunction"]
$remain = $remain / $BootsTimer.Tag["seconds"]
## Move the gradient a little bit each time.
$BootsTimer.Content.Foreground.GradientStops[2].Offset = [Math]::Max(0.0, $remain)
$BootsTimer.Content.Foreground.GradientStops[1].Offset = [Math]::Max(0.0, $remain - 0.05)
## When we get to the end ... make a few changes
if($remain -le 0) {
## The first time we hit the end, we want to add a mouse click handler...
if($this.Interval.Seconds -eq 0) {
## Which will now only fire every few seconds
## So it's easier to close the window ;)
$this.Interval = [TimeSpan]"0:0:2"
## If you click on the finished window, it just goes away
$BootsTimer.Add_MouseDown( { $BootsTimer.Close() } )
## But if they chose -SingleAlarm, they don't neeto bother
if($BootsTimer.Tag["SingleAlarm"]) { $BootsTimer.Close() }
}
& $BootsTimer.Tag["AlarmFunction"]
}
} )
## Now start the timer running
$BootsTimer.Tag["Timer"].Start()
}
}
|
PowerShellCorpus/PoshCode/Find-Replace.ps1
|
Find-Replace.ps1
|
<#
.SYNOPSIS
Finds and Replaces multiple entries, in multiple files.
.DESCRIPTION
By default, performs an ordinal (case-sensitive and culture-insensitive) search to find an old value and replace it.
.PARAMETER Path
One or more files Paths to process. Excepts values from the Pipeline. Will except the output from Get-ChildItem.
.PARAMETER Object
Any object or array of objects with Find and Replace properties that will be used to make the swap.
-Object (Import-CSV SomeFile.csv)
-Object @{Find = 'this'; Replace = 'that'}, @{Find = 'something'; Replace = 'other'}
.PARAMETER Find
One or more strings to Find.
.PARAMETER Replace
A string to replace those matching -Find.
.PARAMETER Regex
Treat find values as Regular Expressions.
.PARAMETER WhatIf
Test Find and Replace without making any changes.
.PARAMETER Backup
Backup the original file to <OriginalFileName>_yyyyMMddHHmmss.
.PARAMETER PassThru
Passes changed (or needing to be changed with WhatIf enabled) files through the pipeline.
.PARAMETER Encoding
.INPUTS
Excepts file names and file objects for the Path parameter.
.OUTPUTS
None, unless PassThru specified. With PassThru, passes changed (or needing to be changed with WhatIf enabled) files through the pipeline.
.EXAMPLE
Get-ChildItem SomePath\\* -recurse -include *.config,*.xslt,*.xml,*.txt | Find-Replace.ps1 -Object (Import-Csv Replacements.csv) -PassThru | set-content ChangedFiles.txt
#>
[CmdletBinding(DefaultParametersetName="string")]
param (
[Parameter(
Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True,
Position=0,
HelpMessage="One or more file Paths to process."
)]
[string[]]$Path,
[Parameter(
ParameterSetName="object",
Mandatory=$True,
Position=1,
HelpMessage="Any object or array of objects with Find and Replace properties that will be used to make the swap."
)]
$Object,
[Parameter(
ParameterSetName="string",
Mandatory=$True,
Position=1,
HelpMessage="An array of strings to Find."
)]
[string[]]$Find,
[Parameter(
ParameterSetName="string",
Mandatory=$False,
Position=2,
HelpMessage="A string to replace those matching -Find."
)]
[string]$Replace,
[Parameter( HelpMessage="Treat find values as Regular Expressions." )]
[switch]$Regex,
[Parameter( HelpMessage="Test Find and Replace without making any changes." )]
[switch]$WhatIf,
[Parameter( HelpMessage="Backup the original file to <OriginalFileName>_yyyyMMddHHmmss." )]
[switch]$Backup,
[Parameter( HelpMessage="Passes changed (or needing to be changed with WhatIf enabled) files through the pipeline." )]
[switch]$PassThru,
[string]$Encoding = 'ASCII'
)
BEGIN {
$replaceCache = $null
if ($PsCmdlet.ParameterSetName -eq 'string') {
$replaceCache = $Find | Foreach { @{find=$_; replace=$Replace} }
} else {
$replaceCache = $Object | Where {$_.Find -is [string] -and $_.Find.length -gt 0 -and $_.Replace -is [string] } | Foreach { @{find=$_.find; replace=$_.replace}}
}
if ($replaceCache -eq $null) {
Write-Warning 'No find values found or specified.'
Exit
}
$numFiles = 0
$numLines = 0
$numFilesChanged = 0
$numLinesChanged = 0
$RunTime = Get-Date
}
PROCESS {
$Path
foreach ($file in @($Path)){
Write-Verbose "Processing $file"
$numFiles++
$lineNum = 0
$changesNum = 0
Get-Content $file | Foreach {
$line = $_
$lineNum++
Write-Debug ('{0: 0}: {1}' -f $lineNum, $line)
Foreach ($replace in @($replaceCache)) {
Write-Debug ('Find: [{0}] Replace: [{1}]' -f $replace.find, $replace.replace)
if ($Regex) {
$line = $line -replace $replace.find, $replace.replace
} else {
$line = $line.Replace($replace.find, $replace.replace)
}
}
if ($_ -cne $line) {
$changesNum++
Write-Verbose " Changed line $lineNum from '$_' to '$line' in $file."
}
$line
} | Where {-not $WhatIf} | Set-Content -encoding:$Encoding -Path ($file + '_FindReplace')
$numLines += $lineNum
$numLinesChanged += $changesNum
if ($changesNum -gt 0) {
$numFilesChanged++
if (-not $WhatIf) {
if ($Backup) {
Copy-Item ($file + '_FindReplace') ('{0}_{1:yyyyMMddHHmmss}' -f $file, $RunTime) -Verbose:$Verbose
}
Remove-Item $file
Rename-Item ($file + '_FindReplace') $file
Write-Verbose " Changed $changesNum of $lineNum Lines"
}
if ($PassThru) { $file }
}
}
}
END {
$totals = "Totals: Changed $numFilesChanged of $numFiles Files Changed $numLinesChanged of $numLines Lines"
if ($WhatIf) {
Write-Host "What if: $totals"
} else {
Write-Verbose $totals
}
}
|
PowerShellCorpus/PoshCode/sudo for Powershell_2.ps1
|
sudo for Powershell_2.ps1
|
# sudo.ps1
#
# Authors: pezhore, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
# Other powershell peoples.
#
# Sources:
# http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
# http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta
#
# Version:
# 1.0 Initial version
# 1.1 added -ps flag, cleaned up passed $file/$script full path
# 1.2 Comments
# 1.3 Fixed passing working directory to powershell/auto closing
param(
[switch]$ps, # Switch for running args as powershell script
[string]$file, # Script/Program to run
[string]$arguments = $args # Arguments to program/script
)
# Find our powershell full path
$powershell = (get-command powershell).definition
# Get current directory
$dir = get-location
#If we're running this as a elevated powershell script
if ($ps){
# Script verification
if([System.IO.File]::Exists("$(get-location)\\$file")) {
# Set the $script to full path of the ps script
$script = (get-childitem $file).fullname
}
# Create a powershell process
$psi = new-object System.Diagnostics.ProcessStartInfo $powershell
$psi.WorkingDirectory = Get-Location
# Combine the script and its arguments
$sArgs = $script + " " + $arguments
# Set the arguments to be the ps script and it's arguments
$psi.Arguments = "-noexit -command set-location $dir; $sArgs"
# Magic to run as elevated
$psi.Verb = "runas";
}
# We're running something other than a powershells script
else {
# File verification
if([System.IO.File]::Exists("$(get-location)\\$file")) {
# Get full path
$file = (get-childitem $file).fullname
}
# Same as above, create proccess/arguments/runas
$psi = new-object System.Diagnostics.ProcessStartInfo $file
$psi.Arguments = $arguments
$psi.Verb = "runas"
}
# Start the process
[System.Diagnostics.Process]::Start($psi)
|
PowerShellCorpus/PoshCode/Findup_3.ps1
|
Findup_3.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace Findup
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
// Checked = false; // Set if the file has already been checked.
// string SHA512_1st1K; // SHA512 hash of first 1K bytes.
// string SHA512_All; // SHA512 hash of complete file.
}
public FileInfo FI { get; private set; }
public bool Checked { get; set; }
public string SHA512_1st1K { get; set; }
public string SHA512_All { get; set; }
}
class Recurse // Return FileInfoExt list of files matching filenames, file specifications (IE: *.*), and in directories in pathRec
{
public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
foreach (string d in pathRec)
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
return;
}
public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
if (File.Exists(pathRec))
{
try
{
returnList.Add(new FileInfoExt(new FileInfo(pathRec)));
}
catch (Exception e)
{
Console.WriteLine("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
returnList.AddRange(Dir.GetFiles(searchPattern).Select(s => new FileInfoExt(s)));
}
catch (Exception e)
{
Console.WriteLine("Add files from Directory error: " +e.Message);
}
if (recursiveFlag == true)
{
try
{
foreach (string d in (Directory.GetDirectories(pathRec)))
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
}
catch (Exception e)
{
Console.WriteLine("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
string filePart = Path.GetFileName(pathRec);
string dirPart = Path.GetDirectoryName(pathRec);
if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
Recursive(dirPart, filePart, recursiveFlag, returnList);
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
catch (Exception e)
{
Console.WriteLine("Parse error on: " + pathRec);
Console.WriteLine("Exception: " + e.Message);
return;
}
}
return;
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long bytesInDupes = 0; // bytes in all the duplicates
long numOfDupes = 0; // number of duplicate files found.
long bytesRec = 0; // number of bytes recovered.
long delFiles = 0; // number of files deleted.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i],"-help",true) == 0) || (System.String.Compare(args[i],"-h",true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" ");
return;
}
if (System.String.Compare(args[i],"-recurse",true) == 0)
{
recurse = true;
continue;
}
if (System.String.Compare(args[i],"-delete",true) == 0)
{
delete = true;
continue;
}
if (System.String.Compare(args[i],"-noprompt",true) == 0)
{
noprompt = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
return;
}
Recurse recurseMe = new Recurse();
recurseMe.Recursive(paths, "*.*", recurse, fs);
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
return;
}
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Checked == true) // If file was already matched, then skip to next.
continue;
for (c = i+1; c < fs.Count; c++)
{
if (fs[c].Checked == true) // skip already matched inner loop files.
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (fs[i].FI.FullName == fs[c].FI.FullName) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
fs[i].SHA512_1st1K = ComputeInitialHash(fs[i].FI.FullName);
if (fs[c].SHA512_1st1K == null)
fs[c].SHA512_1st1K = ComputeInitialHash(fs[c].FI.FullName);
if (fs[i].SHA512_1st1K != fs[c].SHA512_1st1K) // if the 1st 1K has the same hash..
continue;
if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file.
continue;
if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName);
if (fs[c].SHA512_All == null)
fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName);
if (fs[i].SHA512_All != fs[c].SHA512_All)
continue;
if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate.
continue;
}
Console.WriteLine(" Match: " + fs[i].FI.FullName);
Console.WriteLine(" with: " + fs[c].FI.FullName);
fs[c].Checked = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates.
if (delete != true) // if delete is specified, try to delete the duplicate file.
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y'))
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length;
delFiles++;
}
catch (Exception e)
{
Console.WriteLine("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("Files checked: " + fs.Count);
Console.WriteLine("Duplicate files: " + numOfDupes);
Console.WriteLine("Bytes in duplicate files: " + bytesInDupes);
Console.WriteLine("Duplicates deleted: " + delFiles);
Console.WriteLine("Bytes recovered: " + bytesRec);
return;
}
private static readonly byte[] readBuf = new byte[1024];
private static string ComputeInitialHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var hash = SHA512.Create().ComputeHash(readBuf, 0, length);
return BitConverter.ToString(hash);
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return (null);
}
}
private static string ComputeFullHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
return BitConverter.ToString(SHA512.Create().ComputeHash(stream));
}
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return (null);
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-MX.ps1
|
Get-MX.ps1
|
#Returns the priority mail server (SMTP) for a particular email address.
function Get-MX {
param([string] $domain = $( Throw "Query required in the format domain.com or email@domain.com.") )
#rip domain out of full email address if necessary:
if ($domain.IndexOf("@")) { $domain = $domain.SubString($domain.IndexOf("@")+1) }
#get all the MX records for this domain, sorted by descending preference
$mxrecords = @(get-dns $domain -type MX | sort-object -Property PREFERENCE -des)
#verify that there are some records
if ($mxrecords.Length -eq 0) { Throw "No records found." }
#The correct record is the one with the lowest preference:
$mxrecords[0].EXCHANGE
}
|
PowerShellCorpus/PoshCode/LDAPLogging_1.ps1
|
LDAPLogging_1.ps1
|
\nfunction Private:Configure-Logging {\n<#\n .SYNOPSIS\n Enables, disables or view current LDAP Logging settings on a domain controller.\n\n .DESCRIPTION\n Enables, disables or view current LDAP Logging settings on a domain controller.\n \n Use one of the following aliases:\n \n Get-LDAPLogging\n View current LDAP logging settings\n \n Enable-LDAPLogging\n Enables LDAP logging. Logging is set to log every single LDAP query and stores it in directory services log.\n\n Disable-LDAPLogging\n Disables LDAP logging. Logging is set to its default values.\n\n .EXAMPLE\n PS C:\\> Get-LDAPLogging\n\n .EXAMPLE\n PS C:\\> Enable-LDAPLogging DC1\n\n .INPUTS\n N/A\n\n .OUTPUTS\n N/A\n\n .NOTES\n Author: Patrick Sczepanski \n Version: 1.0\n Email: patrick -at- sczepanski -dot- com\n patrick -dot- redtoo -at- redtoo -dot- com\n Blog: http://redtoo.com/blog\n Copyright: 2012\n\n .LINK\n Get-LDAPLogging\n Enable-LDAPLogging\n Disable-LDAPLogging\n Get-LDAPEventLog\n\n#>\n \n Param (\n [string]\n $HostName = $env:COMPUTERNAME\n )\n \n [System.Nullable``1[[System.Int32]]]$EnableLogging = $null\n switch ( $MyInvocation.InvocationName ) {\n "Enable-LDAPLogging" { \n [System.Nullable``1[[System.Int32]]]$EnableLogging = $true\n [bool]$ReadWrite = $true\n [int]$Threshold = 1\n [int]$FieldEngDef = 5\n break\n }\n "Disable-LDAPLogging" { \n [System.Nullable``1[[System.Int32]]]$EnableLogging = $false\n [bool]$ReadWrite = $true\n [int]$Threshold = 0\n [int]$FieldEngDef = 0\n break\n }\n Default { \n [System.Nullable``1[[System.Int32]]]$EnableLogging = $null\n [bool]$ReadWrite = $false\n }\n }\n\n if ( -not (Test-Connection $HostName -Quiet -Count 1) ) {\n Write-Warning "Cannot Ping $HostName"\n continue\n }\n if ( -not ( \n Get-WmiObject -query "select producttype from Win32_OperatingSystem where producttype='2'" `\n -ComputerName $HostName -ErrorAction SilentlyContinue) ) {\n Write-Warning "$HostName is not a domain controller or you do not have access."\n continue\n }\n \n $NTDSParams = "SYSTEM\\CurrentControlSet\\Services\\NTDS\\Parameters"\n $ExpThre = "Expensive Search Results Threshold"\n $IneThre = "Inefficient Search Results Threshold"\n\n $NTDSDiag = "SYSTEM\\CurrentControlSet\\Services\\NTDS\\Diagnostics"\n $FieldEng = "15 Field Engineering"\n\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( "LocalMachine", $HostName )\n\n try {\n $key = $baseKey.OpenSubKey($NTDSParams,$ReadWrite)\n if ( $EnableLogging -eq $true ) { \n $key.SetValue( $ExpThre, 1, [Microsoft.Win32.RegistryValueKind]::DWord )\n $key.SetValue( $IneThre, 1, [Microsoft.Win32.RegistryValueKind]::DWord )\n } elseif ( $EnableLogging -eq $false ) {\n $key.DeleteValue( $ExpThre )\n $key.DeleteValue( $IneThre )\n }\n $ExpThreValue = $key.GetValue($ExpThre)\n $IneThreValue = $key.GetValue($IneThre)\n $key.Close()\n }\n catch {\n Write-Warning "Failed to read or change $NTDSParams.`r`n$_"\n }\n try {\n $key = $baseKey.OpenSubKey($NTDSDiag,$ReadWrite)\n if ( $EnableLogging -ne $null ) { \n $key.SetValue( $FieldEng, $FieldEngDef )\n } \n $FieldEngValue = $key.GetValue($FieldEng)\n $key.Close()\n }\n catch {\n Write-Warning "Failed to read or change $NTDSDiag.`r`n$_"\n }\n $baseKey.Close()\n New-Object PSObject -Property @{\n "FieldEngineering" = $FieldEngValue\n "ExpensiveThreshold" = $ExpThreValue\n "InefficientThreshold" = $IneThreValue\n }\n}\nNew-Alias Get-LDAPLogging Configure-Logging -Force\nNew-Alias Enable-LDAPLogging Configure-Logging -Force\nNew-Alias Disable-LDAPLogging Configure-Logging -Force\n\nFunction Global:Get-LDAPEventLog {\n<#\n .SYNOPSIS\n Searches the Directory Service Eventlog for event ID 1644, parses the message text and returns a custom object.\n\n .DESCRIPTION\n Searches the Directory Service Eventlog for event ID 1644, parses the message text and returns a custom object.\n \n Use "Enable-LDAPLogging" to enable logging LDAP queries on a domain controller.\n\n .EXAMPLE\n PS C:\\> Get-LDAPEventLog\n\n .INPUTS\n [string],[int]\n\n .OUTPUTS\n [LDAPLookups]\n\n .NOTES\n Author: Patrick Sczepanski \n Version: 1.0\n Email: patrick -at- sczepanski -dot- com\n patrick -dot- redtoo -at- redtoo -dot- com\n Blog: http://redtoo.com/blog\n Copyright: 2012\n\n .LINK\n Get-LDAPLogging\n Enable-LDAPLogging\n Disable-LDAPLogging\n\n#>\nParam (\n [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]\n [string]\n $DNSHostName = $env:COMPUTERNAME,\n \n [int]\n $LookupMinutes = 60\n \n )\n Begin {\n $Script:AlreadyLookedUp = @{}\nAdd-Type @'\nusing System;\n public class LDAPLookups {\n public string DNSHostName;\n public string ClientIP;\n public System.Nullable<int> ClientPort;\n public string ClientName;\n public string StartNode;\n public string Filter;\n public string SearchScope;\n public string Attributes;\n public string ServerControls;\n public System.Nullable<int> VisitedEntries;\n public System.Nullable<int> ReturnedEntries;\n public string Date;\n public string Time;\n }\n'@ \n\n$RegEx = @"\n(?msx)\n # Option m = multi-line e.g. ^=start of line and $=end of line \n # Option s = single-line e.g. . includes end-of-line \n # Option x = spaces and comments are allowed in the pattern \nClient:\\r\\n\n (?<Client>.*)\\:(?<Port>.*)\\r\\n?\n\nStarting\\snode\\:\\r\\n\n (?<StartNode>.*?)\\r\\n\n\nFilter:\\r\\n\n (?<Filter>.*?)\\r\\n\n\nSearch\\sscope:\\r\\n\n (?<SearchScope>.*?)\\r\\n\n\nAttribute\\sselection:\\r\\n\n (?<Attributes>.*?)\\r\\n\n\nServer\\scontrols:\\r\\n\n (?<ServerControls>.*?)\\r\\n\n\nVisited\\sentries:\\r\\n\n (?<VisitedEntries>.*?)\\r\\n\n\nReturned\\sentries:\\r\\n\n (?<ReturnedEntries>.*)\n"@\n }\n Process {\n Write-Host "... $DNSHostName ..."\n Get-WinEvent -ComputerName $DNSHostName -FilterHashtable @{ "LogName"="Directory Service" ; "ID"=1644; StartTime= [datetime]::Now.AddMinutes( -$LookupMinutes ) } |\n Foreach-Object { \n if ( $_.Message -match $RegEx ) { \n New-Object LDAPLookups -Property @{\n "DNSHostName" = $DNSHostName\n "ClientIP" = $Matches.Client \n "ClientPort" = ($Matches.Port).Trim()\n "ClientName" = $( $ClientIP = $Matches.Client\n try {\n if( -not $AlreadyLookedUp.contains( $ClientIP ) ){\n $AlreadyLookedUp.$ClientIP = ( [System.Net.Dns]::GetHostByAddress( $ClientIP ).HostName )\n }\n }\n catch {\n $AlreadyLookedUp.$ClientIP = $ClientIP\n }\n $AlreadyLookedUp.$ClientIP\n )\n "StartNode" = ($Matches.StartNode).Trim()\n "Filter" = ($Matches.Filter).trim()\n "SearchScope" = ($Matches.SearchScope).trim()\n "Attributes" = ($Matches.Attributes).trim()\n "ServerControls" = ($Matches.ServerControls).trim()\n "VisitedEntries" = ($Matches.VisitedEntries).trim()\n "ReturnedEntries" = ($Matches.ReturnedEntries).trim()\n "Date" = $_.TimeCreated.ToString( "yyyy.MM.dd" )\n "Time" = $_.TimeCreated.ToString( "HH:mm:ss" )\n }\n }\n } \n } \n End {\n Remove-Variable -Scope Script -Name AlreadyLookedUp\n }\n} \nWrite-Host "LDAPLogging functions loaded into Global."
|
PowerShellCorpus/PoshCode/Add-Identity.ps1
|
Add-Identity.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[alias("Name","ComputerName")] $Computer = @($env:computername),
[string] $NTDomain = ($env:UserDomain),
[string[]] $LocalGroups = @("Administrators"),
[string[]] $Identities, # can be domain user or group
[switch] $Output,
[switch] $Add,
[switch] $Remove
)
begin{
$Global:objReport = @()
# list current members in defined group
Function ListMembers ($Group){
$members = $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
return $members
}
}
process{
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet -EA "Stop"){
foreach ($Group in $LocalGroups){
try{
$tmpComputer = [ADSI]("WinNT://" + $Computer + ",computer")
$tmpGroup = $tmpComputer.psbase.children.find($Group)
foreach ($User in $(ListMembers $tmpGroup)){
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = "Existing"
}#end object
$Global:objReport+= $objoutput
}
if ($Identities){
foreach ($User in $Identities){
$Action = "none"
If ($Add){
$tmpGroup.Add("WinNT://" + $NTDomain + "/" + $User)
$Action = "Added"
}
If ($Remove){
$tmpGroup.Remove("WinNT://" + $NTDomain + "/" + $User)
$Action = "Removed"
}
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = $Action
}#end object
$Global:objReport+= $objoutput
}
}
}
catch{
$continue = $False
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = $Error[0].Exception.InnerException.Message.ToString().Trim()
}#end object
$Global:objReport+= $objoutput
}
}
}
}
end{
$Global:objReport
}
|
PowerShellCorpus/PoshCode/Out-Voice 1.2.ps1
|
Out-Voice 1.2.ps1
|
# ---------------------------------------------------------------------------
## <Script>
## <Author>
## Joel "Jaykul" Bennett
## </Author>
## <Description>
## Outputs text as spoken words
## </Description>
## <Usage>
## Out-Speech "Hello World"
## </Usage>
## </Script>
# ---------------------------------------------------------------------------
param([array]$Collection, [switch]$wait, [switch]$purge, [switch]$readfiles, [switch]$readxml, [switch]$notxml, [switch]$passthru)
begin
{
if ($args -eq '-?') {
''
'Usage: Out-Speech [[-Collection] <array>]'
''
'Parameters:'
' -Collection : A collection of items to speak.'
' -? : Display this usage information'
' Switches:'
' -wait : Wait for the machine to read each item (NOT asynchronous).'
' -purge : Purge all other speech requests before making this call.'
' -readfiles : Read the contents of the text files indicated.'
' -readxml : Treat input as speech XML markup.'
' -notxml : Do NOT parse XML (if text starts with "<" but is not XML).'
' -passthru : Pass on the input as output.'
''
'Examples:'
' PS> Out-Speech "Hello World"'
' PS> Select-RandomLine quotes.txt | Out-Speech -wait'
' PS> Out-Speech -readfiles "Hitchhiker''s Guide To The Galaxy.txt"'
''
exit
}
# To override this default, use the other flag values given below.
$SPF_DEFAULT = 0 # Specifies that the default settings should be used.
## The defaults are:
#~ * Speak the given text string synchronously
#~ * Not purge pending speak requests
#~ * Parse the text as XML only if the first character is a left-angle-bracket (<)
#~ * Not persist global XML state changes across speak calls
#~ * Not expand punctuation characters into words.
$SPF_ASYNC = 1 # Specifies that the Speak call should be asynchronous.
$SPF_PURGEBEFORESPEAK = 2 # Purges all pending speak requests prior to this speak call.
$SPF_IS_FILENAME = 4 # The string passed is a file name, and the file text should be spoken.
$SPF_IS_XML = 8 # The input text will be parsed for XML markup.
$SPF_IS_NOT_XML= 16 # The input text will not be parsed for XML markup.
$SPF = $SPF_DEFAULT
if(!$wait){ $SPF += $SPF_ASYNC }
if($purge){ $SPF += $SPF_PURGEBEFORESPEAK }
if($readfiles){ $SPF += $SPF_IS_FILENAME }
if($readxml){ $SPF += $SPF_IS_XML }
if($notxml){ $SPF += $SPF_IS_NOT_XML }
$Voice = new-object -com SAPI.SpVoice
if ($collection.count -gt 0) {
foreach( $item in $collection ) {
$exit = $Voice.Speak( ($item | out-string), $SPF )
}
}
}
process
{
if ($_)
{
$exit = $Voice.Speak( ($_ | out-string), $SPF )
if($passthru) { $_ }
}
}
|
PowerShellCorpus/PoshCode/Get-Hostname_5.ps1
|
Get-Hostname_5.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/Start-Demo 3.3.2.ps1
|
Start-Demo 3.3.2.ps1
|
## Start-Demo.ps1
##################################################################################################
## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett
##
## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time)
## As a result, I've changed the names and keys for a lot of the operations, so that they make
## sense with only a single letter to tell them apart (sorry if you had them memorized).
##
## I've also been adding features as I come across needs for them, and you'll contribute your
## improvements back to the PowerShell Script repository as well.
##################################################################################################
## Revision History (version 3.3)
## 3.3.2 Fixed: Changed the "x" to match the "a" in the help text
## 3.3.1 Fixed: Added a missing bracket in the script
## 3.3 - Added: Added a "Clear Screen" option
## - Added: Added a "Rewind" function (which I'm not using much)
## 3.2 - Fixed: Put back the trap { continue; }
## 3.1 - Fixed: No Output when invoking Get-Member (and other cmdlets like it???)
## 3.0 - Fixed: Commands which set a variable, like: $files = ls
## - Fixed: Default action doesn't continue
## - Changed: Use ReadKey instead of ReadLine
## - Changed: Modified the option prompts (sorry if you had them memorized)
## - Changed: Various time and duration strings have better formatting
## - Enhance: Colors are settable: prompt, command, comment
## - Added: NoPauseAfterExecute switch removes the extra pause
## If you set this, the next command will be displayed immediately
## - Added: Auto Execute mode (FullAuto switch) runs the rest of the script
## at an automatic speed set by the AutoSpeed parameter (or manually)
## - Added: Automatically append an empty line to the end of the demo script
## so you have a chance to "go back" after the last line of you demo
##################################################################################################
##
param(
$file=".\\demo.txt",
[int]$command=0,
[System.ConsoleColor]$promptColor="Yellow",
[System.ConsoleColor]$commandColor="White",
[System.ConsoleColor]$commentColor="Green",
[switch]$FullAuto,
[int]$AutoSpeed = 3,
[switch]$NoPauseAfterExecute
)
$RawUI = $Host.UI.RawUI
$hostWidth = $RawUI.BufferSize.Width
# A function for reading in a character
function Read-Char() {
$_OldColor = $RawUI.ForeGroundColor
$RawUI.ForeGroundColor = "Red"
$inChar=$RawUI.ReadKey("IncludeKeyUp")
# loop until they press a character, so Shift or Ctrl, etc don't terminate us
while($_input.Character -eq 0){
$inChar=$RawUI.ReadKey("IncludeKeyUp")
}
$RawUI.ForeGroundColor = $_OldColor
return $inChar.Character
}
function Rewind($lines, $index, $steps = 1) {
$started = $index;
$index -= $steps;
while(($index -ge 0) -and ($lines[$index].Trim(" `t").StartsWith("#"))){
$index--
}
if( $index -lt 0 ) { $index = $started }
return $index
}
$file = Resolve-Path $file
while(-not(Test-Path $file)) {
$file = Read-Host "Please enter the path of your demo script (Crtl+C to cancel)"
$file = Resolve-Path $file
}
Clear-Host
$_lines = Get-Content $file
# Append an extra (do nothing) line on the end so we can still go back after the last line.
$_lines += "Write-Host 'The End'"
$_starttime = [DateTime]::now
$FullAuto = $false
Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
Write-Host -nonew -back black -fore $promptColor @"
<Demo Started :: $(split-path $file -leaf)>$(' ' * ($hostWidth -(18 + $(split-path $file -leaf).Length)))
"@
Write-Host -nonew -back black -fore $promptColor "Press"
Write-Host -nonew -back black -fore Red " ? "
Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth -17))"
Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth)
# We use a FOR and an INDEX ($_i) instead of a FOREACH because
# it is possible to start at a different location and/or jump
# around in the order.
for ($_i = $Command; $_i -lt $_lines.count; $_i++)
{
# Put the current command in the Window Title along with the demo duration
$Dur = [DateTime]::Now - $_StartTime
$RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i])
# Echo out the commmand to the console with a prompt as though it were real
Write-Host -nonew -fore $promptColor "[$_i]PS> "
if ($_lines[$_i].Trim(" ").StartsWith("#")) {
Write-Host -fore $commentColor "$($_Lines[$_i]) "
continue
} else {
Write-Host -nonew -fore $commandColor "$($_Lines[$_i]) "
}
if( $FullAuto ) { Start-Sleep $autoSpeed; $ch = [char]13 } else { $ch = Read-Char }
switch($ch)
{
"?" {
Write-Host -Fore $promptColor @"
Running demo: $file
(n) Next (p) Previous
(q) Quit (s) Suspend
(t) Timecheck (v) View $(split-path $file -leaf)
(g) Go to line by number
(f) Find lines by string
(a) Auto Execute mode
(c) Clear Screen
"@
$_i-- # back a line, we're gonna step forward when we loop
}
"n" { # Next (do nothing)
Write-Host -Fore $promptColor "<Skipping Line>"
}
"p" { # Previous
Write-Host -Fore $promptColor "<Back one Line>"
while ($_lines[--$_i].Trim(" ").StartsWith("#")){}
$_i-- # back a line, we're gonna step forward when we loop
}
"a" { # EXECUTE (Go Faster)
$AutoSpeed = [int](Read-Host "Pause (seconds)")
$FullAuto = $true;
Write-Host -Fore $promptColor "<eXecute Remaining Lines>"
$_i-- # Repeat this line, and then just blow through the rest
}
"q" { # Quit
Write-Host -Fore $promptColor "<Quiting demo>"
$_i = $_lines.count;
break;
}
"v" { # View Source
$lines[0..($_i-1)] | Write-Host -Fore Yellow
$lines[$_i] | Write-Host -Fore Green
$lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow
$_i-- # back a line, we're gonna step forward when we loop
}
"t" { # Time Check
$dur = [DateTime]::Now - $_StartTime
Write-Host -Fore $promptColor $(
"{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString()))
$_i-- # back a line, we're gonna step forward when we loop
}
"s" { # Suspend (Enter Nested Prompt)
Write-Host -Fore $promptColor "<Suspending demo - type 'Exit' to resume>"
$Host.EnterNestedPrompt()
$_i-- # back a line, we're gonna step forward when we loop
}
"g" { # GoTo Line Number
$i = [int](Read-Host "line number")
if($i -le $_lines.Count) {
if($i -gt 0) {
# extra line back because we're gonna step forward when we loop
$_i = Rewind $_lines $_i (($_i-$i)+1)
} else {
$_i = -1 # Start negative, because we step forward when we loop
}
}
}
"f" { # Find by pattern
$match = $_lines | Select-String (Read-Host "search string")
if($match -eq $null) {
Write-Host -Fore Red "Can't find a matching line"
} else {
$match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) }
if($match.Count -lt 1) {
$_i = $match.lineNumber - 2 # back a line, we're gonna step forward when we loop
} else {
$_i-- # back a line, we're gonna step forward when we loop
}
}
}
"c" {
Clear-Host
$_i-- # back a line, we're gonna step forward when we loop
}
"$([char]13)" { # on enter
Write-Host
trap [System.Exception] {Write-Error $_; continue;}
Invoke-Expression ($_lines[$_i]) | out-default
if(-not $NoPauseAfterExecute -and -not $FullAuto) {
$null = $RawUI.ReadKey("NoEcho,IncludeKeyUp") # Pause after output for no apparent reason... ;)
}
}
default
{
Write-Host -Fore Green "`nKey not recognized. Press ? for help, or ENTER to execute the command."
$_i-- # back a line, we're gonna step forward when we loop
}
}
}
$dur = [DateTime]::Now - $_StartTime
Write-Host -Fore $promptColor $(
"<Demo Complete -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s>" -f
$dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString())
Write-Host -Fore $promptColor $([DateTime]::now)
Write-Host
|
PowerShellCorpus/PoshCode/InvokeCSharp.ps1
|
InvokeCSharp.ps1
|
#< #
#.Synopsis
@@# Create a class instance and/or invoke a method on C# source code.
@@# For details, see:
@@# http://vincenth.net/blog/archive/2009/10/27/call-inline-c-from-powershell-with-invokecsharp.aspx
#.Description
# This function compiles the provided C# source code (only if necessary, compiled
# assemblies are cached). The code can be supplied either inline in a string or
# in a source file. Relative source filename paths are interpreted
# relative to the parent folder of the calling script.
# This enables simple organization and reference of related .ps1 and .cs files.
#
# If a method name is specified, that method is invoked with any supplied
# parameters and the function then returns the result of the method.
# Both static and nonstatic methods are supported, including overloaded
# methods.
#
# If no method name is specified, an instance of the specified class is
# created, passing any supplied parameters to the class constructor, and the
# function then returns the class instance. You can then program against the
# class instance in standard PowerShell fashion.
#
# If necessary for compilation, you can specify names of any referenced
# assemblies.
#.Parameter code
# The complete C# source code - effectively this is an inline C# source file.
# Note that it is possible but not necessary to declare classes within a
# namespace.
# Either the code parameter or the file parameter must be specified.
#.Parameter file
# Absolute or relative path to a C# source file. Relative paths (beginning
# with '.\\' or '..\\') are interpreted relative to the folder that contains
# the calling script (i.e. the script that calls this function).
# Either the code parameter or the file parameter must be specified.
#.Parameter class
# The name of the class to be instantiated / that contains the method to
# be invoked. Include the namespace in which the class is declared, if any.
# If you specify the -file parameter and the class name is identical to the
# file name, you can omit the -class parameter.
#.Parameter method
# Either the name of the method to be invoked, '()' to invoke a
# constructor to create and resturn a class instance, or '' to return
# the cached assembly. The last option allows you to precompile assemblies
# without calling a method or creating a class instance.
#
# If the specified method is not static, an instance of the class will
# be created on the fly.
#.Parameter parameters
# To pass parameters to the constructor or method, specify them as an
# array of objects (e.g. with the comma operator or @() ).
#.Parameter reference
# If necessary, specify an array of assembly filenames to be added as
# assembly references when the source code is compiled.
#.Parameter forceCompile
# Specify this switch to force recompilation. This is useful if you specify
# the file parameter and the file contents has changed (when specifying a
# source file name, the cache key is the file name only - changes to the file
# do not automatically cause cache invalidation).
#.Returns
# Either the cached assembly, a class instance or a method result (depending
# on the value specified for the method parameter).
#.Example
# # Create a class instance from a .cs file, passing a parameter to the class constructor:
# # Note that the class name can be omitted here, since it is implied from the .cs file name
# $myClassInstance = InvokeCSharp -file '.\\MyClass.cs' -parameters 'A text'
#
# # Call some simple inline code. Note that you could also wrap the code in a namespace,
# # add using statements and reference other assemblies.
# $code = @"
# public class MyClass2
# {
# public static int MyStaticMethod(int a, int b)
# {
# return a * b;
# }
# }
# "@
# $result = InvokeCSharp -code $code -class 'MyClass2' -method 'MyStaticMethod' -parameters 3, 7 # Will return 21
##>
function global:InvokeCSharp
{
param(
[string] $code = '',
[string] $file = '',
[string] $class = '',
[string] $method = '()',
[Object[]] $parameters = $null,
[string[]] $reference = @(),
[switch] $forceCompile
)
# Stores a cache of generated assemblies. If this library is dot-sourced
# from a script, these objects go away when the script exits.
if(-not (Test-Path Variable:\\macaw.solutionsfactory.assemblycache))
{
${GLOBAL:macaw.solutionsfactory.assemblycache} = @{}
}
if (($code -eq '') -and ($file -eq '')) { throw 'Neither code nor file are specified. Specify either one or the other.' }
# If a source file was specified, see if it was already loaded, compiled and cached:
if ($file -ne '')
{
if ($code -ne '') { throw 'Both code and file are specified. Specify either one or the other.' }
# We interpret the current directory as the directory containing the calling script, instead of the currect directory of the current process.
if ($file.StartsWith('.'))
{
$callingScriptFolder = Split-Path -path ((Get-Variable MyInvocation -Scope 1).Value).MyCommand.Path -Parent
$file = Join-Path -Path $callingScriptFolder -ChildPath $file
}
# If no class name is specified, we assume by convention that the file name is equal to the class name.
if ($class -eq '') { $class = [System.IO.Path]::GetFileNameWithoutExtension($file) }
# Use the real full path as the cache key:
$file = [System.IO.Path]::GetFullPath((Convert-Path -path $file))
$cacheKey = $file
}
else
{
# See if the code has already been compiled and cached
$cacheKey = $code
}
if ($class -eq '') { throw 'Required parameter missing: class' }
# See if the code must be (re)compiled:
$cachedAssembly = ${macaw.solutionsfactory.assemblycache}[$cacheKey]
if(($cachedAssembly -eq $null) -or $forceCompile)
{
if ($code -eq '') { $code = [System.IO.File]::ReadAllText($file) }
Write-Verbose "Compiling C# code:`r`n$code`r`n"
# Obtains an ICodeCompiler from a CodeDomProvider class.
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
# Get the location for System.Management.Automation DLL
$dllName = [PsObject].Assembly.Location
# Configure the compiler parameters
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$assemblies = @("System.dll", $dllName)
$compilerParameters.ReferencedAssemblies.AddRange($assemblies)
$compilerParameters.ReferencedAssemblies.AddRange($reference)
$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
}
# There were no errors. Store the resulting assembly in the cache.
else
{
${macaw.solutionsfactory.assemblycache}[$cacheKey] = $compilerResults.CompiledAssembly
}
$cachedAssembly = ${macaw.solutionsfactory.assemblycache}[$cacheKey]
}
# Prevent type mismatch issues caused by PowerShell wrapping of managed objects in PSObject.
# We need to explicitly unwrap those objects because otherwise the .NET reflection classes will
# not find the constructor or method whose signature matches the specified parameters.
# This unwrapping eliminates the need to always wrap all your parameters in @() and to explicitly
# cast each parameter to the correct type in each call to InvokeCSharp.
if ($parameters -ne $null)
{
for($i = 0; $i -lt $parameters.Length; $i++)
{
$parameters[$i] = [System.Management.Automation.LanguagePrimitives]::ConvertTo( `
$parameters[$i], `
[System.Type]::GetType($parameters[$i].GetType().FullName) `
)
}
}
if ($method -eq '') # We return the assembly
{
$result = $cachedAssembly
}
elseif ($method -eq '()') # We create and return a class instance
{
$result = $cachedAssembly.CreateInstance($class, $false, [System.Reflection.BindingFlags]::CreateInstance, $null, $parameters, $null, @())
}
else # We invoke the method and return the method result
{
$classType = $cachedAssembly.GetType($class)
$parameterTypes = @()
if ($parameters -ne $null) { foreach($p in $parameters) { $parameterTypes += $p.GetType() } }
$methodInfo = $classType.GetMethod($method, [System.Type[]]$parameterTypes)
if ($methodInfo.IsStatic)
{
$instance = $null
}
else
{
$instance = $cachedAssembly.CreateInstance($class, $false, [System.Reflection.BindingFlags]::CreateInstance, $null, $null, $null, @())
}
$result = $methodInfo.Invoke($instance, $parameters);
}
return $result
}
|
PowerShellCorpus/PoshCode/Remove Duplicate Notes.ps1
|
Remove Duplicate Notes.ps1
|
# remove outlook duplicate notes and put the removed note in a file
$outlook = new-object -comobject outlook.application
$session = $outlook.session
$session.logon()
$olFoldersEnum = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$notes = $session.getdefaultfolder($olFoldersEnum::olFolderNotes).items
Write-Host "Number of notes:" $notes.count
$noteStringModifiedDateMap = @{}
$notesToDelete = @()
Foreach ($e in $notes)
{
$noteText = $e.Body
$noteModified = $e.LastModificationTime
if ($noteStringModifiedDateMap.ContainsKey($noteText))
{
$mapElement = $noteStringModifiedDateMap.Get_Item($noteText)
if ($mapElement.LastModificationTime -gt $noteModified) # delete the new one
{ $notesToDelete += $mapElement }
else
{ $notesToDelete += $e }
}
else
{ $noteStringModifiedDateMap.Add($noteText, $e) }
}
$notesToDelete | Export-Csv "C:\\toDelete.csv"
foreach ($e in $notesToDelete)
{ $e.Delete() }
Write-Host "done!"
|
PowerShellCorpus/PoshCode/Get VMware Information_1.ps1
|
Get VMware Information_1.ps1
|
Connect-VIServer YOURSERVER
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "Power State"
$Sheet.Cells.Item(1,3) = "Description"
$Sheet.Cells.Item(1,4) = "Number of CPUs"
$Sheet.Cells.Item(1,5) = "Memory (MB)"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-VM | Select-Object -property "Name","PowerState","Description","NumCPU","MemoryMB"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$powerstate = $objItem.PowerState
If ($PowerState -eq 1) {$power = "Powerd On"}
Else {$power = "Powerd Off"}
$Sheet.Cells.Item($intRow,2) = $power
$Sheet.Cells.Item($intRow,3) = $objItem.Description
$Sheet.Cells.Item($intRow,4) = $objItem.NumCPU
$Sheet.Cells.Item($intRow,5) = $objItem.MemoryMB
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
$Sheet = $Excel.WorkSheets.Item(2)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "Free Space"
$Sheet.Cells.Item(1,3) = "Capacity"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-Datastore | Select-Object -property "Name","FreeSpaceMB","CapacityMB"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$Sheet.Cells.Item($intRow,2) = $objItem.FreeSpaceMB
$Sheet.Cells.Item($intRow,3) = $objItem.CapacityMB
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
$Sheet = $Excel.WorkSheets.Item(3)
$Sheet.Cells.Item(1,1) = "Name"
$Sheet.Cells.Item(1,2) = "State"
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems = Get-VMhost | Select-Object -property "Name","State"
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$state = $objItem.State
If ($state -eq 0) {$status = "Connected"}
Else {$status = "Disconnected"}
$Sheet.Cells.Item($intRow,2) = $status
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
|
PowerShellCorpus/PoshCode/Get-VMHostNetworks_1.ps1
|
Get-VMHostNetworks_1.ps1
|
Function Get-VMHostNetworks
{
<#
.SYNOPSIS
Return a list of networks from a given host
.DESCRIPTION
After connecting to your VI server, we get a list of virtual switches on the datacenter and from
that we pull out the VHostID that matches the server we passed in at the command-line. Using the
VHostID we return a list of networks objects on that server.
.PARAMETER VMHost
The name of the VMWare Host Server to pull networks from
.PARAMETER VIServer
The name of your VSPhere Server
.EXAMPLE
Get-VMHostNetworks -VMHost v1.copmany.com -VIServer vc.company.com
Name Key VLanId PortBinding NumPorts
---- --- ------ ----------- --------
Management Network key-vim.host.PortGroup-Mana... 0
DMZ Network key-vim.host.PortGroup-DMZ ... 100
Admin Network key-vim.host.PortGroup-Admi... 101
Description
-----------
This shows the output from the command using all parameters.
.NOTES
This script requires the VMware vSphere PowerCLI to be downloaded and installed, please see
the second link for the download.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/VMWareManagement#Get-VMHostNetworks
.LINK
http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli
.LINK
http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Connect-VIServer.html
.LINK
http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualSwitch.html
.LINK
http://www.vmware.com/support/developer/PowerCLI/PowerCLI41U1/html/Get-VirtualPortGroup.html
#>
Param
(
[string]$VMHost,
[string]$VIServer
)
Begin
{
Try
{
If ($DefaultVIServers -eq $null)
{
Connect-VIServer -Server $VIServer |Out-Null
}
$VSwitches = Get-VirtualSwitch
}
Catch
{
Return $Error[0]
}
}
Process
{
foreach ($Vswitch in $VSwitches)
{
If ($VSwitch.VMHost.Name -like "$($VMhost)*")
{
$VHostID = $VSwitch.VMHost.Id
}
}
$VMNetworks = Get-VirtualPortGroup |Where-Object {$_.VMhostID -eq $VhostID}
}
End
{
Return $VMNetworks
}
}
|
PowerShellCorpus/PoshCode/Citrix-Functions.ps1
|
Citrix-Functions.ps1
|
#########################################
#### Citrix Farm Functions ####
#########################################
# Get Citrix Farm
function Get-CitrixFarm{
param($Server)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$Server)
$mfarm = [system.Activator]::CreateInstance($type)
$mfarm.Initialize(1)
return $mFarm
}
# Get Online Servers by Zone
function Get-CitrixOnline {
Param($zone)
$mfzone = New-Object -ComObject MetaFrameCOM.MetaFrameZone
$mfzone.Initialize($zone)
$servers = $mfzone.OnlineServers
$servers
}
# Get Citrix Load Evaluators (only 4.0/4.5)
function Get-CitrixLE{
Param($server=$(throw "Server is Required"))
function Load-Farm{
param($srv)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
$mfarm = [system.Activator]::CreateInstance($type)
$mfarm.Initialize(1)
return $mFarm
}
$Farm = load-farm $server
if($Farm.LoadEvaluators){
foreach($eval in $Farm.LoadEvaluators)
{
$eval.loadData(1)
"+ Load Evaluator: {0}" -f $eval.LEName
$servers = $eval.AttachedServers(1)
if($servers.count -ne 0)
{
" + Servers"
$servers | %{" - {0}" -f $_.ServerName}
}
$rules = $eval.rules | Select-Object RuleType,HWM,LWM,Schedules
if($rules.count -ne 0)
{
" + Rules"
foreach($rule in $rules)
{
" - {0}" -f $rule
}
}
}
}
}
# Gets the Citrix Printer Drivers for the Farm (Can be REAL slow)
function Get-CitrixPrintDrivers{
Param($server=$(throw "Server is Required"))
function Load-Farm{
param($srv)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
$mfarm = [system.Activator]::CreateInstance($type)
$mfarm.Initialize(1)
return $mFarm
}
$farm = Load-Farm $Server
$farm.Drivers
}
# Gets Citrix Policies
function Get-CitrixPolicies{
param($Server)
function Load-Farm{
param($srv)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
$mfarm = [system.Activator]::CreateInstance($type)
$mfarm.Initialize(1)
return $mFarm
}
$farm = Load-Farm $server
$type = [System.Type]::GetTypeFromProgID("MetaFrameCOM.MetaFrameUserPolicy")
foreach($pol in $Farm.policies($type))
{
$pol.loadData(1)
"+ Name: {0}" -f $pol.Name
" - Description: {0}" -f $pol.Description
" - Enabled: {0}" -f $pol.Enabled
if($pol.AllowedAccounts)
{
" + AllowedAccounts"
foreach($aa in $pol.AllowedAccounts)
{
" - {0}" -f $aa.AccountName
}
}
if($pol.UserPolicy2)
{
" + UserPolicy"
$props = $pol.UserPolicy2 | Get-Member -membertype Property | %{$_.Name} | Sort-Object Name
foreach($prop in $props)
{
if(($pol.UserPolicy2.$prop -match "\\d") -and ($pol.UserPolicy2.$prop -ne 0))
{
" - {0}:{1}" -f $prop,$pol.UserPolicy2.$prop
}
}
}
write-Output " "
}
}
# Set-CitrixLoadEvalutor
function Set-CitrixLoadEvalutor{
Param($server = $(throw '$Server is Required'),$LoadEvaluator = "MFDefaultLE")
# Loading Server Object
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeServer",$Server)
$mfServer = [system.Activator]::CreateInstance($type)
$mfServer.Initialize(6,$Server)
# Getting Current LE
$le = $mfServer.AttachedLE
$le.LoadData(1)
Write-Host "Old Evaluator: $($le.LEName)"
Write-Host "Setting Load Evaluator on $server to $LoadEvaluator"
# Assigning New LE
$mfServer.AttachLEByName($LoadEvaluator)
# Checking LE
$le = $mfServer.AttachedLE
$le.LoadData(1)
Write-Host "Load Evaluator Set to $($le.LEName)"
}
#########################################
#### Citrix App Functions ####
#########################################
# Gets Citrix App
function Get-CTXApplication{
Param($Server,$AppName)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaFrameApplication",$Server)
$app = [system.Activator]::CreateInstance($type)
Write-Verbose "Loading Farm for $Server"
$app.Initialize(3,$appName)
$app.LoadData(0)
$app
}
# Outputs the number of Users using a Citrix App or Apps
function Get-ApplicationUserCount {
Param([string]$app,[string]$farmServer = $(throw '$FarmServer is Required'))
function List-AllCitrixApps{
Param($mFarm)
ForEach($app in $mFarm.Applications)
{
$name = $app.BrowserName.PadRight(25)
$count = "$($app.Sessions.Count)"
$count = $count.PadRight(10)
Write-Host "$name $count"
}
}
function List-App{
param($mApp,$mfFarm)
ForEach($app in $mfFarm.Applications)
{
if($app.BrowserName -eq "$mApp")
{
$name = $app.BrowserName.PadRight(25)
$count = "$(($app.Sessions | ?{$_.SessionState -eq 1}).Count)"
$count = $count.PadRight(10)
Write-Host "$name $count"
}
}
}
function Load-Farm{
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$srv)
$mfarm = [system.Activator]::CreateInstance($type)
$mfarm.Initialize(1)
return $mFarm
}
Write-Host
$title1 = "Application".PadRight(25)
$title2 = "===========".PadRight(25)
Write-Host "$title1 User Count" -ForegroundColor White
Write-Host "$title2 ==========" -ForegroundColor Red
$mf = Load-Farm $farmServer
While($true)
{
$oldpos = $host.UI.RawUI.CursorPosition
If($app)
{
List-App $app $mf
}
else
{
List-AllCitrixApps $mf
}
sleep(5)
$host.UI.RawUI.CursorPosition = $oldpos
}
Write-Host ""
}
# Finds what Server a User is on
function Find-CitrixUser {
Param([string]$LoginName,[switch]$verbose)
$user = $LoginName.Split("\\")[1]
$Domain = $LoginName.Split("\\")[0]
$mfuser = New-Object -ComObject MetaframeCOM.MetaframeUser
$mfuser.Initialize(1,$Domain,1,$user)
Write-Host
Write-Host "User: $($mfuser.UserName) found on the Following:"
foreach ($s in $mfuser.Sessions)
{
if($verbose)
{
Write-Host
Write-Host "$($s.ServerName)"
Write-Host "-=-=-=-=-=-"
Write-Host "AppName : $($s.AppName)" -foregroundcolor yellow
Write-Host "SessionName : $($s.SessionName)" -foregroundcolor yellow
Write-Host "SessionID : $($s.SessionID)" -foregroundcolor yellow
Write-Host "ClientAddress : $($s.ClientAddress)" -foregroundcolor yellow
Write-Host "ClientEncryption : $($s.ClientEncryption)" -foregroundcolor yellow
Write-Host
Write-Host "Processes"
Write-Host "========="
foreach ($proc in $s.Processes)
{
Write-Host $proc.ProcessName -foregroundcolor Green
}
Write-host
}
else
{
write-Host " -> $($s.ServerName)"
}
}
}
# Gets Servers Published for specified App (or just returns count)
function Get-CitrixAppServers {
Param($app = $(throw '$app is required'),[switch]$count)
$mfm = New-Object -com MetaFrameCOM.MetaFrameFarm
$mfm.Initialize(1)
$servers = $mfm.Applications | ?{$_.AppName -eq $app}
$servers = $servers.Servers | sort -Property ServerName
if($count)
{
Write-Host
Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
Write-Host
}
else
{
Write-Host ""
Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
Write-Host "-----------------------------------------------" -ForegroundColor gray
foreach($server in $servers){Write-Host "$($server.ServerName)" -ForegroundColor Green}
Write-Host "-----------------------------------------------" -ForegroundColor gray
Write-Host "Found [$($Servers.Count)] Servers for Application [$app]" -ForegroundColor White
Write-Host ""
}
}
# Returns Users currently using Citrix App
function Get-CitrixAppUsers {
Param($app = $(throw '$app is required'),[switch]$count)
$ErrorActionPreference = "SilentlyContinue"
Write-host
$mfm = New-Object -com MetaFrameCOM.MetaFrameFarm
$mfm.Initialize(1)
$users = $mfm.Applications | ?{$_.AppName -eq $app}
$Users = $users.Sessions | sort -Property UserName
if($count){
Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
Write-Host
}
else{
Write-Host ""
Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
Write-Host "-----------------------------------------------------" -ForegroundColor gray
foreach($user in $Users){
If($User.SessionState -eq 1){
Write-Host ($User.UserName).PadRight(10) -ForegroundColor Green -NoNewline
}
else{
Write-Host ($User.UserName).PadRight(10) -ForegroundColor yellow -NoNewline
}
}
Write-Host
Write-Host "-----------------------------------------------------" -ForegroundColor gray
Write-Host "Found [$($Users.Count)] Users for Application [$app]" -ForegroundColor White
Write-Host
}
}
# Sets PNFolder for App
function Set-CTXAppFolder{
param($Server,$folder,$filter,[switch]$add,[switch]$remove,[switch]$verbose,[switch]$whatif)
if($verbose){$VerbosePreference = "Continue"}
Write-Verbose "Loading Remote DCOM"
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeFarm",$Server)
$mfarm = [system.Activator]::CreateInstance($type)
Write-Verbose "Loading Farm for $Server"
$mfarm.Initialize(1)
if($filter)
{
Write-Verbose "Getting Apps for $Filter"
$Applications = $mFarm.Applications | Where-Object{$_.BrowserName -match $filter}
}
else
{
Write-Verbose "Returning All Apps"
$Applications = $mFarm.Applications | Where-Object{$_.BrowserName -match $filter}
}
foreach($app in $Applications)
{
Write-Verbose "Loading $($app.BrowserName)"
$app.LoadData(0)
if($Remove)
{
if($app.PNFolder -eq $folder)
{
Write-Verbose "Removing $Folder for $($app.BrowserName)"
$app.PNFolder = ""
if(!$whatif){$app.SaveData()}
}
}
if($add)
{
Write-Verbose "Adding $Folder for $($app.BrowserName)"
$app.PNFolder = $folder
if(!$whatif){$app.SaveData()}
}
"APP: {0,-15}Folder:{1}" -f $app.BrowserName,$app.PNFolder
}
}
# Adds user to Citrix App
function Add-CTXApplicationUser{
Param($Server,$AppName,$UserName)
$domain = $userName.split('\\')[0]
$user = $userName.split('\\')[1]
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaFrameApplication",$Server)
$app = [system.Activator]::CreateInstance($type)
Write-Verbose "Loading Farm for $Server"
$app.Initialize(3,$appName)
$app.LoadData(0)
$app.AddUser(1,$domain,2,$user)
$app.SaveData()
}
##########################################
#### Citrix Server Functions ####
##########################################
# Get a Citrix Server Object
function Get-CitrixServer{
Param($Server)
$type = [System.Type]::GetTypeFromProgID("MetaframeCOM.MetaframeServer",$Server)
$mfServer = [system.Activator]::CreateInstance($type)
$mfServer.Initialize(6,$Server)
$mfServer
}
# Publish Application to Server(s)
function Publish-CitrixApplication{
Param([string]$server,[string]$app)
Begin{
Write-Host
function cPublish {
Param([string]$Srv,[string]$myapp)
$Srv = $Srv.toUpper()
$mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
$mfSrv.Initialize(6,"$Srv")
$mfApp = New-Object -ComObject MetaFrameCOM.MetaFrameApplication
$mfApp.Initialize(3,"Applications\\$myapp")
$mfApp.LoadData($true)
$mfAppBinding = New-Object -ComObject MetaFrameCOM.MetaFrameAppSrvBinding
$mfAppBinding.Initialize(6,$Srv,"Applications\\$app")
if($mfAppBinding)
{
Write-Host "Publishing App[$myapp] on Server [$Srv]" -ForegroundColor Green
$mfApp.AddServer($mfAppBinding)
$mfApp.SaveData()
}
else
{
Write-Host "Unable To Create App Binding" -ForegroundColor Red
}
}
$process = @()
}
Process{
if($_){
if($_.ServerName){
$process += $_.ServerName
}
else{
$process += $_
}
}
}
End{
if($Server){$Process += $Server}
foreach($s in $process){
cPublish -srv $s -myapp $app
Write-Host
}
}
}
# UnPublish All Application from Server(s)
function UnPublish-CitrixServer{
Param([string]$server)
Begin{
function cUnPublish {
Param([string]$Srv)
$Srv = $Srv.toUpper()
$mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
$mfSrv.Initialize(6,"$Srv")
If($mfSrv.Applications.Count -gt 0)
{
Write-Host "Removing All Published Applications from $Srv" -ForegroundColor Red
Write-Host "===================================================" -ForegroundColor Green
ForEach($a in $mfSrv.Applications)
{
$myApp = $a.AppName
Write-Host "Removing App [$myApp] from Server [$Srv]" -ForegroundColor White
$a.RemoveServer($Srv)
$a.SaveData()
}
}
else
{
Write-Host "No Published Applications for $Srv" -ForegroundColor Red
}
}
Write-Host
$process = @()
}
Process{
if($_){
if($_.ServerName)
{
$process += $_.ServerName
}
else
{
$process += $_
}
}
}
End{
if($Server){$Process += $Server}
foreach($s in $process){
cUnPublish $s
Write-Host
}
}
}
# Remove a Citrix App from Server
function Remove-CitrixApplication {
Param([string]$server,[string]$app)
Begin{
function RemoveApp {
Param([string]$Srv,[string]$myapp)
$AppRemoved = $false
$Srv = $Srv.toUpper()
$mfSrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
$mfSrv.Initialize(6,"$Srv")
If($mfSrv.Applications.Count -gt 0)
{
ForEach($a in $mfSrv.Applications)
{
If($a.AppName -eq "$myapp")
{
Write-Host "Removing App [$myApp] from Server [$Srv]" -ForegroundColor Green
$a.RemoveServer($Srv)
$a.SaveData()
$AppRemoved = $true
}
}
}
else
{
Write-Host "No Applications Published for $Srv" -ForegroundColor Red
$AppRemoved = $true
}
If($AppRemoved -eq $false)
{
Write-Host "This Application not Published for $Srv" -ForegroundColor Red
}
}
Write-Host
$process = @()
}
Process{
if($_)
{
if($_.ServerName){
$process += $_.ServerName
}
else
{
$process += $_
}
}
}
End{
if($Server){$Process += $Server}
if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME}
foreach($s in $process)
{
RemoveApp -Srv $s -myapp $app
Write-Host
}
}
}
# List Citrix Apps Published to Server
function Get-CitrixApplications {
Param([string]$Server)
Begin {
Write-Host
function cGetApps {
param([string]$srv)
$srv = $srv.ToUpper()
$mfsrv = New-Object -ComObject MetaFrameCOM.MetaFrameServer
$mfsrv.Initialize(6,"$srv")
Write-Host "SERVER $srv" -foregroundcolor Red
Write-Host "==================" -ForegroundColor Green
If($mfSrv.Applications.Count -gt 0) {
$mfSrv.Applications | %{Write-Host "Published: $($_.AppName.ToUpper())"}
}
else {
Write-Host "No Applications Published for $srv" -foregroundcolor white
}
}
$process = @()
}
Process{
if($_){
if($_.ServerName){
$process += $_.ServerName
}
else{
$process += $_
}
}
}
End {
if($Server){$Process += $Server}
foreach($s in $process){
cGetApps $s
Write-Host
}
}
}
# Return Current Terminal Server User Count
function Get-TSUserCount {
Param([string]$Server)
Begin{
function TsUserCount {
param([string]$srv)
$msg = "Checking For Users on Server [$srv]"
$msg = $msg.PadRight($pad)
Write-host $msg -ForegroundColor White
$msg = "==========================================="
$msg = $msg.PadRight($pad)
Write-host $msg -ForegroundColor gray
$msg = "Terminal Server User Count on Server "
$msg1 = "[$srv]"
$msg1 = $msg1.PadRight($pad)
$ts = Get-WmiObject Win32_PerfFormattedData_TermService_TerminalServices -ComputerName $srv
$count = $ts.activeSessions
If($count -eq 0)
{
Write-host "$msg [Users:$count]" -ForegroundColor Green
}
else
{
Write-host "$msg [Users:$count]" -ForegroundColor Yellow
}
}
$process = @()
}
Process{
if($_){
if($_.ServerName)
{
$process += $_.ServerName
}
else
{
$process += $_
}
}
}
End{
if($Server){$Process += $Server}
if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME}
foreach($s in $process)
{
TSUserCount $s
Write-Host
}
}
}
|
PowerShellCorpus/PoshCode/Get-Parameter_1.ps1
|
Get-Parameter_1.ps1
|
function Get-Parameter ($Cmdlet) {
foreach ($paramset in (Get-Command $Cmdlet).ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
$process = "" | Select-Object Name, ParameterSet, Aliases, IsMandatory, CommonParameter
$process.Name = $param.Name
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
$process.IsMandatory = $param.IsMandatory
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob") { $process.CommonParameter = $TRUE }
else { $process.CommonParameter = $FALSE }
$output += $process
}
Write-Output $Output
#Write-Host "`n"
}
}
|
PowerShellCorpus/PoshCode/Test-GroupMembership.ps1
|
Test-GroupMembership.ps1
|
Function Test-GroupMembership {
Param($user,$group)
Get-QADUser $user | select memberof | %{
$result = $false
foreach ($i in $_.memberof) {
if ((Get-QADGroup $i).name -match $group){
$result = $true
break
}
}
$obj = "" | select Name,Group,IsMember
$obj.Name = $user
$obj.Group = $group
$obj.IsMember = $result
write $obj
}
}
|
PowerShellCorpus/PoshCode/Update VM Tools.ps1
|
Update VM Tools.ps1
|
########################################################
#connect to VirtualCenter server (i.e. virtual-center-1)
if ($args[0] -eq $null)
{$hostName = Read-Host "What host do you want to connect to?"}
else
{$hostName = $args[0]}
#connect to selected Virtualcenter or host server
Connect-VIServer $hostName
########################################################
#get all vms listed in virtualcenter
$vms = get-vm
########################################################
#check power state on each vm
#if 'On' update tools
Foreach ($i in $vms)
{ #if virtualcenter is virtualized skip it
# a system restart would stop this script
if ((get-vm -name $i).Name -eq $hostname)
{"Skipping " + $hostname}
#if primary DC or DNS is virtualized skip it too
#elseif ((get-vm -name $i).Name -eq "DNS/DC/DHCP")
#{"Skipping DNS/DC/DHCP server name"}
else
{
if ((get-vm -name $i).PowerState -eq "PoweredOn")
{ $i
Get-Date -format "hh:mm:ss"
@@ update-tools -guest (get-vmguest -vm (get-vm -name $i))
Get-Date -format "hh:mm:ss"
}#if
#}#if
}#foreach
|
PowerShellCorpus/PoshCode/LetterDiamondOneliner v3.ps1
|
LetterDiamondOneliner v3.ps1
|
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z
# trimmed 130 chars w/o arg
&{param([char]$c)$p=$c-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
# trimmed to 127 chars w/o arg
&{$p=[char]$args[0]-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
|
PowerShellCorpus/PoshCode/Get-Parameter 1.1.ps1
|
Get-Parameter 1.1.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)
{
[array]$p = $set.Parameters | Select-Object *
}
else
{
# Get a list of common parameters
$cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name
[array]$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object *
}
if($p.count -le 0 -and !$IncludeCommonParameters)
{
Write-Warning "The specified cmdlet ('$cmd') has no parameters."
return
}
$params = $p | Foreach-Object {$_.Name}
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/List AD Computers CSV.ps1
|
List AD Computers CSV.ps1
|
$datetime = Get-Date -Format "yyMMdd-HHmm"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
[string]$DomainName = $objDomain.name
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("(objectCategory=computer)")
$Results = $objSearcher.FindAll()
$LogDir = "."
$LogFile = "$DomainName-ComputerObjects-$datetime.csv"
Add-Content "$LogDir\\$LogFile" "UUID,Hostname,IP Address,Domain,OS,OS Version,OS Release,Manufacturer,Model,Platform,Memory(MB),Processors,Disk-Usage(KB)"
Write-Host -ForegroundColor Black -BackgroundColor Yellow "Gathering information for all systems on the $DomainName domain"
Write-Host -ForegroundColor Black -BackgroundColor Yellow "Results will be written to:" -noNewLine
Write-Host " $LogDir\\$LogFile" | Write-Host "" | Write-Host ""
$WMI_CSP = "Win32_ComputerSystemProduct"
$WMI_CS = "Win32_ComputerSystem"
$WMI_Disk = "Win32_LogicalDisk"
$WMI_OS = "Win32_OperatingSystem"
$WMI_Proc = "Win32_Processor"
foreach ($objResult in $Results)
{
$objComputer = $objResult.Properties
$computer = $objComputer.name
$pingStatus = Get-WMIObject Win32_PingStatus -Filter "Address = '$computer'"
$ipAddress = $pingStatus.ProtocolAddress
if($pingStatus.StatusCode -eq 0)
{
# Output minimal information to Console & Complete information to CSV file (Successful Ping)
$UUID = Get-WMIObject $WMI_CSP -ComputerName $computer | Select UUID
$_UUID = $UUID.UUID
$OS = Get-WMIObject $WMI_OS -ComputerName $computer | Select Caption
$_OS = $OS.Caption
if($_OS)
{if($_OS.Contains(",")) {$_OS = $_OS.Replace(",","")} if($_OS.Contains("(R)")) {$_OS = $_OS.Replace("(R)","")}}
$CSDVer = Get-WMIObject $WMI_OS -ComputerName $computer | Select CSDVersion
$_CSDVer = $CSDVer.CSDVersion
$Ver = Get-WMIObject $WMI_OS -ComputerName $computer | Select Version
$_Ver = $Ver.Version
$Mfr = Get-WMIObject $WMI_CSP -ComputerName $computer | Select Vendor
$_Mfr = $Mfr.Vendor
if($_Mfr)
{if($_Mfr.Contains("HP")) {$_Mfr = $_Mfr.Replace("HP","Hewlett-Packard")}}
$HW = Get-WMIObject $WMI_CSP -ComputerName $computer | Select Name
$_HW = $HW.Name
$Platform = Get-WMIObject $WMI_Proc -ComputerName $computer -filter "DeviceID = 'CPU0'" | Select Manufacturer
$_Platform = $Platform.Manufacturer
$RAMKB = Get-WMIObject $WMI_CS -ComputerName $computer | Select TotalPhysicalMemory
[int64]$_RAMKB = $RAMKB.TotalPhysicalMemory
[int64]$_RAMMB = $_RAMKB / 1kb
$Processors = Get-WMIObject $WMI_CS -ComputerName $computer | Select NumberOfProcessors
[int64]$NumOfProcs = $Processors.NumberOfProcessors
$Space = Get-WMIObject $WMI_Disk -ComputerName $computer -filter "DeviceID = 'c:'" | Select FreeSpace
[int64]$DiskFree = $Space.FreeSpace
$Size = Get-WMIObject $WMI_Disk -ComputerName $computer -filter "DeviceID = 'c:'" | Select Size
[int64]$DiskSize = $Size.Size
[int64]$DiskUsage = ($DiskSize - $DiskFree) / 1kb
Write-Host -ForegroundColor Green "Reply received from $computer ($ipAddress)"
Add-Content "$LogDir\\$LogFile" "$_UUID,$computer,$ipAddress,$DomainName,$_OS,$_CSDVer,$_Ver,$_Mfr,$_HW,$_Platform,$_RAMMB,$NumOfProcs,$DiskUsage"
}
else
{
# Output minimal information to Console & Minimal information to CSV file (Unsucccessful Ping)
Write-Host -ForegroundColor Red "No Reply received from $computer ....................[SKIPPED]"
Add-Content "$LogDir\\$LogFile" "HOST NOT ONLINE,$computer,---,$DomainName,---,---,---,---,---,---,---,---"
}
}
|
PowerShellCorpus/PoshCode/WhoIs.ps1
|
WhoIs.ps1
|
param([String] $DomainName = '192.168.0.1')
$socket = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$Socket.Connect('whois.arin.net', 43) | out-null
$bytes = [System.Text.Encoding]::ASCII.GetBytes($domainName + "`n")
$Socket.Send($bytes) | out-null
$bytes = [Array]::CreateInstance("byte", 2048)
$Socket.Receive($bytes) | out-null
$result = [System.Text.Encoding]::ASCII.GetString($bytes).Trim()
$Socket.Close()
$Data = New-Object Object
$Data | Add-Member NoteProperty Raw ($result)
$result -split "`n" | % {
if (![String]::IsNullOrEmpty($_)) {
$num = $_.IndexOf(":")
if ($num -gt 0) {
$itemName = $_.SubString(0,$num).Trim()
$itemValue = $_.SubString($num+1).Trim()
if (($Data | Get-Member $itemName)) {
$Data.($itemName) += "|" + $itemValue
}
else {
$Data | Add-Member NoteProperty ($itemName) ($itemValue)
}
}
}
}
$Data
|
PowerShellCorpus/PoshCode/Protect-Variable.ps1
|
Protect-Variable.ps1
|
function Protect-Variable {
param(
[Parameter(Mandatory=$true,Position=0)][String]$Name, [Int]$Scope = 1,
[Parameter(ParameterSetName="ValidateScriptBlock")][ScriptBlock]$ScriptBlock,
[Parameter(ParameterSetName="ValidateCount")][Int]$MinCount,
[Parameter(ParameterSetName="ValidateCount")][Int]$MaxCount,
[Parameter(ParameterSetName="ValidateLength")][Int]$MinLength,
[Parameter(ParameterSetName="ValidateLength")][Int]$MaxLength,
[Parameter(ParameterSetName="ValidatePattern")][Regex]$Pattern,
[Parameter(ParameterSetName="ValidateRange")][Int]$MinValue,
[Parameter(ParameterSetName="ValidateRange")][Int]$MaxValue,
[Parameter(ParameterSetName="ValidateSet")][String[]]$Set,
[Parameter(ParameterSetName="ValidateNotNull")][Switch]$NotNull,
[Parameter(ParameterSetName="ValidateNotNullOrEmpty")][Switch]$NotEmpty
)
$Variable = Get-Variable $Name -Scope 1
if($ScriptBlock) {
$Attribute = new-object System.Management.Automation.ValidateScriptAttribute $ScriptBlock
$Variable.Attributes.Add($Attribute)
}
if($MinCount -or $MaxCount) {
if(!$MinCount) { $MinCount = [Int]::MinValue }
if(!$MaxCount) { $MaxCount = [Int]::MaxValue }
$Attribute = new-object System.Management.Automation.ValidateCountAttribute $MinCount, $MaxCount
$Variable.Attributes.Add($Attribute)
}
if($MinLength -or $MaxLength) {
$Attribute = new-object System.Management.Automation.ValidateLengthAttribute $MinLength, $MaxLength
$Variable.Attributes.Add($Attribute)
}
if($Pattern) {
$Attribute = new-object System.Management.Automation.ValidatePatternAttribute $Pattern
$Variable.Attributes.Add($Attribute)
}
if($MinValue -or $MaxValue) {
$Attribute = new-object System.Management.Automation.ValidateRangeAttribute $MinValue, $MaxValue
$Variable.Attributes.Add($Attribute)
}
if($Set) {
$Attribute = new-object System.Management.Automation.ValidateSetAttribute $Set
$Variable.Attributes.Add($Attribute)
}
if($NotNull) {
$Attribute = new-object System.Management.Automation.ValidateNotNullAttribute
$Variable.Attributes.Add($Attribute)
}
if($NotEmpty) {
$Attribute = new-object System.Management.Automation.ValidateNotNullOrEmptyAttribute
$Variable.Attributes.Add($Attribute)
}
}
|
PowerShellCorpus/PoshCode/Get-FailingDrive.ps1
|
Get-FailingDrive.ps1
|
Function Get-FailingDrive {
<#
.SYNOPSIS
Checks for any potentially failing drives and reports back drive information.
.DESCRIPTION
Checks for any potentially failing drives and reports back drive information. This only works
against local hard drives using SMART technology. Reason values and their meanings can be found
here: http://en.wikipedia.org/wiki/S.M.A.R.T#Known_ATA_S.M.A.R.T._attributes
.PARAMETER Computer
Remote or local computer to check for possible failed hard drive.
.PARAMETER Credential
Provide alternate credential to perform query.
.NOTES
Author: Boe Prox
Version: 1.0
http://learn-powershell.net
.EXAMPLE
Get-FailingDrive
WARNING: ST9320320AS ATA Device may fail!
MediaType : Fixed hard disk media
InterFace : IDE
DriveName : ST9320320AS ATA Device
Reason : 1
SerialNumber : 202020202020202020202020533531584e5a4d50
FailureImminent : True
Description
-----------
Command ran against the local computer to check for potential failed hard drive.
#>
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[string[]]$Computername,
[parameter()]
[System.Management.Automation.PSCredential]$Credential
)
Begin {
$queryhash = @{}
$BadDriveHash = @{}
}
Process {
ForEach ($Computer in $Computername) {
If ($PSBoundParameters['Computer']) {
$queryhash['Computername'] = $Computer
$BadDriveHash['Computername'] = $Computer
} Else {
$queryhash['Computername'] = $Env:Computername
$BadDriveHash['Computername'] = $Env:Computername
}
If ($PSBoundParameters['Credential']) {
$queryhash['Credential'] = $Credential
$BadDriveHash['Credential'] = $Credential
}
Write-Verbose "Creating SplatTable"
$queryhash['NameSpace'] = 'root\\wmi'
$queryhash['Class'] = 'MSStorageDriver_FailurePredictStatus'
$queryhash['Filter'] = "PredictFailure='False'"
$queryhash['ErrorAction'] = 'Stop'
$BadDriveHash['Class'] = 'win32_diskdrive'
$BadDriveHash['ErrorAction'] = 'Stop'
[regex]$regex = "(?<DriveName>\\w+\\\\[A-Za-z0-9_]*)\\w+"
Try {
Write-Verbose "Checking for failed drives"
Get-WmiObject @queryhash | ForEach {
$drive = $regex.Matches($_.InstanceName) | ForEach {$_.Groups['DriveName'].value}
Write-Verbose "Gathering more information about failing drive"
$BadDrive = gwmi @BadDriveHash | Where {$_.PNPDeviceID -like "$drive*"}
If ($BadDrive) {
Write-Warning "$($BadDriveHash['Computername']): $($BadDrive.Model) may fail!"
New-Object PSObject -Property @{
DriveName = $BadDrive.Model
FailureImminent = $_.PredictFailure
Reason = $_.Reason
MediaType = $BadDrive.MediaType
SerialNumber = $BadDrive.SerialNumber
InterFace = $BadDrive.InterfaceType
Partitions = $BadDrive.Partitions
Size = $BadDrive.Size
Computer = $BadDriveHash['Computername']
}
}
}
} Catch {
Write-Warning "$($Error[0])"
}
}
}
}
|
PowerShellCorpus/PoshCode/Re-IP VMs.ps1
|
Re-IP VMs.ps1
|
foreach ($entry in (import-csv "spreadsheet.csv")) {
$ipScript = @"
`$NetworkConfig = Get-WmiObject -Class Win32_NetworkAdapterConfiguration
`$NicAdapter = `$NetworkConfig | where {`$_.DHCPEnabled -eq "True"}
`$NicAdapter.EnableStatic('$entry.IP','$entry.Netmask')
`$NicAdapter.SetGateways('$entry.Gateway')
"@
Get-VM $entry.VMName | Invoke-VMScript -HostUser $entry.HU -HostPassword $entry.HP -GuestUser $gu -GuestPassword $gp $ipScript
}
|
PowerShellCorpus/PoshCode/Compare-TwitterNames_2.ps1
|
Compare-TwitterNames_2.ps1
|
#This script will compare the names of the people you follow on Twitter
#and the people following you. It returns a comparison object consisting
#of the Twitter name of a subject and a side indicator -
#"<=" means that you are following a subject who is not following you,
#"=>" means that you are followed by someone who you are not following.
function GetTwitterNames([string]$query)
{
$wc = new-object System.Net.WebClient
$wc.Credentials = $script:credential.GetNetworkCredential()
$nbrofpeople = 0
$page = "&page="
$names = @()
do
{
$url = $query
if ($nbrofpeople -gt 0)
{
$url = $url+$page+($nbrofpeople/100 +1)
}
[xml]$nameslist = $wc.DownloadString($url)
$names += $nameslist.users.user | select name
$nbrofpeople += 100
} while ($names.count -eq $nbrofpeople)
return $names
}
$twitter = "http://twitter.com/statuses/"
$friends = $twitter + "friends.xml?lite=true"
$followers = $twitter + "followers.xml?lite=true"
$credential = Get-Credential
$friendslist = GetTwitterNames($friends)
$followerslist = GetTwitterNames($followers)
$sync = 0
if ($friendslist.count -gt $followerslist.count)
{
$sync = ($friendslist.count)/2
}
else
{
$sync = ($followerslist.count)/2
}
$Status = @{Name='Status';Expression={if ($_.sideindicator -like '=>') {'Followed By'} else {'Following'}}}
compare-object $friendslist $followerslist -SyncWindow ($sync) -Property name | Select-Object Name, $Status
|
PowerShellCorpus/PoshCode/Get-PDC09Videos_1.ps1
|
Get-PDC09Videos_1.ps1
|
#requires -version 2.0
PARAM (
[Parameter(Position=1, Mandatory=$true)]
[ValidateSet("wmv","wmvhigh","ppt")] # the "mp4" files aren't there yet
[String]$MediaType,
[string]$Destination = $PWD
)
Import-Module BitsTransfer
Push-Location $Destination
$Extension = $(switch -wildcard($MediaType){"wmv*"{"wmv"} "mp4"{"mp4"} "ppt"{"pptx"}})
$BaseUrl = "http://ecn.channel9.msdn.com/o9/pdc09/{0}/{2}.{1}"
Start-BitsTransfer -TransferType Download -Source @(
"CL09","CL18","FT02","FT06","FT11","PR05","SVC01","SVC10","SVC20","SVR03","CL30","CL33","FT30",
"FT31","PR31","SVC30","SVC37","SVR33","VTL30","VTL32","CL04","CL14","CL25","FT18","FT19","FT25",
"PR02","SVC13","SVR01","SVR14","CL13","CL29","FT10","FT28","FT57","PR11","SVC52","SVR15","SVR17",
"CL11","CL17","CL23","FT03","FT08","PR10","SVR16","VTL01","CL01","FT50","FT52","FT55","FT59","PR13",
"SVC02","SVC03","SVC15","CL31","CL34","FT32","FT34","FT36","SVC31","SVC32","SVR31","VTL31","CL15",
"FT12","FT17","FT58","SVC16","SVC28","SVC53","SVR11","VTL05","CL06","FT04","FT07","FT29","PR06",
"SVC09","SVC17","SVR13","VTL04","CL12","CL22","FT22","FT23","FT26","SVC04","SVC14","SVC19","SVC54",
"SVR12","CL02","CL05","CL16","FT21","FT56","PR03","SVC08","SVC18","SVR10","VTL03","CL10","FT13",
"FT53","FT60","PR07","SVC06","SVC25","SVR07","SVR18","VTL02","CL03","CL21","CL27","FT14","FT20",
"FT24","PR09","SVC12","SVR09","SVR19","CL32","CL35","CL36","FT33","FT35","PR30","PR33","SVC33",
"SVC36","SVR32","CL07","CL24","CL28","FT09","FT16","FT27","PR12","SVC27","SVR02","SVR06","CL26",
"FT05","FT54","PR01","PR14","SVC23","SVC26","SVR08","KYN01-PGM","KYN02-PGM" |
ForEach { $BaseUrl -f $MediaType, $Extension, $_ }
)
Pop-Location
|
PowerShellCorpus/PoshCode/sophos_mrupdate.ps1
|
sophos_mrupdate.ps1
|
<#
.SYNOPSIS
Updates the Sophos Message Relay configuration.
.DESCRIPTION
Points the local Message Router service to a new parent relay server.
.PARAMETER mrinit
The mrinit.conf file to use.
.PARAMETER loglevel
The current loglevel (used by the Log function).
Defaults to 'information' (debug messages will not be printed).
Valid values are 'debug', 'information', 'warning', and 'error'.
.EXAMPLE
# Update settings using the configuration in the file AMW_mrinit.conf
sophos_mrupdate.ps1 -mrinit AMW_mrinit.conf
#>
param([Parameter(Mandatory=$true)][string]$mrinit,
[Parameter(Mandatory=$false)][string]$loglevel=1)
# LOGGING #####################################################################
# Set severity constants
$MSG_DEBUG = 0
$MSG_INFORMATION = 1
$MSG_WARNING = 2
$MSG_ERROR = 3
$MSG_SEVERITY = @('debug', 'information', 'warning', 'error')
if ($MSG_SEVERITY -notcontains $loglevel.ToLower()) {
Write-Error ('Invalid loglevel! ' +
'Must be debug, information, warning, or error.')
exit 1
} else {
foreach ($index in (0..($MSG_SEVERITY.Count - 1))) {
if ($MSG_SEVERITY[$index] -eq $loglevel) {
$loglevel = $index
}
}
}
# Set configurable settings for logging
$LOG_FILE = 'c:\\windows\\temp\\sophos_mrupdate.log'
$SMTP_TO = 'sophos-virusalerts@company.com'
$SMTP_SERVER = 'smtp.company.com'
$SMTP_SUBJECT = 'Sophos MRUpdate Error'
$SMTP_FROM = 'sophos-mrupdate@company.com'
function Log {
<#
.SYNOPSIS
Writes a message to the Log.
.DESCRIPTION
Logs a message to the logfile if the severity is higher than $loglevel.
.PARAMETER severity
The severity of the message. Can be Information, Warning, or Error.
Use the $MSG_XXXX constants.
Note that Error will halt the script and send an email.
.PARAMETER message
A string to be printed to the log.
.EXAMPLE
Log $MSG_ERROR "Something has gone terribly wrong!"
#>
param([Parameter(Mandatory=$true)][int]$severity,
[Parameter(Mandatory=$true)][string]$message,
[Parameter()][switch]$sendmail)
if ($severity -ge $loglevel) {
$timestamp = Get-Date -Format 'yyyy-MM-dd hh:mm:ss'
$output = ("$timestamp`t$($env:computername)`t" +
"$($MSG_SEVERITY[$severity])`t$message")
Write-Output $output >> $LOG_FILE
if (($severity -ge $MSG_ERROR) -or $sendmail) {
Send-MailMessage -To $SMTP_TO `
-SmtpServer $SMTP_SERVER `
-Subject "$SMTP_SUBJECT on $($env:computername)" `
-Body $output `
-From $SMTP_FROM
exit 1
}
}
}
# MAIN ########################################################################
# The path to the Remote Management System files
$CURRENT_PATH = $pwd
$RMS_PATH = 'C:\\Program Files (x86)\\Sophos\\Remote Management System\\'
if (-not (Test-Path $RMS_PATH)) {
$RMS_PATH = 'C:\\Program Files\\Sophos\\Remote Management System\\'
if (-not (Test-Path $RMS_PATH)) {
Log $MSG_ERROR "The path '$RMS_PATH' could not be found!"
}
}
#Copy over the new mrinit.conf file
Log $MSG_DEBUG "Copying file '$mrinit'..."
if (Test-Path ".\\$mrinit") {
try {
Copy-Item -Path ".\\$mrinit" -Destination ($RMS_PATH + 'mrinit.conf') -Force
} catch {
LOG $MSG_ERROR "Unable to copy $mrinit to the RMS directory!"
}
} else {
LOG $MSG_ERROR "File '$mrinit' missing! Check the SCCM package."
exit 1
}
Log $MSG_DEBUG "Changing directory to $RMS_PATH..."
cd $RMS_PATH
# Get the backup copies of mrinit.conf out of the way. For some reason
# RMS will inexplicably use the backup copy instead of the new one if you don't
Log $MSG_DEBUG 'Renaming mrinit.conf.orig to mrinit.conf.orig.old'
try {
Rename-Item '.\\mrinit.conf.orig' '.\\mrinit.conf.orig.old' `
-Force `
-ea SilentlyContinue
} catch {
Log $MSG_ERROR "Unable to rename the file 'mrinit.orig'!"
}
# This is the command that actually grabs the new mrinit.conf file and makes
# the important updates to the system.
.\\ClientMRInit.exe
# Let's restart the Message Router
net stop "Sophos Message Router"
net start "Sophos Message Router"
cd $CURRENT_PATH
# Voila! We're done.
|
PowerShellCorpus/PoshCode/List AD Computers XLS.ps1
|
List AD Computers XLS.ps1
|
# Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
# WMI Class variables
$WMI_CSP = "Win32_ComputerSystemProduct"
$WMI_CS = "Win32_ComputerSystem"
$WMI_Disk = "Win32_LogicalDisk"
$WMI_OS = "Win32_OperatingSystem"
$WMI_Proc = "Win32_Processor"
# Set up a directory search for all computer objects in the current domain
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
[string]$DomainName = $objDomain.name
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("(objectCategory=computer)")
$Results = $objSearcher.FindAll()
# Counter variable for rows
$intRow = 1
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
#Create column headers
$Sheet.Cells.Item($intRow,1) = "UUID"
$Sheet.Cells.Item($intRow,1).Font.Bold = $True
$Sheet.Columns.Item('a').ColumnWidth = 42
$Sheet.Cells.Item($intRow,2) = "Hostname"
$Sheet.Cells.Item($intRow,2).Font.Bold = $True
$Sheet.Columns.Item('b').ColumnWidth = 14
$Sheet.Cells.Item($intRow,3) = "IP Address"
$Sheet.Cells.Item($intRow,3).Font.Bold = $True
$Sheet.Columns.Item('c').ColumnWidth = 11
$Sheet.Cells.Item($intRow,4) = "Domain"
$Sheet.Cells.Item($intRow,4).Font.Bold = $True
$Sheet.Columns.Item('d').ColumnWidth = 10
$Sheet.Cells.Item($intRow,5) = "OS"
$Sheet.Cells.Item($intRow,5).Font.Bold = $True
$Sheet.Columns.Item('e').ColumnWidth = 42
$Sheet.Cells.Item($intRow,6) = "OS Version"
$Sheet.Cells.Item($intRow,6).Font.Bold = $True
$Sheet.Columns.Item('f').ColumnWidth = 13
$Sheet.Cells.Item($intRow,7) = "OS Release"
$Sheet.Cells.Item($intRow,7).Font.Bold = $True
$Sheet.Columns.Item('g').ColumnWidth = 11
$Sheet.Cells.Item($intRow,8) = "Manufacturer"
$Sheet.Cells.Item($intRow,8).Font.Bold = $True
$Sheet.Columns.Item('h').ColumnWidth = 17
$Sheet.Cells.Item($intRow,9) = "Model"
$Sheet.Cells.Item($intRow,9).Font.Bold = $True
$Sheet.Columns.Item('i').ColumnWidth = 34
$Sheet.Cells.Item($intRow,10) = "Platform"
$Sheet.Cells.Item($intRow,10).Font.Bold = $True
$Sheet.Columns.Item('j').ColumnWidth = 12
$Sheet.Cells.Item($intRow,11) = "Memory (MB)"
$Sheet.Cells.Item($intRow,11).Font.Bold = $True
$Sheet.Columns.Item('k').ColumnWidth = 13
$Sheet.Cells.Item($intRow,12) = "Processors"
$Sheet.Cells.Item($intRow,12).Font.Bold = $True
$Sheet.Columns.Item('l').ColumnWidth = 10
$Sheet.Cells.Item($intRow,13) = "Disk Usage (KB)"
$Sheet.Cells.Item($intRow,13).Font.Bold = $True
$Sheet.Columns.Item('m').ColumnWidth = 15
foreach ($objResult in $Results) {
$intRow++
$objComputer = $objResult.Properties
[string]$computer = $objComputer.name
$pingStatus = Get-WMIObject Win32_PingStatus -Filter "Address = '$computer'"
$ipAddress = $pingStatus.ProtocolAddress
if($pingStatus.StatusCode -eq 0) {
$UUID = Get-WMIObject $WMI_CSP -ComputerName $computer | Select UUID
$_UUID = $UUID.UUID
$OS = Get-WMIObject $WMI_OS -ComputerName $computer | Select Caption
$_OS = $OS.Caption
if($_OS)
{if($_OS.Contains(",")) {$_OS = $_OS.Replace(",","")} if($_OS.Contains("(R)")) {$_OS = $_OS.Replace("(R)","")}}
$CSDVer = Get-WMIObject $WMI_OS -ComputerName $computer | Select CSDVersion
$_CSDVer = $CSDVer.CSDVersion
$Ver = Get-WMIObject $WMI_OS -ComputerName $computer | Select Version
$_Ver = $Ver.Version
$Mfr = Get-WMIObject $WMI_CSP -ComputerName $computer | Select Vendor
$_Mfr = $Mfr.Vendor
if($_Mfr)
{if($_Mfr.Contains("HP")) {$_Mfr = $_Mfr.Replace("HP","Hewlett-Packard")}}
$HW = Get-WMIObject $WMI_CSP -ComputerName $computer | Select Name
$_HW = $HW.Name
$Platform = Get-WMIObject $WMI_Proc -ComputerName $computer -filter "DeviceID = 'CPU0'" | Select Manufacturer
$_Platform = $Platform.Manufacturer
$RAMKB = Get-WMIObject $WMI_CS -ComputerName $computer | Select TotalPhysicalMemory
[int64]$_RAMKB = $RAMKB.TotalPhysicalMemory
[int64]$_RAMMB = $_RAMKB / 1kb
$Processors = Get-WMIObject $WMI_CS -ComputerName $computer | Select NumberOfProcessors
[int64]$NumOfProcs = $Processors.NumberOfProcessors
$Space = Get-WMIObject $WMI_Disk -ComputerName $computer -filter "DeviceID = 'c:'" | Select FreeSpace
[int64]$DiskFree = $Space.FreeSpace
$Size = Get-WMIObject $WMI_Disk -ComputerName $computer -filter "DeviceID = 'c:'" | Select Size
[int64]$DiskSize = $Size.Size
[int64]$DiskUsage = ($DiskSize - $DiskFree) / 1kb
# Output minimal information to Console & Complete information to XLS file (Successful Ping)
Write-Host -ForegroundColor Green "Reply received from $computer ($ipAddress)"
$Sheet.Cells.Item($intRow,1) = $_UUID
$Sheet.Cells.Item($intRow,2) = $computer
$Sheet.Cells.Item($intRow,3) = $ipAddress
$Sheet.Cells.Item($intRow,4) = $DomainName
$Sheet.Cells.Item($intRow,5) = $_OS
$Sheet.Cells.Item($intRow,6) = $_CSDVer
$Sheet.Cells.Item($intRow,7) = $_Ver
$Sheet.Cells.Item($intRow,8) = $_Mfr
$Sheet.Cells.Item($intRow,9) = $_HW
$Sheet.Cells.Item($intRow,10) = $_Platform
$Sheet.Cells.Item($intRow,11) = $_RAMMB
$Sheet.Cells.Item($intRow,12) = $NumOfProcs
$Sheet.Cells.Item($intRow,13) = $DiskUsage
}
else {
# Output minimal information to Console & Minimal information to XLS file (Unsucccessful Ping)
Write-Host -ForegroundColor Red "No Reply received from $computer ....................[SKIPPED]"
$Sheet.Cells.Item($intRow, 1) = "HOST NOT ONLINE"
$Sheet.Cells.Item($intRow, 2) = $computer
$Sheet.Cells.Item($intRow, 3) = "---"
$Sheet.Cells.Item($intRow, 4) = $DomainName
$Sheet.Cells.Item($intRow, 5) = "---"
$Sheet.Cells.Item($intRow, 6) = "---"
$Sheet.Cells.Item($intRow, 7) = "---"
$Sheet.Cells.Item($intRow, 8) = "---"
$Sheet.Cells.Item($intRow, 9) = "---"
$Sheet.Cells.Item($intRow, 10) = "---"
$Sheet.Cells.Item($intRow, 11) = "---"
$Sheet.Cells.Item($intRow, 12) = "---"
$Sheet.Cells.Item($intRow, 13) = "---"
}
}
$Sheet.UsedRange.EntireColumn.AutoFit()
Clear
|
PowerShellCorpus/PoshCode/1c3a8f71-b8a5-455c-bc04-31657019f3d5.ps1
|
1c3a8f71-b8a5-455c-bc04-31657019f3d5.ps1
|
#Params is file or folder
param([string] $PSUnitTestFile, [string] $Category ="All", [switch] $ShowReportInBrowser)
Write-Debug "PSUnit.Run.ps1: Parameter `$PSUnitTestFile=`"$PSUnitTestFile`""
Write-Debug "PSUnit.Run.ps1: Parameter `$Category=`"$Category`""
#Don't run the script with an empty path to test file
if ([String]::IsNullOrEmpty($PSUnitTestFile))
{
Throw "The `$PSUnitTestFile parameter is required!"
}
#Make sure the test file exists
if( ! (Test-Path -Path $PSUnitTestFile) )
{
Throw "`$PSUnitTestFile: $PSUnitTestFile is not a valid file!"
}
#This is there to prevent this script from running itself as a test
$PSUnitTestFileInfo = Get-Item -Path $PSUnitTestFile
if ($PSUnitTestFileInfo.Name -eq "PSUnit.Run.ps1")
{
Throw "This script can't run itself as a test!"
}
#Data Model for the test result report
$TestEnvironment = @{}
$TestStatistics = @{}
$TestResults = New-Object -TypeName "System.Collections.ArrayList"
$Statistics = @{}
$TestStartTime = [DateTime]::Now
$TestEndTime = [DateTime]::Now
#Deleting test functions from global scope
$TestFunctions = Get-Item function:Test.*
If ($TestFunctions)
{
Write-Debug "PSUnit.Run.ps1: Deleting test functions from global scope!"
$TestFunctions | Remove-Item
}
#Loading test functions into global scope
$ScriptLines = Get-Content -Path $PSUnitTestFile -Encoding "UTF8"
$ScriptText = [String]::Join("`n`r", $ScriptLines)
Invoke-Expression $ScriptText
#Make sure that the $PSTestScript has tests defined
if (! (Test-Path -Path function:Test.*))
{
Throw "Script `"$PSUnitTestFile`" doesn't have any test functions defined!"
}
#Get all Test. functions. This will get every function in global scope, even the ones that we didn't explicitly load
$TestFunctions = Get-Item function:Test.*
function Execute-Test([System.Management.Automation.FunctionInfo] $Test)
{
Try
{
Write-Debug "Execute-Test: Executing: $($Test.Name)"
& $Test
}
Catch
{
Write-Debug "Execute-Test: Caught exception: $($_.Exception.GetType().FullName)"
Throw $_
}
}
function Report-TestResult([System.Management.Automation.FunctionInfo] $Test, [string] $Result, [System.Management.Automation.ErrorRecord] $Reason)
{
#Creating test results object collection
$TestResult = New-Object -TypeName "System.Management.Automation.PSObject"
$TestResult = Add-Member -passthru -InputObject $TestResult -MemberType NoteProperty -Name "Test" -Value $Test
$TestResult = Add-Member -passthru -InputObject $TestResult -MemberType NoteProperty -Name "Result" -Value $Result
$TestResult = Add-Member -passthru -InputObject $TestResult -MemberType NoteProperty -Name "Reason" -Value $Reason
$null = $TestResults.Add($TestResult);
#Writing Console output
if($Test.Name.Length -ge 99)
{
$TestNameString = $Test.Name.Substring(0, 95) + "..."
}
else
{
$TestNameString = $Test.Name
}
switch ($Result)
{
"PASS"
{
Write-Host "$($TestNameString.PadRight(100, ' '))" -foregroundcolor "blue" -backgroundcolor "white" -nonewline
Write-Host "PASS" -foregroundcolor "black" -backgroundcolor "green" -nonewline
Write-Host $(" N/A".PadRight(100, ' ')) -foregroundcolor "blue" -backgroundcolor "white"
}
"FAIL"
{
if($Reason.ToString().Length -ge 99)
{
$ReasonString = $Reason.ToString().Substring(0, 95) + "..."
}
else
{
$ReasonString = $Reason.ToString()
}
Write-Host "$($TestNameString.PadRight(100, ' '))" -foregroundcolor "blue" -backgroundcolor "white" -nonewline
Write-Host "FAIL" -foregroundcolor "white" -backgroundcolor "red" -nonewline
Write-Host $(" $ReasonString".PadRight(100, ' ')) -foregroundcolor "red" -backgroundcolor "white"
}
"SKIP"
{
Write-Host "$($TestNameString.PadRight(100, ' '))" -foregroundcolor "blue" -backgroundcolor "white" -nonewline
Write-Host "SKIP" -foregroundcolor "black" -backgroundcolor "yellow" -nonewline
Write-Host $(" N/A".PadRight(100, ' ')) -foregroundcolor "blue" -backgroundcolor "white"
}
}
}
function Get-ExpectedExceptionTypeName([System.Management.Automation.FunctionInfo] $Test)
{
$ExpectedExceptionTypeName = "ExpectedException Parameter is not defined in function $($Test.Name)"
$ExpectedExceptionParameter = $Test.Parameters["ExpectedException"]
if( $ExpectedExceptionParameter -ne $Null)
{
$ExpectedExceptionTypeName = $ExpectedExceptionParameter.ParameterType.FullName
}
else
{
Write-Debug "Get-ExpectedExceptionTypeName: $($Test.Name) doesn't use ExpectedException parameter"
}
return $ExpectedExceptionTypeName
}
function Get-TestFunctionCategory([System.Management.Automation.FunctionInfo] $Test)
{
$TestFunctionCategory = "All"
$Test.Parameters.GetEnumerator() | ForEach-Object `
{
if($_.Key -match '^Category_(?<CATEGORY>.*)$')
{
$TestFunctionCategory = $Matches["CATEGORY"]
}
}
Write-Debug "Get-TestFunctionCategory: Found Category=`"$TestFunctionCategory`""
return $TestFunctionCategory
}
function Get-TestFunctionSkip([System.Management.Automation.FunctionInfo] $Test)
{
$IsSkipSet = $false
$SkipParameter = $Test.Parameters["Skip"]
if( $SkipParameter -ne $Null)
{
$IsSkipSet = $true
Write-Debug "Get-TestFunctionSkip: $($Test.Name) uses Skip parameter"
}
else
{
Write-Debug "Get-TestFunctionSkip: $($Test.Name) doesn't use Skip parameter"
}
return $IsSkipSet
}
if ($TestFunctions -eq $Null)
{
Write-Error "No function that starts with test.* was found in function: drive. Make sure that $PSUnitTestFile is in the correct path."
}
else
{
$TestStartTime = [DateTime]::Now
#Execute each function
$TestFunctions | ForEach-Object `
{
$CurrentFunction = $_
$ExpectedExceptionTypeName = Get-ExpectedExceptionTypeName -Test $CurrentFunction
$TestFunctionCategory = Get-TestFunctionCategory -Test $CurrentFunction
$TestFunctionSkip = Get-TestFunctionSkip -Test $CurrentFunction
if ($TestFunctionSkip)
{
Report-TestResult -Test $CurrentFunction -Result "SKIP"
return
}
if (($TestFunctionCategory -ne $Category) -and ($Category -ne "All"))
{
Write-Debug "PSUnit.Run.ps1: Not running `"$($CurrentFunction.Name)`". Its category is `"$TestFunctionCategory`", but the required category is `"$Category`""
return
}
Try
{
$FunctionOutput = Execute-Test $_
Report-TestResult -Test $CurrentFunction -Result "PASS"
}
Catch
{
$ActualExceptionTypeName = $_.Exception.GetType().FullName
Write-Debug "PSUnit.Run.ps1: Execution of `"$CurrentFunction`" caused following Exception `"$($_.Exception.GetType().FullName)`""
Write-Debug "PSUnit.Run.ps1: ExpectedException = `"$ExpectedExceptionTypeName`""
if ($ActualExceptionTypeName -eq $ExpectedExceptionTypeName)
{
Report-TestResult -Test $CurrentFunction -Result "PASS"
}
else
{
Report-TestResult -Test $CurrentFunction -Result "FAIL" -Reason $_
}
}
}
$TestEndTime = [DateTime]::Now
}
function Get-TestResultStatistics([System.Collections.ArrayList] $Results)
{
$Stats = @{}
$Stats["Total"] =0
$Stats["Passed"] = 0
$Stats["Failed"] = 0
$Stats["Skipped"] = 0
if(!$Results -or $Results.Count -eq 0)
{
return $Stats
}
$Stats["Total"] = $Results.Count
$Results | Foreach-Object `
{
switch ( $_.Result )
{
"PASS" {$Stats["Passed"]++}
"FAIL" {$Stats["Failed"]++}
"SKIP" {$Stats["Skipped"]++}
}
}
return $Stats
}
function Get-TestReportFileName([System.Collections.HashTable] $EnvironmentData, [System.Collections.HashTable] $Stats )
{
$StatsTotal = 0
$StatsPassed = 0
$StatsFailed = 0
$StatsSkipped = 0
If($Stats.Total) {$StatsTotal = $Stats.Total}
If($Stats.Passed) {$StatsPassed = $Stats.Passed}
If($Stats.Failed) {$StatsFailed = $Stats.Failed}
If($Stats.Skipped) {$StatsSkipped = $Stats.Skipped}
$StatsFileNamePart = "T{0}P{1}F{2}S{3}" -f $StatsTotal, $StatsPassed, $StatsFailed, $StatsSkipped
$StartDateString = $EnvironmentData.StartTime.ToString("yyyy-MM-dd-HH-mm-ss")
$TestFile = dir $($EnvironmentData.TestFilename)
$FileName = $TestFile.Name
$TestReportFileName = "PSUnitTestReport_{0}_{1}_{2}.html" -f $FileName, $StartDateString, $StatsFileNamePart
Write-Debug "Get-TestReportFileName: `$TestReportFileName = $TestReportFileName"
return $TestReportFileName
}
function Get-TestReportTitleAsHtml([System.Collections.HashTable] $EnvironmentData)
{
$TestReportTitle = "PSUnit Test Report - {0} - {1}" -f $EnvironmentData.TestFilename, $EnvironmentData.StartTime
$TestReportTitle = Encode-Html -StringToEncode $TestReportTitle
return $TestReportTitle
}
function Compile-TestResultReport()
{
$TestFile = dir $PSUnitTestFile
$TestEnvironment["TestFileName"] = $TestFile.FullName
$TestEnvironment["SourceCodeRevision"] = "Not yet implemeted!"
$TestEnvironment["Category"] = $Category
$TestEnvironment["StartTime"] = $TestEndTime
$TestEnvironment["EndTime"] = $TestEndTime
$TestEnvironment["Duration"] = ($TestEnvironment.EndTime - $TestEnvironment.StartTime).TotalSeconds
$TestEnvironment["UserName"] = $env:username
$TestEnvironment["MachineName"] = $env:computername
$TestEnvironment["PowerShellVersion"] = $host.version.ToString()
$OSProperties = get-wmiobject -class "Win32_OperatingSystem" -namespace "root\\CIMV2" -computername $env:computername
$OperatingSystem = "{0} {1} Build {2}" -f $OSProperties.Caption, $OSProperties.CSDVersion, $OSProperties.BuildNumber
$TestEnvironment["OperatingSystem"] = $OperatingSystem
$Statistics = Get-TestResultStatistics -Results $TestResults
$TestReportFileName = Get-TestReportFileName -EnvironmentData $TestEnvironment -Stats $Statistics
$TestEnvironment["TestReportFileName"] = $TestReportFileName
$TestReportTitle = Get-TestReportTitleAsHtml -EnvironmentData $TestEnvironment
$TestEnvironment["TestReportTitle"] = $TestReportTitle
$ReportHtml = Render-TestResultReport -Results $TestResults -HeaderData $TestEnvironment -Statistics $Statistics
#Get PSUNIT_HOME folder
$PSUnitHome = dir env:PSUNIT_HOME
Write-Debug "PSUNIT_HOME: $PSUnitHome"
$TestReportFile = Join-Path -Path $($PSUnitHome.Value) -ChildPath $TestReportFileName
#Save report as file in PSUnit Home folder
$ReportHtml > $TestReportFile
if ($ShowReportInBrowser)
{#Open Report File
& ($TestReportFile)
}
}
Compile-TestResultReport
|
PowerShellCorpus/PoshCode/Get-MailAttachment.ps1
|
Get-MailAttachment.ps1
|
param([Microsoft.Exchange.WebServices.Data.FileAttachment]$attachment)
"Downloading Attachment"
$attachment.Load()
"Done"
$path = "C:\\temp\\"+$attachment.Name
"Writing to $path"
set-content -value $mm[1].Attachments[0].Content -enc byte -path $path
"Done"
ii $path
|
PowerShellCorpus/PoshCode/Hostprofile Update GUI.ps1
|
Hostprofile Update GUI.ps1
|
################################################################################################################
#
# Purpose: Host Profile Update
# Author: David Chung
#
# Ver 1.0 - 09/22/2011 Initial Script
# Ver 1.1 - 09/26/2011 Added Full GUI support (Primal Forms)
# Ver 1.2 - 09/26/2011 Enabled User and Password Field
# Added Login Fail-safe feature.
# Added Compliance Check Only Box
# Search for Powered On Hosts only
# Windows Resize Disabled
# Removed Progress Bar
# Ver 1.3 - 09/28/2011 Added hosts in maintenace mode in cluster check
# -stops host profile update if any host in the cluster is in mainteance mode prior to the update
# Ver 1.4 09/29/2011 Added checks that if the cluster is not selected, the script does not proceed.
#
################################################################################################################
#Generated Form Function
function GenerateForm {
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$button4 = New-Object System.Windows.Forms.Button
$groupBox3 = New-Object System.Windows.Forms.GroupBox
$ComplianceBox1 = New-Object System.Windows.Forms.CheckBox
$label4 = New-Object System.Windows.Forms.Label
$ClusterName = New-Object System.Windows.Forms.ListBox
$BeginButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$groupBox2 = New-Object System.Windows.Forms.GroupBox
$ProgressLog = New-Object System.Windows.Forms.ListBox
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$LoginButton = New-Object System.Windows.Forms.Button
$Password = New-Object System.Windows.Forms.TextBox
$User = New-Object System.Windows.Forms.TextBox
$vCenter = New-Object System.Windows.Forms.TextBox
$label3 = New-Object System.Windows.Forms.Label
$label2 = New-Object System.Windows.Forms.Label
$label1 = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$BeginButton_OnClick=
{
#TODO: Place custom script here
$scluster = $ClusterName.SelectedItem
if ($scluster -eq $null) {
$ProgressLog.items.add("")
$ProgressLog.items.add("Please select a cluster from the cluster list")
[Windows.Forms.Application]::DoEvents()
}
Else {
$vcluster = Get-Cluster $scluster
$ProgressLog.items.add("Collecting Powered On Hosts in $vcluster...")
[Windows.Forms.Application]::DoEvents()
$VMhosts = $vcluster| Get-VMHost | where {$_.PowerState -eq "PoweredOn"} | sort name
$ProgressLog.items.add("....completed")
$ProgressLog.items.add("")
[Windows.Forms.Application]::DoEvents()
If ($ComplianceBox1.Checked) {
$ProgressLog.items.add("Checking Hosts in $vcluster...")
[Windows.Forms.Application]::DoEvents()
ForEach ($VMhost in $VMhosts) {
$profile = Test-VMHostProfileCompliance -VMHost $VMhost
If ($PROFILE -ne $null) {
$hostprofile = Get-vmhostprofile -entity $VMhost
$ProgressLog.items.add("$VMHost is NOT Compliant.")
[Windows.Forms.Application]::DoEvents()
}
Else {
$ProgressLog.items.add("$vmhost is Compliant.")
[Windows.Forms.Application]::DoEvents()
}
}
$ProgressLog.items.add("")
$ProgressLog.items.add("Compliance Check is Completed")
$ProgressLog.items.add("")
}
Else {
$ProgressLog.items.add("Checking Hosts in $vcluster...")
[Windows.Forms.Application]::DoEvents()
$VMhosts = $vcluster| Get-VMHost | where {$_.PowerState -eq "PoweredOn"} | sort name
$ClusterHostCount = @($VMhosts).Count
$ClusterConnectedCount = @($VMhosts | where {$_.ConnectionState -eq "Connected"}).Count
If ($ClusterHostCount -ne $ClusterConnectedCount){
$ProgressLog.items.add("WARNING: One or more hosts in $vcluster in Maint. mode.")
$ProgressLog.items.add("Please try to remediate before updating the host profile.")
[Windows.Forms.Application]::DoEvents()
}
Else {
ForEach ($VMhost in $VMhosts) {
$profile = Test-VMHostProfileCompliance -VMHost $VMhost
If ($PROFILE -ne $null) {
$hostprofile = Get-vmhostprofile -entity $VMhost
$ProgressLog.items.add("$VMHost is NOT Compliant.")
[Windows.Forms.Application]::DoEvents()
if ($vcluster.DrsAutomationLevel -ne "FullyAutomated"){
$ProgressLog.items.add("WARNING: DRS FullyAutomated not set on $vcluster")
$ProgressLog.items.add("WARNING: Enabling DRS FullyAutomated")
[Windows.Forms.Application]::DoEvents()
Set-Cluster -Cluster $vcluster -DrsAutomationLevel FullyAutomated -Confirm:$false
}
foreach ($vm in ($VMHost | get-vm)){
if ((get-cddrive -VM $vm).ConnectionState.Connected -eq "true"){
$ProgressLog.items.add("WARNING: $VM has a CDROM drive attached, detaching.")
$ProgressLog.items.add("WARNING: Detaching CDROM.")
[Windows.Forms.Application]::DoEvents()
Set-CDDrive -CD (get-cddrive -VM $vm) -StartConnected:$false -Connected:$False -Confirm:$false
}
}
$ProgressLog.items.add("Setting $VMhost to Maintenance Mode...")
[Windows.Forms.Application]::DoEvents()
Set-VMHost -State 'Maintenance' -VMHost $VMhost -Evacuate:$true -Confirm:$false
$ProgressLog.items.add("Applying Host Profilie...")
[Windows.Forms.Application]::DoEvents()
Apply-VMHostProfile -Entity $VMHost -Profile $hostprofile -ErrorAction SilentlyContinue -Confirm:$false
$ProgressLog.items.add("Taking the Host out of maintenance mode....")
[Windows.Forms.Application]::DoEvents()
Set-VMHost -VMHost $VMhost -State 'Connected'
Test-VMHostProfileCompliance -VMHost $VMhost
}
Else {
$ProgressLog.items.add("$vmhost is Compliant.")
$ProgressLog.items.add("")
[Windows.Forms.Application]::DoEvents()
}
}
$ProgressLog.items.add("Compliance Update is Completed")
}
}
}
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
$form1.Close()
}
$LoginButton_OnClick=
{
#TODO: Place custom script here
if ($VCenter.text -like "" -or $Password.text -like "" -or $User.text -like "") {
$ProgressLog.items.add("Field can not be empty. Try Again")
[Windows.Forms.Application]::DoEvents()
}
Else {
$LoginButton.Enabled = $false
$V = $vCenter.text
$PSW = $Password.text
$iUser = $User.text
#$BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($PSW)
#$PSW = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR)
$ProgressLog.items.add("Connecting to $V...")
[Windows.Forms.Application]::DoEvents()
#Connect-VIServer -Server $V -User $iUser -Password $PSW -WarningAction:SilentlyContinue
$connection = Connect-VIServer $V -User $iuser -Password $PSW -WarningAction:SilentlyContinue
if ($connection.Port -notlike "*443*") {
$ProgressLog.items.add("....Failed!")
$ProgressLog.items.add("Failed to connect. Check vCenter and credentials.")
$LoginButton.Enabled = $true
[Windows.Forms.Application]::DoEvents()
}
Else {
$ProgressLog.items.add("....connected")
$ProgressLog.items.add("")
$ProgressLog.items.add("Getting Cluster Name from $V...")
[Windows.Forms.Application]::DoEvents()
$Clusters = Get-Cluster | sort name
Foreach ($Cluster in $Clusters){
$ClusterName.items.add($Cluster.Name)
[Windows.Forms.Application]::DoEvents()
}
$ProgressLog.items.add("....completed")
[Windows.Forms.Application]::DoEvents()
$BeginButton.Enabled = $True
}
}
}
$button4_OnClick=
{
#TODO: Place custom script here
$vCenter.Text = $null
$User.Text = $null
$Password.Text = $null
$ClusterName.items.clear()
$ProgressLog.items.clear()
[Windows.Forms.Application]::DoEvents()
$BeginButton.Enabled = $false
$LoginButton.Enabled = $true
Disconnect-VIServer * -ErrorAction:SilentlyContinue -Confirm:$false
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 583
$System_Drawing_Size.Width = 452
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.FormBorderStyle = 1
$form1.Name = "form1"
$form1.Text = "Host Profile Update by David Chung"
$button4.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 277
$System_Drawing_Point.Y = 548
$button4.Location = $System_Drawing_Point
$button4.Name = "button4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button4.Size = $System_Drawing_Size
$button4.TabIndex = 5
$button4.Text = "Reset Form"
$button4.UseVisualStyleBackColor = $True
$button4.add_Click($button4_OnClick)
$form1.Controls.Add($button4)
$groupBox3.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 124
$groupBox3.Location = $System_Drawing_Point
$groupBox3.Name = "groupBox3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 66
$System_Drawing_Size.Width = 427
$groupBox3.Size = $System_Drawing_Size
$groupBox3.TabIndex = 4
$groupBox3.TabStop = $False
$groupBox3.Text = "Profile Update"
$form1.Controls.Add($groupBox3)
$ComplianceBox1.CheckAlign = 64
$ComplianceBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 262
$System_Drawing_Point.Y = 42
$ComplianceBox1.Location = $System_Drawing_Point
$ComplianceBox1.Name = "ComplianceBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 150
$ComplianceBox1.Size = $System_Drawing_Size
$ComplianceBox1.TabIndex = 3
$ComplianceBox1.Text = "Compliance Check Only"
$ComplianceBox1.UseVisualStyleBackColor = $True
$groupBox3.Controls.Add($ComplianceBox1)
$label4.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 29
$label4.Location = $System_Drawing_Point
$label4.Name = "label4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label4.Size = $System_Drawing_Size
$label4.TabIndex = 2
$label4.Text = "Select Cluster"
$groupBox3.Controls.Add($label4)
$ClusterName.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterName.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 113
$System_Drawing_Point.Y = 19
$ClusterName.Location = $System_Drawing_Point
$ClusterName.Name = "ClusterName"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 30
$System_Drawing_Size.Width = 122
$ClusterName.Size = $System_Drawing_Size
$ClusterName.Sorted = $True
$ClusterName.TabIndex = 0
$groupBox3.Controls.Add($ClusterName)
$BeginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 345
$System_Drawing_Point.Y = 13
$BeginButton.Location = $System_Drawing_Point
$BeginButton.Name = "BeginButton"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$BeginButton.Size = $System_Drawing_Size
$BeginButton.TabIndex = 2
$BeginButton.Text = "Begin"
$BeginButton.UseVisualStyleBackColor = $True
$BeginButton.add_Click($BeginButton_OnClick)
$BeginButton.Enabled = $False
#
$groupBox3.Controls.Add($BeginButton)
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 358
$System_Drawing_Point.Y = 548
$CloseButton.Location = $System_Drawing_Point
$CloseButton.Name = "CloseButton"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$CloseButton.Size = $System_Drawing_Size
$CloseButton.TabIndex = 3
$CloseButton.Text = "Close"
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.add_Click($CloseButton_OnClick)
$form1.Controls.Add($CloseButton)
$groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 196
$groupBox2.Location = $System_Drawing_Point
$groupBox2.Name = "groupBox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 345
$System_Drawing_Size.Width = 427
$groupBox2.Size = $System_Drawing_Size
$groupBox2.TabIndex = 1
$groupBox2.TabStop = $False
$groupBox2.Text = "Progress Log"
$form1.Controls.Add($groupBox2)
$ProgressLog.DataBindings.DefaultDataSourceUpdateMode = 0
$ProgressLog.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 20
$ProgressLog.Location = $System_Drawing_Point
$ProgressLog.Name = "ProgressLog"
$ProgressLog.SelectionMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 316
$System_Drawing_Size.Width = 414
$ProgressLog.Size = $System_Drawing_Size
$ProgressLog.TabIndex = 3
$groupBox2.Controls.Add($ProgressLog)
$groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 12
$groupBox1.Location = $System_Drawing_Point
$groupBox1.Name = "groupBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 106
$System_Drawing_Size.Width = 427
$groupBox1.Size = $System_Drawing_Size
$groupBox1.TabIndex = 0
$groupBox1.TabStop = $False
$groupBox1.Text = "vCenter Login"
$form1.Controls.Add($groupBox1)
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 345
$System_Drawing_Point.Y = 41
$LoginButton.Location = $System_Drawing_Point
$LoginButton.Name = "LoginButton"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$LoginButton.Size = $System_Drawing_Size
$LoginButton.TabIndex = 6
$LoginButton.Text = "Login"
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.add_Click($LoginButton_OnClick)
$groupBox1.Controls.Add($LoginButton)
$Password.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 113
$System_Drawing_Point.Y = 71
$Password.Location = $System_Drawing_Point
$Password.Name = "Password"
$Password.PasswordChar = '*'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 122
$Password.Size = $System_Drawing_Size
$Password.TabIndex = 5
$groupBox1.Controls.Add($Password)
$User.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 113
$System_Drawing_Point.Y = 44
$User.Location = $System_Drawing_Point
$User.Name = "User"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 122
$User.Size = $System_Drawing_Size
$User.TabIndex = 4
$groupBox1.Controls.Add($User)
$vCenter.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 113
$System_Drawing_Point.Y = 17
$vCenter.Location = $System_Drawing_Point
$vCenter.Name = "vCenter"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 122
$vCenter.Size = $System_Drawing_Size
$vCenter.TabIndex = 3
$groupBox1.Controls.Add($vCenter)
$label3.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 74
$label3.Location = $System_Drawing_Point
$label3.Name = "label3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label3.Size = $System_Drawing_Size
$label3.TabIndex = 2
$label3.Text = "Password"
$groupBox1.Controls.Add($label3)
$label2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 47
$label2.Location = $System_Drawing_Point
$label2.Name = "label2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label2.Size = $System_Drawing_Size
$label2.TabIndex = 1
$label2.Text = "User Name"
$groupBox1.Controls.Add($label2)
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 20
$label1.Location = $System_Drawing_Point
$label1.Name = "label1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label1.Size = $System_Drawing_Size
$label1.TabIndex = 0
$label1.Text = "VI Server"
$groupBox1.Controls.Add($label1)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Get-Scope_1.ps1
|
Get-Scope_1.ps1
|
function Get-Scope{
$rtnScope = 0
$global:scope = $false
$scope = $true
while($($ErrorActionPreference = "silentlycontinue"; switch((get-Variable -Name scope -Scope $rtnScope).value){$null{$true} $true{$true} $false{$ErrorActionPreference = "continue"; return ($rtnScope - 1)}})){
$rtnScope++
}
}
Example.
function gg{
Get-Scope
};
function iii{
gg
};
iii ==> result is 2
|
PowerShellCorpus/PoshCode/Get-DatastoreMostFree.ps1
|
Get-DatastoreMostFree.ps1
|
#Parameter- Name of the VMware cluster the VM will be assigned to
function Get-DatastoreMostFree ($Cluster, [switch] $Second)
{
<#
.SYNOPSIS
Return the datastore in the cluster with the most unprovisioned disk space. This takes thin provisioning into account.
.DESCRIPTION
Queries all the datastores in the cluster and returns the datastore with the most free disk space. Used in conjunction with a mass cloning of virtual machines script. (Clone_Template_fromCSV.ps1)
.NOTES
1- You will need to modify the 2nd to last line's with criteria for your own environment. I'm filtering out anything that's designed to hold guest VMs, like any datastores hosting ISO files and template VMs.
2- Error and constraint checking need to be added. If you try to put a VM a full LUN it will fail.
.LINK
.EXAMPLE
Get-DatastoreMostFree.ps1 clustername
#>
# Prep
Set-Variable -Name ScriptDir -Value "\\\\vmscripthost201\\repo" -Scope Local
. $ScriptDir\\Get-mDataStoreList.ps1
# Amount of free space on a LUN for it to be an eligible target
$LUNSizeFreeMB = 300*1024
$DSTs = Get-mDataStoreList $Cluster
if (!$Second) {
$DST = $DSTs | Where-Object { $_.FreeSpaceMB -gt $LUNSizeFreeMB } | Select Name,@{n="Provisioned";e={($_.extensiondata.summary.capacity - $_.extensiondata.summary.freespace + $_.extensiondata.summary.Uncommitted)}} | Sort Provisioned -Descending | Select-Object -Last 1 -Property Name }
else {
$DST = $DSTs | Where-Object { $_.FreeSpaceMB -gt $LUNSizeFreeMB } | Select Name,@{n="Provisioned";e={($_.extensiondata.summary.capacity - $_.extensiondata.summary.freespace + $_.extensiondata.summary.Uncommitted)}} | Sort Provisioned -Descending | Select-Object -Last 2 | Select-Object -First 1 -Property Name }
write-output $dst
}
|
PowerShellCorpus/PoshCode/Out-Html_2.ps1
|
Out-Html_2.ps1
|
################################################################################
# Out-HTML - converts cmdlets help to HTML format
# Based on Out-wiki by Dimitry Sotnikov (http://dmitrysotnikov.wordpress.com/2008/08/18/out-wiki-convert-powershell-help-to-wiki-format/)
#
# Modify the invocation line at the bottom of the script if you want to document
# fewer command, subsets or snapins
# Open default.htm to view in frameset or index.htm for index page with links.
################################################################################
# Created By: Vegard Hamar
################################################################################
param($outputDir = "./help")
function FixString {
param($in = "")
if ($in -eq $null) {
$in = ""
}
return $in.Replace("&", "&").Replace("<", "<").Replace(">", ">")
}
function Out-HTML {
param($commands = $null, $outputDir = "./help")
$commandsHelp = $commands | sort-object PSSnapIn, noun | get-help -full
#create an output directory
if ( -not (Test-Path $outputDir)) {
md $outputDir | Out-Null
}
#Generate frame page
$indexFileName = $outputDir + "/index.htm"
#Generate frameset
@'
<html>
<head>
<title>PowerShell Help</title>
</head>
<frameset cols="250,*">
<frame src="./index.htm" />
<frame src="" name="display"/>
</frameset>
</html>
'@ | Out-File "$outputDir/default.htm"
#Generate index
@'
<html>
<head>
<title>PowerShell Help</title>
</head>
<body>
'@ | out-file $indexFileName
$SnapIn = ""
foreach ($c in $commandsHelp) {
if ($SnapIn -ne $c.PSSnapIn.Name) {
"<a href='#" + $c.PSSnapIn.name + "'>* " + $c.PSSnapIn.Name.Replace(".", " ") + "</a></br>" | out-file $indexFileName -Append
$SnapIn = $c.PSSnapIn.Name
}
}
$SnapIn = ""
foreach ($c in $commandsHelp) {
if ($SnapIn -ne $c.PSSnapIn.Name) {
"<h3><a name='$($c.PSSnapIn.Name)'>" +$c.PSSnapIn.Name.Replace(".", " ") + "</a></h3>" | Out-File $indexFileName -Append
$SnapIn = $c.PSSnapIn.Name
}
"<a href='" + $c.name + ".htm' target='display'>* $($c.Name)</a></br>" | out-file $indexFileName -Append
}
#Generate all single help files
$outputText = $null
foreach ($c in $commandsHelp) {
$fileName = ( $outputDir + "/" + $c.Name + ".htm" )
@"
<html>
<head>
<title>$($c.Name)</title>
</head>
<body>
<h1>$($c.Name)</h1>
<div>$($c.synopsis)</div>
<h2> Syntax </h2>
<code>$(FixString($c.syntax | out-string -width 2000).Trim())</code>
<h2> Detailed Description </h2>
<div>$(FixString($c.Description | out-string -width 2000))</div>
<h2> Related Commands </h2>
<div>
"@ | out-file $fileName
foreach ($relatedLink in $c.relatedLinks.navigationLink) {
if($relatedLink.linkText -ne $null -and $relatedLink.linkText.StartsWith("about") -eq $false){
" * <a href='$($relatedLink.linkText).htm'>$($relatedLink.linkText)</a><br/>" | out-file $fileName -Append
}
}
@"
</div>
<h2> Parameters </h2>
<table border='1'>
<tr>
<th>Name</th>
<th>Description</th>
<th>Required?</th>
<th>Pipeline Input</th>
<th>Default Value</th>
</tr>
"@ | out-file $fileName -Append
$paramNum = 0
foreach ($param in $c.parameters.parameter ) {
@"
<tr valign='top'>
<td>$($param.Name) </td>
<td>$(FixString(($param.Description | out-string -width 2000).Trim())) </td>
<td>$(FixString($param.Required)) </td>
<td>$(FixString($param.PipelineInput)) </td>
<td>$(FixString($param.DefaultValue)) </td>
</tr>
"@ | out-file $fileName -Append
}
" </table>}" | out-file $fileName -Append
# Input Type
if (($c.inputTypes | Out-String ).Trim().Length -gt 0) {
@"
<h2> Input Type </h2>
<div>$(FixString($c.inputTypes | out-string -width 2000).Trim())</div>
"@ | out-file $fileName -Append
}
# Return Type
if (($c.returnValues | Out-String ).Trim().Length -gt 0) {
@"
<h2> Return Values </h2>
<div>$(FixString($c.returnValues | out-string -width 2000).Trim())</div>
"@ | out-file $fileName -Append
}
# Notes
if (($c.alertSet | Out-String).Trim().Length -gt 0) {
@"
<h2> Notes </h2>
"<div>$(FixString($c.alertSet | out-string -Width 2000).Trim())</div>
"@ | out-file $fileName -Append
}
# Examples
if (($c.examples | Out-String).Trim().Length -gt 0) {
" <h2> Examples </h2>" | out-file $fileName -Append
foreach ($example in $c.examples.example) {
@"
<h3> $(FixString($example.title.Trim(('-',' '))))</h3>
<pre>$(FixString($example.code | out-string ).Trim())</pre>
<div>$(FixString($example.remarks | out-string -Width 2000).Trim())</div>
"@ | out-file $fileName -Append
}
}
@"
</body>
</html>
"@ | out-file $fileName -Append
}
@"
</body>
</html>
"@ | out-file $indexFileName -Append
}
Out-HTML (Get-Command ) $outputDir
|
PowerShellCorpus/PoshCode/ISE-CopyOutPutToEditor_1.ps1
|
ISE-CopyOutPutToEditor_1.ps1
|
function ISE-CopyOutPutToEditor () {
$count = $psise.CurrentOpenedRunspace.OpenedFiles.count
$psIse.CurrentOpenedRunspace.OpenedFiles.Add()
$Newfile = $psIse.CurrentOpenedRunspace.OpenedFiles[$count]
$Newfile.Editor.Text = $psIse.CurrentOpenedRunspace.output.Text
$Newfile.Editor.Focus()
}
$null = $psIse.CustomMenu.Submenus.Add("Copy Output to Editor", {ISE-CopyOutPutToEditor}, 'Ctrl+O')
|
PowerShellCorpus/PoshCode/count-object_1.ps1
|
count-object_1.ps1
|
#a function to count how many items there are, whether its an array, a collection, or actually just
# a single no array/non list/non collection object in which case it would be 1
function count-object ($InputObject)
{
if ($inputobject -eq $Null ) { return 0}
if ($inputobject -is [system.array]) { return $inputobject.length }
if ($inputobject -is [system.collections.ICollection] -or
$inputobject -is [system.collections.IList] -or
$inputobject -is [system.collections.IDictionary] ) { return $inputobject.count }
#strings are ienumerable, they also have a length, but i think we want to treat 1 string as one object
if ($inputobject -is [string]) { return 1 }
#-1 to show that it is enumerable, but we can't know its length, it could be infinate,
#or take a long time even to enumerate without going over
if ($inputobject -is [system.collections.IEnumerable]) { return -1 }
#otherwise just return 1
return 1
}
set-alias count count-object
count (get-process)
count (1,2,3)
count "hello"
count 3
count @{first = 1; second = 2 }
$a = new-object system.collections.arraylist
[void] $a.add(4);
[void] $a.add("yo");
count $a
|
PowerShellCorpus/PoshCode/Get-DellWarranty_2.ps1
|
Get-DellWarranty_2.ps1
|
function Get-DellWarranty {
<#
.Synopsis
Provides warranty information for one or more Dell service tags.
.Description
Queries the Dell Website for a list of service tags and returns the warranty information as a custom object.
If a service tag has multiple warranties, they are returned as multiple separate objects.
If no service tag is specified, it will attempt to retrieve and lookup the local system's service tag.
The service tag can be provided to the command in several ways:
1. Using the -servicetag parameter
2. By passing one or more Service Tags via the pipeline
3. By passing objects that have either servicetag or serialnumber defined as a property, such as win32_bios WMI objects
See examples for details.
.Parameter ServiceTag
ALIAS: serialnumber
The Dell service tag you wish to query. Example: XYZ12A3
.Example
C:\\PS> Get-DellWarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Description
-----------
If no service tags are provided, the script retrieves the local computer's serial number from WMI and queries for it.
.Example
C:\\PS> Get-DellWarranty -ServiceTag XXXX123
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Description
-----------
You can pass the service tag as a parameter, or as the first positional parameter (e.g. Get-DellWarranty XXXX123)
.Example
C:\\PS> "XXXX123","XXXX124","XXXX125" | get-dellwarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Service Tag : XXXX124
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/14/2009
End Date : 6/15/2011
Days Left : 145
Service Tag : XXXX125
Description : NBD On-Site Service
Provider : DELL
Warranty Extension Notice * : No
Start Date : 6/14/2008
End Date : 6/15/2010
Days Left : 0
Description
-----------
You can pass serial numbers via the pipeline either directly or as a variable.
.Example
C:\\PS> get-wmiobject win32_bios -computername "computer1","computer2","1.2.3.4" | get-dellwarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Service Tag : XXXX124
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/14/2009
End Date : 6/15/2011
Days Left : 145
Service Tag : XXXX125
Description : NBD On-Site Service
Provider : DELL
Warranty Extension Notice * : No
Start Date : 6/14/2008
End Date : 6/15/2010
Days Left : 0
Description
-----------
You can also pass any object that has a "serialnumber" or "servicetag" property. In this example, we query computers directly for their serial numbers,
and pass those results (which are WMI objects that have a serialnumber property) via pipeline directly to the command to obtain warranty information.
.Notes
AUTHOR: Justin Grote <jgrote NOSPAM-AT allieddigital NOSPAM-DOT net>
WARNING: Since Dell does not provide a formal API, this script works by screen-scraping the HTML from the Dell product support site.
Any future change to the layout or logic of this site will break the script or cause unpredictable results.
HISTORY: v1.0 [31 Jan 2011] - Initial Module Creatio
.Link
http://support.dell.com/support/topics/global.aspx/support/my_systems_info
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[alias("serialnumber")]
[string[]]$ServiceTag
)
PROCESS {
# If nothing was passed, retrieve the local system service tag
if ($ServiceTag -eq $null) {
write-verbose "No Service Tags provided. Using Local Computer's Service Tag"
write-verbose "START Obtaining Serial number via WMI for localhost"
$ServiceTag = (get-wmiobject win32_bios).SerialNumber
write-verbose "SUCCESS Obtaining Serial number via WMI for localhost - $ServiceTag"
}
# Detect if an array of service tags were passed via parameter and unwind them.
foreach ($strServicetag in $servicetag) {
write-verbose "START Querying Dell for Service Tag $_"
Get-DellWarrantyWorker $strServicetag
write-verbose "SUCCESS Querying Dell for Service Tag $_"
}
}
}
Function Get-DellWarrantyWorker {
Param(
[String]$serviceTag
)
#Dell Warranty URL Path
$URL = "http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=$serviceTag"
trap [System.FormatException] {
write-error -category invalidresult "The service tag $serviceTag was not found. This is either because you entered the tag incorrectly, it is not present in Dell's database, or Dell changed the format of their website causing this search to fail." -recommendedaction "Please check that you entered the service tag correctly"
return;
}
#Screenscrape the HTML for the warranty Table
$HTML = (New-Object Net.WebClient).DownloadString($URL)
If ($HTML -Match '<table[\\w\\s\\d"=%]*contract_table">.+?</table>') {
$htmltable = $Matches[0]
} else {
throw (New-Object System.FormatException)
}
$HtmlLines = $htmltable -Split "<tr" | Where-Object { $_ -Match '<td' }
$Header = ($HtmlLines[0] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*' | Where-Object { $_ -ne '' }
#Convert the warranty table fields into a powershell object
For ($i = 1; $i -lt $HtmlLines.Count; $i++) {
$Output = New-Object PSObject
$Output | Add-Member NoteProperty "Service Tag" -value $serviceTag
$Values = ($HtmlLines[$i] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*|<a.+?>'
For ($j = 1; $j -lt $Values.Count; $j++) {
$Output | Add-Member NoteProperty $Header[$j - 1] -Value $Values[$j]
}
#Minor formatting fix if days remaining on warranty is zero
if ($output.'Days Left' -match '<<0') {write-host -fore darkgreen "match!";$output.'Days Left' = 0}
return $Output
}
}
|
PowerShellCorpus/PoshCode/NTFS ACLs Folder Tree.ps1
|
NTFS ACLs Folder Tree.ps1
|
#######################################
# TITLE: listACL.ps1 #
# AUTHOR: Santiago Fernandez Mu±oz #
# #
# DESC: This script generate a HTML #
# report show all ACLs asociated with #
# a Folder tree structure starting in #
# root specified by the user #
#######################################
param ([string] $computer = 'localhost',
[string] $path = $(if ($help -eq $false) {Throw "A path is needed."}),
[int] $level = 0,
[string] $scope = 'administrator',
[switch] $help = $false,
[switch] $debug = $false
)
#region Initializations and previous checkings
#region Initialization
$allowedLevels = 10
$Stamp = get-date -uformat "%Y%m%d"
$report = "$PWD\\$computer.html"
$comparison = ""
$UNCPath = "\\\\" + $computer + "\\" + $path + "\\"
#endregion
#region Previou chekings
if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."}
if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path }
switch ($scope) {
micro {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")'
}
user {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")'
}
}
#endregion
#endregion
#region Function definitions
function drawDirectory([ref] $directory) {
$dirHTML = '
<div class="'
if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level }
$dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div>
<div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div>
<div class="container">
<div class="heACL">
<table class="info3" cellpadding="0" cellspacing="0">
<thead>
<th scope="col"><b>Owner</b></th>
<th scope="col"><b>Privileges</b></th>
</thead>
<tbody>'
foreach ($itemACL in $directory.value.ACL) {
$acls = $null
if ($itemACL.AccessToString -ne $null) {
$acls = $itemACL.AccessToString.split("`n")
}
$dirHTML += '<tr><td>' + $itemACL.Owner + '</td>
<td>
<table>
<thead>
<th>User</th>
<th>Control</th>
<th>Privilege</th>
</thead>
<tbody>'
foreach ($acl in $acls) {
$temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}")
if ($debug) {
write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp
}
if ($temp.count -eq 1) {
continue
}
if ($scope -ne 'administrator') {
if ( Invoke-Expression $comparison ) {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
} else {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
}
$dirHTML += '</tbody>
</table>
</td>
</tr>'
}
$dirHTML += '
</tbody>
</table>
</div>
</div>
</div>'
return $dirHTML
}
#endregion
#region Printing help message
if ($help) {
Write-Host @"
/ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ\\
Ę Script gather access control lists per directory Ę
\\ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ/
USAGE: ./listACL -computer <machine or IP>
-path <path>
-level <0-10>
-help:[$false]
PARAMETERS:
computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost)
path [REQUIRED] - Folder's path to query.
level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels.
0 show that there's no limit in the going down (Default: 0)
scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are:
Ę user, show important information to the user.
Ę micro, show user scope information plus important information for the IT Department.
Ę administrator, show all information.
help [OPTIONAL] - This help.
"@
exit 0
}
#endregion
if (Test-Path $report)
{
Remove-item $report
}
#To normalize I check if last character in the path is the folder separator character
if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) }
#region Header, style and javascript functions needed by the html report
@"
<html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
<title>Access Control List for $path in $computer</title>
<!-- Styles -->
<style type="text/css">
body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; }
table{ font-size:100%; table-layout:fixed; width:100%; }
td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; }
.title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; }
.he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; }
.he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; }
.he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; }
.he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; }
.he0 .expando{ font-size:100%; }
.info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; }
.disalign TD{ padding-bottom:5px; padding-right:10px; }
.info TD{ padding-right:10px; width:50%; }
.info3 TD{ padding-right:10px; width:33%; }
.info4 TD, .info4 TH{ padding-right:10px; width:25%; }
.info5 TD, .info5 TH{ padding-right:0px; width:20%; }
.info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; }
.subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; }
.subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; }
.subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; }
.subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; }
.subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; }
.explainlink{ color:#000000; text-decoration:none; cursor:pointer; }
.explainlink:hover{ color:#0000FF; text-decoration:underline; }
.spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; }
.filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; }
.container{ display:block; position:relative; }
.rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; }
.rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; }
#uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; }
#dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; }
#objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; }
#gposummary { display:block; }
#gpoinformation { display:block; }
</style>
</head>
<body>
<table class="title" cellpadding="0" cellspacing="0">
<tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr>
<tr>
<td id="dtstamp">Data obtained on: $(Get-Date)</td>
<td><div id="objshowhide" tabindex="0"></div></td>
</tr>
</table>
<div class="filler"></div>
"@ | Set-Content $report
#endregion
#region Information gathering
$colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName
$colACLs = @()
#We start going through the path pointed out by the user
foreach($file in $colFiles)
{
#To control the current level in the tree we are in it's needed to count the number of separator characters
#contained in the path. However in order to make the count correctly it's needed to delete the path
#provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be
#string used to do the level count.
#It's needed to use a REGEX object to get ALL separator character matches.
$matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count
if ($level -ne 0 -and ($matches - 1) -gt $level) {
continue
}
if ($debug) {
Write-Host $file.FullName "->" $file.Mode
}
if ($file.Mode -notlike "d*") {
continue
}
$myobj = "" | Select-Object Folder,ACL,level
$myobj.Folder = $file
$myobj.ACL = Get-Acl $file.FullName
$myobj.level = $matches - 1
$colACLs += $myobj
}
#endregion
#region Setting up the report
'<div class="gposummary">' | Add-Content $report
for ($i = 0; $i -lt $colACLs.count; $i++) {
drawDirectory ([ref] $colACLs[$i]) | Add-Content $report
}
'</div></body></html>' | Add-Content $report
#endregion
|
PowerShellCorpus/PoshCode/New-SelfRestartingTask_1.ps1
|
New-SelfRestartingTask_1.ps1
|
function New-SelfRestartingTask {
<#
.Notes
For production use you should consider investigating more specific matching in the Query clause.
There are many possibilities here: you could watch for instances of a process with specific command-line parameters, or a certain caption, etc. Or, you could match against one process, but fire off a different one when it crashes.
Have a look at the Win32_Process class to see all the properties available for matching.
.Link
Win32_Process Class http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx
.Link
__InstanceDeletionEvent http://msdn.microsoft.com/en-us/library/aa394652%28VS.85%29.aspx
.Link
ScriptCenter article on Events http://www.microsoft.com/technet/scriptcenter/topics/winpsh/events.mspx
.Synopsis
Restarts an application when it exits or crashes
.Description
Create a WMIEvent handler to watch for the termination of a specific executable and restart it.
.Parameter Application
The path to an application you want to restart when it crashes
.Parameter Parameters
Parameters to be passed to the application when we (re)start it
.Parameter Start
Automatically start the process (even if it's already running)
.Parameter Interval
Polling interval to check whether the application has exited or not
.Example
New-SelfRestartingTask notepad -Start
Description
-----------
Starts notepad right away and monitors for crash or exit and restarts it.
.Example
New-SelfRestartingTask C:\\Program` Files\\Internet` Explorer\\IExplore.exe http://HuddledMasses.org
Description
-----------
Monitors for the termination of Internet Explorer and restarts it pointed at my blog.
Note that this does NOT start IE, so it could already be running, or you should start it by hand later...
#>
param(
[Parameter(Mandatory=$true, Position=0)]
[string]$Application
,
[Parameter(Mandatory=$false)]
[double]$Interval = 5.0
,
[Parameter(Mandatory=$false)]
[switch]$Start
,
[Parameter(ValueFromRemainingArguments=$true)]
[string[]]$Parameters
)
$ExecutablePath = gcm $Application -type application | select -expand definition -first 1 | %{ $_ -replace '\\\\','\\\\' }
if($Parameters) {
$Parameters = "-ArgumentList `"$($Parameters -join '", "')`""
}
$sb = Invoke-Expression "{ Start-Process `"$ExecutablePath`" $Parameters }"
Register-WMIEvent -Action $sb -Query "Select * From __InstanceDeletionEvent Within $Interval Where TargetInstance ISA 'Win32_Process' And TargetInstance.ExecutablePath='$ExecutablePath'" | Out-Null
if($Start){
sleep -milli 500
&$sb
}
}
|
PowerShellCorpus/PoshCode/Import-Asup.ps1
|
Import-Asup.ps1
|
Function Import-ASUP
{
param(
[string]
$Path
)
Begin {
Function ConvertTo-Bool($bool) {
switch ($bool) {
"yes" {return $true}
"true" {return $true}
"enabled" {return $true}
"no" {return $False}
"false" {return $False}
"disabled" {return $False}
}
}
}
Process {
$asup = Get-Content $Path
$Storage = New-Object PSObject -Property @{SysInfo=@{};HostAdapters=@{};Disks=@();Shelves=@();SES=@{}}
$process = 0
$subprocess=0
$AggrHold = @{}
Foreach ($line in $asup) {
switch -regex ($line)
{
"====="
{
$Process = 0
}
"===== SYSCONFIG-A ====="
{
$process = 1
$subprocess = 0
}
"===== ENVIRONMENT ====="
{
$process = 2
$subprocess = 0
}
"===== SYSCONFIG-R ====="
{
$process = 3
$subprocess = 0
}
"===== STORAGE ====="
{
$process = 4
$subprocess = 0
}
}
switch ($process)
{
1
{
switch -regex ($Line)
{
"\\s+System\\sID\\:\\s(?<SystemID>\\S+)\\s\\((?<SystemName>\\S+)\\)\\;\\spartner\\sID\\:\\s(?<PartnerID>\\S+)\\s\\((?<PartnerName>\\S+)\\)"
{
$Storage.SysInfo.Add("SystemID",$Matches.SystemID)
$Storage.SysInfo.Add("SystemName",$Matches.SystemName)
$Storage.SysInfo.Add("PartnerID",$Matches.PartnerID)
$Storage.SysInfo.Add("PartnerName",$Matches.PartnerName)
}
"\\s+System\\sSerial\\sNumber\\:\\s(?<SN>\\S+)"
{
$Storage.SysInfo.Add("SerialNumber",$Matches.SN)
}
"\\s+System\\sRev\\:\\s(?<Rev>\\S+)"
{
$Storage.SysInfo.Add("Rev",$Matches.Rev)
}
"\\s+System\\sStorage\\sConfiguration\\:\\s(?<config>.+)"
{
$Storage.SysInfo.Add("StorageConfiguration",$Matches.config)
}
"System\\sACP\\sConnectivity\\:\\s(?<ACP>.+)"
{
$Storage.SysInfo.Add("ACP",$Matches.ACP)
}
"slot\\s0\\:\\sSystem\\sBoard\\s(?<board>.+)"
{
$subProcess=1
$Slot = New-Object PSObject -Property @{
"Board"=$Matches.board
"ModelName"=""
"PartNumber"=""
"Revision"=""
"SerialNumber"=""
"BIOSversion"=""
"LoaderVersion"=""
"AgentFWversion"=""
"Processors"=""
"ProcessorID"=""
"MicrocodeVersion"=""
"MemorySize"=""
"CMOSRAMStatus"=""
"Controller"=""
}
}
}
switch ($subProcess)
{
1
{
switch -regex ($Line)
{
"\\s+Model\\sName\\:\\s+(?<Model>.+)"
{
$Slot.ModelName = $Matches.Model
}
"\\s+Part\\sNumber\\:\\s+(?<Part>.+)"
{
$Slot.PartNumber = $Matches.Part
}
"\\s+Revision\\:\\s+(?<REV>.+)"
{
$Slot.Revision = $Matches.REV
}
"\\s+Serial\\sNumber\\:\\s+(?<SN>.+)"
{
$Slot.SerialNumber = $Matches.SN
}
"\\s+BIOS\\sversion\\:\\s+(?<BIOS>.+)"
{
$Slot.BIOSversion = $Matches.BIOS
}
"\\s+Loader\\sversion\\:\\s+(?<LV>.+)"
{
$Slot.LoaderVersion = $Matches.LV
}
"\\s+Agent\\sFW\\sversion\\:\\s+(?<FW>.+)"
{
$Slot.AgentFWversion = $Matches.FW
}
"\\s+Processors\\:\\s+(?<proc>.+)"
{
$Slot.Processors = $Matches.proc
}
"\\s+Processor\\sID\\:\\s+(?<procID>.+)"
{
$Slot.ProcessorID = $matches.procId
}
"\\s+Microcode\\sVersion\\:\\s+(?<microcode>.+)"
{
$Slot.MicrocodeVersion = $Matches.microcode
}
"\\s+Memory\\sSize\\:\\s+(?<memory>.+)"
{
$Slot.MemorySize = $Matches.memory
}
"\\s+CMOS\\sRAM\\sStatus\\:\\s+(?<CMOS>.+)"
{
$Slot.CMOSRAMStatus = $Matches.CMOS
}
"\\s+Controller\\:\\s+(?<Controller>.+)"
{
$Slot.Controller = $Matches.Controller
$Storage.SysInfo.Add("SystemBoard",$slot)
$subprocess = 0
}
}
}
}
}
2
{
switch -regex ($Line)
{
"^Channel\\:\\s+(?<Channel>\\d\\w)\\sShelf\\:\\s+(?<Shelf>\\d)\\sShelf\\sSerial\\sNumber:\\s+(?<ShelfSN>.+)"
{
$Shelf = New-Object PSObject -Property @{
"Channel"=$Matches.Channel
"Shelf"=$Matches.Shelf
"SerialNumber"=$Matches.ShelfSN
"ShelfVendor"=""
"ShelfModel"=""
"ShelfRevisionLevel"=""
"ModelName"=""
"ModuleASerialNumber"=""
"ModuleAFirmware"=""
"ModuleBSerialNumber"=""
"ModuleBFirmware"=""
"LocalAcessID"=""
}
}
"^Shelf\\sproduct\\sid\\:\\s(?<model>.+)"
{
$Shelf.ModelName = $Matches.model
}
"Module\\sA\\sSerial\\sNumber\\:\\s(?<SN>\\S+)\\s+Firmware\\srev\\:\\s(?<Rev>\\S+)"
{
$Shelf.ModuleASerialNumber = $Matches.SN
$Shelf.ModuleAFirmware = $Matches.Rev
}
"Module\\sB\\sSerial\\sNumber\\:\\s(?<SN>\\S+)\\s+Firmware\\srev\\:\\s(?<Rev>\\S+)"
{
$Shelf.ModuleBSerialNumber = $Matches.SN
$Shelf.ModuleBFirmware = $Matches.Rev
if (!$Storage.SES.Contains($Shelf.Channel))
{
$Storage.SES.Add($Shelf.Channel,@{})
}
($Storage.SES[$Shelf.Channel]).add($shelf.Shelf, $shelf)
}
"\\s+Channel\\:\\s+(?<channel>\\d\\w)"
{
$_channel = $matches.channel
}
"\\s+shelf\\:\\s+(?<channel>\\d)$"
{
$_Shelf = $matches.channel
$subprocess = 1
}
}
switch ($subProcess)
{
1
{
switch -regex ($Line)
{
"local\\saccess\\:\\s(?<Port>\\d\\w\\.\\d{2,3})$"
{
$Storage.SES[$_channel][$_Shelf].LocalAcessID = $Matches.Port
}
"^\\s+Module\\stype\\:\\s(?<Module>\\S+)\\;"
{
$Storage.SES[$_channel][$_Shelf].ModelName = $Matches.Module
}
"SES\\sConfiguration"
{
$subProcess = 2
}
}
}
2
{
switch -regex ($Line)
{
"\\s+vendor\\sidentification\\=(?<Vendor>.+)"
{
$Storage.SES[$_channel][$_Shelf].ShelfVendor=$Matches.Vendor
}
"\\s+product\\sidentification\\=(?<ShelfModel>.+)"
{
$Storage.SES[$_channel][$_Shelf].ShelfModel = $Matches.ShelfModel
}
"\\s+product\\srevision\\slevel\\=(?<ShelfRevisionLevel>.+)"
{
$Storage.SES[$_channel][$_Shelf].ShelfRevisionLevel = $Matches.ShelfRevisionLevel
$subprocess = 0
}
}
}
}
}
3
{
Switch -regex ($line)
{
"^Aggregate\\s(?<aggr>\\S+)\\s"
{
$subprocess =1
$aggr=$matches.aggr
}
"^Spare\\sdisks$|^Partner\\sdisks$"
{
$subprocess =1
$aggr=$null
}
}
switch -regex ($line)
{
"^\\s{6}(?<R>\\S+)\\s+(?<D>\\S+)(\\s+\\S+){5}\\s+(?<T>\\S+)\\s+\\S+\\s+(?<UMB>\\d+)\\/(?<UB>\\d+)\\s+(?<PMB>\\d+)\\/(?<PB>\\d+)"
{
$aggrHold.Add($Matches.D, @{
Aggregate=$aggr
RaidType=$Matches.R
DiskType=$Matches.T
UsedMB=$Matches.UMB
UsedBlocks=$Matches.UB
PhysicalMB=$Matches.PMB
PhysicalBlocks=$Matches.PB
})
}
"^(?<R>\\S+)\\s+(?<D>\\S+)(\\s+\\S+){5}\\s+(?<T>\\S+)\\s+\\S+\\s+(?<UMB>\\d+)\\/(?<UB>\\d+)\\s+(?<PMB>\\d+)\\/(?<PB>\\d+)"
{
$aggrHold.Add($Matches.D, @{
Aggregate=""
RaidType=$Matches.R
DiskType=$Matches.T
UsedMB=$Matches.UMB
UsedBlocks=$Matches.UB
PhysicalMB=$Matches.PMB
PhysicalBlocks=$Matches.PB
})
}
}
}
4
{
switch -regex ($line)
{
"^Slot\\:\\s+(?<slot>\\d\\w)$"
{
$subprocess = 1
$Adapter = New-Object PSObject -Property @{
Name=""
Description=""
FirmwareRev=""
FCNodeName=""
FCPacketSize=""
LinkDataRate=""
SRAMParity=$false
ExternalGBIC=$false
State=""
InUse=$false
Redundant=$false
}
}
"^Shelf\\sname\\:\\s+(?<Shelf>.+)"
{
$subprocess = 2
$shelf = New-Object PSObject -Property @{
Name=""
Channel=""
Module=""
ShelfID=0
ShelfUID=""
ShelfSN=""
TermSwitch=""
ShelfState=""
ModuleState=""
SerialNumber=""
ShelfVendor=""
ShelfModel=""
ShelfRevisionLevel=""
ModelName=""
ModuleASerialNumber=""
ModuleAFirmware=""
ModuleBSerialNumber=""
ModuleBFirmware=""
LocalAcessID=""
}
}
"^Disk\\:\\s+(?<Shelf>.+)"
{
$subprocess = 3
$disk = New-Object PSObject -Property @{
"Name"=""
"shelf"=0
"Bay"=0
"RaidType"=""
"Aggregate"=""
"DiskType"=""
"SN"=""
"Vendor"=""
"Model"=""
"Firmware"=""
"RPM"=0
"WWN"=""
"UID"=""
"DownRev"=""
"PrimaryPort"=""
"Secondaryname"=""
"SecondaryPort"=""
"PowerOnHours"=0
"UsedMB"=""
"UsedBlocks"=""
"PhysicalMB"=""
"PhysicalBlocks"=""
"BlocksRead"=[int64]0
"BlocksWritten"=[int64]0
"TimeInterval"=""
"GlistCount"=0
"ScrubLastDone"=""
"ScrubCount"=0
"LipCount"=0
"DynamicallyQualified"=$false
"PowerCycleCount"=0
"PowerCycleError"=0
"CurrentOwner"=""
"HomeOwner"=""
"ReservationOwner"=""
}
}
"SHARED\\sSTORAGE\\sHOSTNAME\\s+SYSTEM\\sID"
{
$subprocess = 4
}
}
switch ($subprocess)
{
1
{
switch -regex ($line)
{
"^Slot\\:\\s+(?<name>\\d\\w)$"
{
$Adapter.name = $matches.name
break
}
"^Description\\:\\s+(?<Description>.+)"
{
$Adapter.Description = $matches.Description;
break
}
"^Firmware\\sRev\\:\\s+(?<FirmwareRev>.+)"
{
$Adapter.FirmwareRev = $matches.FirmwareRev
break
}
"^FC\\sNode\\sName\\:\\s+(?<FCNodeName>.+)"
{
$Adapter.FCNodeName = $matches.FCNodeName
break
}
"^FC\\sPacket\\sSize\\:\\s+(?<FCPacketSize>.+)"
{
$Adapter.FCPacketSize = $matches.FCPacketSize
break
}
"^Link\\sData\\sRate\\:\\s+(?<LinkDataRate>.+)"
{
$Adapter.LinkDataRate = $matches.LinkDataRate
break
}
"^SRAM\\sParity\\:\\s+(?<SRAMParity>.+)"
{
$Adapter.SRAMParity = ConvertTo-Bool $matches.SRAMParity
break
}
"^External\\sGBIC\\:\\s+(?<ExternalGBIC>.+)"
{
$Adapter.ExternalGBIC = ConvertTo-Bool $matches.ExternalGBIC
break
}
"^State\\:\\s+(?<State>.+)"
{
$Adapter.State = $matches.State
break
}
"^In\\sUse\\:\\s+(?<InUse>.+)"
{
$Adapter.InUse = ConvertTo-Bool $matches.InUse
break
}
"^Redundant\\:\\s+(?<Redundant>.+)"
{
$Adapter.Redundant = ConvertTo-Bool $matches.Redundant
break
}
Default
{
if ($Adapter)
{
$Storage.HostAdapters.Add($Adapter.Name,$Adapter)
}
}
}
}
2
{
switch -regex ($line)
{
"^Shelf\\sname\\:\\s+(?<name>.+)"
{
$Shelf.Name = $matches.name
break
}
"^Channel\\:\\s+(?<Channel>.+)"
{
$Shelf.Channel = $matches.Channel
break
}
"^Module\\:\\s+(?<Module>.+)"
{
$Shelf.Module = $matches.Module
break
}
"Shelf\\sid\\:\\s+(?<ShelfID>.+)"
{
$Shelf.ShelfID = $matches.ShelfID
break
}
"Shelf\\sUID\\:\\s+(?<ShelfUID>.+)"
{
$shelf.ShelfUID = $Matches.ShelfUID
break
}
"Shelf\\sS\\/N\\:\\s+(?<ShelfSN>.+)"
{
$shelf.ShelfSN = $Matches.ShelfSN
break
}
"Term\\sswitch\\:\\s+(?<TermSwitch>.+)"
{
$Shelf.TermSwitch = $Matches.TermSwitch
break
}
"Shelf\\sstate\\:\\s+(?<ShelfState>.+)"
{
$shelf.ShelfState = $Matches.ShelfState
break
}
"Module\\sstate\\:\\s+(?<ModuleState>.+)"
{
$shelf.ModuleState = $matches.ModuleState
$Storage.shelves += $shelf
break
}
}
}
3
{
switch -regex ($line)
{
"^Disk\\:\\s+(?<Name>.+)"
{
$Disk.name = $matches.name
break
}
"^Shelf\\:\\s+(?<shelf>.+)"
{
$Disk.shelf = $matches.shelf
break
}
"^Bay\\:\\s+(?<Bay>.+)"
{
$Disk.Bay = $matches.Bay
break
}
"^Serial\\:\\s+(?<SN>.+)"
{
$Disk.SN = $matches.SN
break
}
"^Vendor\\:\\s+(?<Vendor>.+)"
{
$Disk.Vendor = $matches.Vendor
break
}
"^Model\\:\\s+(?<Model>.+)"
{
$Disk.Model = $matches.Model
break
}
"^Rev\\:\\s+(?<Firmware>.+)"
{
$Disk.Firmware = $matches.Firmware
break
}
"^RPM\\:\\s+(?<RPM>.+)"
{
$Disk.RPM = $matches.RPM
break
}
"^WWN\\:\\s+(?<WWN>.+)"
{
$Disk.WWN = $matches.WWN
break
}
"^UID\\:\\s+(?<UID>.+)"
{
$Disk.UID = $matches.UID
break
}
"^Downrev\\:\\s+(?<DownRev>.+)"
{
$Disk.DownRev = $matches.DownRev
break
}
"^Pri\\sPort\\:\\s+(?<PrimaryPort>.+)"
{
$Disk.PrimaryPort = $matches.PrimaryPort
break
}
"^Sec\\sName\\:\\s+(?<Secondaryname>.+)"
{
$Disk.Secondaryname = $matches.Secondaryname
break
}
"^Sec Port\\:\\s+(?<SecondaryPort>.+)"
{
$Disk.SecondaryPort = $matches.SecondaryPort
break
}
"^Power-on Hours\\:\\s+(?<PowerOnHours>.+)"
{
$Disk.PowerOnHours = $matches.PowerOnHours
break
}
"^Blocks read\\:\\s+(?<BlocksRead>.+)"
{
$Disk.BlocksRead = $matches.BlocksRead
break
}
"^Blocks written\\:\\s+(?<BlocksWritten>.+)"
{
$Disk.BlocksWritten = $matches.BlocksWritten
break
}
"^Time interval\\:\\s+(?<TimeInterval>.+)"
{
$Disk.TimeInterval = $matches.TimeInterval
break
}
"^Glist count\\:\\s+(?<GlistCount>.+)"
{
$Disk.GlistCount = $matches.GlistCount
break
}
"^Scrub last done\\:\\s+(?<ScrubLastDone>.+)"
{
$Disk.ScrubLastDone = $matches.ScrubLastDone
break
}
"^Scrub count\\:\\s+(?<ScrubCount>.+)"
{
$Disk.ScrubCount = $matches.ScrubCount
break
}
"^LIP count\\:\\s+(?<LipCount>.+)"
{
$Disk.LipCount = $matches.LipCount
break
}
"^Dynamically qualified\\:\\s+(?<DynamicallyQualified>.+)"
{
$Disk.DynamicallyQualified = $matches.DynamicallyQualified
break
}
"^Power\\scycle\\scount\\:\\s+(?<PowerCycleCount>.+)"
{
$Disk.PowerCycleCount = $matches.PowerCycleCount
break
}
"^Power\\scycle\\son\\serror\\:\\s+(?<PowerCycleError>.+)"
{
$Disk.PowerCycleError = $matches.PowerCycleError
break
}
"^Current owner\\:\\s+(?<CurrentOwner>.+)"
{
$Disk.CurrentOwner = $matches.CurrentOwner
break
}
"^Home owner\\:\\s+(?<HomeOwner>.+)"
{
$Disk.HomeOwner = $matches.HomeOwner
break
}
"^Reservation owner\\:\\s+(?<ReservationOwner>.+)"
{
$Disk.ReservationOwner = $matches.ReservationOwner
break
}
Default
{
if ($Disk)
{
#merge this data with what we scrapped from sysconfig-r
$Disk.RaidType = $aggrHold[$Disk.Name].RaidType
$Disk.Aggregate = $aggrHold[$Disk.Name].Aggregate
$Disk.DiskType = $aggrHold[$Disk.Name].DiskType
$Disk.UsedMB = $aggrHold[$Disk.Name].UsedMB
$Disk.UsedBlocks = $aggrHold[$Disk.Name].UsedBlocks
$Disk.PhysicalMB = $aggrHold[$Disk.Name].PhysicalMB
$Disk.PhysicalBlocks = $aggrHold[$Disk.Name].PhysicalBlocks
$Storage.Disks +=$Disk
}
}
}
}
}
}
}
}
Write-output $Storage
}
}
|
PowerShellCorpus/PoshCode/AnalizeScript.ps1
|
AnalizeScript.ps1
|
<#
.SYNOPSIS
Analyzes script and gives starting lines & columns of script components
.DESCRIPTION
AnalizeScript opens a dialog box for user selection; checks that input is
a powershell script; parses and agrigates the script components into the
following tokens:
Unknown(s)
Command(s)
CommandParameter(s)
CommandArgument(s)
Variable(s)
Member(s)
LoopLabel(s)
Attribute(s)
Keyword(s)
LineContinuation(s)
.LINK
None
.NOTES
Name: AnalizeScript.ps1
Author: Paul A. Drinnon
Date Created: 03/24/2011
Date Revised: - (New Release)
Version: 1.0
History: 1.0
This script can be altered to output other "Types" of tokenized content
Below is a complete list
Types
______________________________________
Name Example / Value
Comment
__________________ ___________ _____
Unknown 0
Command 1
CommandParameter 2
CommandArgument 3
Number 4
String 5
Variable -$! 6
Member 7
LoopLabel 8
Attribute 9
Type 10
Operator (-+*/=|...) 11
GroupStart ({ 12
GroupEnd )} 13
Keyword 14
Comment 15
StatementSeparator 16
NewLine 17
LineContinuation 18
Position 19
requires -Version 2.0
** Licensed under a Creative Commons Attribution 3.0 License **
#>
Add-Type -TypeDefinition @"
using System;
using System.Windows.Forms;
public class WindowWrapper : IWin32Window {
private IntPtr _hWnd;
public WindowWrapper(IntPtr handle) {
_hWnd = handle;
}
public IntPtr Handle {
get { return _hWnd; }
}
}
"@ -ReferencedAssemblies "System.Windows.Forms.dll"
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle
$owner = New-Object WindowWrapper -ArgumentList $handle
function Select-File
{
param (
[String]$Title = "Enter a Windows PowerShell script",
[String]$InitialDirectory = $home,
[String]$Filter = "All Files(*.*)|*.*"
)
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.Filter = $filter
$dialog.InitialDirectory = $initialDirectory
$dialog.ShowHelp = $true
$dialog.Title = $title
$result = $dialog.ShowDialog($owner)
if ($result -eq "OK") {
return $dialog.FileName
}
else {
Write-Error "Operation cancelled by user."
}
}
function TokenName-Count ($file, $str)
{
$content = gc $file
$a = [System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) |
? { $_.Type -eq $str } | Measure-Object | select Count
$su = $str.ToUpper() + "S"
"$su`t`t$a"
}
function CustomTable ($file, $str)
{
$content = gc $file
[System.Management.Automation.PsParser]::Tokenize($content, [ref] $null) |
? { $_.Type -eq $str } | ft content, startline, startcolumn -auto
}
$selectPSfile = ""
while (-!($selectPSfile -match ".ps1|.psm1|.psd1|.ps1xml")) {
$selectPSfile = Select-File
}
$TokenNames = `
"Unknown", `
"Command", `
"CommandParameter", `
"CommandArgument", `
"Variable", `
"Member", `
"LoopLabel",`
"Attribute",`
"Keyword", `
"LineContinuation"
$date = (Get-Date).ToShortDateString()
"`n$selectPSfile`t`t`t`t$date`n"
$TokenNames | foreach {
[string]$s = $_
TokenName-Count $selectPSfile $s
CustomTable $selectPSfile $s
}
|
PowerShellCorpus/PoshCode/Get-NestedGroups_2.ps1
|
Get-NestedGroups_2.ps1
|
<#
.SYNOPSIS
Enumerate all AD group memberships of an account (including nested membership).
.DESCRIPTION
This script will return all the AD groups an account is member of.
.PARAMETER UserName
The username whose group memberships to find.
.EXAMPLE
.\\Get-NestedGroups.ps1 'johndoe'
Name DistinguishedName
---- -----------------
Domain Users CN=Domain Users,CN=Users,DC=contoso,DC=com
Finance CN=Finance,OU=Department,OU=Groups,DC=contos...
.NOTES
ScriptName : Get-NestedGroups
Created By : Gilbert van Griensven
Date Coded : 06/17/2012
The script iterates through all nested groups and skips circular nested groups.
.LINK
#>
Param
(
[Parameter(Mandatory=$true)]$UserName
)
Begin
{
Function LoadADModule {
If (!(Get-Module ActiveDirectory)) {
If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) {
Import-Module ActiveDirectory
Return $True
} Else {
Return $False
}
} Else {
Return $True
}
}
Function GetNestedGroups ($strGroupDN) {
$currentGroupmemberships = (Get-ADGroup $strGroupDN -Properties MemberOf | Select-Object MemberOf).MemberOf
foreach ($groupDN in $currentGroupmemberships) {
if (!(($Script:UserGroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains $groupDN)) {
$arrProps = @{
Name = (Get-ADGroup $groupDN).Name
DistinguishedName = $groupDN
}
$Script:UserGroupMembership += (New-Object psobject -Property $arrProps)
GetNestedGroups $groupDN
}
}
}
Function FindGroupMembership ($strUsername) {
$Script:UserGroupMembership = @()
$arrProps = @{
Name = "Domain Users"
DistinguishedName = (Get-ADGroup "Domain Users").DistinguishedName
}
$Script:UserGroupMembership += (New-Object psobject -Property $arrProps)
GetNestedGroups (Get-ADGroup "Domain Users").DistinguishedName
$directMembershipGroups = (Get-ADUser $strUsername -Properties MemberOf | Select-Object MemberOf).MemberOf
foreach ($groupDN in $directMembershipGroups) {
$arrProps = @{
Name = (Get-ADGroup $groupDN).Name
DistinguishedName = $groupDN
}
$Script:UserGroupMembership += (New-Object psobject -Property $arrProps)
GetNestedGroups $groupDN
}
}
}
Process
{
If (!(LoadADModule)) {
Write-Host "Could not load module ActiveDirectory!"
Return
}
If ($UserName) {
FindGroupMembership $UserName
Return $Script:UserGroupMembership
}
}
End
{
Remove-Module ActiveDirectory -ErrorAction SilentlyContinue
}
|
PowerShellCorpus/PoshCode/ConvertTo-Hex_11.ps1
|
ConvertTo-Hex_11.ps1
|
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx
param ( [string]$SidString )
# Create SID .NET object using SID string provided
$sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring
# Create a byte array of the proper length
$sidBytes = New-Object byte[] $sid.BinaryLength
#Convert to bytes
$sid.GetBinaryForm( $sidBytes, 0 )
# Iterate through bytes, converting each to the hexidecimal equivalent
$hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") }
# Join the hex array into a single string for output
$hexArr -join ''
|
PowerShellCorpus/PoshCode/Search-NetworkService.ps1
|
Search-NetworkService.ps1
|
#Define PreReqs
$timeStamp = Get-Date -UFormat "%m-%d-%Y-%H-%M"
$systemVars = Gwmi Win32_ComputerSystem -Comp "."
$userName = $systemVars.UserName
$compName = $systemVars.Name
#User Vars
$serviceName = "Spooler" # Spooler will check the Print Spooler <<< Change To Suit Your needs
$errorLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_Errors.txt" #Service Not Installed
$fullLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_All.txt" #Services Needed To Be Started / Running
#Write Some Info To Logs
"Check Service: " + $serviceName > $errorLog; Get-Date >> $errorLog; $compName >> $errorLog; $userName >> $errorLog; "_____________" >> $errorLog; "" >> $errorLog;
"Check Service: " + $serviceName > $fullLog; Get-Date >> $fullLog; $compName >> $fullLog; $userName >> $fullLog; "_____________" >> $fullLog; "" >> $fullLog;
# Define Functions
function Get-NetView {
switch -regex (NET.EXE VIEW) { "^\\\\\\\\(?<Name>\\S+)\\s+" {$matches.Name}}
}
function Process-PCs ($currentName) {
$olStatus = Ping-Address $currentName
If ($olStatus -eq "True") {
Check-Service $currentName
}
#Else {Write-Host "PC Not Online"}
Write-Host " "
}
function Ping-Address ($pingAddress) {
$ping = new-object system.net.networkinformation.ping
$pingReply = $ping.send($pingAddress)
If ($pingReply.status -eq "Success") {
Return "True"
}
Else {
Return "False"
}
}
function Check-Service ($currentName) {
$currentService = Get-Service -ComputerName $currentName -Name $serviceName -ErrorAction SilentlyContinue
If ($currentService.Status -eq $Null){
$currentServiceStatus = "Not Installed"
$currentName >> $errorLog
}
ElseIf ($currentService.Status -eq "Running"){
$currentServiceStatus = "Running"
}
ElseIf ($currentService.Status -eq "Stopped"){
$currentServiceStatus = "Stopped"
}
Else {
$currentServiceStatus = "Unknown"
}
Write-Host $serviceName " is " $currentServiceStatus " on " $currentName
$serviceName + " was " + $currentServiceStatus + " on " + $currentName >> $fullLog
If ($currentService.Status -eq "Stopped"){
Write-Host "Service was stoppped, trying to start it . . ."
$currentService | Start-Service -ErrorAction SilentlyContinue
If ($currentService.Status -eq "Running"){
" Service Successfully Started" >> $fullLog
}
Else {
" Service Could Not Be Started" >> $fullLog
}
}
}
#Run Everything
cls
Get-NetView | %{Process-PCs $_}
# Test a single PC, Uncomment line below change pc name and comment line above
# Process-PCs "localhost" | %{Process-PCs $_}
|
PowerShellCorpus/PoshCode/New-Script 2.ps1
|
New-Script 2.ps1
|
## New-Script function
## Creates a new script from the most recent commands in history
##################################################################################################
## Example Usage:
## New-Script ScriptName 4
## creates a script from the most recent four commands
## New-Script Clipboard -id 10,11,12,14
## sends the the specified commands from the history to the clipboard
## Notepad (New-Script ScriptName 20)
## sends the most recent twenty commands to the script, and then opens the script in notepad
##################################################################################################
## As a tip, I use a prompt function something like this to get the ID into the prompt:
##
## function prompt {
## return "`[{0}]: " -f ((get-history -count 1).Id + 1)
## }
##################################################################################################
## Revision History
## 1.0 - initial release
## 1.1 - fix bug with specifying multiple IDs
## 2.0 - use the current folder as the default instead of throwing an exception
## - prompt to overwrite if not -Force
##################################################################################################
#function New-Script {
param(
[string]$script=(Read-Host "A name for your script"),
[int]$count=1,
[int[]]$id=@((Get-History -count 1| Select Id).Id),
[switch]$Force
)
# if there's only one id, then the count counts, otherwise we just use the ids
if($id.Count -eq 1) { 1..($count-1)|%{ $id += $id[-1]-1 } }
# Get the CommandLines from the history items...
$commands = Get-History -id $id | &{process{ $_.CommandLine }}
if($script -eq "clipboard") {
if( @(Get-PSSnapin -Name "pscx").Count ) {
$commands | out-clipboard
} elseif(@(gcm clip.exe).Count) {
$commands | clip
}
} else {
$folder = Split-Path $script
if(!$folder) {
# default to putting it in my "Windows PowerShell\\scripts" folder which I have in my path...
$folder = Join-Path (Split-Path $Profile) "Scripts"
}
if(!(Test-Path $folder)) {
# if that fails, put it in the current path (on the file system)
$folder = Get-Location -PSProvider "FileSystem"
}
# add the ps1 extension if it's not already there ...
$file = Join-Path $folder (Split-Path $script -leaf)
if(!(([IO.FileInfo]$file).Extension)) {
$file = "$file.ps1"
}
# write an error message if the file already exists, unless -Force
if((Test-Path $file) -and (!$Force)) {
Write-Error "The file already exists, do you want to overwrite?"
}
# and confirm before setting the content if the file already exists, unless -Force
$commands | set-content $file -Confirm:((Test-Path $file) -and (!$Force))
Get-Item $file
}
#}
|
PowerShellCorpus/PoshCode/Start-rdp_4.ps1
|
Start-rdp_4.ps1
|
\nFunction Global:Start-RDP {\n<#\n .Synopsis\n This Cmdlet starts a microsoft terminal session against the hostname provided.\n \n it is possible to collect credential information from a PSCredential file saved on the disk\n \n .Description \n This cmdlet starts a Microsoft terminal sesion against the hostname provided, by creating a rdp \n file and calling the mstsc with the rdp file as data. it will be possible to save credentials into \n the file in a semi secure way.\n \n Thsi script uses the pscredential type and the import-/export pscredential script from halr9000. These \n scripts makes i possible to save encrypted username/password data as a file. These data are only decryptable \n by the user encrypting it.\n \n When using the -LeaveRDPFile option is used then it is only a HASH of the password that is left in the file. \n ! This hash key can be decrypted by brute force attacks.\n \n .Parameter Hostname\n \n this is the hostname/ip of the server you want to connect to\n \n .Parameter Fullscreen\n \n Use this paramenter when wanting to connect rdp in fullscreen mode\n \n .Parameter Credentials\n \n Credentials can be both a path to a file \n a pscredential type object\n \n .Parameter Console\n \n use this parameter when wanting to connect to the admin/console session.\n \n .Parameter Path\n \n use this path as temp/permanent place to store the .rdp files.\n \n .Parameter LeaveRDPFile\n \n use this parameter when you want to leave the rdp files after connect. \n \n ! Remember this might be a security risk.\n \n .Example\n \n Start-Rdp -Hostname Server1.local.domain -credentials (get-credential) \n \n This will prompt for username and password and subsequent connect to the specified server\n \n .Example\n Export-pscredential\n start-rdp -hostname Server1.local.domain -credentials credentials.enc.xml \n This will prompt for username and password save the credentials to a file and subsequent connect \n to the specified server using the user/password data from the file\n \n .Example\n Export-pscredential\n Get-content serverlist.txt | start-rdp -credentials credentials.enc.xml \n This will prompt for username and password save the credentials to a file and subsequent connect \n to the servers listed in the serverlist.txt file, using the user/password data from the file\n .Requirements \n Import-pscredential cmdlet http://poshcode.org/501\n \n .Link\n http://doitsmarter.blogspot.com/\n http://poshcode.org/4067\n \n .Notes\n ====================================================================\n Author(s): \n Allan Christiansen <christiansen.allan@Gmail.com>, http://doitsmarter.blogspot.com/\n \n Credits/Special thanks:\n Hal Rottenberg <hal@halr9000.com> for the Import/export-pscredential cmdlets. \n http://poshcode.org/501\n \n Date: 2013-03-13\n Revision: 1.0\n Output includes the following data\n None\n \n ====================================================================\n Disclaimer: This script is written as best effort and provides no \n warranty expressed or implied. Please contact the author(s) if you \n have questions about this script before running or modifying\n ==================================================================== \n#>\n Param(\n [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$True,HelpMessage="Enter the hostname to connect to")]\n $Hostname="",\n [Parameter(ValueFromPipeline=$false,Position=1,Mandatory=$false,HelpMessage="Select to start in fullscreen mode")]\n [Switch]$FullScreen,\n [Parameter(ValueFromPipeline=$false,Position=2,Mandatory=$false,HelpMessage="select to connect in admin mode")]\n [Switch]$Console,\n [Parameter(ValueFromPipeline=$false,Position=3,Mandatory=$false,HelpMessage="Enter path to Credential store .xml or input pscredential")]\n $Credentials,\n [Parameter(ValueFromPipeline=$false,Position=4,Mandatory=$false,HelpMessage="Path for directory to store rdp files")]\n $Path = "$Home\\Documents\\RDP",\n [Parameter(ValueFromPipeline=$false,Position=5,Mandatory=$false,HelpMessage="Remove .RDP file after start")]\n [Switch]$leaveRDPFile\n )\nBegin { \n If (!(test-path $Path -erroraction silentlycontinue)) {\n mkdir $Path | Out-Null\n }\n IF (($Credentials.gettype()).type -eq "PSCredential") {\n $cred = $Credentials\n } Else {\n If (test-path $Credentials -erroraction silentlycontinue) {\n $cred = Import-pscredential $Credentials\n } else {\n # Not Pscredential type object -\n # not a valid file path\n # lets ask the user\n $cred = get-credentials\n }\n $Encrypted = $cred.password | ConvertFrom-SecureString\n }\n \n #test screenmode and set to correct value\n $ScreenMode=1\n If ($Fullscreen) {\n $ScreenMode = 2\n }\n}\nProcess {\n #run through all hosts pased to script\n Foreach ($Hosts in $hostname) {\n IF ($Hosts -ne "") { \n $Filename = "$Path\\$Hosts.rdp"\n $RDPFileData = \n“screen mode id:i:$ScreenMode\ndesktopwidth:i:1024\ndesktopheight:i:768\nsession bpp:i:16\nwinposstr:s:0,1,0,0,800,600\nfull address:s:$Hosts\ncompression:i:1\nkeyboardhook:i:2\naudiomode:i:0\nredirectdrives:i:1\nredirectprinters:i:0\nredirectcomports:i:0\nredirectsmartcards:i:1\ndisplayconnectionbar:i:1\nautoreconnection enabled:i:1\nusername:s:$($cred.username)\nalternate shell:s:\nshell working directory:s:\ndisable wallpaper:i:1\ndisable full window drag:i:1\ndisable menu anims:i:1\ndisable themes:i:0\ndisable cursor setting:i:0\nbitmapcachepersistenable:i:1\npassword 51:b:$encrypted\n”\n If (!(test-path $Filename -erroraction silentlycontinue)) {\n Set-Content -path $Filename -Value $RDPFileData -Force -erroraction silentlycontinue\n } \n $param = ""\n If ($Console) {\n $Param += "/admin"\n } \n #\n IF ($Param -ne "") {\n Mstsc $Filename $Param\n } Else {\n Mstsc $Filename\n }\n \n #Remove the .rdp files if requested\n If (!$LeaveRDPFile) {\n Sleep 1\n Remove-item $filename -force\n }\n }\n }\n}\nEnd {\n # No cleanup needed\n}\n}\n New-Alias -name Global:RDP -Value Start-Rdp -Force\nIf ((get-command import-pscredential -erroraction silentlycontinue) -eq $False) {\n write-error "Import-/export-pscredential cmdlets from http://poshcode.org/473 are required for this cmdlet to have 100% functionality"\n Exit 1\n}
|
PowerShellCorpus/PoshCode/Convert-StringSID_2.ps1
|
Convert-StringSID_2.ps1
|
function Convert-StringSID {
<#
.Synopsis
Takes a SID string and outputs a Win32_SID object.
.Parameter sidstring
The SID in SDDL format. Example: S-1-5-21-39260824-743453154-142223018-195717
.Description
Takes a SID string and outputs a Win32_SID object.
Note: it also adds an extra property, base64_sid, the base64 representation
of the binary SID.
.Example
PS> Convert-StringSID 'S-1-5-21-39260824-743453154-142223018-195717'
.Example
PS> $list_of_sids |
Convert-StringSID |
%{Write-Output "$($_.ReferenceDomainName)\\$($_.AccountName)"}
MYDOMAIN\\somename
MYDOMAIN\\anotheraccount
.Notes
NAME: Convert-StringSID
AUTHOR: tojo2000
#Requires -Version 2.0
#>
param([Parameter(Position = 0,
Mandatory = $true,
ValueFromPipeline = $true]
[string]$sidstring)
BEGIN {}
PROCESS{
[wmi]$obj = 'Win32_SID.SID="{0}"' -f $sidstring
$encoded = [System.Convert]::ToBase64String($obj.BinaryRepresentation)
$obj |
Add-Member -MemberType NoteProperty -Name base64_sid -Value $encoded
Write-Output $obj
}
END{}
}
|
PowerShellCorpus/PoshCode/Set-Computername_4.ps1
|
Set-Computername_4.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/Get-HtmlHelp_3.ps1
|
Get-HtmlHelp_3.ps1
|
Hello,
I wanted to reach out to inquire about the possibility of advertising on your blog in the form of sponsored guest posts.
Either I can have content written or you can write content that is relevant to your audience and helps to promote our client's service. We then pay for that post and the opportunity to have exposure to your readers.
If this is something you can do, please email me.
Thank you,
-Brandon Murphy
brandon@submitdigital.com
www.SubmitDigital.com
http://huddledmasses.org
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.