full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Get-DelegateType.ps1
|
Get-DelegateType.ps1
|
Set-StrictMode -Version 2
function Get-DelegateType {
<#
.Synopsis
Declares a non-generic delegate type for the method signature provided.
.Description
The Get-DelegateType function is the equivalent to declaring a delegate type in C#
with the 'delegate' keyword. PowerShell has no such equivalent, hence this
function.
This function was created in order to provide GetDelegateForFunctionPointer a
non-generic delegate.
.Parameter Parameters
Specifies the parameters of the desired method signature.
.Parameter ReturnType
Specifies the return type of the desired method signature.
.Example
PS> Get-DelegateType -Parameters @([String]) -ReturnType ([IntPtr])
Description
-----------
Returns a delegate type whose method signature contains a string as its parameter
and an IntPtr as a return type. What Get-DelegateType returns is the equivalent to
the following C# declaration:
public IntPtr MyDelegateType(String str);
.Example
PS> Get-DelegateType @([String], [Int])
Description
-----------
Returns a delegate type whose method signature contains a string and an int as its
parameter and an a Void return type.
.Outputs
System.MulticastDelegate
Get-DelegateType returns a System.MulticastDelegate derived delegate based upon the
provided method signature.
.Link
http://www.exploit-monday.com/
http://blogs.msdn.com/b/joelpob/archive/2004/02/15/73239.aspx
#>
Param (
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $Parameters,
[Parameter(Position = 1)] [Type] $ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
return $TypeBuilder.CreateType()
}
|
PowerShellCorpus/PoshCode/Resizer of pictures_3.ps1
|
Resizer of pictures_3.ps1
|
[reflection.assembly]::LoadWithPartialName("System.Drawing")
$SizeLimit=1280 # required size of picture's long side
$logfile="resizelog.txt" # log file for errors
$toresize=$args[0] # list of directories to find and resize images. can be empty
@@ if ([string]$toresize -eq “”) { # if script startup parameter empty, use some default values
$toresize=@("n:\\path1", "n:\\path2\\", "s:\\path3")
}
echo $toresize # visual control
#Write-Host -NoNewLine ("Press any key.") # Optional "Press any key"
#$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#Write-Host ""
$error.clear()
# first part. find and resize jpgs
Get-ChildItem -recurse $toresize -include *.jpg | foreach {
$OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open found jpg
if ($error.count -ne 0) { # error handling
$error | out-file $logfile -append -encoding default
$error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default
echo $_>>$logfile
$error.clear()
}
$LongSide=$OldBitmap.Width # locating long side of picture
if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height }
if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process jpg
if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculate dimensions of picture resize to
$newH=$SizeLimit
$newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height)
} else {
$newW=$SizeLimit
$newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width)
}
$NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap
$g=[System.Drawing.Graphics]::FromImage($NewBitmap)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic # use high quality resize algorythm
$g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # resize our picture
$name=$_.DirectoryName+"\\"+$_.name+".new" # generating name for new picture
$NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save newly created resized jpg
$NewBitmap.Dispose() # cleaning up our mess
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if resized jpg has greater size than original
Write-host -NoNewLine "+" # draw "+"
$n.delete() # and delete it
} else { # if resized jpg is smaller than original
if ($n.Exists -and $_.Exists) {
$name=$_.FullName
$_.Delete() # delete original
$n.MoveTo($name) # rename new file to original name (replace old file with new)
echo ($Name + " " + $LongSide) # write its name for visual control
}
}
} else { # if long side is smaller than limit, draw dot for visual
Write-host -NoNewLine "."
$OldBitmap.Dispose()
}
}
#second part. process other than jpgs bitmaps
Get-ChildItem -recurse $toresize -include *.bmp, *.tif, *.gif | foreach {
$OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open picture
if ($error.count -ne 0) { # handle errors if any
$error | out-file $logfile -append -encoding default
$error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default
$error.clear()
}
$LongSide=$OldBitmap.Width # find picture's long side
if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height }
if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process picture
if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculating new dimensions
$newH=$SizeLimit
$newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height)
} else {
$newW=$SizeLimit
$newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width)
}
$NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap
$g=[System.Drawing.Graphics]::FromImage($NewBitmap)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # copy resized image to it
$name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" # generating new name, jpg extension
$NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save new file
$NewBitmap.Dispose()
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if new file is longer than original,
$n.delete() # delete new file
Write-host -NoNewLine "+" # and draw "+" for beauty
} else { # if new file is shorter than original (as we expect)
echo ($Name + " " + $LongSide) # draw its name
$_.Delete() # delete oroginal
}
} else { # if long side is less than our limit, try to recompress it to jpg
$name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg"
$OldBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg))
$OldBitmap.Dispose()
$n=get-childitem $name
if ($n.length -ge $_.length) { # if new jpg is greater than original
$n.delete() # delete new jpg
Write-host -NoNewLine "-" # draw "-" for visual control
} else {
echo ($Name + " " + $LongSide) # draw new file name
$_.Delete() # delete original
}
}
}
|
PowerShellCorpus/PoshCode/Blow up ESXi.ps1
|
Blow up ESXi.ps1
|
foreach ($i in 10..1) {
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value "This host will self destruct in $i"
}
Start-Sleep 10
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value ""
|
PowerShellCorpus/PoshCode/Write-Log_4.ps1
|
Write-Log_4.ps1
|
function Write-Log {
#region Parameters
[cmdletbinding()]
Param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
[string] $Message,
[Parameter()] [ValidateSet(ōErrorö, ōWarnö, ōInfoö)]
[string] $Level = ōInfoö,
[Parameter()]
[Switch] $NoConsoleOut,
[Parameter()]
[String] $ConsoleForeground = 'White',
[Parameter()] [ValidateRange(1,30)]
[Int16] $Indent = 0,
[Parameter()]
[IO.FileInfo] $Path = ö$env:temp\\PowerShellLog.txtö,
[Parameter()]
[Switch] $Clobber,
[Parameter()]
[String] $EventLogName,
[Parameter()]
[String] $EventSource,
[Parameter()]
[Int32] $EventID = 1,
[Parameter()]
[String] $LogEncoding = "ASCII"
)
#endregion
Begin {}
Process {
try {
$msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format ōyyyy-MM-dd HH:mm:ssö), $Level.ToUpper(), $Message
if ($NoConsoleOut -eq $false) {
switch ($Level) {
'Error' { Write-Error $Message }
'Warn' { Write-Warning $Message }
'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground}
}
}
if (-not $Path.Exists) {
New-Item -Path $Path.FullName -ItemType File -Force
}
if ($Clobber) {
$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Force
} else {
$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Append
}
if ($EventLogName) {
if (-not $EventSource) {
$EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name
}
if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) {
[Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName)
}
$log = New-Object System.Diagnostics.EventLog
$log.set_log($EventLogName)
$log.set_source($EventSource)
switch ($Level) {
ōErrorö { $log.WriteEntry($Message, 'Error', $EventID) }
ōWarnö { $log.WriteEntry($Message, 'Warning', $EventID) }
ōInfoö { $log.WriteEntry($Message, 'Information', $EventID) }
}
}
} catch {
throw ōFailed to create log entry in: æ$PathÆ. The error was: æ$_Æ.ö
}
}
End {}
<#
.SYNOPSIS
Writes logging information to screen and log file simultaneously.
.DESCRIPTION
Writes logging information to screen and log file simultaneously. Supports multiple log levels.
.PARAMETER Message
The message to be logged.
.PARAMETER Level
The type of message to be logged.
.PARAMETER NoConsoleOut
Specifies to not display the message to the console.
.PARAMETER ConsoleForeground
Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
.PARAMETER Indent
The number of spaces to indent the line in the log file.
.PARAMETER Path
The log file path.
.PARAMETER Clobber
Existing log file is deleted when this is specified.
.PARAMETER EventLogName
The name of the system event log, e.g. 'Application'.
.PARAMETER EventSource
The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.PARAMETER EventID
The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.PARAMETER LogEncoding
The text encoding for the log file. Default is ASCII.
.EXAMPLE
PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application'
.EXAMPLE
PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script"
.INPUTS
System.String
.OUTPUTS
No output.
.NOTES
Revision History:
2011-03-10 : Andy Arismendi - Created.
2011-07-23 : Will Steele - Updated.
2011-07-23 : Andy Arismendi
- Added missing comma in param block.
- Added support for creating missing directories in log file path.
#>
}
|
PowerShellCorpus/PoshCode/Get-PSExecutionPolicy.ps1
|
Get-PSExecutionPolicy.ps1
|
#Notes
#1. x86 properites will be empty for x86 machines as this property only pertains x64 machines which have both x64 and x86 shells.
#2. If policy registry key is not present then restricted is the effective setting
param($computerName=$env:computerName)
$reg = Get-WmiObject -List -Namespace root\\default -ComputerName $ComputerName | Where-Object {$_.Name -eq "StdRegProv"}
new-object psobject -property @{
ComputerName=$ComputerName;
Path=($reg.GetStringValue(2147483650,"SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell","Path")).sValue;
Policy=($reg.GetStringValue(2147483650,"SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell","ExecutionPolicy")).sValue;
x86Path=($reg.GetStringValue(2147483650,"SOFTWARE\\Wow6432Node\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell","Path")).sValue
x86Policy=($reg.GetStringValue(2147483650,"SOFTWARE\\Wow6432Node\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell","ExecutionPolicy")).sValue
}
|
PowerShellCorpus/PoshCode/Get-NextPrime_1.ps1
|
Get-NextPrime_1.ps1
|
$primes = 2,3,5 #,7,11,13,17,19,23
$primeIndex = 0
function Get-NextPrime {
[CmdletBinding(DefaultParameterSetName="KnownPrime")]
param(
[Parameter(Position=0,ParameterSetName="KnownPrime")]
$knownPrime = $(if($primeIndex -lt $primes.Count){ $primes[$primeIndex] } else { $primes[-1] } )
,
[Parameter(ParameterSetName="FromTwo")]
[switch]$reset
)
## Hack: to allow you to start over at 2, even though we cache the values,
## we keep a primeIndex, and just reset it to -1
if($reset) {
$global:primeIndex = -1
} elseif($PSBoundParameters.ContainsKey("KnownPrime")){
## Hack: allow you to specify any number to start at:
$global:primeIndex = [array]::BinarySearch($primes,$knownPrime)
if($primeIndex -lt 0) {
Write-Verbose "We don't have a prime like $knownPrime"
$primeIndex = (-1 * $primeIndex) -1
} else {
Write-Verbose "Looking for the first prime LARGER than $($primes[$primeIndex])"
$global:primeIndex += 1
}
}
Write-Verbose "Looking for a prime gt $knownPrime at index $primeIndex"
## If we have a cached "next" value, return that
if($primeIndex -lt $primes.Count) {
$primes[$primeIndex]
$global:primeIndex += 1
return
}
## Otherwise, calculate the next largest prime by ...
## checking every number greater than the current largest prime
$p = $primes[-1]
while($p = $p+2){
## To see if they're divisible by any known prime
if(!$(
foreach($i in $primes){ if($p % $i -eq 0) { $i } }
)){
## If they're not, then they're a new prime. Cache them, and return
$global:primes += $p
$global:primeIndex += 1
if($p -gt $knownPrime) {
return $p
}
}
}
}
|
PowerShellCorpus/PoshCode/Search cmdlet help.ps1
|
Search cmdlet help.ps1
|
function Search-Help($term) {
Get-Command | Where { Get-Help -full -ea SilentlyContinue $_ |
Out-String | Select-String $term }
}
|
PowerShellCorpus/PoshCode/OpsMgr.psd1.ps1
|
OpsMgr.psd1.ps1
|
<#
#Run the following code to create OpsMgr module
#To Use run import-module OpsMgr; Start-OperationsManagerClientShell -ManagementServerName: "" -PersistConnection: $true -Interactive: $true;
if (-not (test-path $home\\Documents\\WindowsPowerShell\\Modules\\OpsMgr))
{new-item $home\\Documents\\WindowsPowerShell\\Modules\\OpsMgr -type directory}
Set-Location "C:\\Program Files\\System Center Operations Manager 2007"
Copy-Item "Microsoft.EnterpriseManagement.OperationsManager.ClientShell.dll","Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Format.ps1xml",`
"Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Types.ps1xml","Microsoft.EnterpriseManagement.OperationsManager.ClientShell.dll-help.xml",`
"Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Functions.ps1","Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Startup.ps1",`
"Microsoft.EnterpriseManagement.OperationsManager.ClientShell.NonInteractiveStartup.ps1" `
-destination $home\\Documents\\WindowsPowerShell\\Modules\\OpsMgr
Set-Location "C:\\Program Files\\System Center Operations Manager 2007\\SDK Binaries"
Copy-Item "Microsoft.EnterpriseManagement.OperationsManager.dll","Microsoft.EnterpriseManagement.OperationsManager.Common.dll" -destination $home\\Documents\\WindowsPowerShell\\Modules\\OpsMgr
#>
@{
ModuleVersion="0.0.0.1"
Description="A Wrapper for Microsoft's Operations Manager Shell "
Author="Chad Miller"
Copyright="© 2010, Chad Miller, released under the Ms-PL"
CompanyName="http://sev17.com"
CLRVersion="2.0"
FormatsToProcess="Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Format.ps1xml"
NestedModules="Microsoft.EnterpriseManagement.OperationsManager.ClientShell"
RequiredAssemblies="Microsoft.EnterpriseManagement.OperationsManager.dll","Microsoft.EnterpriseManagement.OperationsManager.Common.dll"
TypesToProcess="Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Types.ps1xml"
ScriptsToProcess="Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Functions.ps1"
}
|
PowerShellCorpus/PoshCode/Delete AD Users.ps1
|
Delete AD Users.ps1
|
function Delete-ADUser
{
Param($userName = $(throw 'Enter a username to delete'))
$searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"","(&(objectcategory=user)(sAMAccountName=$userName))")
$user = $searcher.findone().GetDirectoryEntry()
$user.psbase.DeleteTree()
}
$NumDays = 90
$LogDir = ".\\Removed-User-Accounts.log"
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findone()
Write-Output `n`n"----------------------------------------" "ACCOUNTS OLDER THAN "$NumDays" DAYS" "PROCESSED ON:" $currentDate "----------------------------------------" `
| Out-File $LogDir -append
if ($users.Count -eq 0)
{
Write-Output " No account needs to be removed." | Out-File $LogDir -append
}
else
{
foreach ($user in $users)
{
# Read the user properties
[string]$adsPath = $user.Properties.adspath
[string]$displayName = $user.Properties.displayname
[string]$samAccountName = $user.Properties.samaccountname
[string]$lastLogonInterval = $user.Properties.lastlogontimestamp
# Delete the user
Delete-ADUser $samAccountName
# Convert the date and time to the local time zone
$lastLogon = [System.DateTime]::FromFileTime($lastLogonInterval)
Write-Output " Removed user " $displayName" | Username: "$samAccountName" | Last Logon: "$lastLogon"`n" `
| Out-File $LogDir -append
}
}
|
PowerShellCorpus/PoshCode/PowerShell CMatrix.ps1
|
PowerShell CMatrix.ps1
|
Set-StrictMode -off
#
# Module: PowerShell Console ScreenSaver Version 0.1
# Author: Oisin Grehan ( http://www.nivot.org )
#
# A PowerShell CMatrix-style screen saver for true-console hosts.
#
# This will not work in Micrisoft's ISE, Quest's PowerGUI or other graphical hosts.
# It should work fine in PowerShell+ from Idera which is a true console.
#
if ($host.ui.rawui.windowsize -eq $null) {
write-warning "Sorry, I only work in a true console host like powershell.exe."
throw
}
#
# Console Utility Functions
#
function New-Size {
param([int]$width, [int]$height)
new-object System.Management.Automation.Host.Size $width,$height
}
function New-Rectangle {
param(
[int]$left,
[int]$top,
[int]$right,
[int]$bottom
)
$rect = new-object System.Management.Automation.Host.Rectangle
$rect.left= $left
$rect.top = $top
$rect.right =$right
$rect.bottom = $bottom
$rect
}
function New-Coordinate {
param([int]$x, [int]$y)
new-object System.Management.Automation.Host.Coordinates $x, $y
}
function Get-BufferCell {
param([int]$x, [int]$y)
$rect = new-rectangle $x $y $x $y
[System.Management.Automation.Host.buffercell[,]]$cells = $host.ui.RawUI.GetBufferContents($rect)
$cells[0,0]
}
function Set-BufferCell {
[outputtype([System.Management.Automation.Host.buffercell])]
param(
[int]$x,
[int]$y,
[System.Management.Automation.Host.buffercell]$cell
)
$rect = new-rectangle $x $y $x $y
# return previous
get-buffercell $x $y
# use "fill" overload with single cell rect
$host.ui.rawui.SetBufferContents($rect, $cell)
}
function New-BufferCell {
param(
[string]$Character,
[consolecolor]$ForeGroundColor = $(get-buffercell 0 0).foregroundcolor,
[consolecolor]$BackGroundColor = $(get-buffercell 0 0).backgroundcolor,
[System.Management.Automation.Host.BufferCellType]$BufferCellType = "Complete"
)
$cell = new-object System.Management.Automation.Host.BufferCell
$cell.Character = $Character
$cell.ForegroundColor = $foregroundcolor
$cell.BackgroundColor = $backgroundcolor
$cell.BufferCellType = $buffercelltype
$cell
}
function log {
param($message)
[diagnostics.debug]::WriteLine($message, "PS ScreenSaver")
}
#
# Main entry point for starting the animation
#
function Start-CMatrix {
param(
[int]$maxcolumns = 8,
[int]$frameWait = 100
)
$script:winsize = $host.ui.rawui.WindowSize
$script:columns = @{} # key: xpos; value; column
$script:framenum = 0
$prevbg = $host.ui.rawui.BackgroundColor
$host.ui.rawui.BackgroundColor = "black"
cls
$done = $false
while (-not $done) {
Write-FrameBuffer -maxcolumns $maxcolumns
Show-FrameBuffer
sleep -milli $frameWait
$done = $host.ui.rawui.KeyAvailable
}
$host.ui.rawui.BackgroundColor = $prevbg
cls
}
# TODO: actually write into buffercell[,] framebuffer
function Write-FrameBuffer {
param($maxColumns)
# do we need a new column?
if ($columns.count -lt $maxcolumns) {
# incur staggering of columns with get-random
# by only adding a new one 50% of the time
if ((get-random -min 0 -max 10) -lt 5) {
# search for a column not current animating
do {
$x = get-random -min 0 -max ($winsize.width - 1)
} while ($columns.containskey($x))
$columns.add($x, (new-column $x))
}
}
$script:framenum++
}
# TODO: setbuffercontent with buffercell[,] framebuffer
function Show-FrameBuffer {
param($frame)
$completed=@()
# loop through each active column and animate a single step/frame
foreach ($entry in $columns.getenumerator()) {
$column = $entry.value
# if column has finished animating, add to the "remove" pile
if (-not $column.step()) {
$completed += $entry.key
}
}
# cannot remove from collection while enumerating, so do it here
foreach ($key in $completed) {
$columns.remove($key)
}
}
function New-Column {
param($x)
# return a new module that represents the column of letters and its state
# we also pass in a reference to the main screensaver module to be able to
# access our console framebuffer functions.
new-module -ascustomobject -name "col_$x" -script {
param(
[int]$startx,
[PSModuleInfo]$parentModule
)
$script:xpos = $startx
$script:ylimit = $host.ui.rawui.WindowSize.Height
[int]$script:head = 1
[int]$script:fade = 0
[int]$script:fadelen = [math]::Abs($ylimit / 3)
$script:fadelen += (get-random -min 0 -max $fadelen)
function Step {
# reached the bottom yet?
if ($head -lt $ylimit) {
& $parentModule Set-BufferCell $xpos $head (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore white) > $null
& $parentModule Set-BufferCell $xpos ($head - 1) (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore green) > $null
$script:head++
}
# time to start rendering the darker green "tail?"
if ($head -gt $fadelen) {
& $parentModule Set-BufferCell $xpos $fade (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore darkgreen) > $null
$script:fade++
}
# are we done animating?
if ($fade -lt $ylimit) {
return $true
}
$false
}
Export-ModuleMember -function Step
} -args $x, $executioncontext.sessionstate.module
}
function Start-ScreenSaver {
# feel free to tweak maxcolumns and frame delay
# currently 8 columns with 50ms wait
Start-CMatrix -max 8 -frame 50
}
function Register-Timer {
# prevent prompt from reregistering if explicit disable
if ($_ssdisabled) {
return
}
if (-not (Test-Path variable:global:_ssjob)) {
# register our counter job
$global:_ssjob = Register-ObjectEvent $_sstimer elapsed -action {
$global:_sscount++;
$global:_sssrcid = $event.sourceidentifier
# hit timeout yet?
if ($_sscount -eq $_sstimeout) {
# disable this event (prevent choppiness)
Unregister-Event -sourceidentifier $_sssrcid
Remove-Variable _ssjob -scope Global
sleep -seconds 1
# start ss
Start-ScreenSaver
}
}
}
}
function Enable-ScreenSaver {
if (-not $_ssdisabled) {
write-warning "Screensaver is not disabled."
return
}
$global:_ssdisabled = $false
}
function Disable-ScreenSaver {
if ((Test-Path variable:global:_ssjob)) {
$global:_ssdisabled = $true
Unregister-Event -SourceIdentifier $_sssrcid
Remove-Variable _ssjob -Scope global
} else {
write-warning "Screen saver is not enabled."
}
}
function Get-ScreenSaverTimeout {
new-timespan -seconds $global:_sstimeout
}
function Set-ScreenSaverTimeout {
[cmdletbinding(defaultparametersetname="int")]
param(
[parameter(position=0, mandatory=$true, parametersetname="int")]
[int]$Seconds,
[parameter(position=0, mandatory=$true, parametersetname="timespan")]
[Timespan]$Timespan
)
if ($pscmdlet.parametersetname -eq "int") {
$timespan = new-timespan -seconds $Seconds
}
if ($timespan.totalseconds -lt 1) {
throw "Timeout must be greater than 0 seconds."
}
$global:_sstimeout = $timespan.totalseconds
}
#
# Eventing / Timer Hooks, clean up and Prompt injection
#
# timeout
[int]$global:_sstimeout = 180 # default 3 minutes
# tick count
[int]$global:_sscount = 0
# modify current prompt function to reset ticks counter to 0 and
# to reregister timer, while saving for later on module onload
$self = $ExecutionContext.SessionState.Module
$function:global:prompt = $self.NewBoundScriptBlock(
[scriptblock]::create(
("{0}`n`$global:_sscount = 0`nRegister-Timer" `
-f ($global:_ssprompt = gc function:prompt))))
# configure our timer
$global:_sstimer = new-object system.timers.timer
$_sstimer.Interval = 1000 # tick once a second
$_sstimer.AutoReset = $true
$_sstimer.start()
# we start out disabled - use enable-screensaver
$global:_ssdisabled = $true
# arrange clean up on module remove
$ExecutionContext.SessionState.Module.OnRemove = {
# restore prompt
$function:global:prompt = [scriptblock]::Create($_ssprompt)
# kill off eventing subscriber, if one exists
if ($_sssrcid) {
Unregister-Event -SourceIdentifier $_sssrcid
}
# clean up timer
$_sstimer.Dispose()
# clear out globals
remove-variable _ss* -scope global
}
Export-ModuleMember -function Start-ScreenSaver, Get-ScreenSaverTimeout, `
Set-ScreenSaverTimeout, Enable-ScreenSaver, Disable-ScreenSaver
|
PowerShellCorpus/PoshCode/where-property_1.ps1
|
where-property_1.ps1
|
function where-property([string] $PropertyName,[string]$SubProperty , $is,$isnot,$contains,$in,$SelectProperty)
{
process {
$useprop = $SelectProperty
Function _outobj {
if ($useprop )
{
, $_.$useprop
}
else
{
, $_
}
}
if ($is)
{
if ($_.$Propertyname -eq $is) { _outobj}
}
elseif ($isnot)
{
if ($_.$Propertyname -ne $is) { _outobj}
}
elseif($contains)
{
if ($subproperty)
{
foreach ($prop in $_.$propertyname )
{
if ($prop)
{
$foundmatch = $false
$subpropertyvalue = $prop.$subproperty
if ($subpropertyvalue -contains $contains ) { $foundmatch = $true }
if ($foundmatch) { _outobj }
}
}
}
else
{
if ($_.$Propertyname -contains $contains) { _outobj}
}
}
elseif($in)
{
if ($subproperty)
{
foreach ($prop in $_.$propertyname )
{
if ($prop)
{
$foundmatch = $false
#{ "RpcSs","AppID" -contains $_.servicesdependedon.name }
if ($in -contains $prop.$subproperty )
{
$foundmatch = $true
}
if ($foundmatch) { _outobj }
}
}
}
else
{
if ($in -contains $_.$Propertyname ) { _outobj}
}
#if ($in -contains $_.$Propertyname) { _outobj}
}
}
}
set-alias ?. where-property
set-alias and. where-property
set-alias and-property where-property
#get-processes with a specific name
gps | where-property processname -is svchost
#get-processes all but a specific name
gps | where-property processname -isnot svchost
#get-processes with the processname in a specific list
gps | where-property processname -in iexplore,chrome
#get verbs in a specific group
get-verb | where-property group -in common
#get-commands that have a specific named parameter
get-command | where-property parameters -subproperty keys -contains Begin
#and using an a lias to this for the and since it seems more HUMAN to say where X and Y, rather than Where x where y
get-command | where-property parameters -subproperty keys -contains Name | and-property commandtype -is alias
#get displayname of services that depend other services appid,rpcss
get-service | where-property ServicesDependedOn -SubProperty name -in AppID,rpcss | and-property status -is running -SelectProperty Displayname
|
PowerShellCorpus/PoshCode/Trim Working Set for PID_1.ps1
|
Trim Working Set for PID_1.ps1
|
## Trim Working set
Function TrimWorkingSet {
param([int] $procid)
<#.NOTES
AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com)
WEBSITE: http://tekout.wordpress.com
CREATED: 9/20/2012
This starts the Evil Monkey series of scripts.
.DESCRIPTION
MSDN - http://msdn.microsoft.com/en-us/library/windows/desktop/ms686234(v=vs.85).aspx
Trim's working set to minimum levels (-1, -1)
You can give a max / min values by modifying the signature.
.WARNING
***********READ CAREFULLY***********
!!!! Do not use in production environment before thoroughly testing and understanding the script. !!!!
Do not use this to Trim Working Set for SQL Databases, there will be data-loss.
Do not use this to Trim Working Set database for msExchange store.exe
I havent tried this on IIS w3wp.exe processes.
More NEGATIVE effects here - http://support.microsoft.com/kb/2001745
I have primarily used this to trim browser WorkingSet data. Tested on firefox / iexplore / chrome. It works with no tab crashing.
Trimming Working Set data, doesnt mean that browser Working Set values wont climb to their previous numbers.
I have seen some IE windows go back to similar working set numbers.
However, this script is really useful for a stuck browser and freezing screeing situations.
***********READ CAREFULLY***********
.EXAMPLE
TrimWorkingSet(1920)
#>
$sig = @"
[DllImport("kernel32.dll")]
public static extern bool SetProcessWorkingSetSize( IntPtr proc, int min, int max );
"@
$apptotrim = (get-process -Id $procid).Handle
Add-Type -MemberDefinition $sig -Namespace User32 -Name Util -UsingNamespace System.Text -PassThru
[User32.Util]::SetProcessWorkingSetSize($apptotrim,-1,-1)
}
TrimWorkingSet(5960)
|
PowerShellCorpus/PoshCode/Live@Edu password reset.ps1
|
Live@Edu password reset.ps1
|
#----------------------------------------------
#region Application Functions
#----------------------------------------------
function OnApplicationLoad {
#Note: This function runs before the form is created
#Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
#Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
#Important: Form controls cannot be accessed in this function
#TODO: Add snapins and custom code to validate the application load
return $true #return true for success or false for failure
}
function OnApplicationExit {
#Note: This function runs after the form is closed
#TODO: Add custom code to clean up and unload snapins when the application exits
# Disconnection from Live@Edu
Get-PSSession | ? { $_.ConfigurationName -match 'Exchange' } | Remove-PSSession
$script:ExitCode = 0 #Set the exit code for the Packager
}
#endregion
#----------------------------------------------
# Generated Form Function
#----------------------------------------------
function GenerateForm {
#----------------------------------------------
#region Import Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
#endregion
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object System.Windows.Forms.Form
$lblLiveEDUStatus = New-Object System.Windows.Forms.Label
$grpPassword = New-Object System.Windows.Forms.GroupBox
$lblConfirmPass = New-Object System.Windows.Forms.Label
$lblNewPass = New-Object System.Windows.Forms.Label
$btnCancel = New-Object System.Windows.Forms.Button
$btnOK = New-Object System.Windows.Forms.Button
$txtConfirmPass = New-Object System.Windows.Forms.TextBox
$txtNewPass = New-Object System.Windows.Forms.TextBox
$gbxSearch = New-Object System.Windows.Forms.GroupBox
$lblName = New-Object System.Windows.Forms.Label
$txtName = New-Object System.Windows.Forms.TextBox
$btnSearch = New-Object System.Windows.Forms.Button
$lstResults = New-Object System.Windows.Forms.ListView
$StudentName = New-Object System.Windows.Forms.ColumnHeader
$StudentEmail = New-Object System.Windows.Forms.ColumnHeader
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$FormEvent_Load={
#TODO: Initialize Form Controls here
function Connect-EDUService
{
param
(
$username,
$password
)
$success = $false
try
{
[string] $RemoteURL = "https://ps.outlook.com/powershell"
if ($username -eq $null -and $password -eq $null)
{
$livecred = get-credential
}
else
{
$password = ConvertTo-SecureString $password -AsPlainText -Force
$livecred = New-Object System.Management.Automation.PSCredential $username, $password
}
$eduSession = New-PSSession -ConfigurationName microsoft.exchange `
-ConnectionUri $RemoteURL `
-Credential $liveCred `
-Authentication Basic -AllowRedirection -ErrorAction Stop
Import-PSSession $eduSession -prefix "EDU" | Out-Null
$success = $true
}
catch
{
# Nothing to do really just don't want to asplode the script
}
$success
}
# Attempt connection to Live@EDU servers
$eduConnected = Connect-EDUService
if ($eduConnected)
{
$lblLiveEDUStatus.BackColor = [Drawing.Color]::Green
$lblLiveEDUStatus.ForeColor = [Drawing.Color]::White
$lblLiveEDUStatus.Text = "Successfully connected to Live@EDU Servers"
}
else
{
$lblLiveEDUStatus.BackColor = [Drawing.Color]::Red
$lblLiveEDUStatus.ForeColor = [Drawing.Color]::White
$lblLiveEDUStatus.Text = "Live@EDU Connection FAILED!"
}
}
$handler_btnOK_Click={
#TODO: Place custom script here
# If the passwords match and we have students selected
$passwordsMatch = $false
if ($txtNewPass.Text -ceq $txtConfirmPass.Text)
{
if ($txtNewPass.Text.Length -ge 6)
{
$newPass = ConvertTo-SecureString $txtNewPass.Text -AsPlainText -Force
$passwordsMatch = $true
}
else
{
# ERROR MESSAGE BOX
$message = "Error: New password must be 6 characters or longer."
$caption = "Error"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
[System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
}
else
{
# ERROR MESSAGE BOX
$message = "Error: Passwords do not match."
$caption = "Error"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
[System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
if ($lstResults.SelectedItems.Count -gt 0 -and $passwordsMatch)
{
# Reset the password for each student
foreach ($i in $lstResults.SelectedItems)
{
$error.clear()
Set-EDUMailbox -Identity $i.subitems[1].text -Password $newPass
if ($error[0] -ne $null)
{
#Display message box with error details
$message = $error[0].Exception.Message
$caption = "Error"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
[System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
else
{
#Display message box indicating success
$message = "Password for {0} successfully changed" -f $i.Text
$caption = "Success"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Information
[System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
}
}
elseif ($passwordsMatch)
{
# SELECT A STUDENT MESSAGE BOX
$message = "Error: You must have a student selected."
$caption = "Error"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
[System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
}
$handler_btnCancel_Click={
#TODO: Place custom script here
$form1.Close()
}
$handler_btnSearch_Click={
# Init search array
$searchResults = @()
# Do Ambiguous name resolution search
Get-EduMailBox -anr $txtName.Text |
ForEach-Object { $searchResults += $_ }
# Update the student boxes
$lstResults.BeginUpdate()
$lstResults.SelectedItems.Clear()
$lstResults.Items.Clear()
if ($searchResults.count -gt 0)
{
foreach ($r in $searchResults)
{
$lvi = New-Object System.Windows.Forms.ListViewItem
$lvi.Text = $r.displayname
$liveID = $r.windowsLiveId
foreach ($si in $liveID)
{
if ($si -ne $null)
{
$lvi.SubItems.Add($si)
}
else
{
$lvi.SubItems.Add("")
}
}
$lstResults.Items.Add($lvi)
}
}
$lstResults.EndUpdate()
}
$handler_lstResults_SelectedIndexChanged={
#TODO: Place custom script here
if ($lstResults.SelectedItems.Count -gt 0)
{
$grpPassword.Enabled = $true
}
else
{
$grpPassword.Enabled = $false
}
}
#----------------------------------------------
# Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
#
# form1
#
$form1.Controls.Add($lblLiveEDUStatus)
$form1.Controls.Add($grpPassword)
$form1.Controls.Add($gbxSearch)
$form1.Controls.Add($lstResults)
$form1.ClientSize = New-Object System.Drawing.Size(659,339)
$form1.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$form1.Name = "form1"
$form1.Text = "Student Email Password Reset"
$form1.add_Load($FormEvent_Load)
#
# lblLiveEDUStatus
#
$lblLiveEDUStatus.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left
$lblLiveEDUStatus.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lblLiveEDUStatus.Location = New-Object System.Drawing.Point(0,317)
$lblLiveEDUStatus.Name = "lblLiveEDUStatus"
$lblLiveEDUStatus.Size = New-Object System.Drawing.Size(331,21)
$lblLiveEDUStatus.TabIndex = 14
$lblLiveEDUStatus.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
#
# grpPassword
#
$grpPassword.Controls.Add($lblConfirmPass)
$grpPassword.Controls.Add($lblNewPass)
$grpPassword.Controls.Add($btnCancel)
$grpPassword.Controls.Add($btnOK)
$grpPassword.Controls.Add($txtConfirmPass)
$grpPassword.Controls.Add($txtNewPass)
$grpPassword.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$grpPassword.Enabled = $False
$grpPassword.Location = New-Object System.Drawing.Point(338,13)
$grpPassword.Name = "grpPassword"
$grpPassword.Size = New-Object System.Drawing.Size(309,99)
$grpPassword.TabIndex = 12
$grpPassword.TabStop = $False
$grpPassword.Text = "Change Password"
#
# lblConfirmPass
#
$lblConfirmPass.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lblConfirmPass.Location = New-Object System.Drawing.Point(6,41)
$lblConfirmPass.Name = "lblConfirmPass"
$lblConfirmPass.Size = New-Object System.Drawing.Size(86,23)
$lblConfirmPass.TabIndex = 13
$lblConfirmPass.Text = "Confirm: "
$lblConfirmPass.TextAlign = [System.Drawing.ContentAlignment]::MiddleRight
#
# lblNewPass
#
$lblNewPass.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lblNewPass.Location = New-Object System.Drawing.Point(6,15)
$lblNewPass.Name = "lblNewPass"
$lblNewPass.Size = New-Object System.Drawing.Size(86,23)
$lblNewPass.TabIndex = 12
$lblNewPass.Text = "New Password: "
$lblNewPass.TextAlign = [System.Drawing.ContentAlignment]::MiddleRight
#
# btnCancel
#
$btnCancel.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btnCancel.Location = New-Object System.Drawing.Point(227,67)
$btnCancel.Name = "btnCancel"
$btnCancel.Size = New-Object System.Drawing.Size(75,23)
$btnCancel.TabIndex = 6
$btnCancel.Text = "Cancel"
$btnCancel.UseVisualStyleBackColor = $True
$btnCancel.add_Click($handler_btnCancel_Click)
#
# btnOK
#
$btnOK.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btnOK.Location = New-Object System.Drawing.Point(146,67)
$btnOK.Name = "btnOK"
$btnOK.Size = New-Object System.Drawing.Size(75,23)
$btnOK.TabIndex = 5
$btnOK.Text = "OK"
$btnOK.UseVisualStyleBackColor = $True
$btnOK.add_Click($handler_btnOK_Click)
#
# txtConfirmPass
#
$txtConfirmPass.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$txtConfirmPass.Location = New-Object System.Drawing.Point(98,41)
$txtConfirmPass.Name = "txtConfirmPass"
$txtConfirmPass.Size = New-Object System.Drawing.Size(204,20)
$txtConfirmPass.TabIndex = 4
#
# txtNewPass
#
$txtNewPass.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$txtNewPass.Location = New-Object System.Drawing.Point(98,15)
$txtNewPass.Name = "txtNewPass"
$txtNewPass.Size = New-Object System.Drawing.Size(204,20)
$txtNewPass.TabIndex = 3
#
# gbxSearch
#
$gbxSearch.Controls.Add($lblName)
$gbxSearch.Controls.Add($txtName)
$gbxSearch.Controls.Add($btnSearch)
$gbxSearch.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$gbxSearch.Location = New-Object System.Drawing.Point(13,12)
$gbxSearch.Name = "gbxSearch"
$gbxSearch.Size = New-Object System.Drawing.Size(318,100)
$gbxSearch.TabIndex = 11
$gbxSearch.TabStop = $False
$gbxSearch.Text = "Student Search"
#
# lblName
#
$lblName.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lblName.Location = New-Object System.Drawing.Point(6,16)
$lblName.Name = "lblName"
$lblName.Size = New-Object System.Drawing.Size(88,23)
$lblName.TabIndex = 4
$lblName.Text = "Student Name: "
$lblName.TextAlign = [System.Drawing.ContentAlignment]::MiddleRight
#
# txtName
#
$txtName.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$txtName.Location = New-Object System.Drawing.Point(100,16)
$txtName.Name = "txtName"
$txtName.Size = New-Object System.Drawing.Size(212,20)
$txtName.TabIndex = 0
#
# btnSearch
#
$btnSearch.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$btnSearch.Location = New-Object System.Drawing.Point(237,42)
$btnSearch.Name = "btnSearch"
$btnSearch.Size = New-Object System.Drawing.Size(75,23)
$btnSearch.TabIndex = 1
$btnSearch.Text = "Search"
$btnSearch.UseVisualStyleBackColor = $True
$btnSearch.add_Click($handler_btnSearch_Click)
#
# lstResults
#
$lstResults.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right
$System_Windows_Forms_ColumnHeader_11 = New-Object System.Windows.Forms.ColumnHeader
$System_Windows_Forms_ColumnHeader_11.Text = "Student Name"
$System_Windows_Forms_ColumnHeader_11.Width = 157
[void]$lstResults.Columns.Add($System_Windows_Forms_ColumnHeader_11)
$System_Windows_Forms_ColumnHeader_12 = New-Object System.Windows.Forms.ColumnHeader
$System_Windows_Forms_ColumnHeader_12.Text = "Email Address"
$System_Windows_Forms_ColumnHeader_12.Width = 218
[void]$lstResults.Columns.Add($System_Windows_Forms_ColumnHeader_12)
$lstResults.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$lstResults.FullRowSelect = $True
$lstResults.GridLines = $True
$lstResults.HeaderStyle = [System.Windows.Forms.ColumnHeaderStyle]::Nonclickable
$lstResults.HideSelection = $False
$lstResults.Location = New-Object System.Drawing.Point(13,118)
$lstResults.MultiSelect = $False
$lstResults.Name = "lstResults"
$lstResults.Size = New-Object System.Drawing.Size(634,193)
$lstResults.TabIndex = 2
$lstResults.UseCompatibleStateImageBehavior = $False
$lstResults.View = [System.Windows.Forms.View]::Details
$lstResults.add_SelectedIndexChanged($handler_lstResults_SelectedIndexChanged)
#
# StudentName
#
$StudentName.Text = "Student Name"
$StudentName.Width = 157
#
# StudentEmail
#
$StudentEmail.Text = "Email Address"
$StudentEmail.Width = 218
#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($Form_StateCorrection_Load)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call OnApplicationLoad to initialize
if(OnApplicationLoad -eq $true)
{
#Create the form
GenerateForm | Out-Null
#Perform cleanup
OnApplicationExit
}
|
PowerShellCorpus/PoshCode/Compare-TwitterNames_1.ps1
|
Compare-TwitterNames_1.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
}
compare-object $friendslist $followerslist -SyncWindow ($sync) -Property name
|
PowerShellCorpus/PoshCode/Select-Expand.ps1
|
Select-Expand.ps1
|
function Select-Expand {
<#
.Synopsis
Like Select-Object -Expand, but with recursive iteration of a select chain
.Description
Takes a dot-separated series of properties to expand, and recursively iterates the output of each property ...
.Parameter Property
A collection of property names to expand.
Each property can be a dot-separated series of properties, and each one is expanded, iterated, and then evaluated against the next
.Parameter InputObject
The input to be selected from
.Parameter Unique
If set, this becomes a pipeline hold-up, and the total output is checked to ensure uniqueness
.Parameter EmptyToo
If set, Select-Expand will include empty/null values in it's output
.Example
Get-Help Get-Command | Select-Expand relatedLinks.navigationLink.uri -Unique
This will return the online-help link for Get-Command. It's the equivalent of running the following command:
C:\\PS> Get-Help Get-Command | Select-Object -Expand relatedLinks | Select-Object -Expand navigationLink | Select-Object -Expand uri | Where-Object {$_} | Select-Object -Unique
#>
param(
[Parameter(ValueFromPipeline=$false,Position=0)]
[string[]]$Property
,
[Parameter(ValueFromPipeline=$true)]
[Alias("IO")]
[PSObject[]]$InputObject
,
[Switch]$Unique
,
[Switch]$EmptyToo
)
begin {
if($unique) {
$output = @()
}
}
process {
foreach($io in $InputObject) {
foreach($prop in $Property -split "\\.") {
if($io -ne $null) {
$io = $io | Select-Object -Expand $prop
Write-Verbose $($io | out-string)
}
}
if(!$EmptyToo -and ($io -ne $null)) {
$io = $io | Where-Object {$_}
}
if($unique) {
$output += @($io)
} else {
Write-Output $io
}
}
}
end {
if($unique) {
Write-Output $output | Select-Object -Unique
}
}
}
New-Alias slep Select-Expand
|
PowerShellCorpus/PoshCode/Start-Job proxy function.ps1
|
Start-Job proxy function.ps1
|
<#
Example on how to use Proxy Cmdlets in combination with object events.
For more information see:
http://blog.powershell.no/2011/02/07/powershell-using-proxy-cmdlets-in-combination-with-object-events
For more information about proxy functions, see the following article on the
Microsoft PowerShell Team blog:
http://blogs.msdn.com/powershell/archive/2009/01/04/extending-and-or-modifing-commands-with-proxies.aspx
#>
function Start-Job {
<#
To create a proxy function for the Start-Job cmdlet, paste the results of the following command into the body of this function and then remove this comment:
[Management.Automation.ProxyCommand]::Create((New-Object Management.Automation.CommandMetaData (Get-Command Start-Job)))
#>
[CmdletBinding(DefaultParameterSetName='ComputerName')]
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[System.String]
${Name},
[Parameter(ParameterSetName='ComputerName', Mandatory=$true, Position=0)]
[Alias('Command')]
[System.Management.Automation.ScriptBlock]
${ScriptBlock},
[System.Management.Automation.PSCredential]
${Credential},
[Parameter(ParameterSetName='FilePathComputerName', Position=0)]
[Alias('PSPath')]
[System.String]
${FilePath},
[System.Management.Automation.Runspaces.AuthenticationMechanism]
${Authentication},
[Parameter(Position=1)]
[System.Management.Automation.ScriptBlock]
${InitializationScript},
[Switch]
${RunAs32},
[System.Management.Automation.ScriptBlock]
${OnCompletionAction},
[Parameter(ValueFromPipeline=$true)]
[System.Management.Automation.PSObject]
${InputObject},
[Alias('Args')]
[System.Object[]]
${ArgumentList})
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Start-Job', [System.Management.Automation.CommandTypes]::Cmdlet)
# define string variable to become the target command line
#region Initialize helper variable to create command
$scriptCmdPipeline = ''
#endregion
# add new parameter handling
#region Process and remove the Path parameter if it is present
if($OnCompletionAction)
{
$null = $PSBoundParameters.remove('OnCompletionAction')
$scriptCmd = {
& $wrappedCmd @PSBoundParameters | Foreach-Object{
$job = Register-ObjectEvent -InputObject $_ -EventName StateChanged -SourceIdentifier JobEndAlert -Action {
if($sender.State -eq "Completed")
{
#Invoke custom action
& $OnCompletionAction
#Unregister event created by Register-ObjectEvent
Unregister-Event -SourceIdentifier JobEndAlert -Force
}
}
}
}
}
else
{
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
}
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Start-Job
.ForwardHelpCategory Cmdlet
#>
}
|
PowerShellCorpus/PoshCode/Debug Regex match_1.ps1
|
Debug Regex match_1.ps1
|
function Debug-Regex {
<#
.SYNOPSIS
A very simple function to debug a Regex search operation and show any 'Match'
results. (V2.1 Export Alias db & some patterns, 28 Jan 2012).
.DESCRIPTION
Sometimes it is easier to correct any regex usage if each match can be shown
in context. This function will show each successful result in a separate
colour, including the strings both before and after the match. Using the -F
switch will allow only the first of any matches to be returned.
Commonly used regex patterns may be added to this module, 'exported' and then
assigned to a variable before being passed to the function. (They can also be
used with the Select-String Cmdlet).
.EXAMPLE
Debug-Regex '\\b[A-Z]\\w+' 'Find capitalised Words in This string' -first
Use the -F switch to return only the first match. Produces the following...
MATCHES ---------------<match>--------------------
1 [<Find> capitalised Words in This string]
.EXAMPLE
Debug-Regex '\\b[0-9]+\\b' 'We have to find numbers like 123 and 456 in this'
Produces the following...
MATCHES ---------------<match>--------------------
1 [We have to find numbers like <123> and 456 in this]
2 [We have to find numbers like 123 and <456> in this]
.EXAMPLE
PS >$a = Get-Variable regexDouble -ValueOnly
PS >db $a 'Find some double words words in this this string'
Assign the desired Regex string to $a and use this and the alias as parameters.
.NOTES
Based on a suggestion from the book 'Mastering Regular Expressions' by J.Friedl,
page 429.
.LINK
Web Address Http://www.SeaStarDevelopment.BraveHost.com
#>
param ([Parameter(mandatory=$true)][regex]$regex,
[Parameter(mandatory=$true)][string]$string,
[switch]$first)
$m = $regex.match($string)
if (!$m.Success) {
Write-Host "No Match using Regex '$regex'" -Fore Yellow
return
}
$count = 1
Write-Host "MATCHES --------------------<" -Fore Yellow -NoNewLine
Write-Host "match" -Fore White -NoNewLine
Write-Host ">--------------------" -Fore Yellow
while ($m.Success) {
Write-Host "$count $($m.result('[$`<'))" -Fore Yellow -NoNewLine
Write-Host "$($m.result('$&'))" -Fore White -NoNewLine
Write-Host "$($m.result('>$'']'))" -Fore Yellow
if ($first) {
return
}
$count++
$m = $m.NextMatch()
}
}
# Use a CSV file for larger collections of variables if necessary.
Set-Variable -Name regexDouble -value '\\b(\\w+)((?:\\s|<[^>]+>)+)(\\1\\b)' `
-Description 'Find double word pairs within <>'
Set-Variable -Name regexNumbers -value '\\b[0-9]+\\b' `
-Description 'Find only numbers in a string'
New-Alias db Debug-Regex
Export-ModuleMember -Function Debug-Regex -Variable regex* -Alias db
|
PowerShellCorpus/PoshCode/Error handling PowerCLI.ps1
|
Error handling PowerCLI.ps1
|
$vmPath = "[Storage1] MyVM/MyVM.vmx"
$vm = New-VM –VMHost "192.168.1.10" –VMFilePath $vmPath -Name MyVM
# Check if there is an error and if so – handle it
if (!$?) {
if ($error[0].Exception –is [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.DuplicateName]) {
# A VM with the same name already exists. Change the name and try again.
$vm = New-VM –VMHost "192.168.1.10" –VMFilePath $vmPath –Name "myVM (1)"
} elseif ($error[0].Exception –is [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InsufficientResourcesFault]) {
# There aren’t enough resources on this host. Try again on another host.
$vm = New-VM –VMHost "192.168.1.12" –VMFilePath $vmPath
} else {
# Handle unexpected exceptions here …
}
}
|
PowerShellCorpus/PoshCode/Invoke-Command_1.ps1
|
Invoke-Command_1.ps1
|
Param($file,$cmd,[switch]$whatif,[switch]$verbose)
Begin{
function Ping-Server {
Param([string]$srv)
$pingresult = Get-WmiObject win32_pingstatus -f "address='$srv'"
if($pingresult.statuscode -eq 0) {$true} else {$false}
}
$servers = @()
}
Process{
if($_)
{
if($_.ServerName){$servers += $_.ServerName}
else{$servers += $_}
}
}
End{
if($file){Get-Content $file | %{$servers += $_}}
foreach($server in $servers)
{
if(ping-server $server)
{
if($verbose){Write-Host "+ Processing Server $Server"}
$mycmd = $cmd -replace "\\%S\\%",$Server
if($whatif){Write-Host " - WOULD RUN $mycmd"}
else{if($verbose){Write-Host " - Running $mycmd"};invoke-Expression $mycmd}
}
else
{
Write-Host "+ $Server FAILED PING" -foregroundcolor RED
}
}
}
|
PowerShellCorpus/PoshCode/demo.ps1
|
demo.ps1
|
\n[45]: [IO.File]::ReadAllLines( "C:\\Users\\Joel\\Sites\\webalizer.current" ).Length
31873
[46]: (gc C:\\Users\\Joel\\Sites\\webalizer.current).Length
31873
[47]: gph 2
Duration Average Lines Words Chars Type Commmand
-------- ------- ----- ----- ----- ---- --------
0.07910 0.07910 1 3 73 Command [IO.File]::ReadAllLines( "C:\\Users\\Joel\\Sites\\webalizer.current" ).Length
0.88080 0.88080 1 2 49 Command (gc C:\\Users\\Joel\\Sites\\webalizer.current).Length
|
PowerShellCorpus/PoshCode/ScheduledTasks_1.ps1
|
ScheduledTasks_1.ps1
|
# Windows Scheduled Tasks Management PowerShell Module
# http://powershell.codeplex.com
Function Get-ScheduledTasks
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
$ScheduledTasks = SCHTASKS.EXE /QUERY /FO CSV /NH $HostName
foreach ( $Item in $ScheduledTasks )
{
if ( $Item -ne "" )
{
$Item = $Item -replace("""|\\s","")
$SplitItem = $Item -split(",")
$ScheduledTaskName = $SplitItem[0]
$ScheduledTaskStatus = $SplitItem[3]
if ( $ScheduledTaskName -ne "" )
{
if ( $ScheduledTaskStatus -eq "" )
{
$ScheduledTaskStatus = "Not Running"
}
else
{
$ScheduledTaskStatus = "Running"
}
$objScheduledTaskName = New-Object System.Object
$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskName -Value $ScheduledTaskName
$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskStatus -Value $ScheduledTaskStatus
$objScheduledTaskName | Where-Object { $_.TaskName -match $TaskName }
}
}
}
}
}
Function Start-ScheduledTask
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
SCHTASKS.EXE /RUN /TN $TaskName $HostName
}
}
Function Stop-ScheduledTask
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
SCHTASKS.EXE /END /TN $TaskName $HostName
}
}
Export-ModuleMember Get-ScheduledTasks, Start-ScheduledTask, Stop-ScheduledTask
|
PowerShellCorpus/PoshCode/LibraryMSCS_3.ps1
|
LibraryMSCS_3.ps1
|
# ------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Defines functions for working with Microsoft Cluster Service (MSCS)
### </Description>
### <Usage>
### . ./LibraryMSCS.ps1
### </Usage>
### </Script>
# ------------------------------------------------------------------------
#######################
function Get-Cluster
{
param($cluster)
gwmi -class "MSCluster_Cluster" -namespace "root\\mscluster" -computername $cluster
} #Get-Cluster
#######################
function Get-ClusterName
{
param($cluster)
Get-Cluster $cluster | select -ExpandProperty name
} #Get-ClusterName
#######################
function Get-ClusterNode
{
param($cluster)
gwmi -class MSCluster_Node -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster
} #Get-ClusterNode
#######################
function Get-ClusterSQLVirtual
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "SQL Server"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='VirtualServerName';e={$_.PrivateProperties.VirtualServerName}}, @{n='InstanceName';e={$_.PrivateProperties.InstanceName}}, `
@{n='ServerInstance';e={("{0}\\{1}" -f $_.PrivateProperties.VirtualServerName,$_.PrivateProperties.InstanceName).TrimEnd('\\')}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterSQLVirtual
#######################
function Get-ClusterNetworkName
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "Network Name"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='NetworkName';e={$_.PrivateProperties.Name}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterNetworkName
#######################
function Get-ClusterResource
{
param($cluster)
gwmi -ComputerName $cluster -Namespace "root\\mscluster" -Class MSCluster_Resource | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $this.Cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty Group `
{ gwmi -ComputerName $this.Cluster -Namespace "root\\mscluster" -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToResource" | Select -ExpandProperty Name }
} #Get-ClusterResource
#######################
function Get-ClusterGroup
{
param($cluster)
gwmi -class MSCluster_ResourceGroup -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $this.Cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveGroup" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty PreferredNodes `
{ @(,(gwmi -namespace "root\\mscluster" -computerName $this.Cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToPreferredNode" | Select -ExpandProperty Name)) }
} #Get-ClusterGroup
|
PowerShellCorpus/PoshCode/Remove-LocalProfile_1.ps1
|
Remove-LocalProfile_1.ps1
|
<#
.SYNOPSIS
Interactive menu that allows a user to connect to a local or remote computer and remove a local profile.
.DESCRIPTION
Presents an interactive menu for user to first make a connection to a remote or local machine. After making connection to the machine,
the user is presented with all of the local profiles and then is asked to make a selection of which profile to delete. This is only valid
on Windows Vista OS and above for clients and Windows 2008 and above for server OS.
.NOTES
Name: Remove-LocalProfile
Author: Boe Prox
DateCreated: 26JAN2011
.LINK
http://boeprox.wordpress.com
http://msdn.microsoft.com/en-us/library/ee886409%28v=vs.85%29.aspx
.EXAMPLE
Remove-LocalProfile
Description
-----------
Presents a text based menu for the user to interactively remove a local profile on local or remote machine.
#>
#Prompt for a computer to connect to
$computer = Read-Host "Please enter a computer name"
#Test network connection before making connection
If ($computer -ne $Env:Computername) {
If (!(Test-Connection -comp $computer -count 1 -quiet)) {
Write-Warning "$computer is not accessible, please try a different computer or verify it is powered on."
Break
}
}
Try {
#Verify that the OS Version is 6.0 and above, otherwise the script will fail
If ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0) {
Write-Warning "The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
Break
}
}
Catch {
Write-Warning "$($error[0])"
Break
}
Do {
#Gather all of the user profiles on computer
Try {
[array]$users = Get-WmiObject -ComputerName $computer Win32_UserProfile -filter "LocalPath Like 'C:\\\\Users\\\\%'" -ea stop
}
Catch {
Write-Warning "$($error[0]) "
Break
}
#Cache the number of users
$num_users = $users.count
Write-Host -ForegroundColor Green "User profiles on $($computer):"
#Begin iterating through all of the accounts to display
For ($i=0;$i -lt $num_users; $i++) {
Write-Host -ForegroundColor Green "$($i): $(($users[$i].localpath).replace('C:\\Users\\',''))"
}
Write-Host -ForegroundColor Green "q: Quit"
#Prompt for user to select a profile to remove from computer
Do {
$account = Read-Host "Select a number to delete local profile or 'q' to quit"
#Find out if user selected to quit, otherwise answer is an integer
If ($account -NotLike "q*") {
$account = $account -as [int]
}
}
#Ensure that the selection is a number and within the valid range
Until (($account -lt $num_users -AND $account -match "\\d") -OR $account -Like "q*")
If ($account -Like "q*") {
Break
}
Write-Host -ForegroundColor Yellow "Deleting profile: $(($users[$account].localpath).replace('C:\\Users\\',''))"
#Remove the local profile
($users[$account]).Delete()
Write-Host -ForegroundColor Green "Profile: $(($users[$account].localpath).replace('C:\\Users\\','')) has been deleted"
#Configure yes choice
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Remove another profile."
#Configure no choice
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No","Quit profile removal"
#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription[]] @($yes,$no)
#Determine Default Selection
[int]$default = 0
#Present choice option to user
$userchoice = $host.ui.PromptforChoice("","Remove Another Profile?",$choice,$default)
}
#If user selects No, then quit the script
Until ($userchoice -eq 1)
|
PowerShellCorpus/PoshCode/RSS Enclosure Downloader.ps1
|
RSS Enclosure Downloader.ps1
|
# author: Alexander Grofl
# http://www.therightstuff.de/2008/07/25/RSS+Enclosure+Downloader+In+PowerShell.aspx
$feed=[xml](New-Object System.Net.WebClient).DownloadString("http://the/rss/feed/url")
foreach($i in $feed.rss.channel.item) {
$url = New-Object System.Uri($i.enclosure.url)
$url.ToString()
$url.Segments[-1]
(New-Object System.Net.WebClient).DownloadFile($url, $url.Segments[-1])
}
|
PowerShellCorpus/PoshCode/get windows product key_5.ps1
|
get windows product key_5.ps1
|
function get-windowsproductkey([string]$computer)
{
$Reg = [WMIClass] ("\\\\" + $computer + "\\root\\default:StdRegProv")
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$STR = ''
$decodedChars | % { $str+=$_}
$STR
}
get-windowsproductkey .
|
PowerShellCorpus/PoshCode/HelpModules 1.0.ps1
|
HelpModules 1.0.ps1
|
# HelpModules
# A Module for generating module stubs so you can Update-Help (or Save-Help)
# Includes two options for reading the help from those modules (StubFunctions or Get-ModuleHelp)
# 1.0 - 2013/2/1 - Initial release Friday, Feb 1st, 2013
$PSModuleHelpRoot = Convert-Path "~\\Documents\\WindowsPowerShellModuleHelp"
function New-HelpModule {
#.Synopsis
# Creates a dummy module and fetches the help files for it
[CmdletBinding()]
param(
# The name of the module you want to create a dummy for.
# TODO: currently works only for local modules
# TODO: currently only handles one module at a time (you can pipe them)
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=0)]
[Alias("Name")]
[String]$ModuleName,
# A path to put the help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp").
[Parameter()]
[String]$ModuleHelpRoot = $PSModuleHelpRoot,
# If set, generates a Blank.psm1 with stub functions in it so that you can import the dummy module and use the built-in Get-Help instead of our Get-ModuleHelp
#
# Setting this may pollute your PowerShell session with dozens or hudreds of commands which don't do anything. You probably shouldn't, for instance, add your ModuleHelpRoot path to your PSModulePath if you do this.
[Switch]$StubFunctions,
# The culture you want to fetch help for (defaults to $PSUICulture)
$HelpCulture = ${PSUICulture}
)
process {
# Make the ModuleHelpRoot\\ModuleName folder if it's not there
$ModuleDir = mkdir ${ModuleHelpRoot}\\${ModuleName}\\ -Force
# Generate the stub ModuleManifest from an existing one
# TODO: we need to do the Get-Module remotely on the server
foreach($module in Get-Module $ModuleName -ListAvailable | Select Guid, HelpInfoUri, Version, ExportedCommands) {
New-ModuleManifest -Path ${ModuleHelpRoot}\\${ModuleName}\\${ModuleName}.psd1 -Guid $module.Guid -HelpInfoUri $module.HelpInfoUri -ModuleVersion $module.Version -FunctionsToExport $module.ExportedCommands -RootModule "Blank.psm1"
}
# Update the help files -- this is why we're here.
# TODO: if we're generating a lot of modules, it would be really to only do this once!
PowerShell -NoProfile -Command "&{ `$Env:PSModulePath = '$ModuleHelpRoot'; Update-Help -Module '$ModuleName' -UICulture $HelpCulture}"
# Generate stub FunctionsToExport
if($StubFunctions) {
foreach($file in Get-ChildItem ${ModuleHelpRoot}\\${ModuleName}\\${HelpCulture}\\*.xml) {
foreach($name in Select-Xml "//*[local-name() = 'details']/*[local-name() = 'name']" -Path $file | Select-Object -Expand Node | Select-Object -Expand "#text") {
Add-Content "${ModuleHelpRoot}\\${ModuleName}\\Blank.psm1" ".ExternalHelp $($file.Name)`nfunction $name {}`n"
}
}
}
}
}
function Get-ModuleHelp {
#.Synopsis
# Gets help from the XML help files directly without worrying about whether the commands actually exist.
[CmdletBinding(DefaultParameterSetName="MamlCommandHelpInfo")]
param(
# The command you want help for
[Alias("Name")]
[Parameter(Mandatory=$true, Position = 0, ValueFromPipelineByPropertyName = $true)]
$CommandName,
# The name of the module the command is in
# TODO: Search Get-Module -ListAvailable for modules which *say* they have the command
[Parameter(Mandatory=$true, Position = 1, ValueFromPipelineByPropertyName = $true)]
$ModuleName,
# A path to search for help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp").
$ModuleHelpRoot = $PSModuleHelpRoot,
# Displays only the detailed descriptions of the specified parameters. Wildcards are permitted.
[Parameter(ParameterSetName="MamlCommandHelpInfo#parameter")]
[String]$Parameter,
# Displays only the name, synopsis, and examples".
[Parameter(ParameterSetName="MamlCommandHelpInfo#ExamplesView")]
[Switch]$Examples,
# Displays the entire help topic for a cmdlet, including parameter descriptions and attributes, examples, input and output object types, and additional notes.
[Parameter(ParameterSetName="MamlCommandHelpInfo#FullView")]
[Switch]$Full,
# Adds parameter descriptions and examples to the basic help display.
[Parameter(ParameterSetName="MamlCommandHelpInfo#DetailedView")]
[Switch]$Detailed,
# The culture you want to fetch help for (defaults to $PSUICulture)
$HelpCulture = ${PSUICulture}
)
process {
Write-Verbose "Culture: $HelpCulture HelpSet: $($PSCmdlet.ParameterSetName)"
$matched = $false
foreach($node in Select-Xml "//*[local-name() = 'details']/*[local-name() = 'name' and text() = '$CommandName']/../.." -Path ${ModuleHelpRoot}\\${ModuleName}\\${PSUICulture}\\*.xml | Select-Object -Expand Node) {
if($Parameter) {
foreach($param in $node.parameters.parameter) {
if($param.name -like $Parameter) {
$matched = $true
$param | FixMaml -Type $($PSCmdlet.ParameterSetName)
}
}
if(!$matched) {
throw "No parameter matches criteria $Parameter"
}
} else {
$matched = $true
$node | FixMaml -Type $($PSCmdlet.ParameterSetName)
}
}
}
}
function FixMaml {
#.Synopsis
# Internal command for tweaking the XML just enough that PowerShell will format it properly
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$Node,
[Parameter(Mandatory=$true)]
$Type = "MamlCommandHelpInfo"
)
process {
$node.PSTypeNames.Clear()
$node.PSTypeNames.Add($type)
if($node.description) {
Add-Member -Input $node NoteProperty description @(
$Node.RemoveChild($node.description).para | % {
$p = New-Object PSObject -Property @{ Text = $_ };
$p.PSTypeNames.Clear();
$p.PSTypeNames.Add("MamlParaTextItem");
$p
} )
}
if($node.details) {
# Fix them, but don't output recursively
$null = $node.details | FixMaml -Type $Type
}
Write-Output $node
}
}
Export-ModuleMember -Function New-HelpModule, Get-ModuleHelp -Variable PSModuleHelpRoot
# SIG # Begin signature block
# MIIfIAYJKoZIhvcNAQcCoIIfETCCHw0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUQ3oSz1in4p/LMkuRa71g9N9E
# ISSgghpSMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B
# AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG
# A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh
# d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg
# Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV
# UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu
# dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN
# AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q
# WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC
# i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4
# ezPkeQr78HWIQZz/xQNRmarXbJ+TaYdlKYOFwmAUxMjJOxTawIHwHw103pIiq8r3
# +3R8J+b3Sht/p8OeLa6K6qbmqicWfWH3mHERvOJQoUvlXfrlDqcsn6plINPYlujI
# fKVOSET/GeJEB5IL12iEgF1qeGRFzWBGflTBE3zFefHJwXECAwEAAaOB+jCB9zAd
# BgNVHQ4EFgQUX5r1blzMzHSa1N197z/b7EyALt0wMgYIKwYBBQUHAQEEJjAkMCIG
# CCsGAQUFBzABhhZodHRwOi8vb2NzcC50aGF3dGUuY29tMBIGA1UdEwEB/wQIMAYB
# Af8CAQAwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC50aGF3dGUuY29tL1Ro
# YXd0ZVRpbWVzdGFtcGluZ0NBLmNybDATBgNVHSUEDDAKBggrBgEFBQcDCDAOBgNV
# HQ8BAf8EBAMCAQYwKAYDVR0RBCEwH6QdMBsxGTAXBgNVBAMTEFRpbWVTdGFtcC0y
# MDQ4LTEwDQYJKoZIhvcNAQEFBQADgYEAAwmbj3nvf1kwqu9otfrjCR27T4IGXTdf
# plKfFo3qHJIJRG71betYfDDo+WmNI3MLEm9Hqa45EfgqsZuwGsOO61mWAK3ODE2y
# 0DGmCFwqevzieh1XTKhlGOl5QGIllm7HxzdqgyEIjkHq3dlXPx13SYcqFgZepjhq
# IhKjURmDfrYwggRPMIIDuKADAgECAgQHJ1g9MA0GCSqGSIb3DQEBBQUAMHUxCzAJ
# BgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdU
# RSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVy
# VHJ1c3QgR2xvYmFsIFJvb3QwHhcNMTAwMTEzMTkyMDMyWhcNMTUwOTMwMTgxOTQ3
# WjBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL
# ExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3Vy
# YW5jZSBFViBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# xszlc+b71LvlLS0ypt/lgT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZ
# OtPclNY823Q4pErMTSWC90qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLj
# BuUIkQzEKEFV+8taiRV+ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPr
# UQqYQUEiTmVhh4FBUKZ5XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV
# 215k4TeHMFYE5RG0KYAS8Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6H
# XRpQCyASzEG7bgtROLhLywIDAQABo4IBbzCCAWswEgYDVR0TAQH/BAgwBgEB/wIB
# ATBTBgNVHSAETDBKMEgGCSsGAQQBsT4BADA7MDkGCCsGAQUFBwIBFi1odHRwOi8v
# Y3liZXJ0cnVzdC5vbW5pcm9vdC5jb20vcmVwb3NpdG9yeS5jZm0wDgYDVR0PAQH/
# BAQDAgEGMIGJBgNVHSMEgYEwf6F5pHcwdTELMAkGA1UEBhMCVVMxGDAWBgNVBAoT
# D0dURSBDb3Jwb3JhdGlvbjEnMCUGA1UECxMeR1RFIEN5YmVyVHJ1c3QgU29sdXRp
# b25zLCBJbmMuMSMwIQYDVQQDExpHVEUgQ3liZXJUcnVzdCBHbG9iYWwgUm9vdIIC
# AaUwRQYDVR0fBD4wPDA6oDigNoY0aHR0cDovL3d3dy5wdWJsaWMtdHJ1c3QuY29t
# L2NnaS1iaW4vQ1JMLzIwMTgvY2RwLmNybDAdBgNVHQ4EFgQUsT7DaQP4v0cB1Jgm
# GggC72NkK8MwDQYJKoZIhvcNAQEFBQADgYEALnaF2TeWba+J8wZ4gjHERgcfZcmO
# s8lUeObRQt91Lh5V6vf6mwTAdXvReTwF7HnEUt2mA9enUJk/BVnaxlX0hpwNZ6NJ
# BJUyHceH7IWvZG7VxV8Jp0B9FrpJDaL99t9VMGzXeMa5z1gpZBZMoyCBR7FEkoQW
# G29KvCHGCj3tM8owggSjMIIDi6ADAgECAhAOz/Q4yP6/NW4E2GqYGxpQMA0GCSqG
# SIb3DQEBBQUAMF4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jw
# b3JhdGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMgVGltZSBTdGFtcGluZyBTZXJ2aWNl
# cyBDQSAtIEcyMB4XDTEyMTAxODAwMDAwMFoXDTIwMTIyOTIzNTk1OVowYjELMAkG
# A1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMTQwMgYDVQQD
# EytTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIFNpZ25lciAtIEc0MIIB
# IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomMLOUS4uyOnREm7Dv+h8GEK
# U5OwmNutLA9KxW7/hjxTVQ8VzgQ/K/2plpbZvmF5C1vJTIZ25eBDSyKV7sIrQ8Gf
# 2Gi0jkBP7oU4uRHFI/JkWPAVMm9OV6GuiKQC1yoezUvh3WPVF4kyW7BemVqonShQ
# DhfultthO0VRHc8SVguSR/yrrvZmPUescHLnkudfzRC5xINklBm9JYDh6NIipdC6
# Anqhd5NbZcPuF3S8QYYq3AhMjJKMkS2ed0QfaNaodHfbDlsyi1aLM73ZY8hJnTrF
# xeozC9Lxoxv0i77Zs1eLO94Ep3oisiSuLsdwxb5OgyYI+wu9qU+ZCOEQKHKqzQID
# AQABo4IBVzCCAVMwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcD
# CDAOBgNVHQ8BAf8EBAMCB4AwcwYIKwYBBQUHAQEEZzBlMCoGCCsGAQUFBzABhh5o
# dHRwOi8vdHMtb2NzcC53cy5zeW1hbnRlYy5jb20wNwYIKwYBBQUHMAKGK2h0dHA6
# Ly90cy1haWEud3Muc3ltYW50ZWMuY29tL3Rzcy1jYS1nMi5jZXIwPAYDVR0fBDUw
# MzAxoC+gLYYraHR0cDovL3RzLWNybC53cy5zeW1hbnRlYy5jb20vdHNzLWNhLWcy
# LmNybDAoBgNVHREEITAfpB0wGzEZMBcGA1UEAxMQVGltZVN0YW1wLTIwNDgtMjAd
# BgNVHQ4EFgQURsZpow5KFB7VTNpSYxc/Xja8DeYwHwYDVR0jBBgwFoAUX5r1blzM
# zHSa1N197z/b7EyALt0wDQYJKoZIhvcNAQEFBQADggEBAHg7tJEqAEzwj2IwN3ij
# hCcHbxiy3iXcoNSUA6qGTiWfmkADHN3O43nLIWgG2rYytG2/9CwmYzPkSWRtDebD
# Zw73BaQ1bHyJFsbpst+y6d0gxnEPzZV03LZc3r03H0N45ni1zSgEIKOq8UvEiCmR
# DoDREfzdXHZuT14ORUZBbg2w6jiasTraCXEQ/Bx5tIB7rGn0/Zy2DBYr8X9bCT2b
# W+IWyhOBbQAuOA2oKY8s4bL0WqkBrxWcLC9JG9siu8P+eJRRw4axgohd8D20UaF5
# Mysue7ncIAkTcetqGVvP6KUwVyyJST+5z3/Jvz4iaGNTmr1pdKzFHTx/kuDDvBzY
# BHUwggafMIIFh6ADAgECAhAOaQaYwhTIerW2BLkWPNGQMA0GCSqGSIb3DQEBBQUA
# MHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsT
# EHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNzdXJh
# bmNlIENvZGUgU2lnbmluZyBDQS0xMB4XDTEyMDMyMDAwMDAwMFoXDTEzMDMyMjEy
# MDAwMFowbTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQH
# Ew5XZXN0IEhlbnJpZXR0YTEYMBYGA1UEChMPSm9lbCBILiBCZW5uZXR0MRgwFgYD
# VQQDEw9Kb2VsIEguIEJlbm5ldHQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
# AoIBAQDaiAYAbz13WMx9Em/Z3dTWUKxbyiTsaSOctgOfTMLUAurXWtY3k1XBVufX
# feL4pXQ7yQzm93YzvETwKdUCDJuOSu9EPYioy2nhKvBC6IaJUaw1VY7e9IsdxaxL
# 8js3RQilLk+FO4UHg9w7L8wdHgXaDoksysC2SlhbFq4AVl8XC4R+bq+pahsdMO3n
# Ab7Oo5PExKLVS8vl8QwOh6MaqquIjHmYoPOu9Rv8As0pnWsY9aVPs7T9QetXlW45
# +CKPhdUoEB1yD0kvGTIAQgn5W9VDYmfeVU40IIdt+7khWF10yu7zVT+/lauPzRmv
# CHZMfbmqVyVQqvp5dEu0/7EWbbcLAgMBAAGjggMzMIIDLzAfBgNVHSMEGDAWgBSX
# SAPrFQhrubJYI8yULvHGZdJkjjAdBgNVHQ4EFgQUmJxEqr9ewFZG4rNTp5NQIEIJ
# TrkwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMGkGA1UdHwRi
# MGAwLqAsoCqGKGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j
# cmwwLqAsoCqGKGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j
# cmwwggHEBgNVHSAEggG7MIIBtzCCAbMGCWCGSAGG/WwDATCCAaQwOgYIKwYBBQUH
# AgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVwb3NpdG9yeS5o
# dG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0
# AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4AcwB0AGkAdAB1
# AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQAaABlACAARABp
# AGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQAaABlACAAUgBl
# AGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUAbgB0ACAAdwBo
# AGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkAIABhAG4AZAAg
# AGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUAcgBlAGkAbgAg
# AGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wgYYGCCsGAQUFBwEBBHoweDAkBggr
# BgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMFAGCCsGAQUFBzAChkRo
# dHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNl
# Q29kZVNpZ25pbmdDQS0xLmNydDAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBBQUA
# A4IBAQAch95ik7Qm12L9Olwjp5ZAhhTYAs7zjtD3WMsTpaJTq7zA3q2QeqB46WzT
# vRINQr4LWtWhcopnQl5zaTV1i6Qo+TJ/epRE/KH9oLeEnRbBuN7t8rv0u31kfAk5
# Gl6wmvBrxPreXeossuU9ohij9uqIyk1lF85yW6QqDaE7rvIxpCXwMQv8PlQ/VdlK
# EXbNtq4frbvMQLkpcZljbJRuZYbY3SgfGv6rgbJ93Qw+1Tlq9Y4gsHRmw35uv5IJ
# VUrqcrNq5cyTgdeYodpftzKyqmZCIVvv8nu09DTfspAocJj9n5+XRqtEKIeKH9D/
# mjC/nVZIo+JpSuQG90nSYpUr4xwfMIIGvzCCBaegAwIBAgIQCBxX7l1w65ugsVIM
# cpwbCTANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJE
# aWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTExMDIxMDEyMDAw
# MFoXDTI2MDIxMDEyMDAwMFowczELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD
# ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEyMDAGA1UEAxMpRGln
# aUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBTaWduaW5nIENBLTEwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDF+SPmlCfEgBSkgDJfQKONb3DA5TZxcTp1
# pKoakpSJXqwjcctOZ31BP6rjS7d7vp3BqDiPaS86JOl3WRLHZgRDwg0mgolAGfIs
# 6udM53wFGrj/iAlPJjfvOqT6ImyIyUobYfKuEF5vvNF5m1kYYOXuKbUDKqTO8YMZ
# T2kFcygJ+yIQkyKgkBkaTDHy0yvYhEOvPGP/mNsg0gkrVMHq/WqD5xCjEnH11tfh
# EnrV4FZazuoBW2hlW8E/WFIzqTVhTiLLgco2oxLLBtbPG00YfrmSuRLPQCbYmjaF
# sxWqR5OEawe7vNWz3iUAEYkAaMEpPOo+Le5Qq9ccMAZ4PKUQI2eRAgMBAAGjggNU
# MIIDUDAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwggHDBgNV
# HSAEggG6MIIBtjCCAbIGCGCGSAGG/WwDMIIBpDA6BggrBgEFBQcCARYuaHR0cDov
# L3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsG
# AQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABD
# AGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABh
# AGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQBy
# AHQAIABFAFYAIABDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBn
# ACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABs
# AGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABp
# AG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBl
# AGYAZQByAGUAbgBjAGUALjAPBgNVHRMBAf8EBTADAQH/MH8GCCsGAQUFBwEBBHMw
# cTAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEkGCCsGAQUF
# BzAChj1odHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNz
# dXJhbmNlRVZSb290Q0EuY3J0MIGPBgNVHR8EgYcwgYQwQKA+oDyGOmh0dHA6Ly9j
# cmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hBc3N1cmFuY2VFVlJvb3RDQS5j
# cmwwQKA+oDyGOmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hB
# c3N1cmFuY2VFVlJvb3RDQS5jcmwwHQYDVR0OBBYEFJdIA+sVCGu5slgjzJQu8cZl
# 0mSOMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEB
# BQUAA4IBAQCCBemFr6dMv6/OPbLqYLFo3mfC0ssm4MMvm7VrDlOQhfab4DUC//pp
# g6q0dDIUPC4QTCibCq0ICfnzhBGTj8tgQFbpdy9psoOZVatHJJbLf0uwELSXv8Sl
# mQb+juwUUB5eV5fLR7k02fw6ov9QKcIKYgTu3pY6b6DChQ9v/AjkMnvThK5pYAlG
# Jpzo8P//htnICTpmw6c2jxhP6LGWki5OvgunM5CuvG5P8X6NtEYOZPlZBiIhZABL
# 4noIA+e8iZCeQk8BwLYWf3XqRrKlVC+Mk80RNjRqKFfMlD/pfMgYAwMEfkPa+Zeh
# WUfaEqrgbTgAXTUrxSKGywbKvHpNPSZGMYIEODCCBDQCAQEwgYcwczELMAkGA1UE
# BhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2lj
# ZXJ0LmNvbTEyMDAGA1UEAxMpRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBT
# aWduaW5nIENBLTECEA5pBpjCFMh6tbYEuRY80ZAwCQYFKw4DAhoFAKB4MBgGCisG
# AQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQw
# HAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFDv8
# tjyGeTlXeUzuInWGFRsehB1HMA0GCSqGSIb3DQEBAQUABIIBADwCIAseI2pZ6xNp
# RL8Wzglt6shQ4sR4zuivDf7r7I469V1Qgh/2VZouX1/cDSSBhhbs83t8wl2zaBK9
# t+p+OrbAAYy4CtEPv/T3rVa73KZ5I8DtJtLHoXYGLKJTfQhR1S1WKrIJEngw58LL
# l7uluY/dYJ5Q7B/Y9PeyAWZfiI91sF6jBZWPVqRR59jbrMIwr5l5/W1qP5ZfddNA
# 8zhHmR6vheN+QR1sbMV7XfKDGlw+y8qGFFkV+nOFSFVXeY92LG2S8+mc+u8TzBTw
# T075wfHHtIPfWMYVv2BfqgcVmS4Tl6goONzzmrez7syRqTV9/weSrF85wYgJ65T1
# g2y99e6hggILMIICBwYJKoZIhvcNAQkGMYIB+DCCAfQCAQEwcjBeMQswCQYDVQQG
# EwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5
# bWFudGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMgIQDs/0OMj+vzVu
# BNhqmBsaUDAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAc
# BgkqhkiG9w0BCQUxDxcNMTMwMjAxMjEzNDM5WjAjBgkqhkiG9w0BCQQxFgQUcNVz
# 4rFmgb088c80vaQqF6pfziUwDQYJKoZIhvcNAQEBBQAEggEASa/Q1iWBIoGakICZ
# zhhjvyXWMBWC4+L6rLMMiy5zGo+szfSodWldW5HRnHGRFARL8F3cm5GqnrAMk3Kh
# /HIV7r2JauM0FLcgYRfmQcYVqj/chsUp6tSSlIkDwnGT6E4IyT7ekS98UJ9BDq5q
# fa2+T/I7i8B0sHTZbG2fbwMiyA66sDNR3g9KPWxeT0qjlP8235XI31xglHi9ArKS
# qSDtiNmfHHK84Y3xlLPDdWTorWWsf4tsUTHvyjVST4aduc2NPuD3IvfgB1SWhdcl
# h/BEJTI2YO5ZzIWkSxbPZnFGwV9bX2zTk+alHlMoJr2Y4ySzMCN9hCZlblsHKJOz
# /gEGdQ==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Test-Port_2.ps1
|
Test-Port_2.ps1
|
function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers
To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer 'server' -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
'server' | Test-Port -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
Test-Port -computer @("server1","server2") -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
@("server1","server2") | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file
#>
[cmdletbinding(
DefaultParameterSetName = '',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = '')]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$UDP
)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = "SilentlyContinue"
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine's port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(":")[1]).replace('"',"")).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "$message"
}
#Successfully queried port
Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "True"
$temp.Notes = ""
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient($p)
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine's port
Write-Verbose "Making UDP connection to remote server"
$udpobject.Connect("$c",$p)
#Sends a message to the host to which you have connected.
Write-Verbose "Sending message to remote host"
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes("$(Get-Date)")
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose "Creating remote endpoint"
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose "Waiting for message return"
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
}
Catch {
If ($Error[0].ToString() -match "\\bRespond after a period of time\\b") {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose "Connection Open"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = ""
}
Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose "Host maybe unavailable"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Unable to verify if port is open or if host is unavailable."
}
}
ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
#Close connection
$udpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}
|
PowerShellCorpus/PoshCode/Easy Migration Tool v2.1.ps1
|
Easy Migration Tool v2.1.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: Richard Yaw
# Generated On: 09/12/2010
#
# Easy Migration Script for VMware (Version 2.0)
# - Added a "Reload Tasks" feature.
# - Fixed issue with the Undo feature for SVMotions.
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$MigrationForm = New-Object System.Windows.Forms.Form
$Header = new-object System.Windows.Forms.Label
$MigrateButton = New-Object System.Windows.Forms.Button
$ClusterListBox = New-Object System.Windows.Forms.ListBox
$SourceHostListBox = New-Object System.Windows.Forms.ListBox
$SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox
$SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox
$DestinationListBox = New-Object System.Windows.Forms.ListBox
$vCenterLabel = New-Object System.Windows.Forms.Label
$VCTextBox = New-Object System.Windows.Forms.TextBox
$LoginButton = New-Object System.Windows.Forms.Button
$ClearMsgButton = New-Object System.Windows.Forms.Button
$UndoButton = New-Object System.Windows.Forms.Button
$UndoALLButton = New-Object System.Windows.Forms.Button
$ReloadTaskButton = New-Object System.Windows.Forms.Button
$SaveTaskButton = New-Object System.Windows.Forms.Button
$ClusterLabel = New-Object System.Windows.Forms.Label
$HostToHostButton = New-Object System.Windows.Forms.Button
$VMToHostButton = New-Object System.Windows.Forms.Button
$DBtoDBButton = New-Object System.Windows.Forms.Button
$VMtoDBButton = New-Object System.Windows.Forms.Button
$SourceButton = New-Object System.Windows.Forms.Button
$DestinationButton = New-Object System.Windows.Forms.Button
$ResetButton = New-Object System.Windows.Forms.Button
$ChangeVCButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$MessagesLabel = New-Object System.Windows.Forms.Label
$MessagesListBox = New-Object System.Windows.Forms.ListBox
$TaskLabel = New-Object System.Windows.Forms.Label
$TaskListBox = New-Object System.Windows.Forms.ListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$LoginButton_Click=
{
#TODO: Place custom script here
If ($VCTextBox.Text -eq "")
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Enter a Valid vCenter Server.')
}
Else
{
if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $VCTextBox.Text
$ClusterListBox.Enabled = $true
#Get Cluster
Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) }
If ($ClusterListBox.items -ne $null)
{
$LoginButton.Enabled = $false
$VCTextBox.Enabled = $false
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$ResetButton.Enabled = $true
$ChangeVCButton.Enabled = $true
$ReloadTaskButton.Enabled = $true
#Generate a log file for this session
#$logfile = "C:\\TEMP\\EasyMigrate{0:dd-MM-yyyy_HHmmss}" -f (Get-Date) + ".log"
#$logheader = "Easy Migration Tool v2.0 - Log generated on " + (Get-Date)
#Out-File -InputObject $logheader -FilePath $logfile
#Out-File -InputObject "" -Append -FilePath $logfile
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$HostToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$SourceHostListBox.Enabled = $true
$SourceHostListBox.Items.Clear()
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select One Host'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$HostToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$VMToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$DBtoDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceDBListBox)
$SourceDBListBox.Enabled = $true
$SourceDBListBox.Items.Clear()
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select a Datastore'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$SourceButton_OnClick=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
If ($SourceHostname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Source Host.')
}
Else
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceHostListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$SourceVMname = $SourceVMListBox.SelectedItem
If ($SourceVMname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.')
}
Else
{
if ($DestinationButton.Text -like "Destination Host")
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) }
}
$DestinationListBox.Enabled = $true
$SourceVMListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -like "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
If ($SourceDBname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One Datastore.')
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceDBListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
}
$DestinationButton_OnClick=
{
#TODO: Place custom script here
$DestinationName = $DestinationListBox.SelectedItem
If ($DestinationName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Destination.')
}
Else
{
$DestinationListBox.Enabled = $false
$DestinationButton.Enabled = $false
$MigrateButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$MigrateButton_OnClick=
{
#TODO: Place custom script here
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-VMHost $SourceHostname | Get-VM
foreach($VM in $VMs)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$DestinationName = $DestinationListBox.SelectedItem
If($DestinationButton.Text -eq "Destination Host")
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
Else
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
@@ $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
@@ ElseIf ($SnapshotCount -gt 0)
@@ {
@@ $d = Get-Date
@@ $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
@@ [void]$MessagesListBox.items.add($MsgLine)
@@ }
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-Datastore -Name $SourceDBname | Get-VM
If($VMs.count -gt 0)
{
foreach($VM in $VMs)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
@@ $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBFreeSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
@@ ElseIf ($SnapshotCount -gt 0)
@@ {
@@ $d = Get-Date
@@ $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
@@ [void]$MessagesListBox.items.add($MsgLine)
@@ }
Else
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - No VM is present on the source datastore $SourceDBname."
[void]$MessagesListBox.items.add($MsgLine)
}
$SourceDBListBox.enabled = $true
$SourceButton.enabled = $true
$DestinationListBox.Items.Clear()
$MigrateButton.Enabled = $false
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
$RESETButton_OnClick=
{
#TODO: Place custom script here
$ClusterListBox.Enabled = $true
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
}
$ChangeVCButton_OnClick=
{
#TODO: Place custom script here
$VCTextBox.Text = ""
$VCTextBox.Enabled = $true
$LoginButton.Enabled = $true
$ClusterListBox.Items.Clear()
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$ResetButton.Enabled = $false
$ChangeVCButton.Enabled = $false
$MessagesListBox.Items.Clear()
$TaskListBox.Items.Clear()
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
If ($VCTextBox.Text -ne "")
{
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
#Close Form
$MigrationForm.close()
}
$ClearMsgButton_Click=
{
#TODO: Place custom script here
If($MessagesListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('No messages to clear.')
}
Else
{
$MessagesListBox.items.clear()
}
}
$UndoButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
If ($TaskListBox.SelectedItems.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please select one or more tasks.')
}
Else
{
foreach($Task in $TaskListBox.SelectedItems)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
@@ $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
@@ ElseIf ($SnapshotCount -gt 0)
@@ {
@@ $d = Get-Date
@@ $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
@@ [void]$MessagesListBox.items.add($MsgLine)
@@ }
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
While($TaskListBox.SelectedItems.Count -gt 0)
{
$TaskListBox.Items.Remove($TaskListBox.SelectedItems[0])
}
}
}
}
$UndoALLButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
foreach($Task in $TaskListBox.Items)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
@@ $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
@@ ElseIf ($SnapshotCount -gt 0)
@@ {
@@ $d = Get-Date
@@ $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
@@ [void]$MessagesListBox.items.add($MsgLine)
@@ }
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$TaskListBox.Items.Clear()
}
}
$SaveTaskButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Nothing to save to log file.')
}
Else
{
$SaveFileD = new-object System.Windows.Forms.SaveFileDialog
$SaveFileD.Filter = "Log Files (*.log)|*.log";
$SaveFileD.Title = "Save to a log file";
$SaveFileD.FilterIndex = 2;
$SaveFileD.RestoreDirectory = $true;
if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $SaveFileD.FileName
$Tasks = $TaskListBox.items
$logheader = "Easy Migration Tool v2.0 - Log generated on " + (Get-Date)
#Save a log file for this session to a location selected by the user
Out-File -InputObject $logheader -FilePath $Filename
Out-File -InputObject "" -Append -FilePath $FileName
Out-File -InputObject $Tasks -Append -FilePath $FileName
}
}
}
$ReloadTaskButton_Click=
{
#TODO: Place custom script here
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
#$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Log Files (*.log)|*.log"
if ($OpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $OpenFileDialog.FileName
$LinesCount = (Get-Content $FileName).Count
$LogLines = Get-Content $FileName | Select -Last ($LinesCount - 2)
$TaskListBox.Items.Clear()
foreach ($LogLine in $LogLines)
{
[void]$TaskListBox.items.add($LogLine)
}
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
#----------------------------------------------
#region Generated Form Code
# Start Main Form
$MigrationForm.Text = 'Easy Migration Tool v2.0'
$MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MigrationForm.Name = 'EasyMigrationForm'
$MigrationForm.StartPosition = "CenterScreen"
$MigrationForm.FormBorderStyle = "FixedDialog"
$MigrationForm.MaximizeBox = $false
$MigrationForm.MinimizeBox = $false
$MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1030
$System_Drawing_Size.Height = 500
$MigrationForm.ClientSize = $System_Drawing_Size
# End Main Form
#Start Easy_Migration Header
$Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold)
$Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$Header.Text = 'Easy Migration Tool v2.0'
$Header.Location = new-object System.Drawing.Point(150,15)
$Header.Size = new-object System.Drawing.Size(230, 20)
$MigrationForm.Controls.Add($Header)
#End Easy_Migration Header
# Start vCenter Server Label
$vCenterLabel.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$vCenterLabel.Size = $System_Drawing_Size
$vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$vCenterLabel.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 15
$System_Drawing_Point.Y = 50
$vCenterLabel.Location = $System_Drawing_Point
$vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$vCenterLabel.Name = 'vCenterLabel'
$MigrationForm.Controls.Add($vCenterLabel)
# End vCenter Server Label
# Start vCenter Textbox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 20
$VCTextBox.Size = $System_Drawing_Size
$VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8)
$VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$VCTextBox.Name = 'VCTextBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 50
$VCTextBox.Location = $System_Drawing_Point
$VCTextBox.TabIndex = 1
$MigrationForm.Controls.Add($VCTextBox)
# End vCenter Textbox
# Start Login Button
$LoginButton.TabIndex = 0
$LoginButton.Name = 'LoginButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$LoginButton.Size = $System_Drawing_Size
$LoginButton.Font = new-object System.Drawing.Font("Tahoma",8)
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.Text = 'Login'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 48
$LoginButton.Location = $System_Drawing_Point
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$LoginButton.add_Click($LoginButton_Click)
$MigrationForm.Controls.Add($LoginButton)
# End Login Button
# Start Change VC Button
$ChangeVCButton.TabIndex = 19
$ChangeVCButton.Name = 'ChangeVCButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$ChangeVCButton.Size = $System_Drawing_Size
$ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ChangeVCButton.UseVisualStyleBackColor = $True
$ChangeVCButton.Text = 'Change vCenter'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 355
$System_Drawing_Point.Y = 48
$ChangeVCButton.Location = $System_Drawing_Point
$ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ChangeVCButton.add_Click($ChangeVCButton_OnClick)
$ChangeVCButton.Enabled = $false
$MigrationForm.Controls.Add($ChangeVCButton)
# End Change VC Button
# Start Cluster Listbox
$ClusterLabel.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 85
$System_Drawing_Size.Height = 20
$ClusterLabel.Size = $System_Drawing_Size
$ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$ClusterLabel.Text = 'Select Cluster:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 90
$ClusterLabel.Location = $System_Drawing_Point
$ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterLabel.Name = 'ClusterLabel'
$MigrationForm.Controls.Add($ClusterLabel)
$ClusterListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 100
$ClusterListBox.Size = $System_Drawing_Size
$ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterListBox.Name = 'ClusterListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 90
$ClusterListBox.Location = $System_Drawing_Point
$ClusterListBox.MultiColumn = $false
$ClusterListBox.TabIndex = 5
$ClusterListBox.Sorted = $True
$MigrationForm.Controls.Add($ClusterListBox)
# End Cluster Listbox
# Start Host to Host Button
$HostToHostButton.TabIndex = 3
$HostToHostButton.Name = 'HostToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$HostToHostButton.Size = $System_Drawing_Size
$HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$HostToHostButton.UseVisualStyleBackColor = $True
$HostToHostButton.Text = 'Host to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 90
$HostToHostButton.Location = $System_Drawing_Point
$HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$HostToHostButton.add_Click($HostToHostButton_Click)
$HostToHostButton.Enabled = $false
$MigrationForm.Controls.Add($HostToHostButton)
# End Host to Host Button
# Start VM to Host Button
$VMToHostButton.TabIndex = 3
$VMToHostButton.Name = 'VMToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMToHostButton.Size = $System_Drawing_Size
$VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMToHostButton.UseVisualStyleBackColor = $True
$VMToHostButton.Text = 'VM to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 115
$VMToHostButton.Location = $System_Drawing_Point
$VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMToHostButton.add_Click($VMToHostButton_Click)
$VMToHostButton.Enabled = $false
$MigrationForm.Controls.Add($VMToHostButton)
# End VM to Host Button
# Start Datastore to Datastore Button
$DBtoDBButton.TabIndex = 3
$DBtoDBButton.Name = 'DBtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$DBtoDBButton.Size = $System_Drawing_Size
$DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DBtoDBButton.UseVisualStyleBackColor = $True
$DBtoDBButton.Text = 'Datastore to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 140
$DBtoDBButton.Location = $System_Drawing_Point
$DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DBtoDBButton.add_Click($DBtoDBButton_Click)
$DBtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($DBtoDBButton)
# End Datastore to Datastore Button
# Start VM to Datastore Button
$VMtoDBButton.TabIndex = 3
$VMtoDBButton.Name = 'VMtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMtoDBButton.Size = $System_Drawing_Size
$VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMtoDBButton.UseVisualStyleBackColor = $True
$VMtoDBButton.Text = 'VM to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 165
$VMtoDBButton.Location = $System_Drawing_Point
$VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMtoDBButton.add_Click($VMtoDBButton_Click)
$VMtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($VMtoDBButton)
# End VM to Datastore Button
# Start Source Host List Box
$SourceHostListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceHostListBox.Size = $System_Drawing_Size
$SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceHostListBox.Name = 'SourceHostListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceHostListBox.Location = $System_Drawing_Point
$SourceHostListBox.MultiColumn = $false
$SourceHostListBox.TabIndex = 5
$SourceHostListBox.Sorted = $True
$MigrationForm.Controls.Add($SourceHostListBox)
# End Source Host List Box
# Start Source Datastore List Box
$SourceDBListBox.FormattingEnabled = $True
$SourceDBListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceDBListBox.Size = $System_Drawing_Size
$SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceDBListBox.Name = 'SourceDBListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceDBListBox.Location = $System_Drawing_Point
$SourceDBListBox.MultiColumn = $false
$SourceDBListBox.HorizontalScrollBar = $true
$SourceDBListBox.TabIndex = 5
$SourceDBListBox.Sorted = $True
# End Source Datastore List Box
# Start Source VM List Box
$SourceVMListBox.FormattingEnabled = $True
$SourceVMListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceVMListBox.Size = $System_Drawing_Size
$SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceVMListBox.Name = 'SourceVMListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceVMListBox.Location = $System_Drawing_Point
$SourceVMListBox.MultiColumn = $false
$SourceVMListBox.TabIndex = 5
$SourceVMListBox.Sorted = $True
# End Source VM List Box
# Start Source Button
$SourceButton.TabIndex = 7
$SourceButton.Name = 'Source Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$SourceButton.Size = $System_Drawing_Size
$SourceButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceButton.UseVisualStyleBackColor = $True
$SourceButton.Text = 'Source'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 415
$SourceButton.Location = $System_Drawing_Point
$SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceButton.add_Click($SourceButton_OnClick)
$SourceButton.Enabled = $false
$MigrationForm.Controls.Add($SourceButton)
# End Source Button
# Start Destination List Box
$DestinationListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$DestinationListBox.Size = $System_Drawing_Size
$DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationListBox.Name = 'DestinationListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 210
$DestinationListBox.Location = $System_Drawing_Point
$DestinationListBox.HorizontalScrollBar = $true
$DestinationListBox.MultiColumn = $false
$DestinationListBox.TabIndex = 5
$DestinationListBox.Sorted = $True
$MigrationForm.Controls.Add($DestinationListBox)
# End Destination List Box
# Start Destination Button
$DestinationButton.TabIndex = 7
$DestinationButton.Name = 'Destination Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$DestinationButton.Size = $System_Drawing_Size
$DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationButton.UseVisualStyleBackColor = $True
$DestinationButton.Text = 'Destination'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 415
$DestinationButton.Location = $System_Drawing_Point
$DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationButton.add_Click($DestinationButton_OnClick)
$DestinationButton.Enabled = $false
$MigrationForm.Controls.Add($DestinationButton)
# End Destination Button
# Start Migrate Button
$MigrateButton.TabIndex = 7
$MigrateButton.Name = 'MigrateButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$MigrateButton.Size = $System_Drawing_Size
$MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8)
$MigrateButton.UseVisualStyleBackColor = $True
$MigrateButton.Text = 'Migrate'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 450
$MigrateButton.Location = $System_Drawing_Point
$MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0
$MigrateButton.add_Click($MigrateButton_OnClick)
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Add($MigrateButton)
# End Migrate Button
# Start RESET Button
$ResetButton.TabIndex = 19
$ResetButton.Name = 'ResetButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 140
$System_Drawing_Size.Height = 25
$ResetButton.Size = $System_Drawing_Size
$ResetButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ResetButton.UseVisualStyleBackColor = $True
$ResetButton.Text = 'Reset'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 450
$ResetButton.Location = $System_Drawing_Point
$ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ResetButton.add_Click($ResetButton_OnClick)
$ResetButton.Enabled = $false
$MigrationForm.Controls.Add($ResetButton)
# End RESET Button
# Start CLOSE Button
$CloseButton.TabIndex = 19
$CloseButton.Name = 'CloseButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$CloseButton.Size = $System_Drawing_Size
$CloseButton.Font = new-object System.Drawing.Font("Tahoma",8)
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.Text = 'Close'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 320
$System_Drawing_Point.Y = 450
$CloseButton.Location = $System_Drawing_Point
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$CloseButton.add_Click($CloseButton_OnClick)
$MigrationForm.Controls.Add($CloseButton)
# End CLOSE Button
# Start Messages ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$MessagesLabel.Size = $System_Drawing_Size
$MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MessagesLabel.Text = 'Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 50
$MessagesLabel.Location = $System_Drawing_Point
$MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesLabel.Name = 'MessagesLabel'
$MigrationForm.Controls.Add($MessagesLabel)
$MessagesListBox.FormattingEnabled = $True
$MessagesListBox.SelectionMode = "None"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 140
$MessagesListBox.Size = $System_Drawing_Size
$MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesListBox.Name = 'MessagesListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 70
$MessagesListBox.Location = $System_Drawing_Point
$MessagesListBox.MultiColumn = $false
$MessagesListBox.HorizontalScrollbar = $true
$MigrationForm.Controls.Add($MessagesListBox)
# End Messages ListBox
# Start Task ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$TaskLabel.Size = $System_Drawing_Size
$TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$TaskLabel.Text = 'Recent Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 215
$TaskLabel.Location = $System_Drawing_Point
$TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskLabel.Name = 'TaskLabel'
$MigrationForm.Controls.Add($TaskLabel)
$TaskListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 200
$TaskListBox.Size = $System_Drawing_Size
$TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskListBox.Name = 'TaskListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 235
$TaskListBox.Location = $System_Drawing_Point
$TaskListBox.MultiColumn = $false
$TaskListBox.HorizontalScrollbar = $true
$TaskListBox.SelectionMode = "MultiExtended"
$MigrationForm.Controls.Add($TaskListBox)
# End Task ListBox
# Start Clear Messages Button
$ClearMsgButton.TabIndex = 0
$ClearMsgButton.Name = 'ClearMsgButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ClearMsgButton.Size = $System_Drawing_Size
$ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ClearMsgButton.UseVisualStyleBackColor = $True
$ClearMsgButton.Enabled = $false
$ClearMsgButton.Text = 'Clear Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 450
$ClearMsgButton.Location = $System_Drawing_Point
$ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ClearMsgButton.add_Click($ClearMsgButton_Click)
$MigrationForm.Controls.Add($ClearMsgButton)
# End Clear Messages Button
# Start Undo Button
$UndoButton.TabIndex = 0
$UndoButton.Name = 'UndoButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoButton.Size = $System_Drawing_Size
$UndoButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoButton.UseVisualStyleBackColor = $True
$UndoButton.Enabled = $false
$UndoButton.Text = 'Undo'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 588
$System_Drawing_Point.Y = 450
$UndoButton.Location = $System_Drawing_Point
$UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoButton.add_Click($UndoButton_Click)
$MigrationForm.Controls.Add($UndoButton)
# End Undo Button
# Start UndoALL Button
$UndoALLButton.TabIndex = 0
$UndoALLButton.Name = 'UndoALLButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoALLButton.Size = $System_Drawing_Size
$UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoALLButton.UseVisualStyleBackColor = $True
$UndoALLButton.Enabled = $false
$UndoALLButton.Text = 'Undo ALL'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 696
$System_Drawing_Point.Y = 450
$UndoALLButton.Location = $System_Drawing_Point
$UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoALLButton.add_Click($UndoALLButton_Click)
$MigrationForm.Controls.Add($UndoALLButton)
# End UndoALL Button
# Start Save Task Button
$SaveTaskButton.TabIndex = 0
$SaveTaskButton.Name = 'SaveTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$SaveTaskButton.Size = $System_Drawing_Size
$SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SaveTaskButton.UseVisualStyleBackColor = $True
$SaveTaskButton.Enabled = $false
$SaveTaskButton.Text = 'Save Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 804
$System_Drawing_Point.Y = 450
$SaveTaskButton.Location = $System_Drawing_Point
$SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SaveTaskButton.add_Click($SaveTaskButton_Click)
$MigrationForm.Controls.Add($SaveTaskButton)
# End Save Task Button
# Start Load Task Button
$ReloadTaskButton.TabIndex = 0
$ReloadTaskButton.Name = 'ReloadTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ReloadTaskButton.Size = $System_Drawing_Size
$ReloadTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ReloadTaskButton.UseVisualStyleBackColor = $True
$ReloadTaskButton.Enabled = $false
$ReloadTaskButton.Text = 'Reload Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 912
$System_Drawing_Point.Y = 450
$ReloadTaskButton.Location = $System_Drawing_Point
$ReloadTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ReloadTaskButton.add_Click($ReloadTaskButton_Click)
$MigrationForm.Controls.Add($ReloadTaskButton)
# End Load Task Button
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $MigrationForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$MigrationForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$MigrationForm.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Get-SiSReport_4.ps1
|
Get-SiSReport_4.ps1
|
Function Get-SiSReport
{
<#
.SYNOPSIS
Get the overall SIS usage information.
.DESCRIPTION
This function uses the sisadmin command to get the usage
information for a SIS enabled drive.
.PARAMETER SisDisk
The drive letter of a disk that has SiS enabled
.EXAMPLE
Get-SiSReport -SisDisk o
LinkFiles : 20004
Used : 442378481664
Disk : o
InaccessibleLinkFiles : 0
CommonStoreFiles : 6678
SpaceSaved : 7708860 KB
Free : 0
Description
-----------
This example shows the basic usage of the command
.NOTES
This function will return nothing if the drive being analyzed does not have SiS enabled
This function will return a message if the sisadmin command returns any error
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-SiSReport
#>
Param
(
$SisDisk = "c:"
)
Begin
{
If ($SisDisk.Contains(":") -eq $False)
{
$SisDisk += ":"
}
$SisAdmin = "& sisadmin /v $($SisDisk)"
Try
{
$SisResult = Invoke-Expression $SisAdmin
}
Catch
{
Return "Single Instance Storage is not available on this computer"
}
}
Process
{
If ($SisResult.Count)
{
$ThisDisk = Get-PSDrive $SisDisk
$SisReport = New-Object -TypeName PSObject -Property @{
"Disk" = $SisDisk
"Used (GB)" = [math]::round(($ThisDisk.Used /1024 /1024 /1024),2)
"Free (GB)" = [math]::round(($ThisDisk.Free /1024 /1024 /1024),2)
"Common Store Files" = ($SisResult[($SisResult.Count)-4]).TrimStart("Common store files:")
"Link Files" = ($SisResult[($SisResult.Count)-3]).TrimStart("Link files:")
"Inaccessible Link Files" = ($SisResult[($SisResult.Count)-2]).TrimStart("Inaccessible link files:")
"Space Saved (GB)" = [math]::round(((($SisResult[($SisResult.Count)-1]).TrimStart("Space saved:")).TrimEnd(" KB")/1024 /1024),2)
}
}
}
End
{
Return $SisReport
}
}
|
PowerShellCorpus/PoshCode/Skip-Object_1.ps1
|
Skip-Object_1.ps1
|
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 { $_ }
}
}
}
|
PowerShellCorpus/PoshCode/Add-Slide.ps1
|
Add-Slide.ps1
|
function Add-Slide($pres, $maxShared, $vmUsages, $vmShared, $maxVM, $vmLoad) {
$slide = $pres.slides.range(1).duplicate()
#$totalSlides = ($pres.slides | Measure-Object).Count
#$pres.slides.range(2).moveto($totalSlides)
#region 1
# Add all the boxes. Skip the first position.
$i = 1
foreach ($position in $xOffsets[1..5]) {
$shape = $slide.shapes.addShape(5, $position*72, $vmBoxYOffset*72, $vmBoxSize[0]*72, $vmBoxSize[1]*72)
# Label the name.
$shape.textframe2.textrange.text = "XXX"
$shape.textframe2.textrange.font.size = 24
$shape.line.visible = 0
# Color the VMs based on their load. We do this by selecting some
# fixed HSL endpoints to represent red and green. Luckily yellow is
# in the middle of these in HSL space. Load is between 0 and 100 so
# 0 load gives you a green box, 50 a yellow box, 100 a red box.
$load = $vmLoad[$i-1]
$H = 81 - (81 * $load / 100)
$S = 63 + (46 * $load / 100)
$shape.fill.forecolor.rgb = From-Hsl $H $S 138
# Switch to gradient fill.
$shape.fill.OneColorGradient(1, 2, 0.6)
$i++
}
#endregion
#region 2
# Add the memory profile. First a shared pool box.
$shared = ($vmShared | measure-object -sum).Sum
$perSize = $shared / $maxShared
$maxHeight = ($memBoxYBottom - $memBoxYTop)
$height = $maxHeight * $perSize
$yOffset = $memBoxYTop + ($maxHeight * (1 - $perSize))
$shape = $slide.shapes.addShape(1, $xOffsets[0]*72, $yOffset*72, $vmBoxSize[0]*72, $height*72)
$shape.line.visible = 0
# Only display the text if there is room.
if ($perSize -gt 0.25) {
$shape.textframe2.textrange.text = "Xyzzy"
$shape.textframe2.textrange.font.size = 24
}
# This one is always green.
$shape.fill.forecolor.rgb = 5880731
# Gradient fill.
$shape.fill.OneColorGradient(1, 2, 0.6)
#endregion
#region 3
# Obscure memory stuff..
foreach ($i in 0..4) {
# Total memory for this VM.
$profile = @($vmShared[$i], $vmUsages[$i])
$vmTotal = $profile[0] + $profile[1]
$vmPercent = $vmTotal / $maxVM
# Calculate the heights.
$maxHeight = ($memBoxYBottom - $memBoxYTop)
$height = $maxHeight * $vmPercent
$height1 = $height * ($profile[0] / $vmTotal)
$height2 = $height * ($profile[1] / $vmTotal)
$yOffset1 = $memBoxYTop + ($maxHeight * (1 - $vmPercent))
$yOffset2 = $yOffset1 + $height1
# Make the boxes.
$shape = $slide.shapes.addShape(1, $xOffsets[$i+1]*72, $yOffset1*72, $vmBoxSize[0]*72, $height1*72)
$shape.line.visible = 0
if ($height1 -gt 0.4) {
$shape.textframe2.textrange.text = "Something"
$shape.textframe2.textrange.font.size = 24
}
# Another green.
$shape.fill.forecolor.rgb = 5880731
$shape.fill.OneColorGradient(1, 2, 0.6)
$shape = $slide.shapes.addShape(1, $xOffsets[$i+1]*72, $yOffset2*72, $vmBoxSize[0]*72, $height2*72)
$shape.line.visible = 0
if ($height2 -gt 0.4) {
$shape.textframe2.textrange.text = "Something Else"
$shape.textframe2.textrange.font.size = 24
}
$shape.fill.forecolor.rgb = 4626167
$shape.fill.OneColorGradient(1, 2, 0.6)
}
#endregion
}
|
PowerShellCorpus/PoshCode/Get-StringRange_1.ps1
|
Get-StringRange_1.ps1
|
## Works great for a..f or g..a
## BUT WEIRD for Z..a or A..a or anything non-latin
function Get-CharRange ( [char]$Start, [char]$End ) {
[char[]]($Start..$End)
}
## Cleaner output. Try Get-LetterRange A z vs. Get-CharRange A z
## And international. ## Get-LetterRange 0x0370 0x03FF Greek
## You just specify the character set by name, anything from Arabic and Armenian,
## Bengali, Cherokee, Cyrillic, to Greek, Hebrew, Mongolian, and so on.
## http://msdn.microsoft.com/en-us/library/20bw873z.aspx
function Get-LetterRange ( [char]$Start, [char]$End, [string]$charset = "BasicLatin" ) {
[char[]]($Start..$End) | Where { $_ -match "(?=\\p{Is$charset})\\p{L}" }
}
|
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_4.ps1
|
Get Twitter RSS Feed_4.ps1
|
param ([String] $ScreenName)
$client = New-Object System.Net.WebClient
$idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName"
$data = $client.DownloadString($idUrl)
$start = 0
$findStr = '"id":'
do {
$start = $data.IndexOf($findStr, $start + 1)
if ($start -gt 0) {
$start += $findStr.Length
$end = $data.IndexOf(',', $start)
$userId = $data.SubString($start, $end-$start)
}
} while ($start -le $data.Length -and $start -gt 0)
$feed = "http://twitter.com/statuses/user_timeline/$userId.rss"
$feed
|
PowerShellCorpus/PoshCode/HttpRest 1.1.1.ps1
|
HttpRest 1.1.1.ps1
|
#requires -version 2.0
## HttpRest module
####################################################################################################
## Initial stages of changing HttpRest into a v2-only module
## Based on the REST api from MindTouch's Dream SDK
##
## INSTALL:
## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK
## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
## Unpack it, and you can find these dlls in the "dist" folder.
## Make sure to put them in the folder with this script module.
##
## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream
####################################################################################################
## Version History
## 1.0 First Release
## 1.0.1 Added Get-WebPageContent
## 1.0.2 Bug fix for Invoke-Http credential issues
## 1.1.0 First release of a PowerShell 2.0 (CTP3/Windows7) version....
## 1.1.1 Added Get-WebPageText and Get-Webfile ... cleaned up options
####################################################################################################
## Usage:
## function Get-Google {
## Invoke-Http GET http`://www.google.com/search @{q=$args} |
## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
## }
## #########################################################################
## function Get-WebFile($url,$cred) {
## Invoke-Http GET $url -auth $cred | Receive-Http File
## }
## #########################################################################
## function Send-Paste {
## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
## PROCESS {
## if($_){[IO.FileInfo]$file=$_}
##
## if($file.Exists) {
## $ofs="`n"
## $result = Invoke-Http POST $PastebinURI @{
## format="posh" # PowerShell
## expiry="d" # (d)ay or (m)onth or (f)orever
## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1])
## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
## paste="Send"
## } -Type FORM_URLENCODED -Wait
## $xml = $result.AsDocument().ToXml()
## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
## } else { throw "File Not Found" }
## }}
##
####################################################################################################
if(!$PSScriptRoot){
Write-Debug $($MyInvocation.MyCommand | out-string)
$PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
}
# Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
# Write-Debug "Invocation: $($MyInvocation.MyCommand)"
# Write-Debug "Invocation: $($MyInvocation)"
Write-Debug "PSScriptRoot: '$PSScriptRoot'"
# This Module depends on MindTouch.Dream
$null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" )
# MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
# This Module also depends on utility functions from System.Web
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
## Some utility functions are defined at the bottom
[uri]$global:url = ""
[System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
function Get-DreamMessage($Content,$Type) {
Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})"
if(!$Content) {
Write-Verbose "No Content"
return [MindTouch.Dream.DreamMessage]::Ok()
}
if( $Content -is [System.Xml.XmlDocument]) {
Write-Verbose "Xml Content"
return [MindTouch.Dream.DreamMessage]::Ok( $Content )
}
if(Test-Path $Content -EA "SilentlyContinue") {
Write-Verbose "File Content"
return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
}
if($Type -is [String]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
$Type = [MindTouch.Dream.MimeType]::$Type
}
if($Type -is [MindTouch.Dream.DreamMessage]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
} else {
Write-Verbose "Unspecified string content"
return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
}
}
function Get-DreamPlug {
[CmdletBinding()]
PARAM ( $Url, [hashtable]$With )
if($Url -is [array]) {
Write-Verbose "URL is an array of parts"
if($Url[0] -is [hashtable]) {
Write-Verbose "URL is an array of hashtable parts"
$plug = [MindTouch.Dream.Plug]::New($global:url)
foreach($param in $url.GetEnumerator()) {
if($param.Value) {
$plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
} else {
$plug = $plug.At($param.Key)
}
}
}
else
{
[URI]$uri = Join-Url $global:url $url
$plug = [MindTouch.Dream.Plug]::New($uri)
}
}
elseif($url -is [string])
{
Write-Verbose "String URL"
trap { continue }
[URI]$uri = $url
if(!$uri.IsAbsoluteUri) {
$uri = Join-Url $global:url $url
Write-Verbose "Relative URL, appending to $($global:url) to get: $uri"
}
$plug = [MindTouch.Dream.Plug]::New($uri)
}
else {
Write-Verbose "No URL, using default $($global:url)"
$plug = [MindTouch.Dream.Plug]::New($global:url)
}
if($with) {
foreach($param in $with.GetEnumerator()) {
if($param.Value) {
$plug = $plug.With($param.Key,$param.Value)
}
}
Write-Verbose "Added 'with' params: $plug"
}
return $plug
}
#CMDLET Receive-Http {
Function Receive-Http {
PARAM(
# [Parameter(Position=1, Mandatory=$false)]
# [ValidateSet("Xml", "File", "Text","Bytes")]
# [Alias("As")]
$Output = "Xml"
,
# [Parameter(Position=2, Mandatory=$false)]
[string]$Path
,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
# [Alias("IO")]
# [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
$InputObject
#,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
# [MindTouch.Dream.DreamMessage]
# $response
)
BEGIN {
if($InputObject) {
Write-Output $inputObject | Receive-Http $Output $Path
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
$response = $null
if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
$response = $_.Wait()
} elseif($_ -is [MindTouch.Dream.DreamMessage]) {
$response = $_
} elseif($_) {
throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
}
if($response) {
Write-Debug $($response | Out-String)
if(!$response.IsSuccessful) {
Write-Error $($response | Out-String)
Write-Verbose $response.AsText()
throw "ERROR: '$($response.Status)' Response Status."
} else {
switch($Output) {
"File" {
## Joel's magic filename guesser ...
if(!$Path) {
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
$Path = $fileName.trim("\\/""'")
if(!$Path){
if($response.ResponseUri) {
$fileName = $response.ResponseUri.Segments[-1]
$Path = $fileName.trim("\\/")
if(!([IO.FileInfo]$Path).Extension) {
$Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
}
}
}
}
if($Path) {
$File = Get-FileName $Path
} else {
$File = Get-FileName
}
$null = [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
Get-ChildItem $File
}
"XDoc" {
if($Path) {
$response.AsDocument()[$Path]
} else {
$response.AsDocument()#.ToXml()
}
}
"Xml" {
if($Path) {
$response.AsDocument().ToXml().SelectNodes($Path)
} else {
$response.AsDocument().ToXml()
}
}
"Text" {
if($Path) {
$response.AsDocument()[$Path] | % { $_.AsText }
} else {
$response.AsText()
}
}
"Bytes" {
$response.AsBytes()
}
}
}
}
}
}
## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
## Nobody actually uses HEAD or OPTIONS, right?
## And nobody's even heard of TRACE or CONNECT ;)
# CMDLET Invoke-Http {
Function Invoke-Http {
[CmdletBinding(DefaultParameterSetName="NoCredentials")]
PARAM(
[Parameter(Position=0, Mandatory=$false)]
[ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
[string]$Verb = "Get"
,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Path
,
[Parameter(Position=2, Mandatory=$false)]
[hashtable]$with
,
[Parameter(Mandatory=$false)]
$Content
,
[Parameter(Mandatory=$false)]
$Cookies
,
[Parameter(Mandatory=$false)]
$Type # Of Content
,
[Parameter(ParameterSetName="UseDefaultCredentials")]
[switch]$authenticate
,
[Parameter(ParameterSetName="ManualCredentials")]
$credentials
,
[Parameter(Mandatory=$false)]
[switch]$Persistent ## Note this ALSO causes WaitForResponse
,
[switch]$waitForResponse
)
PROCESS {
$plug = Get-DreamPlug $Path $With
Write-Verbose "Content Type: $Type"
Write-Verbose "Content: $Content"
## Special Handling for FORM_URLENCODED
if($Type -like "Form*" -and !$Content) {
$dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
$Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
} else {
$dream = Get-DreamMessage $Content $Type
Write-Verbose "Created Dream with Content: $($dream.Content)"
}
if(!$plug -or !$dream) {
throw "Can't come up with a request!"
}
if($Persistent -and $global:HttpRestCookies) {
$dream.Cookies.Add( $global:HttpRestCookies );
}
if($Cookies) {
$dream.Cookies.Add( $Cookies );
}
Write-Verbose $("DREAM!",$dream | Out-String )
if($authenticate -or $credentials){
if($credentials -is [System.Management.Automation.PSCredential]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} elseif($credentials -is [System.Net.ICredentials]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} else {
if($credentials) {
Write-Error "Credential must be a PSCredential or a System.Net.ICredentials"
}
$null = Get-HttpCredential # Make sure they have global credentials
Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)"
$plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential())
}
}
Write-Verbose $plug.Uri
## DEBUG:
Write-Debug "URI: $($Plug.Uri)"
Write-Debug "Verb: $($Verb.ToUpper())"
Write-Debug $($dream | Out-String)
$result = $plug.InvokeAsync( $Verb.ToUpper(), $dream )
Write-Debug $($result | Out-String)
# if($DebugPreference -eq "Continue") {
# Write-Debug $($result.Wait() | Out-String)
# }
if($waitForResponse -or $Persistent) {
$result = $result.Wait()
$global:HttpRestCookies = $result.Cookies
}
write-output $result
trap [MindTouch.Dream.DreamResponseException] {
Write-Error @"
TRAPPED DreamResponseException
$($_.Exception.Response | Out-String)
$($_.Exception.Response.Headers | Out-String)
"@
break;
}
}
}
function Get-WebPageContent {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[string]$url
,
[Parameter(Position=1,Mandatory=$false)]
[string]$xpath=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
BEGIN { $out = "Text"; if($Xml) { $out="Xml" } }
PROCESS {
invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http xml $xpath
}
}
function Get-WebPageText {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[string]$url
,
[Parameter(Position=1,Mandatory=$false)]
[string]$xpath=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
BEGIN { $out = "Text"; if($Xml) { $out="Xml" } }
PROCESS {
invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http text $xpath
}
}
function Get-WebFile {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[string]$url
,
[Parameter(Position=1,Mandatory=$false)]
[string]$path=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
PROCESS {
Invoke-Http GET $url $with -Authenticate:$Authenticate -Persist:$Persist | Receive-Http File $path
}
}
new-alias gwpc Get-WebPageContent -EA "SilentlyContinue"
new-alias http Invoke-Http -EA "SilentlyContinue"
new-alias rcv Receive-Http -EA "SilentlyContinue"
# function Get-Http { return Invoke-Http "GET" @args }
# function New-Http { return Invoke-Http "PUT" @args }
# function Update-Http { return Invoke-Http "POST" @args }
# function Remove-Http { return Invoke-Http "DELETE" @args }
# new-alias Set-Http Update-Http
# new-alias Put-Http New-Http
# new-alias Post-Http Update-Http
# new-alias Delete-Http Remove-Http
function Set-HttpDefaultUrl {
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
$global:url = $baseUri
}
function Set-HttpCredential {
param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $($global:url.Host)) )
if($Credential -is [System.Management.Automation.PSCredential]) {
$global:HttpRestCredential = $Credential
} elseif($Credential -is [System.Net.NetworkCredential]) {
$global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
}
}
function Get-HttpCredential {
if(!$global:url) { Set-HttpDefaultUrl }
if(!$global:HttpRestCredential) { Set-HttpCredential }
if(!$Secure) {
return $global:HttpRestCredential.GetNetworkCredential();
} else {
return $global:HttpRestCredential
}
}
# function Authenticate-Http {
# PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
# $plug = [MindTouch.Dream.Plug]::New( $global:url )
# $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
# }
function ConvertTo-UrlDoubleEncode {
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
New-Alias Encode-Twice ConvertTo-UrlDoubleEncode
function Join-Url ( [uri]$baseUri=$global:url ) {
$ofs="/";$BaseUrl = ""
if($BaseUri -and $baseUri.AbsoluteUri) {
$BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
}
return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
}
function ConvertTo-SecureString {
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
## Unit-Test Get-FileName ## Should return TRUE
## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and
## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe"
function Get-FileName {
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
## if the $Path has a file name, and it's folder exists:
if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
$path
## if the $Path is just a folder (and it exists)
} elseif($Path -and (Test-Path $path -Type Container)) {
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
## If there's no valid $Path, and the $FileName has a folder...
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
$fileName
} else {
Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
}
}
function Get-UtcTime {
Param($Format="yyyyMMddhhmmss")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
## Get-CredentialBetter
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-CredentialBetter{
PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
$ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds"
## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
$cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
## Compare to $True, because by default it's $null ...
$cp = $cp.ConsolePrompting -eq $True
if($Console -and !$cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $True
} elseif(!$Console -and $Console.IsPresent -and $cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $False
}
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
$Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
Set-ItemProperty $ShellIdKey ConsolePrompting $cp -ea "SilentlyContinue"
}
Export-ModuleMember -Function * -Alias *
# Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl
# SIG # Begin signature block
# MIIIPgYJKoZIhvcNAQcCoIIILzCCCCsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUQoaUUrGbT13oF6YhXlqqJ9qf
# SqOgggVbMIIFVzCCBD+gAwIBAgIRAO2rPg5HUjL4ofGGpnMP2jwwDQYJKoZIhvcN
# AQEFBQAwgZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2Fs
# dCBMYWtlIENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8G
# A1UECxMYaHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNF
# UkZpcnN0LU9iamVjdDAeFw0wODEwMDYwMDAwMDBaFw0wOTEwMDYyMzU5NTlaMIHE
# MQswCQYDVQQGEwJVUzEOMAwGA1UEEQwFMTQ2MjMxETAPBgNVBAgMCE5ldyBZb3Jr
# MRIwEAYDVQQHDAlSb2NoZXN0ZXIxFDASBgNVBAkMC01TIDA4MDEtMTdBMRowGAYD
# VQQJDBExMzUwIEplZmZlcnNvbiBSZDEaMBgGA1UECgwRWGVyb3ggQ29ycG9yYXRp
# b24xFDASBgNVBAsMC1NFRURVIFRvb2xzMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK50RXT2KUvECfWZ
# weqeXzTCykPPRh9nC3Hzur/mmvkQHA8iinnSKX4j19C1/MV0rAEeCU1bF7Sgxvov
# ORreM1Ye/wEqJLAUP/IGZI/qsmmwasGFGbnuevpA3WieNCr5cFGl8Y5Mx6ejaDFi
# O0GT9EM6gOGZaEEMRbHZc4qXT7CrWScs4Yur5bBZsowaMk5JkvZgihhnN93QolEW
# ObmtQZlbBDqLuoL9fUnIexlqqIrC/4h0K8VM26HvqhgGlQF2wf4t9xCHFJiX2F7D
# B10lef5aXzyPVrvxxrRWyBtCQuL7xdXneRanJaYG3B3kclc+4/6dq9a+s/huXjmE
# omumgGcCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBT5ITlG5CdiD+nI0uTqnXNGnd44QjAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAZxnV+BbJBohpy+wKs6U8hRiPUhDYaijzTyrZontf5
# PEyBbhAkJFIWauIaq9eSQEJeErXO/zuO6+wY/azBzOTleMM9qdGWHFtfAw5WiIuC
# 90TzDBSuP7LImZV5Pb6nxRbesDF2U7EM5sBzYSWAMfpBmYRz97EHPW5QNzpBLFJn
# Dhb/M27rDYh7FVjy1+C5E3glIa0A0q+lcxEtFuUij4JId+oMcfpSgYJZvR1Kvkjd
# GDAtWCzvALaNFd65kChbrOqcClOCacQRnP9N4DJl/RVNKZtcUcVAyTpvOlJBA5vG
# OVcsJT4TnSMjPX6d5pXMwcE1oWCUWvK99W+N81DvBBuZMYICTTCCAkkCAQEwgasw
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIRAO2rPg5HUjL4ofGGpnMP2jwwCQYFKw4DAhoFAKB4MBgGCisGAQQB
# gjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYK
# KwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFDt2csas
# cPdhVfQXLYSciOvpftO/MA0GCSqGSIb3DQEBAQUABIIBAKFpe16JPkouVrUMZZQ1
# 5oOiDnb/XVyBdvQw9DSEOi/g6lbdITlTo9RElg+yWO+w4+igiNYTpS3xyUZ00TI4
# DxWToZuOYXr+a/LseWpg/T/HVGzYT94ZBhEIsz0jpnlwvKt4qcU/tYCDDf+1Yoqk
# P62qr1pnpNEVDEtPWWzlS/iNZNk3SmcVaNg/FL7dLCXsyqyWAS72d3EIKH3CbaPG
# raoxSWRGnsk+qOiAT3lD4luyCc6O+cUg3LwtPLghzYFpW16HCJrCmsNbtwqjnzX4
# Uqs9jRvwirRD5NtABEFpYabxn+a0zUW+nI1Pca4d4CBEvbU4mpdgvStsoizaC+5W
# 20k=
# SIG # End signature block
|
PowerShellCorpus/PoshCode/ConvertToStringData.ps1
|
ConvertToStringData.ps1
|
function ConvertTo-StringData
{
Begin
{
$string = "@{`n"
function Expand-Value
{
param($value)
if ($value -ne $null) {
switch ($value.GetType().Name)
{
'String' { "`"$value`"" }
'Boolean' { "`$$value" }
default { $value }
}
}
else
{ "`$null" }
}
}
Process
{
$string += $_.GetEnumerator() | foreach {"{0} = {1}`n" -f $_.Name,(Expand-Value $_.Value)}
}
End
{
$string += "}"
Write-Output $string
}
} #ConvertTo-StringData
|
PowerShellCorpus/PoshCode/BER Encoding Module.ps1
|
BER Encoding Module.ps1
|
<#
.SYNOPSIS
BER encoding library
.DESCRIPTION
Takes ASN types integer, octet (string), octet (byte array), and OID
(string) values and encodes into byte array using Basic Encoding Rules (BER)
BER encoding is used for SNMP, X.509 certificates, etc.
There will be a companion BER decoding library posted soon. There will also
be a SNMP library that makes use of BER encoding and decoding libraries
.NOTES
Author: Parul Jain, paruljain@hotmail.com
Version: 0.1, April 21, 2012
Requires: PowerShell v2 or better
.EXAMPLE
# The following constructs a GetRequest SNMP message based on
# http://www.rane.com/note161.html
$varbindList = encOID '1.3.6.1.4.1.2680.1.2.7.3.2.0' | encNull | encSeq | encSeq
$pdu = ((encInt 1 | encInt 0 | encInt 0) + $varbindList) | encSeq 0xA0
$message = ((encInt 0 | encOctet 'private') + $pdu) | encSeq
#>
# We need binary right shift for OID encoding. There is no shift in PS v2
# So we add it via inline C# code. Very cool!
Add-Type @"
public class Shift {
public static long Right(long x, int count) { return x >> count; }
}
"@
function byte2hex {
# Not really a part of this library. Helps debug the code
# Takes byte array and converts to hex printable string
[string]$ret = ''
$input | % { $ret += '{0:X2} ' -f $_ }
$ret.TrimEnd(' ')
}
function trimLeft([byte[]]$buffer) {
# Removes leading 0 value bytes from a byte array
$i = 0
while ($buffer[$i] -eq 0) { $i++ }
$buffer[$i..($buffer.length-1)]
}
function encLength([long]$length) {
# BER code is TLV - Type Length Value
# Length itself needs to be encoded if more than 127 bytes
# This function takes the length (of the Value) and encodes it
if ($length -lt 128) { return [byte]$length }
# The length is more than 127 so do the coding
$buffer = [BitConverter]::GetBytes($length)
# Reverse to make Big-endian
[Array]::Reverse($buffer)
# Eliminate leading zeros
[byte[]]$buffer = trimLeft $buffer
# Add length for the length and return
@(128 + $buffer.length) + $buffer
}
function encInt([int]$value) {
# Encodes Integer value to BER and adds to input stream
# BER type for integer is 2
$b = [BitConverter]::GetBytes($value)
[Array]::Reverse($b)
[byte[]]$b = trimLeft $b
$input + [byte[]](2, $b.length) + $b
}
function encOctet($buffer) {
# Encodes octet string to BER and adds to input stream
# The string can be provided as [string] or as [byte[]]
# BER type for octet string is 4
if ($buffer -is [string]) { $b = [Text.Encoding]::UTF8.GetBytes($buffer) }
elseif ($buffer -is [byte[]]) { $b = $buffer }
else { throw('Must be string or byte[] type') }
$input + [byte[]](4, (encLength $b.length)) + $b
}
function encOID ([string]$oid) {
# Encodes OID to BER and adds to input stream
# BER OID encoding is the most complex of all BER encoding
# BER type for OID is 6
# Remove any starting or trailing . from OID string
$oid = ($oid.TrimStart('.')).TrimEnd('.')
$octets = $oid.split('.')
if ($octets.count -lt 2) { throw 'Error: Invalid OID; must have at least two octects' }
if ([int]$octets[0] -gt 2 -or [int]$octets[1] -gt 39) { throw 'Error: Invalid OID' }
[byte[]]$buffer = @()
$buffer += 40 * [int]$octets[0] + [int]$octets[1] # First two octets encode special
# Encode remaining octets normally
if ($octets.count -gt 2) {
for($i=2; $i -lt $octets.count; $i++) {
[byte[]]$buff= @()
$value = [long]$octets[$i]
do {
$b = [System.BitConverter]::GetBytes($value)
$b[0] = $b[0] -bor 0x80
$buff += $b[0]
$value = [shift]::right($value, 7)
} until ($value -eq 0)
$buff[0] = $buff[0] -band 0x7F
[array]::Reverse($buff)
$buffer += $buff
}
}
$input + [byte[]](6, (encLength $buffer.length)) + $buffer
}
function encNull {
# Adds BER Null value to input stream
# BER type for Null is 5
$input + [byte[]](5, 0)
}
function encSeq([byte]$type=0x30) {
# Encodes input stream into a BER Sequence
# For BER Type, 0x30 is used by default but any other Type value can
# be provided
$buffer = @($input)
[byte[]]($type, (encLength $buffer.length)) + $buffer
}
|
PowerShellCorpus/PoshCode/Set-Computername_5.ps1
|
Set-Computername_5.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-Comment.ps1
|
Get-Comment.ps1
|
#Requires -version 3.0
<#
.Synopsis
Gets all of the comments from a script
.Description
Uses the PowerShell 3 Parser to figure out what's a comment
#>
[CmdletBinding()]
param( # The script, or the path to a script file
[String]$Script
)
# Convert paths to script contents (otherwise, assume they passed the contents)
if(Test-Path $Script) {
$Script = Get-Content $Script -Raw # Raw saves having to stitch the lines back together.
}
# You have to initialize these to something for the ParseInput call
$ParseError = $null
$Tokens = $null
$null = [System.Management.Automation.Language.Parser]::ParseInput($Script, [ref]$Tokens, [ref]$ParseError)
# All tokens have a "Kind" and "Text" but not all tokens are comments ;)
$Tokens | ? Kind -eq "Comment" | % Text
|
PowerShellCorpus/PoshCode/Convert-ToMP3.ps1
|
Convert-ToMP3.ps1
|
param([String] $inputPath, [String] $wildcard, [String] $outputPath = $inputPath
gci -path $inputPath\\$wildcard | % {
$outputFile = Join-Path $outputPath ($_.Name.Replace($_.Extension, '.mp3'))
vlc -I dummy $_.FullName ":sout=#transcode{acodec=mp3,ab=128,channels=6}:standard{access=file,mux=asf,dst=$outputFile}" vlc://quit
Get-Process vlc | % { $_.WaitForExit() }
}
|
PowerShellCorpus/PoshCode/NTFS ACLs Folder Tree_3.ps1
|
NTFS ACLs Folder Tree_3.ps1
|
#######################################
# TITLE: listACL.ps1 #
# AUTHOR: Santiago Fernandez Mu±oz #
# #
# DESC: This script generate a HTML #
# report show all ACLs asociated with #
# a Folder tree structure starting in #
# root specified by the user #
#######################################
param ([string] $computer = 'localhost',
[string] $path = $(if ($help -eq $false) {Throw "A path is needed."}),
[int] $level = 0,
[string] $scope = 'administrator',
[switch] $help = $false,
[switch] $debug = $false
)
#region Initializations and previous checkings
#region Initialization
$allowedLevels = 10
$Stamp = get-date -uformat "%Y%m%d"
$report = "$PWD\\$computer.html"
$comparison = ""
$UNCPath = "\\\\" + $computer + "\\" + $path + "\\"
#endregion
#region Previous chekings
#require -version 2.0
if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."}
if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path }
switch ($scope) {
micro {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")'
}
user {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")'
}
}
#endregion
#endregion
#region Function definitions
function drawDirectory([ref] $directory) {
$dirHTML = '
<div class="'
if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level }
$dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div>
<div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div>
<div class="container">
<div class="heACL">
<table class="info3" cellpadding="0" cellspacing="0">
<thead>
<th scope="col"><b>Owner</b></th>
<th scope="col"><b>Privileges</b></th>
</thead>
<tbody>'
foreach ($itemACL in $directory.value.ACL) {
$acls = $null
if ($itemACL.AccessToString -ne $null) {
$acls = $itemACL.AccessToString.split("`n")
}
$dirHTML += '<tr><td>' + $itemACL.Owner + '</td>
<td>
<table>
<thead>
<th>User</th>
<th>Control</th>
<th>Privilege</th>
</thead>
<tbody>'
foreach ($acl in $acls) {
$temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}")
if ($debug) {
write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp
}
if ($temp.count -eq 1) {
continue
}
if ($scope -ne 'administrator') {
if ( Invoke-Expression $comparison ) {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
} else {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
}
$dirHTML += '</tbody>
</table>
</td>
</tr>'
}
$dirHTML += '
</tbody>
</table>
</div>
</div>
</div>'
return $dirHTML
}
#endregion
#region Printing help message
if ($help) {
Write-Host @"
/ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ\\
Ę Script gather access control lists per directory Ę
\\ĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘĘ/
USAGE: ./listACL -computer <machine or IP>
-path <path>
-level <0-10>
-help:[$false]
PARAMETERS:
computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost)
path [REQUIRED] - Folder's path to query.
level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels.
0 show that there's no limit in the going down (Default: 0)
scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are:
Ę user, show important information to the user.
Ę micro, show user scope information plus important information for the IT Department.
Ę administrator, show all information.
help [OPTIONAL] - This help.
"@
exit 0
}
#endregion
if (Test-Path $report)
{
Remove-item $report
}
#To normalize I check if last character in the path is the folder separator character
if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) }
#region Header, style and javascript functions needed by the html report
@"
<html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
<title>Access Control List for $path in $computer</title>
<!-- Styles -->
<style type="text/css">
body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; }
table{ font-size:100%; table-layout:fixed; width:100%; }
td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; }
.title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; }
.he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; }
.he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; }
.he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; }
.he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; }
.he0 .expando{ font-size:100%; }
.info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; }
.disalign TD{ padding-bottom:5px; padding-right:10px; }
.info TD{ padding-right:10px; width:50%; }
.info3 TD{ padding-right:10px; width:33%; }
.info4 TD, .info4 TH{ padding-right:10px; width:25%; }
.info5 TD, .info5 TH{ padding-right:0px; width:20%; }
.info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; }
.subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; }
.subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; }
.subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; }
.subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; }
.subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; }
.explainlink{ color:#000000; text-decoration:none; cursor:pointer; }
.explainlink:hover{ color:#0000FF; text-decoration:underline; }
.spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; }
.filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; }
.container{ display:block; position:relative; }
.rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; }
.rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; }
#uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; }
#dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; }
#objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; }
#gposummary { display:block; }
#gpoinformation { display:block; }
</style>
</head>
<body>
<table class="title" cellpadding="0" cellspacing="0">
<tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr>
<tr>
<td id="dtstamp">Data obtained on: $(Get-Date)</td>
<td><div id="objshowhide" tabindex="0"></div></td>
</tr>
</table>
<div class="filler"></div>
"@ | Set-Content $report
#endregion
#region Information gathering
$colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName
$colACLs = @()
#We start going through the path pointed out by the user
foreach($file in $colFiles)
{
#To control the current level in the tree we are in it's needed to count the number of separator characters
#contained in the path. However in order to make the count correctly it's needed to delete the path
#provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be
#string used to do the level count.
#It's needed to use a REGEX object to get ALL separator character matches.
$matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count
if ($level -ne 0 -and ($matches - 1) -gt $level) {
continue
}
if ($debug) {
Write-Host $file.FullName "->" $file.Mode
}
if ($file.Mode -notlike "d*") {
continue
}
$myobj = "" | Select-Object Folder,ACL,level
$myobj.Folder = $file
$myobj.ACL = Get-Acl $file.FullName
$myobj.level = $matches - 1
$colACLs += $myobj
}
#endregion
#region Setting up the report
'<div class="gposummary">' | Add-Content $report
for ($i = 0; $i -lt $colACLs.count; $i++) {
drawDirectory ([ref] $colACLs[$i]) | Add-Content $report
}
'</div></body></html>' | Add-Content $report
#endregion
|
PowerShellCorpus/PoshCode/Get-Weather.ps1
|
Get-Weather.ps1
|
## Get-Weather
## Parse and display the current weather and forecast from yahoo RSS
## Note that you _could_ modify this a bit to return "current condition" and "forecast" objects
## but for now, it just prints them out in a relatively nice format
###################################################################################################
## Version History:
## 1.1 - Added TempColor function
## 1.0 - My initial cleanup of a script from
## http://fortheloveofcode.wordpress.com/2008/04/28/powershell-webservice-client/
#########
## ToDo: Color code the "text": Showers/Rain/Snow/...
## ToDo: Pull out extreme weather *Warnings*
## ToDo: Parse wind and show the wind-chill when temp is cold
###################################################################################################
# function get-weather {
param($zip=14586,[switch]$celcius)
$url = "http://weather.yahooapis.com/forecastrss?p={0}{1}" -f $zip, $(if($celcius){"&u=c"})
$channel = ([xml](New-Object Net.WebClient).DownloadString($url)).rss.channel
function TempColor ($temp) {
if($celcius) {
if( $temp -lt 0 ) { "blue" } elseif( $temp -lt 10 ) { "cyan" } elseif( $temp -lt 25 ) { "green" } elseif( $temp -lt 30 ) { "yellow" } else { "red" }
} else {
if( $temp -lt 5 ) { "blue" } elseif( $temp -lt 50 ) { "cyan" } elseif( $temp -lt 77 ) { "green" } elseif( $temp -lt 85 ) { "yellow" } else { "red" }
}
}
if($channel) {
$current = $channel.item.condition
Write-Host
Write-Host ("Location: {0}" -f $channel.location.city)
Write-Host ("Last Update: {0}" -f $channel.lastBuildDate)
Write-Host ("Weather: {0}" -f $current.text)-NoNewline
Write-Host (" {0}°{1}" -f $current.temp, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $current.temp)
Write-Host
Write-Host "Forecasts"
Write-Host "---------"
foreach ($f in $channel.item.forecast) {
Write-Host ("`t{0}, {1}: {2}" -f $f.day, $f.date, $f.text) -NoNewline
Write-Host (" {0}-{1}°{2}" -f $f.low, $f.high, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $f.High)
}
Write-Host
}
#}
|
PowerShellCorpus/PoshCode/Get-Pecoff.ps1
|
Get-Pecoff.ps1
|
function Get-Pecoff
{
<#
.SYNOPSIS
Takes file-name and outputs fileobject with two more properties
poff_characteristic and poff_machinetype
.DESCRIPTION
This function creates file objects with PE properties for characteristic and machinetype
.EXAMPLE
For output from get-childitem or any other cmdlet that produces file objects from Win7 x64 machine.
Get-ChildItem "C:\\Windows\\System32"|where {$_.Extension -like ".dll" -or $_.Extension -like ".exe"}|Get-Pecoff|select poff_machinetype,poff_characteristic,fullname|format-table -autosize
poff_machinetype poff_characteristic FullName
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\aaclient.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\accessibilitycpl.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ACCTRES.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acledit.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\aclui.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acppage.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\acproxy.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionCenter.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionCenterCPL.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\ActionQueue.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\activeds.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\actxprxy.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\AdapterTroubleshooter.exe
o
o
I386 EXECUTABLE,LINE_NUMS_STRIPPED,32BIT_MACHINE,LOCAL_SYMS_STRIPPED C:\\Windows\\System32\\TsWpfWrp.exe
o
AMD64 NET_RUN_FROM_SWAP,EXECUTABLE,REMOVABLE_RUN_FROM_SWAP,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xmllite.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xmlprovi.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xolehlp.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsFilt.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsGdiConverter.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsPrint.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XpsRasterService.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpsrchvw.exe
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpsservices.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\XPSSHHDR.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xpssvcs.dll
AMD64 EXECUTABLE,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwizard.exe
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwizards.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwreg.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwtpdui.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\xwtpw32.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\zgmprxy.dll
AMD64 EXECUTABLE,DLL,LARGE_ADDRESS_AWARE C:\\Windows\\System32\\zipfldr.dll
Where AMD64 means 64 bit app.
Where I386 means 32 bit app.
There are other archetectures than AMD64, I384: AM33 AMD64 ARM ARMV7 EBC IA64 M32R MIPS16 MIPSFPU MIPSFPU16
POWERPC POWERPCFP R4000 SH3 SH3DSP SH4 SH5 THUMB WCEMIPSV2
Where NoPE means file did not use PE standard
NoPE NoPE C:\\Windows\\SysWOW64\\typelib.dll
Where:
RELOCS_STRIPPED = 0x1,
Relocation info stripped from file.
EXECUTABLE = 0x2,
File is executable (i.e. no unresolved external references).
LINE_NUMS_STRIPPED = 0x4,
Line numbers stripped from file.
LOCAL_SYMS_STRIPPED = 0x8,
Local symbols stripped from file.
AGGRESSIVE_WS_TRIM = 0x10,
Aggressively trim working set
LARGE_ADDRESS_AWARE = 0x20,
For x86 applications:
on x86 OS
With special effort can allow access to 3Gb
on x64 OS
application can access 4GB
For x64 applications
on x64 OS
application can access 64 bits.
BYTES_REVERSED_LO = 0x80,
Bytes of machine word are reversed.
32BIT_MACHINE = 0x100,
32 bit word machine.
DEBUG_STRIPPED = 0x200,
Debugging info stripped from file in .DBG file
REMOVABLE_RUN_FROM_SWAP = 0x400,
If Image is on removable media, copy and run from the swap file.
Not Sure Why system32 files would have this but they are on my 64bit win 7
NET_RUN_FROM_SWAP = 0x800,
If Image is on Net, copy and run from the swap file.
Not Sure Why system32 files would have this but they are on my 64bit win 7
SYSTEM = 0x1000,
System File.
DLL = 0x2000,
File is a DLL.
UP_SYSTEM_ONLY = 0x4000,
File should only be run on a UP machine
BYTES_REVERSED_HI = 0x8000
Bytes of machine word are reversed.
If get-pecoff cannot determine the file characteristic it will display the hex instead.
This has been useful in debugging the table.
.EXAMPLE
For a single file:
Get-Pecoff -filename "C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\\x64\\MdbgCore.dll"|select poff_machinetype,poff_characteristic,fullname|format-table -autosize
.PARAMETER filename
The full path of file to query.
Get-Pecoff can take the output of getchilditem
Creates file object output that has pe characteristic and pe machinetype properties added
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[Alias('fullname')]
[string]$filename=""
)
process {
#"filename " + $filename
$characteristics = @{}
# these entries were prefixed with IMAGE_FILE_ such as IMAGE_FILE_EXECUTABLE
$characteristics["RELOCS_STRIPPED"] = 0x0001
$characteristics["EXECUTABLE"] = 0x0002
$characteristics["LINE_NUMS_STRIPPED"] = 0x0004
$characteristics["LOCAL_SYMS_STRIPPED"] = 0x0008
$characteristics["AGGRESSIVE_WS_TRIM"] = 0x0010
$characteristics["LARGE_ADDRESS_AWARE"] = 0x0020
$characteristics["RESERVED"] = 0x0040
$characteristics["BYTES_REVERSED_LO"] = 0x0080
$characteristics["32BIT_MACHINE"] = 0x0100
$characteristics["DEBUG_STRIPPED"] = 0x0200
$characteristics["REMOVABLE_RUN_FROM_SWAP"] = 0x0400
$characteristics["NET_RUN_FROM_SWAP"] = 0x0800
$characteristics["SYSTEM"] = 0x1000
$characteristics["DLL"] = 0x2000
$characteristics["UP_SYSTEM_ONLY"] = 0x4000
$characteristics["BYTES_REVERSED_HI"] = 0x8000
#$fileBytes = Get-Content $filename -ReadCount 0 -Encoding byte
$stream=[System.IO.File]::OpenRead($filename)
$fileBytes = New-Object byte[] 1024
$bytesRead = $stream.Read($fileBytes,0,1024)
$signatureOffset = 256*$fileBytes[0x3d]+$fileBytes[0x3c]
#$signatureoffset
$signature = [char[]] $fileBytes[$signatureOffset..($signatureOffset + 3)]
if([String]::Join('', $signature) -ieq "PE`0`0")
{
$coffHeader = $signatureOffset + 4
$characteristicsData = [BitConverter]::ToInt32($fileBytes, $coffHeader + 18)
$poff_characteristic=""
foreach($key in $characteristics.Keys)
{
$flag = $characteristics[$key]
if(($characteristicsData -band $flag) -eq $flag)
{
if ($poff_characteristic -eq "") {$poff_characteristic=$key} else {$poff_characteristic=$poff_characteristic+","+$key}
}
}
$machineDatabin=[BitConverter]::ToInt32($fileBytes, $coffHeader)
$machineDatabin=$machineDatabin -band 0xFFFF # only need lower 2 bytes
$machineData="0x"+[STRING]::Format("{0:X}",$machineDatabin) #.substring(1)
#$machineData
$machineTypes=@{}
# These items used to be prefixed with IMAGE_FILE_MACHINE_ such as IMAGE_FILE_MACHINE_AMD64
$machineTypes["0x"] = "UNKNOWN"
$machineTypes["0x1d3"] = "AM33"
$machineTypes["0x8664"] = "AMD64"
$machineTypes["0x1c0"] = "ARM"
$machineTypes["0x1c4"] = "ARMV7"
$machineTypes["0xebc"] = "EBC"
$machineTypes["0x14c"] = "I386"
$machineTypes["0x200"] = "IA64"
$machineTypes["0x9041"] = "M32R"
$machineTypes["0x266"] = "MIPS16"
$machineTypes["0x366"] = "MIPSFPU"
$machineTypes["0x466"] = "MIPSFPU16"
$machineTypes["0x1f0"] = "POWERPC"
$machineTypes["0x1f1"] = "POWERPCFP"
$machineTypes["0x166"] = "R4000"
$machineTypes["0x1a2"] = "SH3"
$machineTypes["0x1a3"] = "SH3DSP"
$machineTypes["0x1a6"] = "SH4"
$machineTypes["0x1a8"] = "SH5"
$machineTypes["0x1c2"] = "THUMB"
$machineTypes["0x169"] = "WCEMIPSV2"
$poff_machinetype=$machineTypes[$machineData]
if ($poff_machinetype -eq "" -or $poff_machinetype -eq $null) {$poff_machinetype=$machineData}
}
else
{
$poff_characteristic="NoPE"
$poff_machinetype="NoPE"
}
$obj=get-childitem $filename
$obj|Add-Member -MemberType NoteProperty "poff_characteristic" $poff_characteristic
$obj|Add-Member -MemberType NoteProperty "poff_machinetype" $poff_machinetype
#$obj|gm
Write-Output $obj
}
}
|
PowerShellCorpus/PoshCode/Findup_25.ps1
|
Findup_25.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>>
{ {"/x", new List<string>()},{"/i",new List<string>()},{"/xf",new List<string>()},{"/if",new List<string>()},
{"/xd",new List<string>()},{"/id",new List<string>()},{"/paths",new List<string>()} };
public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>>
{ {"/xr", new List<Regex>()},{"/ir",new List<Regex>()},{"/xfr",new List<Regex>()},{"/ifr",new List<Regex>()},
{"/xdr",new List<Regex>()},{"/idr",new List<Regex>()} };
public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "/recurse", false }, { "/noerr", false }, {"/delete",false}, {"/xj", false}};
public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes.
public static long errors = 0;
public static string delconfirm;
public static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
Console.WriteLine(" ");
string optionskey = "/paths";
List<FileInfo> files = new List<FileInfo>();
int i = 0;
for (i = 0; i < args.Length; i++)
{
string argitem = args[i].ToLower();
if ((System.String.Compare(argitem, "/help", true) == 0) || (System.String.Compare(argitem, "/h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [/recurse] [/noerr] [/x /i /xd /id /xf /if] <files/directories/regex> [/delete]");
Console.WriteLine(" ");
Console.WriteLine("Options: /help - displays this help message.");
Console.WriteLine(" /recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" /noerr - discards error messages.");
Console.WriteLine(" /delete - delete each duplicate file with confirmation.");
Console.WriteLine(" /x - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used.");
Console.WriteLine(" /i - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used.");
Console.WriteLine(" /xd - eXcludes all directories - minus drive/files - (using RegEx if -xdr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /id - Include only directories - minus drive/files - (using RegEx if -idr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /xf - eXcludes all files - minus drive/directories - (using RegEx if -xfr) following this switch until another switch is used.");
Console.WriteLine(" /if - Include only files - minus drive/directories - (using RegEx if -ifr) following this switch until another switch is used.");
Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
Console.WriteLine(" /paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
Console.WriteLine(" /xj - Exclude File and Directory Junctions.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" - deletes duplicates after consent is given.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data /recurse /x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc /xr \\"(jim)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc /xr \\"[bf]\\" /ir \\"(smith)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (optionsbools.ContainsKey(argitem))
{
optionsbools[argitem] = true;
optionskey = "/paths";
continue;
}
if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
{
optionskey = argitem;
continue;
}
if (optionspaths.ContainsKey(optionskey))
optionspaths[optionskey].Add(args[i]);
else
{
try {
Regex rgx = new Regex(args[i], RegexOptions.Compiled);
optionsregex[optionskey].Add(rgx);
}
catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);}
}
}
if (optionspaths["/paths"].Count == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
optionspaths["/paths"].Add(".");
}
Console.Write("Getting file info and sorting file list...");
getFiles(optionspaths["/paths"], "*.*", optionsbools["/recurse"], files);
if (files.Count < 2)
{
WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
Console.WriteLine("\\n");
return;
}
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");
var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>();
long filesize = 0;
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) continue;
var breakout = false;
while (true)
{
filesize = (files[i].Length);
try
{
var _SHA512 = SHA512.Create();
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
string SHA512string = Hash2String(_SHA512.Hash);
if (!SizeHashFile.ContainsKey(filesize))
SizeHashFile.Add(filesize, new Dictionary<string,List<FileInfo>>());
if (!SizeHashFile[filesize].ContainsKey(SHA512string))
{
SizeHashFile[filesize][SHA512string] = new List<FileInfo>() {};
}
SizeHashFile[filesize][SHA512string].Add(files[i]);
}
catch (Exception e) { WriteErr("Hash error: " + e.Message); }
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
breakout = (files[i].Length != files[i + 1].Length);
}
if (SizeHashFile.ContainsKey(filesize))
{
foreach (var HG in SizeHashFile[filesize])
{
if (HG.Value.Count > 1)
{
Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count);
foreach (var finfo in HG.Value)
{
Console.WriteLine(finfo.FullName);
numOfDupes++;
dupeBytes += finfo.Length;
if (optionsbools["/delete"])
if (DeleteDupe(finfo)) { bytesrecovered += finfo.Length; deletedfiles++; }
}
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS.
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered);
Console.WriteLine("Errors : {0:N0}", errors);
Console.WriteLine("Execution time : " + (DateTime.Now - startTime));
}
private static void WriteErr(string Str)
{
errors++;
if (!optionsbools["/noerr"])
Console.WriteLine(Str);
}
private static string Hash2String(Byte[] hasharray)
{
string SHA512string = "";
foreach (var c in hasharray)
{
SHA512string += String.Format("{0:x2}", c);
}
return SHA512string;
}
private static Boolean DeleteDupe(FileInfo Filenfo)
{
Console.Write("Delete this file <y/N> <ENTER>?");
delconfirm = Console.ReadLine();
if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y'))
{
try
{
Filenfo.Delete();
Console.WriteLine("File Successfully deleted.");
return true;
}
catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); }
}
return false;
}
private static Boolean CheckNames(string fullname)
{
var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt")
var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp")
if (CheckNamesWorker(fullname, "/x", "/xr", true))
return false;
if (CheckNamesWorker(filePart, "/xf", "/xfr", true))
return false;
if (CheckNamesWorker(dirPart, "/xd", "/xdr", true))
return false;
if (CheckNamesWorker(fullname, "/i", "/ir", false))
return false;
if (CheckNamesWorker(filePart, "/if", "/ifr", false))
return false;
if (CheckNamesWorker(dirPart, "/id", "/idr", false))
return false;
return true;
}
private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType)
{
foreach (var filepath in optionspaths[pathskey])
{
if (filestr.ToLower().StartsWith(filepath) == CheckType)
return true;
}
foreach (var rgx in optionsregex[rgxkey])
{
if (rgx.IsMatch(filestr) == CheckType)
return true;
}
return false;
}
private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
catch (Exception e) { WriteErr("Add file error: " + e.Message); }
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); }
if (recursiveFlag)
{
try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); }
catch (Exception e) { WriteErr("Add Directory error: " + e.Message); }
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-PrimaryIPAddress.ps1
|
Get-PrimaryIPAddress.ps1
|
[system.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |
Where-Object { $_.GetIPProperties().GatewayAddresses } |
ForEach-Object {
$_.GetIPProperties().UnicastAddresses| ForEach-Object {
$_.Address.IPAddressToString
}
}
|
PowerShellCorpus/PoshCode/Get-Speech.ps1
|
Get-Speech.ps1
|
#requires -pssnapin PSEventing -version 1.1
## http://www.codeplex.com/PSEventing/
## ALSO REQUIRES .NET 3.0
# ---------------------------------------------------------------------------
## <Script>
## <Author>
## Joel "Jaykul" Bennett
## </Author>
## <Description>
## Prompts the user for a selection via voice.
## </Description>
## <Usage>
## Get-Speech "Yes","No" "Would you like some cake?"
## </Usage>
## </Script>
# ---------------------------------------------------------------------------
param([string[]]$choices,[string]$prompt,[switch]$purge)
BEGIN {
if ($prompt) {
Write-Output $prompt | &($MyInvocation.InvocationName) $choices
break;
} else {
[Reflection.Assembly]::LoadWithPartialName("System.Speech") | out-null
$speaker = new System.Speech.Synthesis.SpeechSynthesizer
$listener = new System.Speech.Recognition.SpeechRecognizer
$_choices = new System.Speech.Recognition.Choices
foreach($choice in $choices) {
$_choices.Add($choice)
}
$grammar = new System.Speech.Recognition.Grammar (new System.Speech.Recognition.GrammarBuilder $_choices)
## Hook up an event handler
Connect-EventListener grammar SpeechRecognized
## And then start the Recognizer
$listener = new System.Speech.Recognition.SpeechRecognizer
$listener.LoadGrammar($grammar)
}
}
PROCESS {
if($_ -as [string])
{
$speaker.SpeakAsync( $_ ) | out-null
}
if($grammar)
{
$event = Get-Event -Wait
Write-Output $event.Args.Result
}
}
END {
$speaker.Dispose()
$listener.Dispose()
}
|
PowerShellCorpus/PoshCode/Get-MACFromIP.ps1
|
Get-MACFromIP.ps1
|
Function Get-MACFromIP {
param ($IPAddress)
$sign = @"
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
public static class NetUtils
{
[System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref int PhyAddrLen);
public static string GetMacAddress(String addr)
{
try
{
IPAddress IPaddr = IPAddress.Parse(addr);
byte[] mac = new byte[6];
int L = 6;
SendARP(BitConverter.ToInt32(IPaddr.GetAddressBytes(), 0), 0, mac, ref L);
String macAddr = BitConverter.ToString(mac, 0, L);
return (macAddr.Replace('-',':'));
}
catch (Exception ex)
{
return (ex.Message);
}
}
}
"@
$type = Add-Type -TypeDefinition $sign -Language CSharp -PassThru
$type::GetMacAddress($IPAddress)
}
|
PowerShellCorpus/PoshCode/finddupe_7.ps1
|
finddupe_7.ps1
|
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$files=$null
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
for ($i=0;$i -ne $args.count; $i++)
{
if ($args[$i] -eq "-delete")
{
$del=$true;continue
}
else
{
if ($args[$i] -eq "-noprompt")
{
$noprompt=$true;continue
}
else
{
$files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true})
}
}
}
if ($files -eq $null) {write-host "No files found." -f red; exit}
$files | % {$_.fullname}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$md5 = $null
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)}
if ($md5 -eq (get-md5 $files[$c]))
{
write-host "Size and MD5 match: " -fore red -nonewline
"{0} and {1}" -f $filecheck.fullname, $files[$c].fullname
$matches++
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname;write-host "$($files[$c].fullname) deleted." -f Red
}
else
{
del $files[$c].fullname -confirm
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $($matches)."
write-host ""
|
PowerShellCorpus/PoshCode/Start-ProcessAsAdministr.ps1
|
Start-ProcessAsAdministr.ps1
|
function Start-ProcessAsAdministrator
{
<#
.ForwardHelpTargetName Start-Process
.ForwardHelpCategory Cmdlet
#>
[CmdletBinding(DefaultParameterSetName='Default')]
param(
[Parameter(Mandatory=$true, Position=0)]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[System.String]
$FilePath,
[Parameter(Position=1)]
[Alias('Args')]
[ValidateNotNullOrEmpty()]
[System.String[]]
$ArgumentList,
[Parameter(ParameterSetName='Default')]
[Alias('RunAs')]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
$Credential,
[ValidateNotNullOrEmpty()]
[System.String]
$WorkingDirectory,
[Parameter(ParameterSetName='Default')]
[Alias('Lup')]
[Switch]
$LoadUserProfile,
[Parameter(ParameterSetName='Default')]
[Alias('nnw')]
[Switch]
$NoNewWindow,
[Switch]
$PassThru,
[Parameter(ParameterSetName='Default')]
[Alias('RSE')]
[ValidateNotNullOrEmpty()]
[System.String]
$RedirectStandardError,
[Parameter(ParameterSetName='Default')]
[Alias('RSI')]
[ValidateNotNullOrEmpty()]
[System.String]
$RedirectStandardInput,
[Parameter(ParameterSetName='Default')]
[Alias('RSO')]
[ValidateNotNullOrEmpty()]
[System.String]
$RedirectStandardOutput,
[Switch]
$Wait,
[Parameter(ParameterSetName='UseShellExecute')]
[ValidateNotNullOrEmpty()]
[System.Diagnostics.ProcessWindowStyle]
$WindowStyle,
[Parameter(ParameterSetName='Default')]
[Switch]
$UseNewEnvironment
)
process {
$psBoundParameters = $psBoundParameters += @{"Verb"="runas"}
Start-Process @psBoundParameters
}
}
|
PowerShellCorpus/PoshCode/Deleted-ObjectsAD_2.ps1
|
Deleted-ObjectsAD_2.ps1
|
param(
$Domen,
[string[]]$ObjectsDeleted
)
function Ping ($Name){
$ping = new-object System.Net.NetworkInformation.Ping
if ($ping.send($Name).Status -eq "Success") {$True}
else {$False}
trap {Write-Verbose "Error Ping"; $False; continue}
}
[string[]]$ObjectPath
[string[]]$Disks
[string[]]$Info
[string[]]$Computers
$Computers = Get-QADComputer -Service $Domen -OSName '*XP*','*Vista*','*7*' -SizeLimit 0 -ErrorAction SilentlyContinue |
Select-Object name -ExpandProperty name
foreach ($Computer in $Computers){
$Alive = Ping $Computer
if ($Alive -eq "True"){
Write-Host "Seach $Computer" -BackgroundColor Blue
trap {Write-Host "Error WmiObject $Computer";Continue}
$Disks += Get-WmiObject win32_logicaldisk -ComputerName $Computer -ErrorAction SilentlyContinue |
Where-Object {$_.Size -ne $null}
if ($Disks){
foreach ($Disk in $Disks){
if ($Disk.Name -like "*:*") {
$Disk = $Disk.Name.Replace(":","$")
}
trap {Write-Host "Error ChildItem $Computer";Continue}
$ObjectPath += Get-ChildItem "\\\\$Computer\\$Disk\\*" -Recurse -ErrorAction SilentlyContinue
if ($ObjectPath){
foreach ($Object in $ObjectsDeleted){
$ObjectPath |
Where-Object {$_.Name -like $Object} |
% { $Path = $_.FullName;
Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue;
$Info += "" | Select-Object @{e={$Path};n='Path'},`
@{e={"Delete"};n='Action'}
}
}
}
}
}
}
}
$Info | Format-Table -AutoSize -ErrorAction SilentlyContinue
|
PowerShellCorpus/PoshCode/de04269d-38ca-4bb2-8559-9bd6072c319f.ps1
|
de04269d-38ca-4bb2-8559-9bd6072c319f.ps1
|
#==========================================================================
# NAME: getunknownsids.ps1
#
# AUTHOR: Stephen Wheet
# Version: 4.0
# Date: 6/11/10
#
# COMMENT:
# This script was created to find unknown SIDs or old domain permissions
# on folders. It ignores folders where inheirtance is turned on.
#
# This works on NETAPPS and WINDOWS servers. You will need the DLL's
#
# Version 2: completely changed the query method and ACL removal
# Version 3: Added ability to query AD for servers, and handles getting
# getting shares automatically from:
# NETAPP FILERS
# Windows servers
# Version 4: Cleaned up folder checking and added checking for local
# account checking so we could ignore.
#
#==========================================================================
Function checkshare {
Param($PassedShareName)
Process
{
$path = "\\\\$serverFQDN\\$PassedShareName"
$filename = $path.Replace("\\","-") + ".csv"
#Place Headers on out-put file
$list = "Task,Path,Access Entity,"
$list | format-table | Out-File "c:\\reports\\unknownsids\\$filename"
#Populate Folders Array
Write-Host "Writing results to : $filename"
$date = Get-Date
Write-Host $date
Write-Host "Getting Folders in: $Path"
#PSIscontainer means folders only
[Array] $folders = Get-ChildItem -path $path -recurse | ? {$_.PSIsContainer}
#Process data in array
ForEach ($folder in [Array] $folders)
{
#Check to see if there are any folders
If ($folder.pspath){
#Convert Powershell Provider Folder Path to standard folder path
$PSPath = (Convert-Path $folder.pspath)
Write-Host "Checking Dir: $PSPath"
#Check to make sure valid
If ($PSPath){
#Get the ACL's from each folder
$error.clear()
$acl = Get-Acl -Path $PSPath
#Write log if no access
if (!$?) {
$errmsg = "Error,$PSPath,ACCESS DENIED"
$errmsg | format-table | Out-File -append "$filename"
} #end IF
$ACL.Access |
?{!$_.IsInherited} |
?{ $_.IdentityReference -like $unknownsid -or $_.IdentityReference -like $olddomain } |
% {$value = $_.IdentityReference.Value
#Check for Local account
$localsid = 0
If ($value -like $unknownsid){
$checkforlocal = $value.split("-")
$total =$checkforlocal.count -1
@@ if ($checkforlocal[$total] -match "^100.$" -or $checkforlocal[$total] -match "^500"){
$localsid = 1
# You can uncomment the below if you want to report on local accounts.
#$list = ("Local,$PSPath,$value")
#$list | format-table | Out-File -append "$filename"
} #end IF
} #end IF
If (!$localsid){
Write-host "Found - $PSPath - $value"
$list = ("Found,$PSPath,$value")
$list | format-table | Out-File -append "$filename"
#Remove Bad SID
if ($removeacl) { $ACL.RemoveAccessRuleSpecific($_)
Write-host "Deleting - $PSPath - $value"
$list = ("Deleting,$PSPath,$value")
$list | format-table | Out-File -append "$filename"
}#end IF
if ($removeacl -and $value) {
$date = Get-Date
Write-Host $date
Write-host "Setting - $PSPath"
$list = ("Setting,$PSPath")
$list | format-table | Out-File -append "$filename"
Set-ACL $PSpath $ACL
$value = ""
} #end IF
} #end if
} #end foreachobj
} #end if
} #end if
} #end ForEach
}#end Process
} #end function
get-pssnapin -registered | add-pssnapin -passthru
[void][Reflection.Assembly]::LoadFile('C:\\reports\\ManageOntap.dll') #Need this DLL from netapp 3.5SDK
$ReqVersion = [version]"1.2.2.1254"
$QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version #Need Quest plugins installed
if($QadVersion -lt $ReqVersion) {
throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version"
} #end If
#Set variables
$value = ""
$unknownsid = "*S-1-5-21-*" #Broken SID Verify the Broken SID number on your system and replace
$olddomain = "Domain.local*" #Old w2k/nt4 domain
$ErrorActionPreference = "SilentlyContinue"
$removeacl = 0 #change to 1 if you want to remove the SID, 0 for only logging
$localsid = 0
#Get all the servers from the specified OU
$Servers = get-QADComputer -SearchRoot 'domain.local/ou/Server' # change the container.
Foreach ($server in $Servers ) {
$serverFQDN = $server.dnsname
write-host $serverFQDN
#Test ping server to make sure it's up before querying it
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.Send($serverFQDN)
if ($Reply.status -eq "Success"){
Write-Host "Online"
#Check for Netapp .. if found get the shares differently
If ($serverFQDN -like "*netapp*"){
$server = new-object netapp.manage.naserver($serverFQDN,1,0)
#pass authentication
$server.Style = "RPC"
# Issue command to get the shares
$NaElement = New-Object NetApp.Manage.NaElement("system-cli")
$arg = New-Object NetApp.Manage.NaElement("args")
$arg.AddNewChild('arg','cifs')
$arg.AddNewChild('arg','shares')
$NaElement.AddChildElement($arg)
$CifsString = $server.InvokeElem($NaElement).GetChildContent("cli-output")
# Split the returned txt up .. the $null makes it skip a line
$null,$null,$Lines = $CifsString.Split("`n")
Foreach ($line in $Lines ) {
# Had to trick it so skip the line with permissions, then exclude ETC$ adn c$
if (!$line.startswith(" ") -and $line -notlike "*Etc$*" -and $line -notlike "*C$*"){
$l= $line.Split(" ")
checkshare -PassedShareName $l[0] #Pass share to function
} #end if
} #end foreach
} #end if
Else{ #Else if a Windows server query via WMI
Get-WMIObject Win32_Share -Computer $serverFQDN |
where {$_.Name -like "*$*" -and $_.Name -notlike "*ADMIN*" -and $_.Name -notlike "*IPC*" -and $_.Name -notlike "*lib*"} |
%{
#Set path
$sharename = $_.name
checkshare -PassedShareName $sharename #Pass share to function
} #end ForEachObj
} #End Else
} #End If
} #end ForEach
|
PowerShellCorpus/PoshCode/Shell.ShellLink.ps1
|
Shell.ShellLink.ps1
|
## With thanks to Steve McMahon and his article:
## http://vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Creating_and_Modifying_Shortcuts/article.asp
##
## After executing Add-Type, below, you'll be able to:
## new-object Shell.ShellLink ".\\Some Shortcut.lnk"
Add-Type -Ref System.Drawing, System.Windows.Forms @'
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Shell
{
/// <summary>
/// Enables extraction of icons for any file type from
/// the Shell.
/// </summary>
public class FileIcon
{
#region UnmanagedCode
private const int MAX_PATH = 260;
[StructLayout(LayoutKind.Sequential)]
private struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public int dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=80)]
public string szTypeName;
}
[DllImport("shell32")]
private static extern int SHGetFileInfo (
string pszPath,
int dwFileAttributes,
ref SHFILEINFO psfi,
uint cbFileInfo,
uint uFlags);
[DllImport("user32.dll")]
private static extern int DestroyIcon(IntPtr hIcon);
private const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000;
private const int FORMAT_MESSAGE_FROM_HMODULE = 0x800;
private const int FORMAT_MESSAGE_FROM_STRING = 0x400;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x200;
private const int FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xFF;
[DllImport("kernel32")]
private extern static int FormatMessage (
int dwFlags,
IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
string lpBuffer,
uint nSize,
int argumentsLong);
[DllImport("kernel32")]
private extern static int GetLastError();
#endregion
#region Member Variables
private string fileName;
private string displayName;
private string typeName;
private SHGetFileInfoConstants flags;
private Icon fileIcon;
#endregion
#region Enumerations
[Flags]
public enum SHGetFileInfoConstants : int
{
SHGFI_ICON = 0x100, // get icon
SHGFI_DISPLAYNAME = 0x200, // get display name
SHGFI_TYPENAME = 0x400, // get type name
SHGFI_ATTRIBUTES = 0x800, // get attributes
SHGFI_ICONLOCATION = 0x1000, // get icon location
SHGFI_EXETYPE = 0x2000, // return exe type
SHGFI_SYSICONINDEX = 0x4000, // get system icon index
SHGFI_LINKOVERLAY = 0x8000, // put a link overlay on icon
SHGFI_SELECTED = 0x10000, // show icon in selected state
SHGFI_ATTR_SPECIFIED = 0x20000, // get only specified attributes
SHGFI_LARGEICON = 0x0, // get large icon
SHGFI_SMALLICON = 0x1, // get small icon
SHGFI_OPENICON = 0x2, // get open icon
SHGFI_SHELLICONSIZE = 0x4, // get shell size icon
//SHGFI_PIDL = 0x8, // pszPath is a pidl
SHGFI_USEFILEATTRIBUTES = 0x10, // use passed dwFileAttribute
SHGFI_ADDOVERLAYS = 0x000000020, // apply the appropriate overlays
SHGFI_OVERLAYINDEX = 0x000000040 // Get the index of the overlay
}
#endregion
#region Implementation
/// <summary>
/// Gets/sets the flags used to extract the icon
/// </summary>
public FileIcon.SHGetFileInfoConstants Flags
{
get
{
return flags;
}
set
{
flags = value;
}
}
/// <summary>
/// Gets/sets the filename to get the icon for
/// </summary>
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
/// <summary>
/// Gets the icon for the chosen file
/// </summary>
public Icon ShellIcon
{
get
{
return fileIcon;
}
}
/// <summary>
/// Gets the display name for the selected file
/// if the SHGFI_DISPLAYNAME flag was set.
/// </summary>
public string DisplayName
{
get
{
return displayName;
}
}
/// <summary>
/// Gets the type name for the selected file
/// if the SHGFI_TYPENAME flag was set.
/// </summary>
public string TypeName
{
get
{
return typeName;
}
}
/// <summary>
/// Gets the information for the specified
/// file name and flags.
/// </summary>
public void GetInfo()
{
fileIcon = null;
typeName = "";
displayName = "";
SHFILEINFO shfi = new SHFILEINFO();
uint shfiSize = (uint)Marshal.SizeOf(shfi.GetType());
int ret = SHGetFileInfo(
fileName, 0, ref shfi, shfiSize, (uint)(flags));
if (ret != 0)
{
if (shfi.hIcon != IntPtr.Zero)
{
fileIcon = System.Drawing.Icon.FromHandle(shfi.hIcon);
// Now owned by the GDI+ object
//DestroyIcon(shfi.hIcon);
}
typeName = shfi.szTypeName;
displayName = shfi.szDisplayName;
}
else
{
int err = GetLastError();
Console.WriteLine("Error {0}", err);
string txtS = new string('\\0', 256);
int len = FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero, err, 0, txtS, 256, 0);
Console.WriteLine("Len {0} text {1}", len, txtS);
// throw exception
}
}
/// <summary>
/// Constructs a new, default instance of the FileIcon
/// class. Specify the filename and call GetInfo()
/// to retrieve an icon.
/// </summary>
public FileIcon()
{
flags = SHGetFileInfoConstants.SHGFI_ICON |
SHGetFileInfoConstants.SHGFI_DISPLAYNAME |
SHGetFileInfoConstants.SHGFI_TYPENAME |
SHGetFileInfoConstants.SHGFI_ATTRIBUTES |
SHGetFileInfoConstants.SHGFI_EXETYPE;
}
/// <summary>
/// Constructs a new instance of the FileIcon class
/// and retrieves the icon, display name and type name
/// for the specified file.
/// </summary>
/// <param name="fileName">The filename to get the icon,
/// display name and type name for</param>
public FileIcon(string fileName) : this()
{
this.fileName = fileName;
GetInfo();
}
/// <summary>
/// Constructs a new instance of the FileIcon class
/// and retrieves the information specified in the
/// flags.
/// </summary>
/// <param name="fileName">The filename to get information
/// for</param>
/// <param name="flags">The flags to use when extracting the
/// icon and other shell information.</param>
public FileIcon(string fileName, FileIcon.SHGetFileInfoConstants flags)
{
this.fileName = fileName;
this.flags = flags;
GetInfo();
}
#endregion
}
#region ShellLink Object
/// <summary>
/// Summary description for ShellLink.
/// </summary>
public class ShellLink : IDisposable
{
#region ComInterop for IShellLink
#region IPersist Interface
[ComImportAttribute()]
[GuidAttribute("0000010C-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPersist
{
[PreserveSig]
//[helpstring("Returns the class identifier for the component object")]
void GetClassID(out Guid pClassID);
}
#endregion
#region IPersistFile Interface
[ComImportAttribute()]
[GuidAttribute("0000010B-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPersistFile
{
// can't get this to go if I extend IPersist, so put it here:
[PreserveSig]
void GetClassID(out Guid pClassID);
//[helpstring("Checks for changes since last file write")]
void IsDirty();
//[helpstring("Opens the specified file and initializes the object from its contents")]
void Load(
[MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
uint dwMode);
//[helpstring("Saves the object into the specified file")]
void Save(
[MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
[MarshalAs(UnmanagedType.Bool)] bool fRemember);
//[helpstring("Notifies the object that save is completed")]
void SaveCompleted(
[MarshalAs(UnmanagedType.LPWStr)] string pszFileName);
//[helpstring("Gets the current name of the file associated with the object")]
void GetCurFile(
[MarshalAs(UnmanagedType.LPWStr)] out string ppszFileName);
}
#endregion
#region IShellLink Interface
[ComImportAttribute()]
[GuidAttribute("000214EE-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellLinkA
{
//[helpstring("Retrieves the path and filename of a shell link object")]
void GetPath(
[Out(), MarshalAs(UnmanagedType.LPStr)] StringBuilder pszFile,
int cchMaxPath,
ref _WIN32_FIND_DATAA pfd,
uint fFlags);
//[helpstring("Retrieves the list of shell link item identifiers")]
void GetIDList(out IntPtr ppidl);
//[helpstring("Sets the list of shell link item identifiers")]
void SetIDList(IntPtr pidl);
//[helpstring("Retrieves the shell link description string")]
void GetDescription(
[Out(), MarshalAs(UnmanagedType.LPStr)] StringBuilder pszFile,
int cchMaxName);
//[helpstring("Sets the shell link description string")]
void SetDescription(
[MarshalAs(UnmanagedType.LPStr)] string pszName);
//[helpstring("Retrieves the name of the shell link working directory")]
void GetWorkingDirectory(
[Out(), MarshalAs(UnmanagedType.LPStr)] StringBuilder pszDir,
int cchMaxPath);
//[helpstring("Sets the name of the shell link working directory")]
void SetWorkingDirectory(
[MarshalAs(UnmanagedType.LPStr)] string pszDir);
//[helpstring("Retrieves the shell link command-line arguments")]
void GetArguments(
[Out(), MarshalAs(UnmanagedType.LPStr)] StringBuilder pszArgs,
int cchMaxPath);
//[helpstring("Sets the shell link command-line arguments")]
void SetArguments(
[MarshalAs(UnmanagedType.LPStr)] string pszArgs);
//[propget, helpstring("Retrieves or sets the shell link hot key")]
void GetHotkey(out short pwHotkey);
//[propput, helpstring("Retrieves or sets the shell link hot key")]
void SetHotkey(short pwHotkey);
//[propget, helpstring("Retrieves or sets the shell link show command")]
void GetShowCmd(out uint piShowCmd);
//[propput, helpstring("Retrieves or sets the shell link show command")]
void SetShowCmd(uint piShowCmd);
//[helpstring("Retrieves the location (path and index) of the shell link icon")]
void GetIconLocation(
[Out(), MarshalAs(UnmanagedType.LPStr)] StringBuilder pszIconPath,
int cchIconPath,
out int piIcon);
//[helpstring("Sets the location (path and index) of the shell link icon")]
void SetIconLocation(
[MarshalAs(UnmanagedType.LPStr)] string pszIconPath,
int iIcon);
//[helpstring("Sets the shell link relative path")]
void SetRelativePath(
[MarshalAs(UnmanagedType.LPStr)] string pszPathRel,
uint dwReserved);
//[helpstring("Resolves a shell link. The system searches for the shell link object and updates the shell link path and its list of identifiers (if necessary)")]
void Resolve(
IntPtr hWnd,
uint fFlags);
//[helpstring("Sets the shell link path and filename")]
void SetPath(
[MarshalAs(UnmanagedType.LPStr)] string pszFile);
}
[ComImportAttribute()]
[GuidAttribute("000214F9-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellLinkW
{
//[helpstring("Retrieves the path and filename of a shell link object")]
void GetPath(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile,
int cchMaxPath,
ref _WIN32_FIND_DATAW pfd,
uint fFlags);
//[helpstring("Retrieves the list of shell link item identifiers")]
void GetIDList(out IntPtr ppidl);
//[helpstring("Sets the list of shell link item identifiers")]
void SetIDList(IntPtr pidl);
//[helpstring("Retrieves the shell link description string")]
void GetDescription(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile,
int cchMaxName);
//[helpstring("Sets the shell link description string")]
void SetDescription(
[MarshalAs(UnmanagedType.LPWStr)] string pszName);
//[helpstring("Retrieves the name of the shell link working directory")]
void GetWorkingDirectory(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir,
int cchMaxPath);
//[helpstring("Sets the name of the shell link working directory")]
void SetWorkingDirectory(
[MarshalAs(UnmanagedType.LPWStr)] string pszDir);
//[helpstring("Retrieves the shell link command-line arguments")]
void GetArguments(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs,
int cchMaxPath);
//[helpstring("Sets the shell link command-line arguments")]
void SetArguments(
[MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
//[propget, helpstring("Retrieves or sets the shell link hot key")]
void GetHotkey(out short pwHotkey);
//[propput, helpstring("Retrieves or sets the shell link hot key")]
void SetHotkey(short pwHotkey);
//[propget, helpstring("Retrieves or sets the shell link show command")]
void GetShowCmd(out uint piShowCmd);
//[propput, helpstring("Retrieves or sets the shell link show command")]
void SetShowCmd(uint piShowCmd);
//[helpstring("Retrieves the location (path and index) of the shell link icon")]
void GetIconLocation(
[Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
int cchIconPath,
out int piIcon);
//[helpstring("Sets the location (path and index) of the shell link icon")]
void SetIconLocation(
[MarshalAs(UnmanagedType.LPWStr)] string pszIconPath,
int iIcon);
//[helpstring("Sets the shell link relative path")]
void SetRelativePath(
[MarshalAs(UnmanagedType.LPWStr)] string pszPathRel,
uint dwReserved);
//[helpstring("Resolves a shell link. The system searches for the shell link object and updates the shell link path and its list of identifiers (if necessary)")]
void Resolve(
IntPtr hWnd,
uint fFlags);
//[helpstring("Sets the shell link path and filename")]
void SetPath(
[MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}
#endregion
#region ShellLinkCoClass
[GuidAttribute("00021401-0000-0000-C000-000000000046")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComImportAttribute()]
private class CShellLink{}
#endregion
#region Private IShellLink enumerations
private enum EShellLinkGP : uint
{
SLGP_SHORTPATH = 1,
SLGP_UNCPRIORITY = 2
}
[Flags]
private enum EShowWindowFlags : uint
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_MAX = 10
}
#endregion
#region IShellLink Private structs
[StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Unicode)]
private struct _WIN32_FIND_DATAW
{
public uint dwFileAttributes;
public _FILETIME ftCreationTime;
public _FILETIME ftLastAccessTime;
public _FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr , SizeConst = 260)] // MAX_PATH
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)]
private struct _WIN32_FIND_DATAA
{
public uint dwFileAttributes;
public _FILETIME ftCreationTime;
public _FILETIME ftLastAccessTime;
public _FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr , SizeConst = 260)] // MAX_PATH
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0)]
private struct _FILETIME
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
#endregion
#region UnManaged Methods
private class UnManagedMethods
{
[DllImport("Shell32", CharSet=CharSet.Auto)]
internal extern static int ExtractIconEx (
[MarshalAs(UnmanagedType.LPTStr)]
string lpszFile,
int nIconIndex,
IntPtr[] phIconLarge,
IntPtr[] phIconSmall,
int nIcons);
[DllImport("user32")]
internal static extern int DestroyIcon(IntPtr hIcon);
}
#endregion
#endregion
#region Enumerations
/// <summary>
/// Flags determining how the links with missing
/// targets are resolved.
/// </summary>
[Flags]
public enum EShellLinkResolveFlags : uint
{
/// <summary>
/// Allow any match during resolution. Has no effect
/// on ME/2000 or above, use the other flags instead.
/// </summary>
SLR_ANY_MATCH = 0x2,
/// <summary>
/// Call the Microsoft Windows Installer.
/// </summary>
SLR_INVOKE_MSI = 0x80,
/// <summary>
/// Disable distributed link tracking. By default,
/// distributed link tracking tracks removable media
/// across multiple devices based on the volume name.
/// It also uses the UNC path to track remote file
/// systems whose drive letter has changed. Setting
/// SLR_NOLINKINFO disables both types of tracking.
/// </summary>
SLR_NOLINKINFO = 0x40,
/// <summary>
/// Do not display a dialog box if the link cannot be resolved.
/// When SLR_NO_UI is set, a time-out value that specifies the
/// maximum amount of time to be spent resolving the link can
/// be specified in milliseconds. The function returns if the
/// link cannot be resolved within the time-out duration.
/// If the timeout is not set, the time-out duration will be
/// set to the default value of 3,000 milliseconds (3 seconds).
/// </summary>
SLR_NO_UI = 0x1,
/// <summary>
/// Not documented in SDK. Assume same as SLR_NO_UI but
/// intended for applications without a hWnd.
/// </summary>
SLR_NO_UI_WITH_MSG_PUMP = 0x101,
/// <summary>
/// Do not update the link information.
/// </summary>
SLR_NOUPDATE = 0x8,
/// <summary>
/// Do not execute the search heuristics.
/// </summary>
SLR_NOSEARCH = 0x10,
/// <summary>
/// Do not use distributed link tracking.
/// </summary>
SLR_NOTRACK = 0x20,
/// <summary>
/// If the link object has changed, update its path and list
/// of identifiers. If SLR_UPDATE is set, you do not need to
/// call IPersistFile::IsDirty to determine whether or not
/// the link object has changed.
/// </summary>
SLR_UPDATE = 0x4
}
public enum LinkDisplayMode : uint
{
edmNormal = EShowWindowFlags.SW_NORMAL,
edmMinimized = EShowWindowFlags.SW_SHOWMINNOACTIVE,
edmMaximized = EShowWindowFlags.SW_MAXIMIZE
}
#endregion
#region Member Variables
// Use Unicode (W) under NT, otherwise use ANSI
private IShellLinkW linkW;
private IShellLinkA linkA;
private string shortcutFile = "";
#endregion
#region Constructor
/// <summary>
/// Creates an instance of the Shell Link object.
/// </summary>
public ShellLink()
{
if (System.Environment.OSVersion.Platform == PlatformID.Win32NT)
{
linkW = (IShellLinkW)new CShellLink();
}
else
{
linkA = (IShellLinkA)new CShellLink();
}
}
/// <summary>
/// Creates an instance of a Shell Link object
/// from the specified link file
/// </summary>
/// <param name="linkFile">The Shortcut file to open</param>
public ShellLink(string linkFile) : this()
{
Open(linkFile);
}
#endregion
#region Destructor and Dispose
/// <summary>
/// Call dispose just in case it hasn't happened yet
/// </summary>
~ShellLink()
{
Dispose();
}
/// <summary>
/// Dispose the object, releasing the COM ShellLink object
/// </summary>
public void Dispose()
{
if (linkW != null )
{
Marshal.ReleaseComObject(linkW);
linkW = null;
}
if (linkA != null)
{
Marshal.ReleaseComObject(linkA);
linkA = null;
}
}
#endregion
#region Implementation
public string ShortCutFile
{
get
{
return this.shortcutFile;
}
set
{
this.shortcutFile = value;
}
}
/// <summary>
/// Gets a System.Drawing.Icon containing the icon for this
/// ShellLink object.
/// </summary>
private Icon getIcon(bool large)
{
// Get icon index and path:
int iconIndex = 0;
// If there are no details set for the icon, then we must use
// the shell to get the icon for the target:
if (String.IsNullOrEmpty(IconPath))
{
// Use the FileIcon object to get the icon:
FileIcon.SHGetFileInfoConstants flags =
FileIcon.SHGetFileInfoConstants.SHGFI_ICON |
FileIcon.SHGetFileInfoConstants.SHGFI_ATTRIBUTES;
if (large)
{
flags = flags | FileIcon.SHGetFileInfoConstants.SHGFI_LARGEICON;
}
else
{
flags = flags | FileIcon.SHGetFileInfoConstants.SHGFI_SMALLICON;
}
FileIcon fileIcon = new FileIcon(Target, flags);
return fileIcon.ShellIcon;
}
else
{
// Use ExtractIconEx to get the icon:
IntPtr[] hIconEx = new IntPtr[1] {IntPtr.Zero};
int iconCount = 0;
if (large)
{
iconCount = UnManagedMethods.ExtractIconEx(
IconPath,
iconIndex,
hIconEx,
null,
1);
}
else
{
iconCount = UnManagedMethods.ExtractIconEx(
IconPath,
iconIndex,
null,
hIconEx,
1);
}
// If success then return as a GDI+ object
Icon icon = null;
if (hIconEx[0] != IntPtr.Zero)
{
icon = Icon.FromHandle(hIconEx[0]);
//UnManagedMethods.DestroyIcon(hIconEx[0]);
}
return icon;
}
}
/// <summary>
/// Gets the path to the file containing the icon for this shortcut.
/// </summary>
public string IconPath
{
get
{
StringBuilder iconPath = new StringBuilder(260, 260);
int iconIndex = 0;
if (linkA == null)
{
linkW.GetIconLocation(iconPath, iconPath.Capacity, out iconIndex);
}
else
{
linkA.GetIconLocation(iconPath, iconPath.Capacity, out iconIndex);
}
if(iconIndex > 0) {
iconPath.AppendFormat(",{0}",iconIndex);
}
return iconPath.ToString();
}
set
{
StringBuilder iconPath = new StringBuilder(260, 260);
String iconLocation = String.Empty;
int iconIndex = 0;
String[] oldPath = Regex.Split(value, ",(?=\\\\d+$)");
if(oldPath.Length > 1) {
iconLocation = oldPath[0];
iconIndex = Int32.Parse(oldPath[1]);
} else {
iconLocation = value;
}
if(iconIndex == 0) {
if (linkA == null)
{
linkW.GetIconLocation(iconPath, iconPath.Capacity, out iconIndex);
}
else
{
linkA.GetIconLocation(iconPath, iconPath.Capacity, out iconIndex);
}
if(!iconLocation.Equals(iconPath.ToString(), StringComparison.InvariantCulture)) {
iconIndex = 0;
}
}
if (linkA == null)
{
linkW.SetIconLocation(iconLocation, iconIndex);
}
else
{
linkA.SetIconLocation(iconLocation, iconIndex);
}
}
}
/// <summary>
/// Gets the index of this icon within the icon path's resources
/// </summary>
public int IconIndex
{
get
{
StringBuilder iconPath = new StringBuilder(260, 260);
int iconIndex = 0;
if (linkA == null)
{
linkW.GetIconLocation(iconPath, iconPath.Capacity, out
iconIndex);
}
else
{
linkA.GetIconLocation(iconPath, iconPath.Capacity, out
iconIndex);
}
return iconIndex;
}
set
{
StringBuilder iconPath = new StringBuilder(260, 260);
int iconIndex = 0;
if (linkA == null)
{
linkW.GetIconLocation(iconPath, iconPath.Capacity, out
iconIndex);
}
else
{
linkA.GetIconLocation(iconPath, iconPath.Capacity, out
iconIndex);
}
if (linkA == null)
{
linkW.SetIconLocation(iconPath.ToString(), value);
}
else
{
linkA.SetIconLocation(iconPath.ToString(), value);
}
}
}
/// <summary>
/// Gets/sets the fully qualified path to the link's target
/// </summary>
public string Target
{
get
{
StringBuilder target = new StringBuilder(260, 260);
if (linkA == null)
{
_WIN32_FIND_DATAW fd = new _WIN32_FIND_DATAW();
linkW.GetPath(target, target.Capacity, ref fd,
(uint)EShellLinkGP.SLGP_UNCPRIORITY);
}
else
{
_WIN32_FIND_DATAA fd = new _WIN32_FIND_DATAA();
linkA.GetPath(target, target.Capacity, ref fd,
(uint)EShellLinkGP.SLGP_UNCPRIORITY);
}
return target.ToString();
}
set
{
if (linkA == null)
{
linkW.SetPath(value);
}
else
{
linkA.SetPath(value);
}
}
}
/// <summary>
/// Gets/sets the Working Directory for the Link
/// </summary>
public string WorkingDirectory
{
get
{
StringBuilder path = new StringBuilder(260, 260);
if (linkA == null)
{
linkW.GetWorkingDirectory(path, path.Capacity);
}
else
{
linkA.GetWorkingDirectory(path, path.Capacity);
}
return path.ToString();
}
set
{
if (linkA == null)
{
linkW.SetWorkingDirectory(value);
}
else
{
linkA.SetWorkingDirectory(value);
}
}
}
/// <summary>
/// Gets/sets the description of the link
/// </summary>
public string Description
{
get
{
StringBuilder description = new StringBuilder(1024, 1024);
if (linkA == null)
{
linkW.GetDescription(description, description.Capacity);
}
else
{
linkA.GetDescription(description, description.Capacity);
}
return description.ToString();
}
set
{
if (linkA == null)
{
linkW.SetDescription(value);
}
else
{
linkA.SetDescription(value);
}
}
}
/// <summary>
/// Gets/sets any command line arguments associated with the link
/// </summary>
public string Arguments
{
get
{
StringBuilder arguments = new StringBuilder(260, 260);
if (linkA == null)
{
linkW.GetArguments(arguments, arguments.Capacity);
}
else
{
linkA.GetArguments(arguments, arguments.Capacity);
}
return arguments.ToString();
}
set
{
if (linkA == null)
{
linkW.SetArguments(value);
}
else
{
linkA.SetArguments(value);
}
}
}
/// <summary>
/// Gets/sets the initial display mode when the shortcut is
/// run
/// </summary>
public LinkDisplayMode DisplayMode
{
get
{
uint cmd = 0;
if (linkA == null)
{
linkW.GetShowCmd(out cmd);
}
else
{
linkA.GetShowCmd(out cmd);
}
return (LinkDisplayMode)cmd;
}
set
{
if (linkA == null)
{
linkW.SetShowCmd((uint)value);
}
else
{
linkA.SetShowCmd((uint)value);
}
}
}
/// <summary>
/// Gets/sets the HotKey to start the shortcut (if any)
/// </summary>
public Keys HotKey
{
get
{
short key = 0;
if (linkA == null)
{
linkW.GetHotkey(out key);
}
else
{
linkA.GetHotkey(out key);
}
return (Keys)key;
}
set
{
if (linkA == null)
{
linkW.SetHotkey((short)value);
}
else
{
linkA.SetHotkey((short)value);
}
}
}
/// <summary>
/// Saves the shortcut to ShortCutFile.
/// </summary>
public void Save()
{
Save(shortcutFile);
}
/// <summary>
/// Saves the shortcut to the specified file
/// </summary>
/// <param name="linkFile">The shortcut file (.lnk)</param>
public void Save( string linkFile )
{
// Save the object to disk
if (linkA == null)
{
((IPersistFile)linkW).Save(linkFile, true);
shortcutFile = linkFile;
}
else
{
((IPersistFile)linkA).Save(linkFile, true);
shortcutFile = linkFile;
}
}
/// <summary>
/// Loads a shortcut from the specified file
/// </summary>
/// <param name="linkFile">The shortcut file (.lnk) to load</param>
public void Open(
string linkFile
)
{
Open(linkFile,
IntPtr.Zero,
(EShellLinkResolveFlags.SLR_ANY_MATCH |
EShellLinkResolveFlags.SLR_NO_UI),
1);
}
/// <summary>
/// Loads a shortcut from the specified file, and allows flags controlling
/// the UI behaviour if the shortcut's target isn't found to be set.
/// </summary>
/// <param name="linkFile">The shortcut file (.lnk) to load</param>
/// <param name="hWnd">The window handle of the application's UI, if any</param>
/// <param name="resolveFlags">Flags controlling resolution behaviour</param>
public void Open(
string linkFile,
IntPtr hWnd,
EShellLinkResolveFlags resolveFlags
)
{
Open(linkFile,
hWnd,
resolveFlags,
1);
}
/// <summary>
/// Loads a shortcut from the specified file, and allows flags controlling
/// the UI behaviour if the shortcut's target isn't found to be set. If
/// no SLR_NO_UI is specified, you can also specify a timeout.
/// </summary>
/// <param name="linkFile">The shortcut file (.lnk) to load</param>
/// <param name="hWnd">The window handle of the application's UI, if any</param>
/// <param name="resolveFlags">Flags controlling resolution behaviour</param>
/// <param name="timeOut">Timeout if SLR_NO_UI is specified, in ms.</param>
public void Open(
string linkFile,
IntPtr hWnd,
EShellLinkResolveFlags resolveFlags,
ushort timeOut
)
{
uint flags;
if ((resolveFlags & EShellLinkResolveFlags.SLR_NO_UI)
== EShellLinkResolveFlags.SLR_NO_UI)
{
flags = (uint)((int)resolveFlags | (timeOut << 16));
}
else
{
flags = (uint)resolveFlags;
}
if (linkA == null)
{
((IPersistFile)linkW).Load(linkFile, 0); //STGM_DIRECT)
linkW.Resolve(hWnd, flags);
this.shortcutFile = linkFile;
}
else
{
((IPersistFile)linkA).Load(linkFile, 0); //STGM_DIRECT)
linkA.Resolve(hWnd, flags);
this.shortcutFile = linkFile;
}
}
#endregion
}
#endregion
}
'@
|
PowerShellCorpus/PoshCode/wpf datagrid xaml.ps1
|
wpf datagrid xaml.ps1
|
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window"
Title="DataGrid Binding"
Width="640" Height="480">
<Grid >
<TextBlock Height="24" Margin="8,8,8,0" TextWrapping="Wrap" Text="DataGrid" VerticalAlignment="Top" FontSize="18.667" FontFamily="Arial" FontWeight="Bold"/>
<DataGrid HorizontalAlignment="Left" Margin="8,82,0,8" Width="240" Name="HadesDevices" AutoGenerateColumns="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=DeviceGroup}" Header="Manufacturer"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Device}" Header="Model"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Platform}" Header="Platform"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
|
PowerShellCorpus/PoshCode/chkhash_19.ps1
|
chkhash_19.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
"ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, "
"in order to detect corrupt or hacked files."
""
".\\chkhash.ps1 -h for usage."
""
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$fc++ # File checked increment.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{$fm++;continue} # if matched, increment file matches and continue loop
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fm file(s) SHA512 matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Network Config _ Excel.ps1
|
Network Config _ Excel.ps1
|
$excel = New-Object -comobject Excel.Application
$excel.visible = $False #Change to True to see the excel build
$wbook = $excel.Workbooks.Add()
$wsheet = $wbook.Worksheets.Item(1)
$wsheet.Cells.Item(1,1) = "Date"
$wsheet.Cells.Item(1,2) = "Server"
$wsheet.Cells.Item(1,3) = "NETID"
$wsheet.Cells.Item(1,4) = "Description"
$wsheet.Cells.Item(1,5) = "MAC"
$wsheet.Cells.Item(1,6) = "IP"
$wsheet.Cells.Item(1,7) = "DHCPEnabled"
$wsheet.Cells.Item(1,8) = "DHCPServer"
$wsheet.Cells.Item(1,9) = "DNSServerSearchOrder"
$wsheet.Cells.Item(1,10) = "WINSPrimaryServer"
$wsheet.Cells.Item(1,11) = "WINSSecondaryServer"
$wsheet.Cells.Item(1,12) = "DomainDNSRegistrationEnabled"
$wsheet.Cells.Item(1,13) = "FullDNSRegistrationEnabled"
$wsheet.Cells.Item(1,14) = "WINSEnableLMHostsLookup"
$range = $wsheet.UsedRange
$range.Interior.ColorIndex = 19
$range.Font.ColorIndex = 11
$range.Font.Bold = $True
$iRow = 2
$AllAdapters = @("")
$InputFile = "C:\\Scripts\\Servers.txt"
$Servers = Get-Content $InputFile
ForEach($Server in $Servers)
{
$Adapters = Get-Wmiobject Win32_NetworkAdapterConfiguration -Computername `
$Server | Where-Object{$_.IPEnabled -eq $True}
ForEach($Adapter In $Adapters)
{
[String]$DNSServers = ""
$Adapters2 = Get-Wmiobject Win32_NetworkAdapter -Computername $Server `
| Where-Object{$_.Caption -eq $Adapter.Caption}
[String]$NetID = $Adapters2.NetConnectionID
If($Adapter.DNSServerSearchOrder -ne $Null){ForEach($Address In `
$Adapter.DNSServerSearchOrder){$DNSServers += "[" + $Address + "]"}}
$wsheet.Cells.Item($iRow,1) = Get-Date
$wsheet.Cells.Item($iRow,2) = $Server
$wsheet.Cells.Item($iRow,3) = $NETID
$wsheet.Cells.Item($iRow,4) = $Adapter.Description
$wsheet.Cells.Item($iRow,5) = $Adapter.MACAddress
$wsheet.Cells.Item($iRow,6) = $Adapter.IPAddress
$wsheet.Cells.Item($iRow,7) = $Adapter.DHCPEnabled
$wsheet.Cells.Item($iRow,8) = $Adapter.DHCPServer
$wsheet.Cells.Item($iRow,9) = $DNSServers
$wsheet.Cells.Item($iRow,10) = $Adapter.WINSPrimaryServer
$wsheet.Cells.Item($iRow,11) = $Adapter.WINSSecondaryServer
$wsheet.Cells.Item($iRow,12) = $Adapter.DomainDNSRegistrationEnabled
$wsheet.Cells.Item($iRow,13) = $Adapter.FullDNSRegistrationEnabled
$wsheet.Cells.Item($iRow,14) = $Adapter.WINSEnableLMHostsLookup
$iRow = $iRow + 1
}
}
$range.EntireColumn.AutoFilter()
$range.EntireColumn.AutoFit()
$excel.ActiveWorkbook.SaveAs("C:\\Scripts\\NetworkScan.xls")
$excel.ActiveWorkbook.Close
$excel.Application.Quit
|
PowerShellCorpus/PoshCode/The Letter Diamond.ps1
|
The Letter Diamond.ps1
|
## Write a program which draws a diamond of the form illustrted
## below. The letter which is to appear at the widest point of the
## figure (E in the example) is to be specified as the input data.
## A
## B B
## C C
## D D
## E E
## D D
## C C
## B B
## A
Param([char]$letter = "E")
$start = [int][char]"B"
$end = [int]$letter
$outerpadding = ($end - $start) + 5
$innerpadding = -1
Write-Host "$(" " * $outerpadding)A"
foreach($char in ([string[]][char[]]($start..$end))) {
$innerpadding += 2
$outerpadding--
Write-Host "$(" " * $outerpadding)$char$(" " * $innerpadding)$char"
}
$end--
foreach($char in ([string[]][char[]]($end..$start))) {
$innerpadding -= 2
$outerpadding++
Write-Host "$(" " * $outerpadding)$char$(" " * $innerpadding)$char"
}
Write-Host "$(" " * $outerpadding) A"
|
PowerShellCorpus/PoshCode/Get_Set Signature (CTP2)_2.ps1
|
Get_Set Signature (CTP2)_2.ps1
|
#Requires -version 2.0
## Authenticode.psm1
####################################################################################################
## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets
## These properly parse paths, so they don't kill your pipeline and script if you include a folder
##
## Usage:
## ls | Get-AuthenticodeSignature
## Get all the signatures
##
## ls | Select-Signed -Mine -Broken | Set-AuthenticodeSignature
## Re-sign anything you signed before that has changed
##
## ls | Select-Signed -NotMine -ValidOnly | Set-AuthenticodeSignature
## Re-sign scripts that are hash-correct but not signed by me or by someone trusted
##
####################################################################################################
## History:
## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-Signed
## - Added -MineOnly and -NotMineOnly switches to Select-Signed
## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files
## It's important to remember that the signatures are NOT checked by PowerShell yet...
## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed
## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly
## - commented out the default Certificate which won't work for "you"
## 1.0 - first working version, includes wrappers for Get and Set
##
## YOU MUST CHANGE THIS ...
# Set-Variable CertificateThumbprint "0DA3A2A2189CD74AE371E6C57504FEB9A59BB22E" -Scope Script -Option ReadOnly
Set-Variable CertificateThumbprint "F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5" -Scope Script -Option ReadOnly
CMDLET Test-Signature {
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
# We can't actually require the type, or we won't be able to check the fake ones
# [System.Management.Automation.Signature]
$Signature
,
[Alias("Valid")]
[Switch]$ForceValid
)
return ( $Signature.Status -eq "Valid" -or
( !$ForceValid -and
($Signature.Status -eq "UnknownError") -and
($_.SignerCertificate.Thumbprint -eq $CertificateThumbprint)
) )
}
CMDLET Set-AuthenticodeSignature -snapin Huddled.BetterDefaults {
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
if(!(Test-Path -PathType Leaf $_)) {
throw "Specified Path is not a File: '$_'"
}
return $true
})]
[string]
$Path
, ## TODO: you should CHANGE THIS to a method which gets *your* default certificate
[Parameter(Position=2, Mandatory=$false)]
$Certificate = $(ls cert:\\CurrentUser\\my\\$CertificateThumbprint)
)
PROCESS {
if( ".psm1" -eq [IO.Path]::GetExtension($Path) ) {
# function setpsm1sig($Path) {
$ps1Path = "$Path.ps1"
Rename-Item $Path (Split-Path $ps1Path -Leaf)
$sig = Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $ps1Path | Select *
Rename-Item $ps1Path (Split-Path $Path -Leaf)
$sig.PSObject.TypeNames.Insert( 0, "System.Management.Automation.Signature" )
$sig.Path = $Path
$sig
} else {
Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $Path
}
}
}
CMDLET Get-AuthenticodeSignature -snapin Huddled.BetterDefaults {
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
if(!(Test-Path -PathType Leaf $_)) {
throw "Specified Path is not a File: '$_'"
}
return $true
})]
[string]
$Path
)
PROCESS {
if( ".psm1" -eq [IO.Path]::GetExtension($Path) ) {
# function getpsm1sig($Path) {
$ps1Path = "$Path.ps1"
Rename-Item $Path (Split-Path $ps1Path -Leaf)
$sig = Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $ps1Path | select *
Rename-Item $ps1Path (Split-Path $Path -Leaf)
$sig.PSObject.TypeNames.Insert( 0, "System.Management.Automation.Signature" )
$sig.Path = $Path
$sig
} else {
Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path
}
}
}
CMDLET Select-Signed -snapin Huddled.BetterDefaults {
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string]
$Path
,
[Parameter()]
[switch]$MineOnly
,
[Parameter()]
[switch]$NotMineOnly
,
[Parameter()]
[switch]$BrokenOnly
,
[Parameter()]
[switch]$TrustedOnly
,
[Parameter()]
[switch]$ValidOnly
,
[Parameter()]
[switch]$InvalidOnly
,
[Parameter()]
[switch]$UnsignedOnly
)
if(!(Test-Path -PathType Leaf $Path)) {
# if($ErrorAction -ne "SilentlyContinue") {
# Write-Error "Specified Path is not a File: '$Path'"
# }
} else {
$sig = Get-AuthenticodeSignature $Path
# Broken only returns ONLY things which are HashMismatch
if($BrokenOnly -and $sig.Status -ne "HashMismatch")
{
Write-Debug "$($sig.Status) - Not Broken: $Path"
return
}
# Trusted only returns ONLY things which are Valid
if($TrustedOnly -and $sig.Status -ne "Valid")
{
Write-Debug "$($sig.Status) - Not Trusted: $Path"
return
}
# AllValid returns only things that are SIGNED and not HashMismatch
if($ValidOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) )
{
Write-Debug "$($sig.Status) - Not Valid: $Path"
return
}
# NOTValid returns only things that are SIGNED and not HashMismatch
if($InvalidOnly -and ($sig.Status -eq "Valid"))
{
Write-Debug "$($sig.Status) - Valid: $Path"
return
}
# Unsigned returns only things that aren't signed
# NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files??
if($UnsignedOnly -and $sig.SignerCertificate )
{
Write-Debug "$($sig.Status) - Signed: $Path"
return
}
# Mine returns only things that were signed by MY CertificateThumbprint
if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $CertificateThumbprint)))
{
Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Does not match your default certificate print: $CertificateThumbprint"
Write-Debug " $Path"
return
}
# NotMine returns only things that were signed by MY CertificateThumbprint
if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $CertificateThumbprint)))
{
if($sig.SignerCertificate) {
Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Matches your default certificate print: $CertificateThumbprint"
Write-Debug " $Path"
}
return
}
if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) )
{
# Write-Debug ("You asked for Broken ({0}) or Trusted ({1}) or Valid ({2}) or Invalid ({3}) or Unsigned ({4}) and the cert is: ({5})" -f [int]$BrokenOnly, [int]$TrustedOnly, [int]$ValidOnly, [int]$InvalidOnly, [int]$UnsignedOnly, $sig.SignerCertificate)
Write-Debug "$($sig.Status) - Not Signed: $Path"
return
}
get-childItem $sig.Path
}
}
Export-ModuleMember Set-AuthenticodeSignature,Get-AuthenticodeSignature,Test-Signature,Select-Signed
# SIG # Begin signature block
# MIIK0AYJKoZIhvcNAQcCoIIKwTCCCr0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUlcaRTm+/m0Lma0cwCp9wfClq
# laagggbEMIIGwDCCBKigAwIBAgIJAKpDRVMtv0LqMA0GCSqGSIb3DQEBBQUAMIHG
# MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl
# c3RlcjEaMBgGA1UEChMRSHVkZGxlZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRp
# ZmljYXRlIEF1dGhvcml0eTErMCkGA1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmlj
# YXRlIEF1dGhvcml0eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNz
# ZXMub3JnMB4XDTA4MDcwMjAzNTA1OVoXDTA5MDcwMjAzNTA1OVowgcAxCzAJBgNV
# BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazESMBAGA1UEBxMJUm9jaGVzdGVyMRow
# GAYDVQQKExFIdWRkbGVkTWFzc2VzLm9yZzEuMCwGA1UECxMlaHR0cDovL0h1ZGRs
# ZWRNYXNzZXMub3JnL0NvZGVDZXJ0LmNydDEVMBMGA1UEAxMMSm9lbCBCZW5uZXR0
# MScwJQYJKoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwggIiMA0G
# CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXuceXJZYARJbSTU4hoh91goVp2POx
# 6Mz/QZ6D5jcT/JNhdW2GwYQ9YUxNj8jkhXg2Ixbgb1djRGMFC/ekgRkgLxyiuhRh
# NrVE1IdV4hT4as3idqnvWOi0S3z2R2EGdebqwm2mrRmq9+DbY+FGxuNwLboWZx8Z
# roGlLLHRPzt9pabQq/Nu/FIFO+4JzZ8S5ZnEaKTm4dpD0g6j653OWYVvNXJbS/W4
# Dis5aRkHT1q1Gp02dYHh3NTKrpv1nus9BTDlJRwmU/FgGLNQIvnRwqVoBh+I7tVq
# NIRnI1RpDTGyFEohbH8mRlwq3z4ijtb6j9boUJEqd8hQshzUMcALoTIR1tN/5APX
# u2j4OqGFESM/OG0i2hLKbnP81u581aZT1BfVfQxvDuWrFiurMxllVGY1NvKkXwc8
# aOZktqMQWbWAs2bxZqERbOILXOmkL/mvPdy+e5yQveriHAhrDONu7a79ylreMHBR
# XrmYJTK2G/aHvB5vrXjMPw0TBeph0sM2BN2eVzenAAMsIiGlXPXvtKrpKRiBdx5f
# 9SV5dyUG2tR8ANDuc2AMB8FKICuMUd8Sx96p4FOBQhXhvF/RZcWZIW5o+A4sHvYE
# /s4oiX7LxGrQK2abNiCVs9BDLI/EcSs/TP+ZskBqu7Qb+AVeevoY3T7skihuyC/l
# h7EwqjfNpVQ9UwIDAQABo4G0MIGxMB0GA1UdDgQWBBTgB9XYJV/kJAvnkWmKDHsh
# 7Cn3PzAfBgNVHSMEGDAWgBQ+5x4ah0JG0o4iUj0TebNd4MCVxTAJBgNVHRMEAjAA
# MBEGCWCGSAGG+EIBAQQEAwIEEDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzALBgNV
# HQ8EBAMCBsAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRp
# ZmljYXRlMA0GCSqGSIb3DQEBBQUAA4ICAQAw8B6+s48CZZo5h5tUeKV7OWNXKRG7
# xkyavMkXpEi58BSLutmE3O7smc3uvu3TdCXENNUlGrcq/KQ8y2eEI8QkHgT99VgX
# r+v5xu2KnJXiOOIxi65EZybRFFFaGJNodTcrK8L/tY6QLF02ilOlEgfcc1sV/Sj/
# r60JS1iXIMth7nYZVjtWeYXOrsd+I+XwJuoVNJlELNdApOU4ZVNrPEuV+QRNMimj
# lqIOv2tn9TDdNGUqaOCI0w+a1XQvapEPWETfQK+o9pvYINTswGDjNeb7Xz8ar2JB
# 9IVs2xtxDohHB75kyRrlY1hkoY5j12ZhWOlm0L9Ks6XvmMtXJIjj0/m9Z+3s+9p6
# U7IYjz5NnzmDvtNUn2y9zxB/rUx/JqoUO3BWRKiLX0lvGRWJlzFr9978kH2SXxAD
# rsKfzB7YZzMh9hZkGNlJf4T+HTB/OXG1jyfkyqQvhNB/tDAaq+ejDtKNBF4hMS7K
# Z0B4vagIxFwMuTiei4UaOjrGzeCfT9w1Bmj6uLJme5ydQVM0V7z3Z6jR3LVq4c4s
# Y1dfPmYlw62cbyV9Kb/H2hYw5K0OMX60LfLQZOzIPzAeRJ87NufwZnC1afxsSCmU
# bvSx4kCMgRZMXw+d1SHRhh7z+06YTQjnUMmtTGt7DtUkU6I8LKEWF/mAzF7sq/7P
# AyhPsbu91X5FuzGCA3YwggNyAgEBMIHUMIHGMQswCQYDVQQGEwJVUzERMA8GA1UE
# CBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hlc3RlcjEaMBgGA1UEChMRSHVkZGxl
# ZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTErMCkG
# A1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmljYXRlIEF1dGhvcml0eTEnMCUGCSqG
# SIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAqkNFUy2/QuowCQYF
# Kw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkD
# MQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJ
# KoZIhvcNAQkEMRYEFIYZXAMANzMI+/t73Dzr8alaIgYPMA0GCSqGSIb3DQEBAQUA
# BIICAAW33N0H+Xe84dtN52nWzutpJkpGdAig0Cq3GAjxIZ9y5KiFXh2FO5fA3W4q
# OUNi03RskQHoYQwlP0KiRcdTouggQNVVlHvOBCgT1pcvlLSR7jM+rPKbdPa/6WdJ
# Kr3ZuoPRWvfk12Wu5PgrKs6Rvo3y5hXQNuITchxH58GJXkykz8a28yBVOszrujzP
# 2lwM/RldO1j01DOz7KeyyIWCV1hFyuawEnKANUYh5RO/MRlJ//T8rUPnO0NoHqR9
# X3sqPqHHGGvtk8RZQgwSkDOnEw7JTqJityn7cRKnocm2yrQZ/VoYEI562tw0Xjvy
# Zcn83U+EKo1TdphRWJ2qBvOMK6lR1VPbRKCLvIp21q3tdCCBgqmfc3eDqIINdXVJ
# cmzeqh2yGquQj6ozsjdJtjrKnZnxhk7Clikc1SzMBWT2MxEtAfkJC/Ok8l+Sa1MY
# +uWRL6p+55IE8x5TeNl251IYIp7g4LsPAaFZtiDBERrXRxtBTDszAUyTNJXuDcwS
# T1CYQtrTYpEJxH1uk7C+SbQnq/fu2LJMHZGTB2Smh0CygXRkUxuN6Zpq1VwIT/lB
# N8BAmhjx6F/h/v8MdLvMXzV4jcATZp6ywCf6k9OfuqCOETDSl9b6Lxm//guHgmUV
# mpzU7n21ZOBv8ElUGZLvIfQCsmZ/ON7obwpFfhamuFIsSJ0w
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Connect-VMHost.ps1
|
Connect-VMHost.ps1
|
#requires -version 2 -pssnapin VMware.VimAutomation.Core
Function Connect-VMHost {
<#
.Summary
Used to Connect a disconnected host to vCenter.
.Parameter VMHost
VMHost to reconnect to virtual center
.Example
Get-VMHost | Where-Object {$_.state -eq "Disconnected"} | Connect-VMHost
Will Attempt to reconnect any host that are currently disconnected.
.Example
Connect-VMHost -Name ESX1.get-admin.local
Will reconnect ESX1 to vCenter
#>
[CmdletBinding(
SupportsShouldProcess=$True,
SupportsTransactions=$False,
ConfirmImpact="low",
DefaultParameterSetName="ByString"
)]
Param(
[Parameter(
Mandatory=$True,
Valuefrompipeline=$true,
ParameterSetName="ByObj"
)]
[VMware.VimAutomation.Client20.VMHostImpl[]]
$VMHost,
[Parameter(
Mandatory=$True,
Position=0,
ParameterSetName="ByString"
)]
[string[]]
$Name
)
Begin {
IF ($Name) {
$VMHost = $Name|%{ Get-VMHost -Name $_ }
}
}
process {
Foreach ($VMHostImpl in ($VMHost|Get-View)) {
$ReconnectSpec = New-Object VMware.Vim.HostConnectSpec
$ReconnectSpec.HostName = $VMHostImpl.Summary.Config.Name
$ReconnectSpec.Port = $VMHostImpl.Summary.Config.Port
$ReconnectSpec.Force = $true
if ($pscmdlet.ShouldProcess($VMHostImpl.name)) {
$VMHostImpl.ReconnectHost_Task($ReconnectSpec)
}
}
}
}
|
PowerShellCorpus/PoshCode/VMware _ Windows Admin.ps1
|
VMware _ Windows Admin.ps1
|
#========================================================================
# Created on: 5/17/2012 2:03 PM
# Created by: Clint Jones
# Organization: Virtually Genius!
# Filename: Get-VMHostVersions
#========================================================================
#Import modules
Add-PSSnapin "Vmware.VimAutomation.Core"
#Path to the log files
$log = "C:\\Scripts\\VMware\\Logs\\hostversions.txt"
#Creates directory structure for log files
$pathverif = Test-Path -Path c:\\scripts\\vmware\\logs
switch ($pathverif)
{
True {}
False {New-Item "c:\\scripts\\vmware\\logs" -ItemType directory}
default {Write-Host "An error has occured when checking the file structure"}
}
#Connect to VMware servers
$viserver = Read-Host "Enter VMware server:"
$creds = Get-Credential
Connect-ViServer -Server $viserver -Credential $creds
#Get the version number of the host
Get-VMHost | Select-Object Name, Version | Format-Table -AutoSize | Out-File -FilePath $log -Append
|
PowerShellCorpus/PoshCode/8fad46f9-26e1-4da7-8cc9-eb8a10d893dc.ps1
|
8fad46f9-26e1-4da7-8cc9-eb8a10d893dc.ps1
|
$devEnvArgs = '"' + "$pwd"+"\\Installer\\myInstaller.sln" + '"';
$devSwitches = '"' + "/rebuild Release 2>&1" + '"';
$output = &$vsExe $devEnvArgs $devSwitches;
|
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_7.ps1
|
Get Twitter RSS Feed_7.ps1
|
param ([String] $ScreenName)
$client = New-Object System.Net.WebClient
$idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName"
$data = $client.DownloadString($idUrl)
$start = 0
$findStr = '"id":'
do {
$start = $data.IndexOf($findStr, $start + 1)
if ($start -gt 0) {
$start += $findStr.Length
$end = $data.IndexOf(',', $start)
$userId = $data.SubString($start, $end-$start)
}
} while ($start -le $data.Length -and $start -gt 0)
$feed = "http://twitter.com/statuses/user_timeline/$userId.rss"
$feed
|
PowerShellCorpus/PoshCode/Import-Certificate_2.ps1
|
Import-Certificate_2.ps1
|
#requires -Version 2.0
function Import-Certificate
{
param
(
[IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."),
[string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."),
[switch] $LocalMachine,
[switch] $CurrentUser,
[string] $CertPassword,
[switch] $Verbose
)
begin
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
}
process
{
if ($Verbose)
{
$VerbosePreference = 'Continue'
}
if (-not $LocalMachine -and -not $CurrentUser)
{
Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'."
}
try
{
if ($_)
{
$certfile = $_
}
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword
}
catch
{
Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue
}
if ($cert -and $LocalMachine)
{
$StoreScope = "LocalMachine"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
if ($cert -and $CurrentUser)
{
$StoreScope = "CurrentUser"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
}
end
{ }
}
|
PowerShellCorpus/PoshCode/ISEFun.psm1.ps1
|
ISEFun.psm1.ps1
|
# Module version 0.1
# Author: Bartek Bielawski (@bielawb on twitter)
# Purpose: Add functionality to PowerShell ISE
# Description: Adds Add-ons menu 'ISEFun' with all functions included.
# User can add any action there using Add-MyMenuItem function
# One of functions (Copy item from history) was build using WPK - won't work if the latter is not loaded.
# There is also pretty large code for Windows Forms form (change token colors using ColorDialog
# Edit-Function will allow you modify any function in ISE editor
# Expand-Alias will expand aliases in current file
# Have ISE - Fun! ;)
if (-not ($MyISEMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | Where-Object { $_.DisplayName -eq 'ISEFun'} ) ) {
$MyISEMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add('ISEFun',$null,$null)
}
# Helper function to add menu items, exported cause it can be used also for other stuff. :>
function Add-MyMenuItem {
<#
.Synopsis
Adds items to ISEFun Add-Ons sub-menu
.Description
Function can be used to add menu items to ISEFun menu. All you need is command, name and hotkey - we will take care of the rest for you. ;)
.Example
Add-MyMenuItem 'Write-Host fooo' 'Fooo!' 'CTRL+9'
Description
-----------
This command will add item 'Fooo!' to ISEFun menu. This item will write 'fooo' to the host and can be launched using shortcut CTRL + 9
#>
PARAM (
# Script that will be launched when menu item will be selected
[Parameter(Mandatory = $true, HelpMessage = 'Command that you want to add to menu')]
[string]$Command,
# Title for the command in the menu
[string]$DisplayName,
# Hot key to use given item
[string]$HotKey = $null
)
if (!$DisplayName) {
$DisplayName = $Command -replace '-',' '
}
if ( -not ($MyISEMenu.Submenus | Where-Object { $_.DisplayName -eq $DisplayName} ) ) {
try {
[void]$Script:MyISEMenu.Submenus.Add($DisplayName,[scriptblock]::Create($Command),$HotKey)
} catch {
# Probably hotkey already use, adding item without it
[void]$Script:MyISEMenu.Submenus.Add($DisplayName,[scriptblock]::Create($Command),$null)
}
}
}
Add-MyMenuItem Add-MyMenuItem 'Add items'
# Next few lines are just garbage you get when you wanna be smart and create GUI in the script.
# Forgive me for adding this stuff here, I could probably compile it in some dll and skip this but...
# ... well - it gives impression that my module is bigger than it actually is. ;)
#
# Our form to change colours... :)
$handler_bClose_Click=
{
$Main.Hide()
}
$handler_bColor_Click=
{
$Dialog = New-Object Windows.Forms.ColorDialog -Property @{
Color = [drawing.color]::FromArgb($psISE.Options.TokenColors.Item($Combo.SelectedItem).ToString())
FullOpen = $true
}
if ($Dialog.ShowDialog() -eq 'OK') {
$psISE.Options.TokenColors.Item($Combo.SelectedItem) = [windows.media.color]::FromRgb($Dialog.Color.R, $Dialog.Color.G, $Dialog.Color.B)
$Combo.ForeColor = $Dialog.Color
}
}
$handler_selectedValue = {
$Combo.ForeColor = [drawing.color]::FromArgb($psISE.Options.TokenColors.Item($Combo.SelectedItem).ToString())
$bColor.Focus()
}
$OnLoadForm_StateCorrection = {
$Main.WindowState = $InitialFormWindowState
}
$Script:Main = New-Object Windows.Forms.Form -Property @{
Text = "Token colors selector"
MaximizeBox = $False
Name = "Main"
HelpButton = $True
MinimizeBox = $False
ClientSize = New-Object System.Drawing.Size 426, 36
}
$Main.DataBindings.DefaultDataSourceUpdateMode = 0
$Combo = New-Object Windows.Forms.ComboBox -Property @{
FormattingEnabled = $True
Size = New-Object System.Drawing.Size 239, 23
Name = "Combo"
Location = New-Object System.Drawing.Point 12, 7
Font = New-Object System.Drawing.Font("Lucida Console",11.25,0,3,238)
TabIndex = 4
}
$Combo.DataBindings.DefaultDataSourceUpdateMode = 0
$Combo.Items.AddRange($psISE.Options.TokenColors.Keys)
$Combo.Add_SelectedValueChanged($handler_SelectedValue)
$InitialFormWindowState = New-Object Windows.Forms.FormWindowState
$bClose = New-Object Windows.Forms.Button -Property @{
TabIndex = 2
Name = "bClose"
Size = New-Object System.Drawing.Size 75, 23
UseVisualStyleBackColor = $True
Text = "Close"
Location = New-Object System.Drawing.Point 338, 7
}
$bClose.DataBindings.DefaultDataSourceUpdateMode = 0
$bClose.add_Click($handler_bClose_Click)
$bColor = New-Object Windows.Forms.Button -Property @{
TabIndex = 1
Name = "bColor"
Size = New-Object System.Drawing.Size 75, 23
UseVisualStyleBackColor = $True
Text = "Color"
Location = New-Object System.Drawing.Point 257, 7
}
$bColor.DataBindings.DefaultDataSourceUpdateMode = 0
$bColor.add_Click($handler_bColor_Click)
$Main.Controls.AddRange(@($bColor,$bClose,$Combo))
$InitialFormWindowState = $Main.WindowState
$Main.add_Load($OnLoadForm_StateCorrection)
$HelpMessage = @'
This GUI will help you change you token colors.
It's updating text color as you select tokens that you want to modify.
Button 'Color' opens up color dialog.
I won't describe actions performed by 'Close' button. I hope you are able to guess it... ;)
'@
$Main.add_HelpButtonClicked( { [void][windows.forms.MessageBox]::Show($HelpMessage,'Help','OK','Information')})
function Set-TokenColor {
<#
.Synopsis
GUI to add some Token Colors.
.Description
Really. It is just that. No more to it. Seriously!
OK. GUI is pretty smart. You can select tokens that are available, color will change and match the one you currently have. See for yourself. ;)
.Example
Can show you click-click-click example :)
#>
$Script:Main.ShowDialog()| Out-Null
}
Add-MyMenuItem Set-TokenColor
function Expand-Alias {
<#
.Synopsis
Function to expand all command aliases in current script.
.Description
If you want to expand all aliases in a script/ module that you write in PowerShell ISE - this function will help you with that.
It's using Tokenizer to find all commands, Get-Alias to find aliases and their definition, and simply replace alias with command hidden by it.
.Example
Expand-Alias
#>
# Read in current file
if (!$psISE.CurrentFile) {
throw 'No files opened!'
}
if ( -not ($Script = $psISE.CurrentFile.Editor.Text) ) {
throw 'No code!'
}
$line = $psISE.CurrentFile.Editor.CaretLine
$column = $psISE.CurrentFile.Editor.CaretColumn
if ( -not ($commands = [System.Management.Automation.PsParser]::Tokenize($Script, [ref]$null) | Where-Object { $_.Type -eq 'Command' } | Sort-Object -Property Start -Descending) ) {
return
}
foreach ($command in $commands) {
if (Get-Alias $command.Content -ErrorAction SilentlyContinue) {
# $command
$psISE.CurrentFile.Editor.Select($command.StartLine, $command.StartColumn, $command.EndLine, $command.EndColumn)
$psISE.CurrentFile.Editor.InsertText($(Get-Alias $command.Content | Select-Object -ExpandProperty Definition))
}
}
$psISE.CurrentFile.Editor.SetCaretPosition($line, $column)
}
Add-MyMenuItem Expand-Alias
function Edit-Function {
<#
.Synopsis
Simpe function to edit functions in ISE.
.Description
Need to edit function on-the-fly? Want to see how a given function looks like to change it a bit and rename it?
Or maybe just preparing module and you want to change functions you define to make sure changes will work as expected?
Well, with Edit-Function, which is very simple (thank you PowerShell team!) you can do it. :)
.Example
Edit-Function Edit-Function
Description
-----------
You can open any function that exists in your current session, including the function that you reading help to now.
Be careful with that one though. If you change it in wrong direction you may not be able to open it again and fix it.
At least not in the way you could originaly, with Edit-Function. :)
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,HelpMessage='Function name is mandatory parameter.')]
[ValidateScript({Get-Command -CommandType function $_})]
[string]
$Name
)
if (!$psISE) {
Throw 'Implemented for PowerShell ISE only!'
}
$file = $psISE.CurrentPowerShellTab.Files.Add()
$file.Editor.InsertText("function $name {`n")
$file.Editor.InsertText($(Get-Command -CommandType function $name | Select-Object -ExpandProperty definition))
$file.Editor.InsertText("}")
}
Add-MyMenuItem Edit-Function
function Copy-HistoryItem {
<#
.Synopsis
Function build using WPK to give you functionality similar to one you already have in PowerShell.exe
.Description
Display you command history and let you choose from it. Copies selected command to you commandPane.
.Example
Copy-HistoryItem
GUI, so it's not easy to show examples...
#>
try {
New-Window -Width 800 -Height 100 {
New-ListBox -On_PreviewMouseDoubleClick {
$psISE.CurrentPowerShellTab.CommandPane.InsertText($this.SelectedValue)
$this.parent.close()
} -Items $(Get-History | Select-Object -ExpandProperty CommandLine)
} -Show
} catch {
throw 'Requires WPK to work, will be rewritten soon...'
}
}
Add-MyMenuItem Copy-HistoryItem 'Copy item from History' F7
New-Alias -Name edfun -Value Edit-Function
New-Alias -Name expa -Value Expand-Alias
New-Alias -Name cphi -Value Copy-HistoryItem
Export-ModuleMember -Function * -Alias *
# Get rid off menu if module is going to be unloaded.
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
[void]$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Remove($MyISEMenu)
}
|
PowerShellCorpus/PoshCode/LibraryMSCS_2.ps1
|
LibraryMSCS_2.ps1
|
# ------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Defines functions for working with Microsoft Cluster Service (MSCS)
### </Description>
### <Usage>
### . ./LibraryMSCS.ps1
### </Usage>
### </Script>
# ------------------------------------------------------------------------
#######################
function Get-Cluster
{
param($cluster)
gwmi -class "MSCluster_Cluster" -namespace "root\\mscluster" -computername $cluster
} #Get-Cluster
#######################
function Get-ClusterName
{
param($cluster)
Get-Cluster $cluster | select -ExpandProperty name
} #Get-ClusterName
#######################
function Get-ClusterNode
{
param($cluster)
gwmi -class MSCluster_Node -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster
} #Get-ClusterNode
#######################
function Get-ClusterSQLVirtual
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "SQL Server"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='VirtualServerName';e={$_.PrivateProperties.VirtualServerName}}, @{n='InstanceName';e={$_.PrivateProperties.InstanceName}}, `
@{n='ServerInstance';e={("{0}\\{1}" -f $_.PrivateProperties.VirtualServerName,$_.PrivateProperties.InstanceName).TrimEnd('\\')}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterSQLVirtual
#######################
function Get-ClusterNetworkName
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster | where {$_.type -eq "Network Name"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='NetworkName';e={$_.PrivateProperties.Name}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterNetworkName
#######################
function Get-ClusterResource
{
param($cluster)
gwmi -ComputerName $cluster -Namespace "root\\mscluster" -Class MSCluster_Resource | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty Group `
{ gwmi -ComputerName $cluster -Namespace "root\\mscluster" -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToResource" | Select -ExpandProperty Name }
} #Get-ClusterResource
#######################
function Get-ClusterGroup
{
param($cluster)
gwmi -class MSCluster_ResourceGroup -namespace "root\\mscluster" -computername $cluster | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveGroup" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty PreferredNodes `
{ @(,(gwmi -namespace "root\\mscluster" -computerName $cluster -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToPreferredNode" | Select -ExpandProperty Name)) }
} #Get-ClusterGroup
|
PowerShellCorpus/PoshCode/0ddea161-baf2-439c-b797-afb5c636692f.ps1
|
0ddea161-baf2-439c-b797-afb5c636692f.ps1
|
#Variables
$Date = Get-Date
$TempReport = $env:TEMP + "\\temp.csv"
$FinalReport = $env:USERPROFILE + "\\" + $Date.Year + "_" + $Date.Month + "_" + $Date.Day + "_" + $Date.Hour + ":" + $Date.Minute + "_Scheduled_Task_Report.csv"
$title = Write-Host "Scheduled Task Reporter" -ForegroundColor green
$message = Write-Host "Which servers would you like to report on?" -ForegroundColor yellow
$EXIT = New-Object System.Management.Automation.Host.ChoiceDescription "&Exit", `
"Exits the script. . . "
$ALL = New-Object System.Management.Automation.Host.ChoiceDescription "&All Server Report", `
"Queries for all SERVERS in the domain and reports on their scheduled tasks."
$SRV = New-Object System.Management.Automation.Host.ChoiceDescription "&Single Host Report", `
"Queries for the exact server or workstation name entered."
$OTHR = New-Object System.Management.Automation.Host.ChoiceDescription "A&NR Report", `
"Peforms an ANR (Ambiguous Name Request) lookup. ANR allows you to do a report against one or more computers by typing part of the computer name."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($EXIT, $ALL, $SRV, $OTHR)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0 {Write-Host "No selection made. Exiting script. . ."}
1 {Get-QADComputer -sizelimit 0| Where {$_.osname -like "*Server*"} | Sort | % {schtasks /query /s $_.name /FO CSV /V | where {$_.length -gt 0} > $TempReport }}
2 {$Computer = Read-Host -Prompt "Enter the server name"
Get-QADComputer $Computer | Sort | % {schtasks /query /s $_.name /FO CSV /V | where {$_.length -gt 0} > $TempReport}} # | set-content 'export-csv $outputdestination'}}
3 {$Search = Read-Host -Prompt "Type all or part of the computer name"
Get-QADComputer -ANR $Search | ForEach-Object {schtasks /query /s $_.name /FO CSV /V | where {$_.length -gt 0} > $TempReport}}
|
PowerShellCorpus/PoshCode/Move-Mailbox 2010.ps1
|
Move-Mailbox 2010.ps1
|
$DistGroup = XC2010Move
$MB2Move = Get-DistributionGroup XC2010Move | Get-DistributionGroupMember | Get-Mailbox | Where {($_.RecipientTypeDetails -eq "LegacyMailbox") -and ($_.MailboxMoveStatus -eq ‘None’)} | Get-Random -Count 20
$batch = "MoveMB_{0:ddMMM_yyyy}" -f (Get-Date)
ForEach ($SingleMailbox in $MB2Move) {New-MoveRequest –Identity $SingleMailbox -BadItemLimit 100 -AcceptLargeDataLoss -Batchname $batch}
$MB2RemoveFromDG = Get-DistributionGroup XC2010Move | Get-DistributionGroupMember | Get-Mailbox | Where {($_.RecipientTypeDetails -eq "UserMailbox") -and ($_.MailboxMoveStatus -eq ‘Completed’)}
ForEach ($member in $MB2RemoveFromDG){Remove-DistributionGroupMember -Identity XC2010Move -Member $member -Confirm:$False}
ForEach ($member in $MB2RemoveFromDG){Remove-MoveRequest -Identity $member -Confirm:$False}
|
PowerShellCorpus/PoshCode/Set-UserCannotChangePass.ps1
|
Set-UserCannotChangePass.ps1
|
#########1#########2#########3#########4#########5#########6#########7#########8#########9#########1
#########0#########0#########0#########0#########0#########0#########0#########0#########0#########0
#
# Author: Erik McCarty
#
# Description: Set the "user Cannot Change Password" property on an active
# directory user object
#
# Remarks: There is poor documentation on the internet that would lead you
# to believe the $user.userAccountControl property value bit 0x000040 can
# be set to turn on the "user Cannot Change Password" account property.
# However you cannot assign this permission by directly modifying the
# userAccountControl attribute.
#
# History:
# 20080107 EWM Initial Creation
#
# reference:
# http://msdn2.microsoft.com/en-us/library/aa746398.aspx
# http://mow001.blogspot.com/2006/08/powershell-and-active-directory-part-8.html
# http://ewmccarty.spaces.live.com/blog/cns!CE2AE9EFF99E6598!132.entry
# Example:
#
# Set-UserCannotChangePassword "BMcClellan"
#
#########1#########2#########3#########4#########5#########6#########7#########8#########9#########1
#########0#########0#########0#########0#########0#########0#########0#########0#########0#########0
#
function set-UserCannotChangePassword( [string] $sAMAccountName ){
# set variables
$everyOne = [System.Security.Principal.SecurityIdentifier]'S-1-1-0'
$self = [System.Security.Principal.SecurityIdentifier]'S-1-5-10'
$SelfDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule (
$self,'ExtendedRight','Deny','ab721a53-1e2f-11d0-9819-00aa0040529b')
$SelfAllow = new-object System.DirectoryServices.ActiveDirectoryAccessRule (
$self,'ExtendedRight','Allow','ab721a53-1e2f-11d0-9819-00aa0040529b')
$EveryoneDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule (
$Everyone,'ExtendedRight','Deny','ab721a53-1e2f-11d0-9819-00aa0040529b')
$EveryOneAllow = new-object System.DirectoryServices.ActiveDirectoryAccessRule (
$Everyone,'ExtendedRight','Allow','ab721a53-1e2f-11d0-9819-00aa0040529b')
# find the user object in the default domain
$searcher = New-Object DirectoryServices.DirectorySearcher
$searcher.filter = "(&(samaccountname=$sAMAccountName))"
$results = $searcher.findone()
$user = $results.getdirectoryentry()
# set "user cannot change password"
$user.psbase.get_ObjectSecurity().AddAccessRule($selfDeny)
$user.psbase.get_ObjectSecurity().AddAccessRule($EveryoneDeny)
$user.psbase.CommitChanges()
}
|
PowerShellCorpus/PoshCode/Pomodoro Module.ps1
|
Pomodoro Module.ps1
|
#PomoDoro Module (make sure its a PS1)
#12-3-2011 Karl Prosser
#example
#import-module C:\\amodule\\Pomodoro.psm1 -force
#Start-Pomodoro -ShowPercent -Work "coding" -UsePowerShellPrompt
#future todos
# -limit , a number (by default 0 meaning forever) that will only run the pomodoro that many times
# -Confirm (after one is finished it will ask questions like whether you want to do another and whether you were successful)
# -StartSound - path to it - with the current ones as default
# -BreakSound -path to it -with current ones as default
# possibly some custom sounds and the module gets distributed as a zip.
# document all the functions fully with standard powershell help techniques.
# -useprompt - create a prompt instead and update that each time instead..
# Pomo 4:21> (means we are in the pomodoro with that many minutes left.. if work is specified like "watchlogs" then it could be
# watchlogs 4:21>
# and when its a break then Break 4:21>
# support reason for stopping
# when no progress is shown, do a write-host to state changes.
$script:DefaultLength = 25;
$script:DefaultBreak = 5;
$script:timer = $null
$script:showprogress = $true
function Stop-Pomodoro
{
[CmdletBinding()]
param(
[parameter()]
$reason
)
Unregister-Event "Pomodoro" -ErrorAction silentlycontinue
$script:timer = $null
}
function Set-PomodoroPrompt
{
[CmdletBinding()]
param ()
$script:promptbackup = $function:prompt
$function:prompt = { Get-PomodoroStatus -ForPrompt}
}
function Restore-PomodoroPrompt
{
[CmdletBinding()]
param ()
$function:prompt = $script:promptbackup
}
function Show-PomodoroProgress
{
[cmdletbinding()]param()
$script:showprogress = $true
}
function Hide-PomodoroProgress
{
[cmdletbinding()]param()
$script:showprogress = $false
}
function Get-PomodoroStatus
{
[CmdletBinding(DefaultParameterSetName="summary")]
param(
[Parameter(ParameterSetName="remaining",Position=0)]
[switch]$remaining
,
[Parameter(ParameterSetName="From",Position=0)]
[switch]$From
,
[Parameter(ParameterSetName="Until",Position=0)]
[switch]$Until
,
[Parameter(ParameterSetName="Length",Position=0)]
[switch]$Length
,
[Parameter(ParameterSetName="forPrompt",Position=0)]
[switch]$ForPrompt
)
if($script:timer)
{
if($script:pomoorbreak)
{
$prefix = "Pomodoro - $script:currentwork"
$pomotime = new-object system.TimeSpan 0,0,$script:currentlength,0
}
else
{
$prefix = "Having a Break from work - $script:currentwork"
$pomotime = new-object system.TimeSpan 0,0,$script:currentbreak,0
}
$diff = (get-Date) - $script:starttime
$timeleft = $pomotime - $diff
$endtime = $starttime + $pomotime
}
switch ($PsCmdlet.ParameterSetName)
{
"summary" { "{5} for {4} minutes from {0:hh:mm} to {1:hh:mm} - {2}:{3:00} minutes left." -f $starttime,$endtime ,$timeleft.minutes, $timeleft.seconds ,$pomotime.minutes,$prefix}
"remaining" { $timeleft}
"From" {$script:starttime}
"Until" { $endtime }
"Length" {$pomotime}
"ForPrompt" {
if($script:timer)
{
if ($script:pomoorbreak)
{
if($script:currentwork -and ($script:currentwork.trim() -ne [string]::Empty))
{
"{0} {1}:{2:00}>" -f $(if($script:currentwork.length -gt 8) { $script:currentwork.substring(0,8)} else {$script:currentwork} ),
$timeleft.minutes, $timeleft.seconds
}
else
{
"{0} {1}:{2:00}>" -f "Pomo",$timeleft.minutes, $timeleft.seconds
}
}
else
{
"{0} {1}:{2:00}>" -f "Break",$timeleft.minutes, $timeleft.seconds
}
}
else
{
"No Pomo>"
}
}
}
}
function Start-Pomodoro
{
[CmdletBinding()]
param (
[Parameter()]
[int]$Length = $script:DefaultLength
,
[Parameter()]
[int]$Break = $script:DefaultBreak
,
[Parameter()]
[string]$Work
,
[Parameter()]
[switch]$ShowPercent
,
[Parameter()]
[switch]$HideProgress
,
[Parameter()]
[switch]$UsePowerShellPrompt
)
$script:currentlength = $length
$script:currentbreak = $break;
$script:currentshowpercent = [bool]$showpercent;
$script:currentwork = $work
if($HideProgress) { $script:showprogress = $false } else { $script:showprogress = $true }
#if pomoDoro Already running then stop it
Unregister-Event "Pomodoro" -ErrorAction silentlycontinue
$script:timer = $null
$script:pomoorbreak = $true
$script:starttime = get-Date
$script:timer = New-Object System.Timers.Timer
$script:timer.Interval = 1000
$script:timer.Enabled = $true
$null = Register-ObjectEvent $timer "Elapsed" -SourceIdentifier "Pomodoro" -Action {
$breakmode = & (get-Module Pomodoro) { $script:PomoOrBreak }
$starttime = & (get-Module Pomodoro) { $script:starttime }
$break = & (get-Module Pomodoro) {$script:currentbreak}
$length = & (get-Module Pomodoro) { $script:currentlength }
$work= & (get-Module Pomodoro) { $script:currentwork }
if($breakmode)
{
$prefix = "Pomodoro - $work "
$pomotime = new-object system.TimeSpan 0,0,$length,0
}
else
{
$prefix = "Having a Break from work - $work"
$pomotime = new-object system.TimeSpan 0,0,$break,0
}
$diff = (get-Date) - $starttime
$timeleft = $pomotime - $diff
$endtime = $starttime + $pomotime
$timeleftdisplay = "for {4} minutes from {0:hh:mm} to {1:hh:mm} - {2}:{3:00} minutes left." -f $starttime,$endtime ,$timeleft.minutes, $timeleft.seconds ,$pomotime.minutes
if (($pomotime - $diff) -le 0)
{
write-Progress -Activity " " -Status "done";
$sound = new-Object System.Media.SoundPlayer;
if ($breakmode)
{
$sound.SoundLocation="$env:systemroot\\Media\\tada.wav";
}
else
{
$sound.SoundLocation="$env:systemroot\\Media\\notify.wav";
}
$sound.Play();
sleep 1
$sound.Play();
sleep 1
$sound.Play();
iex "& (get-module pomodoro) {`$script:starttime = get-Date; `$script:pomoorbreak = ! `$$breakmode } "
}
else
{
if ( & (get-Module Pomodoro) { $script:showprogress } )
{
if (& (get-Module Pomodoro) { $script:currentshowpercent} )
{
$perc =100 - ( [int] ([double]$timeleft.totalseconds * 100 / [double]$pomotime.totalseconds))
write-Progress -Activity $prefix -Status "$timeleftdisplay" -PercentComplete $perc
}
else
{
write-Progress -Activity $prefix -Status "$timeleftdisplay"
}
}
}
}
if($UsePowerShellPrompt) { Set-PomodoroPrompt }
}
export-ModuleMember -Function "*"
$myInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
if ($script:promptbackup) { $function:prompt = $script:promptbackup }
}
|
PowerShellCorpus/PoshCode/DekiWiki Module 1.5.ps1
|
DekiWiki Module 1.5.ps1
|
## DekiWiki Module 1.5
#require -version 2.0
## Depends on the HttpRest script-module:
## http :// huddledmasses.org/using-rest-apis-from-powershell-with-the-dream-sdk/
####################################################################################################
## The first of many script cmdlets for working with DekiWiki, based on the HttpREST module
##
## For documentation of the DekiWiki REST API:
## http :// wiki.developer.mindtouch.com/MindTouch_Deki/API_Reference
####################################################################################################
## USAGE:
## Add-Module DekiWiki
## Set-DekiUrl http`://powershell.wik.is
## ...
## ## For usage of each cmdlet, see the comments above each individual function ## ## ## ## ## ## ##
####################################################################################################
## History:
## v 1.5 Rewrite with the "Dream" specific code extracted to the HttpRest module
## v 1.2 Remove-DekiFile
## v 1.0 Set-DekiCredential, Get-DekiContent, Set-DekiContent, New-DekiContent, Set-DekiFile
##
$hr = Add-Module HttpRest -Passthru
Add-Module "$PSScriptRoot\\Utilities.ps1"
$url = "http://powershell.wik.is"
$api = "$url/@api/deki"
#New-Alias Set-DekiCredential Set-HttpCredential -EA "SilentlyContinue"
#New-Alias Set-DekiUrl Set-HttpDefaultUrl -EA "SilentlyContinue"
FUNCTION Set-DekiUrl {
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
Set-HttpDefaultUrl $baseUri
}
FUNCTION Set-DekiCredential {
PARAM($Credential=$(Get-Credential -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $global:url.Host ))
Set-HttpCredential $Credential
}
New-Alias e2 Encode-Twice -EA "SilentlyContinue"
Add-Type '
public class ModuleInfo {
public string Name;
public string[] Author;
public string CompanyName;
public string[] Copyright;
public string[] Description;
public System.Version ModuleVersion;
public string[] RequiredAssemblies;
public string[] Dependencies;
public System.Guid GUID = System.Guid.NewGuid();
public string[] PowerShellVersion;
public string[] ModulesToProcess;
public System.Version CLRVersion;
public string[] FormatsToProcess;
public string[] TypesToProcess;
public string[] OtherItems;
public string ModuleFile;
}
' -EA "SilentlyContinue"
# Retrieve a sitemap of all the pages in a wiki,
# OR Retrieve all the subpages of a page as a sitemap
# Added by Mark E. Schill
CMDLET Get-DekiSiteMap {
PARAM(
[Parameter(Position=0, Mandatory=$false)]
[string]
$StartPage
,
[Parameter(Position=1, Mandatory=$false)]
[ValidateSet("xml","html","google")]
[string]
$Format = "xml"
)
if($StartPage) {
Invoke-Http GET "pages/=$(e2 $StartPage)/tree" @{"format"=$format} | Receive-Http -Out Xml
} else {
Invoke-Http GET "pages" @{"format"=$format} | Receive-Http -Out Xml
}
}
# Get the contents of a page from a DekiWiki
# Note that by default you retrieve the "view" (rendered) markup
# If you want to see it before the extensions run, you should specify at least -mode viewnoexecute
# If you want to see the source so you can make changes, be sure to specify -mode edit
CMDLET Get-DekiContent {
PARAM(
[Parameter(Position=0, Mandatory=$true)]
[string]
$pageName
,
[Parameter(Position=1, Mandatory=$false)]
[int]
$section
,
[Parameter(Position=5, Mandatory=$false)]
[ValidateSet("edit", "raw", "view", "viewnoexecute")]
[string]
$mode="view"
)
Invoke-Http "GET" "pages/=$(e2 $pageName)/contents" @{mode=$mode;section=$section} | Receive-Http -Out Xml
}
# Get-DekiFile will LIST all files if called with just a PageName
# Otherwise, fileName can be a single fileName, or wildcards
# To download all the attachments on a page, try:
# Get-DekiFile PageName | Get-DekiFile
CMDLET Get-DekiFile {
PARAM(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[string]
$pageName
,
[Parameter(Position=1, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[string]
$fileName
,
[Parameter(Position=2, Mandatory=$false)]
[string]
$destination
)
PROCESS {
## Remember, we can get both on the pipeline, so ...
$files = Invoke-Http "GET" "pages/=$(e2 $pageName)/files" | Receive-Http Xml //file
Write-Verbose "Fetching $($fileName) from the $($files.Count) in $pageName"
if(!$fileName) {
## Add a PageName property, because then you can pipe the output back to Get-DekiFile after filtering...
write-output $files | Add-Member NoteProperty PageName $pageName -passthru
} else {
## Using -like means $fileName allows globbing
foreach($file in $($files | where { $_.filename -like $fileName } )) {
Invoke-Http "GET" "pages/=$(e2 $pageName)/files/=$(e2 $file.filename)" | Receive-Http File $(Get-FileName $file.filename $destination)
}
}
}
}
# Set the contents of a DekiWiki page
# Note that you can pass the content as an XML document, plain text, or a filename...
CMDLET Set-DekiContent {
PARAM(
[Parameter(Position=0, Mandatory=$true)]
[string]
$pageName
,
[Parameter(Position=1, Mandatory=$true,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$content
,
[Parameter(Position=2, Mandatory=$false)]
$section
,
[switch]$new
,
[switch]$append
)
$with = @{"edittime"=$(Get-UtcTime "yyyyMMddhhmmss")}
if($new) {
$with.abort = "exists"
}
if($append) {
$with.section = "0"
} elseif($section) {
$with.section = $section
}
$result = Invoke-Http POST "pages/=$(e2 $pageName)/contents" -With $with -Content $content -Auth $true -Wait
if($result.IsSuccessful) {
return "$url/$($result | Receive-Http Text //edit/page/path)"
} else {
return $result
}
}
# Same as Set-DekiContent, except this one crashes if the page already exists.
# This is technically the only safe way to create new pages without fear of conflicts...
CMDLET New-DekiContent {
PARAM(
[Parameter(Position=0, Mandatory=$true)]
[string]$pageName
,
[Parameter(Position=1, Mandatory=$true,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$content
)
PROCESS {
Set-DekiContent $pageName $content -new
}
}
# Add a new attachment (or a new version of an existing attachment)
# You can use wildcards, and specify arrays. But you could also include descriptions
# USAGE:
## Set-DekiFile Path/PageName *.ps1,*.psm1
## Set-DekiFile Path/PageName @{"Neat.jpg"="A really cool screenshot";"Source.zip"="The source code"}
## Set-DekiFile Path/PageName Something.png
## ls *.png | Set-DekiFile Path/PageName
CMDLET Set-DekiFile {
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$pageName
,
[Parameter(Position=1, Mandatory=$true,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
$Files
)
# Two ways to specify files: 1) hashtable: file = "description" 1) array: file, file, file
$hasDescriptions = $false;
if($files -is [Hashtable]) {
$hasDescriptions = $true;
$fileNames = $files.Keys
} else {
$fileNames = $files
}
foreach($fileName in $fileNames) {
foreach($file in (gci $fileName)) {
$with = @{}
if($hasDescriptions) {
$With.description = $files[$fileName]
}
$result = Http-Invoke PUT "pages/=$(e2 $pageName)/files/=$($file.Name)" $With $file.FullName -Wait
if($result.IsSuccessful) {
return ($result | Receive-Http Text //file/href)
} else {
return $result.Response
}
}
}
}
## Move a page from one place to another (leaving an "alias" placeholder)
CMDLET Move-DekiContent {
PARAM(
[Parameter(Position=0, Mandatory=$true)]
[string]
$pageName
,
[Parameter(Position=1, Mandatory=$true)]
[string]
$newPageName
)
$with = @{"to"="$newPageName"}
$result = Invoke-Http POST "pages/=$(e2 $pageName)/move" -With $with -Auth $true -Wait
if($result.IsSuccessful) {
return "$url/$($result | Receive-Http Text '//page[1]/path' )"
} else {
return $result
}
}
CMDLET New-DekiAlias {
PARAM(
[Parameter(Position=0, Mandatory=$true)]
[string]
$pageName
,
[Parameter(Position=1, Mandatory=$true)]
[string]
$Alias
)
$result = Invoke-Http POST "pages/=$(e2 $pageName)/move" @{"to"="$Alias"} -Auth $true -Wait
if($result.IsSuccessful) {
$aliasPage = "$url/$($result | Receive-Http Text '//page[1]/path' )"
$result = Invoke-Http POST "pages/=$(e2 $Alias)/move" @{"to"="$pageName"} -Auth $true -Wait
if($result.IsSuccessful) {
return $aliasPage
} else {
return $result
}
} else {
return $result
}
}
# Delete a page from a dekiwiki, with an option to RECURSIVELY delete all child pages.
# NOTE: if you delete a page that has children, and don't recurse, the contents are removed
# and then replaced with template text, because they can't go away completely
# NOTE: if you delete a page, it is actually put in the archive
# TODO: add a -Force parameter to allow them to be permanently deleted from the archive
CMDLET Remove-DekiContent {
PARAM(
[Parameter(Position=0, Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$pageName
,
[Parameter(Position=2, Mandatory=$false)][switch]$recurse
)
Http-Invoke DELETE "pages/=$(e2 $pageName)" @{recursive=$($recurse.ToBool())}
if($result.IsSuccessful) {
return "DELETED $url/$PageName"
} else {
return $result.Response
}
}
# Delete a file attachment from a dekiwiki page
# You can use wildcards, and specify arrays:
## USAGE:
## Remove-DekiFile Path/PageName *.ps1,*.psm1
## Remove-DekiFile Path/PageName Something.png
## ls *.png | Remove-DekiFile Path/PageName
CMDLET Remove-DekiFile {
PARAM(
[Parameter(Position=0, Mandatory=$true,ValueFromPipelineByPropertyName=$true)][string]$pageName
,
[Parameter(Position=1, Mandatory=$true,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Name")]
$fileNames
)
$files = Invoke-Http GET "pages/=$(e2 $pageName)/files" | Receive-Http Text //file/filename
foreach($fileName in $fileNames) {
foreach($file in $($files -like $fileName)) {
$path = "pages/=$(e2 $pageName)/files/=$(e2 $file)"
Write-Host $path -fore cyan
$result = Invoke-Http DELETE $path -Auth $true -Wait
if($result.IsSuccessful) {
"DELETED: $api/$path"
} else {
$result.Response
}
}
}
}
Export-ModuleMember Set-DekiCredential, Set-DekiUrl,
Get-HtmlHelp, Get-DekiFile, Get-DekiSiteMap, Get-DekiContent,
Set-DekiContent, New-DekiContent,
Move-DekiContent, New-DekiAlias,
Remove-DekiContent, Remove-DekiFile,
Set-DekiFile
|
PowerShellCorpus/PoshCode/Audit File Share Perms.ps1
|
Audit File Share Perms.ps1
|
Function Get-SharePermissions($ShareName){
$Share = Get-WmiObject win32_LogicalShareSecuritySetting -Filter "name='$ShareName'"
if($Share){
$obj = @()
$ACLS = $Share.GetSecurityDescriptor().Descriptor.DACL
foreach($ACL in $ACLS){
$User = $ACL.Trustee.Name
if(!($user)){$user = $ACL.Trustee.SID}
$Domain = $ACL.Trustee.Domain
switch($ACL.AccessMask)
{
2032127 {$Perm = "Full Control"}
1245631 {$Perm = "Change"}
1179817 {$Perm = "Read"}
}
$obj = $obj + "$Domain\\$user $Perm<br>"
}
}
if(!($Share)){$obj = " ERROR: cannot enumerate share permissions. "}
Return $obj
} # End Get-SharePermissions Function
Function Get-NTFSOwner($Path){
$ACL = Get-Acl -Path $Path
$a = $ACL.Owner.ToString()
Return $a
} # End Get-NTFSOwner Function
Function Get-NTFSPerms($Path){
$ACL = Get-Acl -Path $Path
$obj = @()
foreach($a in $ACL.Access){
$aA = $a.FileSystemRights
$aB = $a.AccessControlType
$aC = $a.IdentityReference
$aD = $a.IsInherited
$aE = $a.InheritanceFlags
$aF = $a.PropagationFlags
$obj = $obj + "$aC | $aB | $aA | $aD | $aE | $aF <br>"
}
Return $obj
} # End Get-NTFSPerms Function
Function Get-AllShares{
$a = Get-WmiObject win32_share -Filter "type=0"
Return $a
} # End Get-AllShares Function
# Create Webpage Header
$z = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`" `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$z = $z + "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$z = "<head><style>"
$z = $z + "TABLE{border-width: 2px;border-style: solid;border-color: black;border-collapse: collapse;}"
$z = $z + "TH{border-width: 2px;padding: 4px;border-style: solid;border-color: black;background-color:lightblue;text-align:left;font-size:14px}"
$z = $z + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;font-size:12px}"
$z = $z + "</style></head><body>"
$z = $z + "<H4>File Share Report for $env:COMPUTERNAME</H4>"
$z = $z + "<table><colgroup><col/><col/><col/><col/><col/><col/></colgroup>"
$z = $z + "<tr><th>ShareName</th><th>Location</th><th>NTFSPermissions<br>IdentityReference|AccessControlType|FileSystemRights|IsInherited|InheritanceFlags|PropagationFlags</th><th>NTFSOwner</th><th>SharePermissions</th><th>ShareDescription</th></tr>"
$MainShares = Get-AllShares
Foreach($MainShare in $MainShares){
$MainShareName = $MainShare.Name
$MainLocation = $MainShare.Path
$MainNTFSPermissions = Get-NTFSPerms -Path $MainLocation
$MainNTFSOwner = Get-NTFSOwner -Path $MainLocation
$MainSharePermissions = Get-SharePermissions -ShareName $MainShareName
$MainShareDescription = $MainShare.Description
$z = $z + "<tr><td>$MainShareName</td><td>$MainLocation</td><td>$MainNTFSPermissions</td><td>$MainNTFSOwner</td><td>$MainSharePermissions</td><td>$MainShareDescription</td></tr>"
}
$z = $z + "</table></body></html>"
$OutFileName = $env:COMPUTERNAME + "ShareReport.html"
Out-File -FilePath .\\$OutFileName -InputObject $z -Encoding ASCII
$OutFileItem = Get-Item -Path .\\$OutFileName
Write-Host " Report available here: $OutFileItem" -Foregroundcolor Yellow
Exit
|
PowerShellCorpus/PoshCode/Scan Remote Event Logs.ps1
|
Scan Remote Event Logs.ps1
|
#requires -version 2.0
function Scan-EventLogs
{
<#
.SYNOPSIS
Scan event logs on specified computer(s) and return a sorted collection events to review.
.Description
Uses PowerShell Remoting with Invoke-Command and Get-EventLog to fetch a list of enabled event logs from one or more computers and sort output.
.PARAMETER ComputerName
Specifies one or more computers to scan and report event logs info from. The default is the local computer.
.PARAMETER Sort
Specifies a property to sort by. The default is MachineName, but
any property of EventLogConfiguration class could be used, including "IsClassicLog" and "FileSize".
.PARAMETER Descending
Indicates whether to be descending or ascending sort order. Default is descending = true.
.PARAMETER Exclude
An array of psobjects created by the New-EventId cmdlet which will be excluded from the output.
.PARAMETER Credential
The network credential to use when connecting to a remote compiuter.
.EXAMPLE
PS > $Exclusions = (New-EventId -Source "W32Time" -EventId 29), (New-EventId -Source "Netlogon" -EventId 5719)
PS > Get-EnabledEvtLogs -CN "ANY-SERVER", "Localhost" -Sort "Source" -Descending $true
#>
# Parameters
Param
(
[parameter(Mandatory=$false)]
[alias("CN")]
[String[]] $ComputerName = $ENV:COMPUTERNAME,
[parameter(Mandatory=$false)]
[String] $Sort = "MachineName",
[parameter(Mandatory=$false)]
[Boolean] $Descending = $true,
[parameter(Mandatory=$false)]
[psobject[]] $Exclude,
[parameter(Mandatory=$false)]
[PSobject] $Credential
)
Process
{
# Help enforcing coding rules...
Set-StrictMode -Version Latest
# The logs we want to scan...
$LogNames = "Security", "System";
$EntryTypes = "FailureAudit", "Error";
$list = $null;
foreach($cn in $ComputerName)
{
foreach($logName in $LogNames)
{
# Determine dates for last month
$LastMonth = (get-date).AddMonths(-1);
$LastMonthFirst = get-date -year $LastMonth.Year -month $LastMonth.Month -day 1
$ThisMonthFirst = get-date -year (get-date).Year -month (get-date).Month -day 1
$EventLogArgs = @{
ComputerName = $cn
LogName = $logName
After = $LastMonthFirst
Before = $ThisMonthFirst
EntryType = $EntryTypes
AsBaseObject = $true
}
# Build args struct
$remoteScript = { param($elArgs) & get-eventlog @elArgs }
# get events...
$events = Invoke-Command -ScriptBlock $remoteScript -ComputerName $cn -Credential $Credential -ArgumentList $EventLogArgs;
# Build the filter algorithm for the where object...
$filterScript =
{
# Loop through the exclusions...
$bInc = $true;
foreach($ex in $Exclude)
{
# first check to make sure the incoming object has a Source property..
$hasSource = get-member -name "Source" -InputObject $_
# if not has Source
if($hasSource -eq $null)
{
$bInc = $false;
}
# in our exlucde list, then not include.
else
{
if($_.Source -eq $ex.Source -and $_.EventID -eq $ex.EventID)
{
$bInc = $false;
}
}
}
$bInc;
};
# Do the actual filtering...
[psobject[]]$filtered = $null;
foreach($evt in $events)
{
$filtered += where -FilterScript $filterScript -InputObject $evt;
}
# prepare final list...
$list += ($filtered | select MachineName, EntryType, TimeGenerated, Source, EventId, Message, UserName);
}
}
# Sort the collection according to callers wishes and format for output...
$list | sort -property @{Expression=$Sort;Descending=$Descending}
}
}
function New-EventId
{
Param
(
[ValidateNotNullOrEmpty()]
[string] $Source,
[ValidateNotNullOrEmpty()]
[int] $EventId
)
process
{
$EventIdItem = new-object psobject;
$EventIdItem | add-member -membertype noteproperty -name Source -value $Source;
$EventIdItem | add-member -membertype noteproperty -Name EventID -value $EventId;
$EventIdItem;
}
}
|
PowerShellCorpus/PoshCode/Findup_26.ps1
|
Findup_26.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>>
{ {"/x", new List<string>()},{"/i",new List<string>()},{"/xf",new List<string>()},{"/if",new List<string>()},
{"/xd",new List<string>()},{"/id",new List<string>()},{"/paths",new List<string>()} };
public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>>
{ {"/xr", new List<Regex>()},{"/ir",new List<Regex>()},{"/xfr",new List<Regex>()},{"/ifr",new List<Regex>()},
{"/xdr",new List<Regex>()},{"/idr",new List<Regex>()} };
public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "/recurse", false }, { "/noerr", false }, {"/delete",false}, {"/xj", false}};
public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes.
public static long errors = 0;
public static string delconfirm;
public static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
Console.WriteLine(" ");
string optionskey = "/paths";
List<FileInfo> files = new List<FileInfo>();
int i = 0;
for (i = 0; i < args.Length; i++)
{
string argitem = args[i].ToLower();
if ((System.String.Compare(argitem, "/help", true) == 0) || (System.String.Compare(argitem, "/h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [/recurse] [/noerr] [/x /i /xd /id /xf /if + [r]] <files/directories/regex> [/delete]");
Console.WriteLine(" ");
Console.WriteLine("Options: /help - displays this help message.");
Console.WriteLine(" /recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" /noerr - discards error messages.");
Console.WriteLine(" /delete - delete each duplicate file with confirmation.");
Console.WriteLine(" /x - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used.");
Console.WriteLine(" /i - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used.");
Console.WriteLine(" /xd - eXcludes all directories - minus drive/files - (using RegEx if /xdr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /id - Include only directories - minus drive/files - (using RegEx if /idr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /xf - eXcludes all files - minus drive/directories - (using RegEx if /xfr) following this switch until another switch is used.");
Console.WriteLine(" /if - Include only files - minus drive/directories - (using RegEx if /ifr) following this switch until another switch is used.");
Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
Console.WriteLine(" /paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
Console.WriteLine(" /xj - Exclude File and Directory Junctions.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" - deletes duplicates after consent is given.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data /recurse /x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc /xfr \\"(jim)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc /xr \\"[bf]\\" /ir \\"(smith)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the path name as specified by the Regex items \\"[bf]\\",\\"(smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (optionsbools.ContainsKey(argitem))
{
optionsbools[argitem] = true;
optionskey = "/paths";
continue;
}
if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
{
optionskey = argitem;
continue;
}
if (optionspaths.ContainsKey(optionskey))
optionspaths[optionskey].Add(args[i]);
else
{
try {
Regex rgx = new Regex(args[i], RegexOptions.Compiled);
optionsregex[optionskey].Add(rgx);
}
catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);}
}
}
if (optionspaths["/paths"].Count == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
optionspaths["/paths"].Add(".");
}
Console.Write("Getting file info and sorting file list...");
getFiles(optionspaths["/paths"], "*.*", optionsbools["/recurse"], files);
if (files.Count < 2)
{
WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
Console.WriteLine("\\n");
return;
}
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");
var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>();
long filesize = 0;
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) continue;
var breakout = false;
while (true)
{
filesize = (files[i].Length);
try
{
var _SHA512 = SHA512.Create();
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
string SHA512string = Hash2String(_SHA512.Hash);
if (!SizeHashFile.ContainsKey(filesize))
SizeHashFile.Add(filesize, new Dictionary<string,List<FileInfo>>());
if (!SizeHashFile[filesize].ContainsKey(SHA512string))
{
SizeHashFile[filesize][SHA512string] = new List<FileInfo>() {};
}
SizeHashFile[filesize][SHA512string].Add(files[i]);
}
catch (Exception e) { WriteErr("Hash error: " + e.Message); }
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
breakout = (files[i].Length != files[i + 1].Length);
}
if (SizeHashFile.ContainsKey(filesize))
{
foreach (var HG in SizeHashFile[filesize])
{
if (HG.Value.Count > 1)
{
Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count);
foreach (var finfo in HG.Value)
{
Console.WriteLine(finfo.FullName);
numOfDupes++;
dupeBytes += finfo.Length;
if (optionsbools["/delete"])
if (DeleteDupe(finfo)) { bytesrecovered += finfo.Length; deletedfiles++; }
}
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS.
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered);
Console.WriteLine("Errors : {0:N0}", errors);
Console.WriteLine("Execution time : " + (DateTime.Now - startTime));
}
private static void WriteErr(string Str)
{
errors++;
if (!optionsbools["/noerr"])
Console.WriteLine(Str);
}
private static string Hash2String(Byte[] hasharray)
{
string SHA512string = "";
foreach (var c in hasharray)
{
SHA512string += String.Format("{0:x2}", c);
}
return SHA512string;
}
private static Boolean DeleteDupe(FileInfo Filenfo)
{
Console.Write("Delete this file <y/N> <ENTER>?");
delconfirm = Console.ReadLine();
if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y'))
{
try
{
Filenfo.Delete();
Console.WriteLine("File Successfully deleted.");
return true;
}
catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); }
}
return false;
}
private static Boolean CheckNames(string fullname)
{
var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt")
var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp")
if (CheckNamesWorker(fullname, "/x", "/xr", true))
return false;
if (CheckNamesWorker(filePart, "/xf", "/xfr", true))
return false;
if (CheckNamesWorker(dirPart, "/xd", "/xdr", true))
return false;
if (CheckNamesWorker(fullname, "/i", "/ir", false))
return false;
if (CheckNamesWorker(filePart, "/if", "/ifr", false))
return false;
if (CheckNamesWorker(dirPart, "/id", "/idr", false))
return false;
return true;
}
private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType)
{
foreach (var filepath in optionspaths[pathskey])
{
if (filestr.ToLower().StartsWith(filepath) == CheckType)
return true;
}
foreach (var rgx in optionsregex[rgxkey])
{
if (rgx.IsMatch(filestr) == CheckType)
return true;
}
return false;
}
private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
catch (Exception e) { WriteErr("Add file error: " + e.Message); }
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); }
if (recursiveFlag)
{
try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); }
catch (Exception e) { WriteErr("Add Directory error: " + e.Message); }
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/NewUser in AD_OCS_Email_1.ps1
|
NewUser in AD_OCS_Email_1.ps1
|
# New User In PowerShell
# ye110wbeard (EnergizedTech) Finally shuts up and writes a script that is USEFUL and doesn't sing about it
# 7/15/2009 :)
# And it couldn't have happened if it wasn't for the Powershell Community
#
# This script in many ways is VERY simple. I simply chose to use simple assignments instead of a fancy "CSV Import" so a Powershell
# Newbie might be able to look at it, and get a better grasp of what everything is in Active Directory when THEY want to do something similiar
#
# For Newbie Users, a line beginning with a '#' is a comment. If you put a '#' the line will be ignored.
# Prompt User for FirstName and LastName of new user
$FirstName = read-host -Prompt "Enter User First Name: "
$LastName = read-host -Prompt "Enter User Last Name: "
# Password must be read from Console as Secure String to be applied. If you're manipulate this to a Batch User process, you can use this one password as a default. The Exchange New-Mailbox has the "Change Password at login" enabled by default
$TempPassword = read-host -AsSecureString -Prompt "Please Enter Temporary Password"
# SAM name will appear as Firstname.Lastname in Active Directory. Adjust to meet your needs
$Sam=$FirstName+"."+$LastName
$max=$Sam.Length
#The SAM account cannot be greater than 20 characters. You have to account for this. A better functionn would stop query and say "Too big stupid" but this is my first time out
if ($max -gt 20) {$max=20}
$Sam=$Sam.Substring(0,$max)
# This is handy if your organization must have the names listed by Lastname, Firstname. Exchange 2007 cannot do this natively (as least not that I have found)
$Name=$Lastname+", "+$FirstName
$DisplayName=$Lastname+", "+$FirstName
# User Alias Displaying as Firstname.Lastname
$Alias=$FirstName+"."+$LastName
# UPN will be your internal login ID. Typically Alias@domain.local or Username@domain.com
$UPN=$FirstName+"."+$LastName+"@Contoso.local"
# UNC Pathname to a share where all user folders reside. Path must exist. Recommend adding $ to sharename to hide from User Browsing
$HomeDir='\\\\CONTOSOFILE\\USERHOME$\\'+$Alias
# Drive Letter assigned to \\\\CONTOSOFILE\\USERHOME$\\USERNAME Folder - Pick one
$HomeDrive='Z:'
# Generic inbound office line and format of User Phone Extension. Display purposes only. Could be prompted as well
$Phone='212-555-0000 x111'
# Your friendly neighbourhood ZIPCODE (or POSTALCODE if you're from Canada 'eh'?)
$PostalZip='90210'
# City the user works in. If you have multiple offices, you could prompt this as well
$City='Toronto'
# Your State (no not Confusion, the one you live in) or Province for those 'Canadians' Again
$StateProv='Ontario'
# Address you work at
$Address='123 Sesame Street'
# Default web site
$Web='www.contosorocks.com'
# Company where you work at, or won't work at if your boss catches you spending too much time drooling over Powershell
$Company='Contoso Rocks Ltd'
# What location in the building? typically floor X, Division Y, the back room behind the boxes
$Office='In the Basement with my stapler'
# A generic description for the user
$Description='New User'
# Job Description. Carpet burner, box stacker, cable monkey
$JobTitle='New User Hired'
# What department. Where you hiding? Network Admins, Secretaries?
$Department='New Department Hire'
# Office Fax Number
$Fax='212-555-1234'
# The ending part of the domain @wherever.com @fabrikam.com etc etc
$ourdomain='@contoso.local'
# This first line is done within the Microsoft Exchange Management Shell from Exchange 2007. I add it's ability to my Powershell with the command
# ADD-PSSNAPIN -name Microsoft.Exchange.Management.Powershell.Admin IF you have the Microsoft Exchange console on the computer running this script. And you have Microsoft Exchange Server 2007 in the environment
New-Mailbox -Name $Name -Alias $Alias -OrganizationalUnit 'Contoso.local/Users' -UserPrincipalName $UPN -SamAccountName $SAM -FirstName $FirstName -Initials '' -LastName $LastName -Password $TempPassword -ResetPasswordOnNextLogon $true -Database 'CONTOSOEXCHANGE\\First Storage Group\\Mailbox Database'
# This command l
set-qaduser -identity $alias -homedirectory $HomeDir -homedrive $Homedrive -city $City -company $Company -department $Department -fax $Fax -office $Office -phonenumber $Phone -postalcode $PostalZip -stateorprovince $StateProv -streetaddress $Address -webpage $web -displayname $displayname -title $JobTitle
#http://www.powergui.org/thread.jspa?messageID=14099 Source post for creating OCS user with Powershell! Thank you Powergui.ORG!
#
# Tips. If you do have Office Communications Server or Live Comm and looking for the Variables used, Check an enabled user in Active Directory while in ADVANCED mode
# and choose the "Attribute Editor" tab. You'll find them all down there. If it doesn't say "Enabled" or contain a value? Don't use it
$SIPHOMESERVER='CN=LC Services,CN=Microsoft,CN=CONTOSO-OCSSERVER,CN=Pools,CN=RTC Service,CN=Microsoft,CN=System,DC=CONTOSO,DC=local'
$oa = @{'msRTCSIP-OptionFlags'=384; 'msRTCSIP-PrimaryHomeServer'=$SIPHOMESERVER; 'msRTCSIP-PrimaryUserAddress'=("sip:"+$alias+$ourdomain); 'msRTCSIP-UserEnabled'=$true }
Set-QADUser $Alias -oa $oa
#http://blogs.msdn.com/johan/archive/2008/10/01/powershell-editing-permissions-on-a-file-or-folder.aspx - Great reference on SETTING NTFS permissions with SET-ACL! Thumbs up!
#Make User Home Folder and Apply NTFS permissions - This was taken almost VERBATIM from the Blogpost. I added in the $alias created from the FirstName Lastname to automatically populate a HomeFolder based upon the user name
$HomeFolderMasterDir='\\\\CONTOSOFILE\\USERHOME$\\'
new-item -path $HomeFolderMasterDir -name $Alias -type directory
$Foldername=$HomeFolderMasterDir+$Alias
$DomainUser='CONTOSO\\'+$Alias
$ACL=Get-acl $Foldername
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule($DomainUser,"FullControl","Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $Foldername $Acl
|
PowerShellCorpus/PoshCode/Sync-Time_1.ps1
|
Sync-Time_1.ps1
|
function sync-time(
[string] $server = "clock.psu.edu",
[int] $port = 37)
{
$servertime = get-time -server $server -port $port -set
#leave off -set to just check the remote time
write-host "Server time:" $servertime
write-host "Local time :" $(date)
}
|
PowerShellCorpus/PoshCode/VerifyCategoryRule_2.ps1
|
VerifyCategoryRule_2.ps1
|
2RIXu3 this is delisious!
xfather123
|
PowerShellCorpus/PoshCode/Write-Log_3.ps1
|
Write-Log_3.ps1
|
function Write-Log {
#region Parameters
[cmdletbinding()]
Param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
[string] $Message,
[Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)]
[string] $Level = “Info”,
[Parameter()]
[Switch] $NoConsoleOut,
[Parameter()]
[String] $ConsoleForeground = 'White',
[Parameter()] [ValidateRange(1,30)]
[Int16] $Indent = 0,
[Parameter()]
[IO.FileInfo] $Path = ”$env:temp\\PowerShellLog.txt”,
[Parameter()]
[Switch] $Clobber,
[Parameter()]
[String] $EventLogName,
[Parameter()]
[String] $EventSource,
[Parameter()]
[Int32] $EventID = 1
[Parameter()]
[String] $LogEncoding = "ASCII"
)
#endregion
Begin {}
Process {
try {
$msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message
if ($NoConsoleOut -eq $false) {
switch ($Level) {
'Error' { Write-Error $Message }
'Warn' { Write-Warning $Message }
'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground}
}
}
if ($Clobber) {
$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Force
} else {
$msg | Out-File -FilePath $Path -Encoding $LogEncoding -Append
}
if ($EventLogName) {
if (-not $EventSource) {
$EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name
}
if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) {
[Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName)
}
$log = New-Object System.Diagnostics.EventLog
$log.set_log($EventLogName)
$log.set_source($EventSource)
switch ($Level) {
“Error” { $log.WriteEntry($Message, 'Error', $EventID) }
“Warn” { $log.WriteEntry($Message, 'Warning', $EventID) }
“Info” { $log.WriteEntry($Message, 'Information', $EventID) }
}
}
} catch {
throw “Failed to create log entry in: ‘$Path’. The error was: ‘$_’.”
}
}
End {}
<#
.SYNOPSIS
Writes logging information to screen and log file simultaneously.
.DESCRIPTION
Writes logging information to screen and log file simultaneously. Supports multiple log levels.
.PARAMETER Message
The message to be logged.
.PARAMETER Level
The type of message to be logged.
.PARAMETER NoConsoleOut
Specifies to not display the message to the console.
.PARAMETER ConsoleForeground
Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified.
.PARAMETER Indent
The number of spaces to indent the line in the log file.
.PARAMETER Path
The log file path.
.PARAMETER Clobber
Existing log file is deleted when this is specified.
.PARAMETER EventLogName
The name of the system event log, e.g. 'Application'.
.PARAMETER EventSource
The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.PARAMETER EventID
The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.EXAMPLE
PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application'
.EXAMPLE
PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script"
.INPUTS
System.String
.OUTPUTS
No output.
.NOTES
Revision History:
2011-03-10 : Andy Arismendi - Created.
2011-07-23 : Will Steele - Updated.
#>
}
|
PowerShellCorpus/PoshCode/Productivity Calculator.ps1
|
Productivity Calculator.ps1
|
<#
Author: mazakane
This short script converts Time settings and displays a "productivity" Report with a goal of 81%
Example:
get-productivity -Start 8:00 -End 17:00
#>
function get-Productivity{
param(
$start,
$end
)
$a = ([datetime]::Parse("$start"))
$b = ([datetime]::Parse("$end"))
$lb = "0:30" #(Half an hour Break for lunch)
$Wrk = ($b-$a)
if (($Wrk.TotalHours) -gt "6") { $worktime = (($b - $a) - $lb) #this is special in my company, if you work less than 6 hours the lunch break isn´t going to be substracted.
Write-Host "`nTotal working hours without Lunch break: $worktime`n"
}
else {$worktime = ($b - $a)
Write-Host "`nTotal working hours including Lunch break: $worktime`n"
}
$total = [int]$worktime.TotalMinutes
# This formula gets the minimum hours at which count you are at least 81% productive.
$prod = (($total*81)/100)/60
Write-warning "`nTo be 81% productive you need to work at least: $prod hours..."
}
|
PowerShellCorpus/PoshCode/PowerBot 2.0.ps1
|
PowerBot 2.0.ps1
|
## PowerBot 2.0
## A simple framework to get you started writing your own IRC bots in PowerShell
####################################################################################################
## Requires Meebey.SmartIrc4net.dll to be in your ...\\WindowsPowerShell\\Libraries\\
## You can get Meebey.SmartIrc4net.dll from
## http://voxel.dl.sourceforge.net/sourceforge/smartirc4net/SmartIrc4net-0.4.0.bin.tar.bz2
####################################################################################################
## Add-Type -path $ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll
$null = [Reflection.Assembly]::LoadFrom("$ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll")
function Start-PowerBot {
PARAM(
$server = "irc.freenode.net"
, [string[]]$channels = @("#PowerShell")
, [string[]]$nick = @(Read-Host 'You must provide a nickname')
, [string]$password
, $realname = "PowerShell Bot"
, $port = 6667
)
if(!$global:irc) {
$global:irc = New-Object Meebey.SmartIrc4net.IrcClient
$irc.ActiveChannelSyncing = $true # $irc will track channels for us
# $irc.Encoding = [Text.Encoding]::UTF8
$irc.Add_OnError( {Write-Error $_.ErrorMessage} )
$irc.Add_OnQueryMessage( {PrivateMessage} )
$irc.Add_OnChannelMessage( {ChannelMessage} )
}
$irc.Connect($server, $port)
$irc.Login($nick, $realname, 0, $nick, $password)
## $channels | % { $irc.RfcJoin( $_ ) }
foreach($channel in $channels) { $irc.RfcJoin( $channel ) }
Resume-PowerBot # Shortcut so starting this thing up only takes one command
}
## Note that PowerBot stops listening if you press a key ...
## You'll have to re-run Resume-Powerbot to get him to listen again
function Resume-PowerBot {
while(!$Host.UI.RawUI.KeyAvailable) { $irc.ListenOnce($false) }
}
function Stop-PowerBot {
$irc.RfcQuit("If people listened to themselves more often, they would talk less.")
$irc.Disconnect()
}
####################################################################################################
## Event Handlers
####################################################################################################
## Event handlers in powershell have TWO automatic variables: $This and $_
## In the case of SmartIrc4Net:
## $This - usually the connection, and such ...
## $_ - the IrcEventArgs, which just has the Data member:
##
function PrivateMessage {
$Data = $_.Data
# Write-Verbose $Data.From
# Write-Verbose $Data.Message
Write-Verbose $($Data | Out-String)
$command, $params = $Data.MessageArray
if($PowerBotCommands.ContainsKey($command)) {
&$PowerBotCommands[$command] $params $Data |
Out-String -width (510 - $Data.From.Length - $nick.Length - 3) |
% { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }}
}
}
function ChannelMessage {
$Data = $_.Data
# Write-Verbose $Data.From
# Write-Verbose $Data.Channel
# Write-Verbose $Data.Message
Write-Verbose $($Data | Out-String)
$command, $params = $Data.MessageArray
if($PowerBotCommands.ContainsKey($command)) {
&$PowerBotCommands[$command] $params $Data |
Out-String -width (510 - $Data.Channel.Length - $nick.Length - 3) |
% { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }}
}
}
####################################################################################################
## The PowerBotCommands hashtable is extremely simple ...
##
## You register a "command" which must be the FIRST WORD of a message (either private, or channel)
## and you provide a scriptblock to process said message.
## The handler scriptblock gets two parameters, for convenience:
## $Params is the rest of the message text after the command word (which is probably all you need)
## $Data is the Data propert of the IrcEventArgs, which has everything in it that you could want
##
## You may do whatever you want in the scriptblock (this runs on your PC, after all), but the
## simplest thing is to respond by returning "something" which will be sent to wherever the message
## came from.
##
## NOTE 1: Evrything you return is output to Out-String and then the channel or user. Be careful!
## NOTE 2: 510 is the Max IRC Message Length, including the channel name etc.
## http`://www.faqs.org/rfcs/rfc1459.html
##
$PowerBotCommands=@{}
## A sample command to get you started
$PowerBotCommands."Hello" = {Param($Query,$Data)
"Hello, $($Data.Nick)!"
}
$PowerBotCommands."!Echo" = {Param($Query,$Data)
"$Query"
}
## "!gh|!get-help|!man"
$PowerBotCommands."!Get-Help" = {Param($Query)
$help = get-help $Query | Select Name,Synopsis,Syntax
if($?) {
if($help -is [array]) {
"You're going to need to be more specific, I know all about $((($help | % { $_.Name })[0..($help.Length-2)] -join ', ') + ' and even ' + $help[-1].Name)"
} else {
@($help.Synopsis,($help.Syntax | Out-String -width 1000).Trim().Split("`n",4,"RemoveEmptyEntries")[0..3])
}
} else {
"I couldn't find the help file for '$Query', sorry. I probably don't have that snapin loaded."
}
}
|
PowerShellCorpus/PoshCode/Hash Checker_4.ps1
|
Hash Checker_4.ps1
|
#.Synopsis
# Test the HMAC hash(es) of a file
#.Description
# Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
#.Example
# Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
#
# Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
# and take the hash of the file (using the extension of the HashFile as the Type of Hash).
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
#
# Takes the MD5 hash and compares it to the provided hash
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
#
# Tests all of the hashes against the provided (Sha1) hash
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
PowerShellCorpus/PoshCode/Ping Alert Script.ps1
|
Ping Alert Script.ps1
|
#Email Alert Parameters
$to = "user@mydomain.com"
$from = "unreachable@mydomain.com"
$smtpserver = "my_exchange_server"
#Array of computers to test
$Computers = ("comp1" , "comp2" , "comp3" , "comp4")
#Variable to hold INT value 0
$zero = 0
Foreach ($Computer in $Computers)
{
if
(
#Checks for a file with the host computers name in the Reports folder and if it doesn't exist creates it with content 0
Test-Path $("C:\\Reports\\" + $Computer + ".txt")
)
{
}
else
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
}
#Reads the content of the file and saves to variable as text
$FailedPings = Get-Content $("C:\\Reports\\" + $Computer + ".txt")
#Converts the value to INT
$INT_FailedPings = [INT]$FailedPings
#Actually runs the ping test
$PingTest = Test-Connection -ComputerName $Computer -count 1
if
(
#If ping is unsuccessful
$PingTest.StatusCode -ne "0"
)
{
while
(
#If previous failed pings value is less or equal to 3
$INT_FailedPings -le 3
)
{
#Increment the value by 1
$INT_FailedPings++
#Write the value out to the reports folder file for this host
$INT_FailedPings > $("C:\\Reports\\" + $Computer + ".txt")
#Send an alert of failed ping
Send-MailMessage -to $to -subject "Warning, Host $Computer is down. You will only receive 4 of these messages!" -from $from -body "Ping to $Computer failed, you will only receive 3 of these messages!" -smtpserver $smtpserver
}
}
elseif
(
#If previous checks have failed the value will be non zero, as checks are now working sets the value back to zero and alerts that host is back up
$INT_FailedPings -ne 0
)
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
Send-MailMessage -to $to -subject "Host $Computer is back up" -from $from -body "Panic over" -smtpserver $smtpserver
}
else
#If ping is successful and past pings were successful do nothing
{
}
}
|
PowerShellCorpus/PoshCode/Find Local Group Members_7.ps1
|
Find Local Group Members_7.ps1
|
# Author: Hal Rottenberg
# Purpose: Find matching members in a local group
# Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx
# Change these two to suit your needs
$ChildGroups = "Domain Admins", "Group Two"
$LocalGroup = "Administrators"
$MemberNames = @()
# uncomment this line to grab list of computers from a file
# $Servers = Get-Content serverlist.txt
$Servers = $env:computername # for testing on local computer
foreach ( $Server in $Servers ) {
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
$Members = @($Group.psbase.Invoke("Members"))
$Members | ForEach-Object {
$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$ChildGroups | ForEach-Object {
$output = "" | Select-Object Server, Group, InLocalAdmin
$output.Server = $Server
$output.Group = $_
$output.InLocalAdmin = $MemberNames -contains $_
Write-Output $output
}
}
|
PowerShellCorpus/PoshCode/Deploy VM with Static IP_3.ps1
|
Deploy VM with Static IP_3.ps1
|
# 1. Create a simple customizations spec:
$custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows `
-OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” `
–DomainUsername “user” –DomainPassword “password”
# 2. Modify the default network customization settings:
$custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseStaticIP -IpAddress 192.168.121.228 -SubnetMask 255.255.248.0 `
-Dns 192.168.108.1 -DefaultGateway 192.168.108.1
# 3. Deploy a VM from a template using the newly created customization:
New-VM -Name “MyNewVM” -Template $template -VMHost $vmHost `
-OSCustomizationSpec $custSpec
|
PowerShellCorpus/PoshCode/Invoke-ScriptThatRequire.ps1
|
Invoke-ScriptThatRequire.ps1
|
###########################################################################\n##\n## Invoke-ScriptThatRequiresSta\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n###########################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates a technique to relaunch a script that requires STA mode.\nThis is useful only for simple parameter definitions that can be\nspecified positionally.\n\n#>\n\nparam(\n $Parameter1,\n $Parameter2\n)\n\nSet-StrictMode -Version Latest\n\n"Current threading mode: " + $host.Runspace.ApartmentState\n"Parameter1 is: $parameter1"\n"Parameter2 is: $parameter2"\n\nif($host.Runspace.ApartmentState -ne "STA")\n{\n "Relaunching"\n $file = $myInvocation.MyCommand.Path\n powershell -NoProfile -Sta -File $file $parameter1 $parameter2\n return\n}\n\n"After relaunch - current threading mode: " + $host.Runspace.ApartmentState
|
PowerShellCorpus/PoshCode/Stored Credential Code_1.ps1
|
Stored Credential Code_1.ps1
|
#STORED CREDENTIAL CODE
$AdminName = Read-Host "Enter your Admin AD username"
$CredsFile = "C:\\$AdminName-PowershellCreds.txt"
$FileExists = Test-Path $CredsFile
if ($FileExists -eq $false) {
Write-Host 'Credential file not found. Enter your password:' -ForegroundColor Red
Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $CredsFile
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\\$AdminName,$password}
else
{Write-Host 'Using your stored credential file' -ForegroundColor Green
$password = get-content $CredsFile | convertto-securestring
$Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\\$AdminName,$password}
sleep 2
Write-Host 'Connecting to Active Directory'
#Establishes connection to Active Directory and Exchange with the specified user acccount and password.
Connect-QADService -Service 'server' -Credential $Cred -ErrorAction Stop | out-Null
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://server.fqdn.com/PowerShell/ -Credential $Cred -Authentication Kerberos -ErrorAction SilentlyContinue
Import-PSSession $Session -ErrorAction SilentlyContinue -AllowClobber
if(!$?)
{write-host "Failed importing the exchange pssession, exiting!"
exit}
#END OF STORED CREDENTIAL CODE
|
PowerShellCorpus/PoshCode/Get-InvocationInfo.ps1
|
Get-InvocationInfo.ps1
|
##############################################################################\n##\n## Get-InvocationInfo\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDisplay the information provided by the $myInvocation variable\n\n#>\n\nparam(\n ## Switch to no longer recursively call ourselves\n [switch] $PreventExpansion\n)\n\nSet-StrictMode -Version Latest\n\n## Define a helper function, so that we can see how $myInvocation changes\n## when it is called, and when it is dot-sourced\nfunction HelperFunction\n{\n " MyInvocation from function:"\n "-"*50\n $myInvocation\n\n " Command from function:"\n "-"*50\n $myInvocation.MyCommand\n}\n\n## Define a script block, so that we can see how $myInvocation changes\n## when it is called, and when it is dot-sourced\n$myScriptBlock = {\n " MyInvocation from script block:"\n "-"*50\n $myInvocation\n\n " Command from script block:"\n "-"*50\n $myInvocation.MyCommand\n}\n\n## Define a helper alias\nSet-Alias gii .\\Get-InvocationInfo\n\n## Illustrate how $myInvocation.Line returns the entire line that the\n## user typed.\n"You invoked this script by typing: " + $myInvocation.Line\n\n## Show the information that $myInvocation returns from a script\n"MyInvocation from script:"\n"-"*50\n$myInvocation\n\n"Command from script:"\n"-"*50\n$myInvocation.MyCommand\n\n## If we were called with the -PreventExpansion switch, don't go\n## any further\nif($preventExpansion)\n{\n return\n}\n\n## Show the information that $myInvocation returns from a function\n"Calling HelperFunction"\n"-"*50\nHelperFunction\n\n## Show the information that $myInvocation returns from a dot-sourced\n## function\n"Dot-Sourcing HelperFunction"\n"-"*50\n. HelperFunction\n\n## Show the information that $myInvocation returns from an aliased script\n"Calling aliased script"\n"-"*50\ngii -PreventExpansion\n\n## Show the information that $myInvocation returns from a script block\n"Calling script block"\n"-"*50\n& $myScriptBlock\n\n## Show the information that $myInvocation returns from a dot-sourced\n## script block\n"Dot-Sourcing script block"\n"-"*50\n. $myScriptBlock\n\n## Show the information that $myInvocation returns from an aliased script\n"Calling aliased script"\n"-"*50\ngii -PreventExpansion
|
PowerShellCorpus/PoshCode/SCOM-RunRemoteExecutable.ps1
|
SCOM-RunRemoteExecutable.ps1
|
# ==============================================================================================
#
# Microsoft PowerShell Source File Ś Created with SAPIEN Technologies PrimalScript 2007
#
# NAME: SCOM-RunRemoteExecutable.ps1
#
# AUTHOR: Jeremy D. Pavleck , Pavleck.NET
# DATE : 9/13/2008
#
# COMMENT: This is a Proof Of Concept script written in response to a mailing list request to
# enable OpsMgr to sound an audible alert on a remote admin PC, such as a console in a
# NOC.
# This is to be run as a Notification Command Channel.
#
# NOTES/WARNING: This script uses a remote WMI call to spawn a process on a named server. As
# such, there are security issues to keep in mind. I havenĺt added the code to allow you
# to use alternate credentials, but use http://poshcode.org/501 as a jumping off point.
# If youĺre running the OpsMgr services under a domain account, add that user to the local
# administrators group on the machine you want to run this command. If youĺre using local
# system, add RMS\\Local System to the admin group.
# RUN AT YOUR OWN RISK!
#
# VERSIONS:
# v1.0 - 09/12/2008 - Initial version
# v1.1 - 09/13/2008 - On the advice of Pete Zerger, added a throttling routine to prevent
# to many executions during an alert storm
# v1.2 - 09/13/2008 - Changed variable names to make it a more Ĺrun remote executableĺ script
#
# ==============================================================================================
# User Settings
$remoteMachine = "adminconsole.pavleck.net"
# The location to the executable. This is the path on the REMOTE machine.
$myExe = "C:\\Program Files\\Real Alternative\\Media Player Classic\\mplayerc.exe"
$myExeParams = "C:\\Windows\\Media\\tada.exe" # Paramters to pass to the executable, such as the location of the sound file, etc.
# Leave blank if none are needed
# Registry & throttling settings
$myKey = "SCOM_PowerShell_Scripts" # Reg key name to use
$myValueName = "LastRunTime" # Data value
$interval = 5 # Wait at least this long, in minutes
# Initialize a couple things
$firstRun = $False
$throttle = $False
# We use the OpsMgr API only because itĺs a very quick and simple way to log to the eventviewer
$momAPI = New-Object -comObject "MOM.ScriptAPI"
# LogScriptEvent Severities
$momErr = 1
$momWarn = 2
$momInfo = 4
# Setup some event ids to use
$errID = 11000
$warnID = 11001
$infoID = 11002
$myName = $MyInvocation.MyCommand.Name # Grab script name
### Registry throttling settings
# First see if our key exists, if not, create it and populate it with the current date/time
# and set $firstRun to $True
If(!$(Test-Path HKLM:\\SOFTWARE\\$myKey)) {
New-Item -Path HKLM:\\Software\\$myKey
New-ItemProperty -Path HKLM:\\SOFTWARE\\$myKey -Name $myValueName -Value (Get-Date)
$firstRun = $True
}
# If this isnĺt the first run, compare previous time with current time - if last run is $interval
# minutes ago or higher, carry on, otherwise exit
If(!($firstRun)) {
$lastRun = (Get-ItemProperty -Path HKLM:\\SOFTWARE\\$myKey).$myValueName
Set-ItemProperty -Path HKLM:\\SOFTWARE\\$myKey -Name $myValueName -Value (Get-Date)
If(((Get-Date) - [DateTime]$lastRun).TotalMinutes -ge $interval) {
$throttle = $False
} else {
$throttle = $True
}
}
# Function DecipherRetCode accepts an integer, and returns the failure assigned to that code.
# This only returns the most common failures, such as permissioning and the like
Function DecipherRetCode([int]$retCode) {
switch ($retCode) {
0 {return "Success"}
2 {return "Access Denied"}
3 {return "Insufficient Privilege"}
8 {return "Unknown Failure"}
21 {return "Invalid Parameter"}
default {return "$($retCode) is uncommon, and will need to be researched manually. "}
}
}
# This line is actually the entire script.
If($throttle) {
# Throttling - cancel response
$momAPI.LogScriptEvent($myName, $warnID, $momWarn, "Notification Workflow requested that $($myname) run, but last response ran less then $($interval) minutes ago. Exiting.")
$momAPI = $null
exit
} else {
$retCode = ([WMICLASS]"\\\\$remoteMachine\\root\\cimv2:win32_process").Create("$myExe $myExeParams")
# If $retCode = 0 ($false) exit the If, anything else is $True, and will log it
If($retCode) {
$momAPI.LogScriptEvent($myName, $errID, $momErr, "Error creating process. Error Code: $($retcode) Error Message: $(DecipherRetCode $retCode)")
}
$momAPI = $null
exit
}
|
PowerShellCorpus/PoshCode/Invoke-SqlCmd_6.ps1
|
Invoke-SqlCmd_6.ps1
|
function Invoke-Sqlcmd2
{
param
(
[string]$ServerInstance="localhost",
[string]$Database,
[string]$Query,
[Int32]$CommandTimeout=30
)
$connectionString = "Server={0};Database={1};Integrated Security=True" -f $ServerInstance, $Database
$connection = New-Object System.Data.SqlClient.SQLConnection($connectionString)
try
{
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandTimeout = $QueryTimeout
$command.CommandType = [System.Data.CommandType]::Text
$command.CommandText = $Query
$dataSet = New-Object System.Data.DataSet
$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
[void]$dataAdapter.Fill($dataSet)
$dataSet.Tables[0]
}
finally
{
if ($connection.State -eq [System.Data.ConnectionState]::Open)
{
$connection.Close()
}
}
}
|
PowerShellCorpus/PoshCode/Set-ExcludeFromPeek.ps1
|
Set-ExcludeFromPeek.ps1
|
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
namespace Huddled {
public static class Dwm {
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[Flags]
public enum DwmWindowAttribute
{
NCRenderingEnabled = 1,
NCRenderingPolicy,
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds,
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds,
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Last
}
[Flags]
public enum DwmNCRenderingPolicy
{
UseWindowStyle,
Disabled,
Enabled,
Last
}
public static void RemoveFromAeroPeek(IntPtr Hwnd) //Hwnd is the handle to your window
{
int renderPolicy = (int)DwmNCRenderingPolicy.Enabled;
DwmSetWindowAttribute(Hwnd, (int)DwmWindowAttribute.ExcludedFromPeek, ref renderPolicy, sizeof(int));
}
}
}
"@
[Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
function Select-Window {
PARAM( [string]$Title="*",
[string]$Process="*",
[switch]$Recurse,
[System.Windows.Automation.AutomationElement]$Parent = [System.Windows.Automation.AutomationElement]::RootElement )
PROCESS {
$search = "Children"
if($Recurse) { $search = "Descendants" }
$Parent.FindAll( $search, [System.Windows.Automation.Condition]::TrueCondition ) |
Add-Member -Type ScriptProperty -Name Title -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty)} -Passthru |
Add-Member -Type ScriptProperty -Name Handle -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty)} -Passthru |
Add-Member -Type ScriptProperty -Name ProcessId -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)} -Passthru |
Where-Object {
((Get-Process -Id $_.ProcessId).ProcessName -like $Process) -and ($_.Title -like $Title)
}
}}
##### Example use, to keep all the Rainlendar2 windows visible
# Select-Window -Process Rainlendar2 | % { [Huddled.Dwm]::RemoveFromAeroPeek( $_.Handle ) }
|
PowerShellCorpus/PoshCode/New-Exch2010NlbCluster.ps1
|
New-Exch2010NlbCluster.ps1
|
###########################################################################
#
# NAME: New-Exch2010NlbCluster.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jer@powershell.no
#
# COMMENT: Script to create a NLB-cluster for the CAS/HUB-roles in Exchange Server 2010.
# For more details, see the following blog-post: http://blog.powershell.no/2010/05/21/script-to-create-a-nlb-cluster-for-the-cas-role-in-exchange-server-2010
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 20.05.2010 - Initial release
#
###########################################################################
#Importing Microsoft`s PowerShell-module for administering NLB Clusters
Import-Module NetworkLoadBalancingClusters
#Variables for creating the new cluster
$ClusterFqdn = Read-Host "Enter FQDN for the new cluster"
$InterfaceName = Read-Host "Enter interface name for NLB-adapter"
$ClusterPrimaryIP = Read-Host "Enter cluster primary IP"
$ClusterPrimaryIPSubnetMask = Read-Host "Enter subnetmask for cluster primary IP"
Write-Host "Choose cluster operation mode"
Write-Host "1 - Unicast"
Write-Host "2 - Multicast"
Write-Host "3 - IGMP Multicast"
switch (Read-Host "Enter the number for your chosen operation mode")
{
1 {$OperationMode = "unicast"}
2 {$OperationMode = "multicastcast"}
3 {$OperationMode = "igmpmulticast"}
default {Write-Warning "Invalid option, choose '1', '2' or '3'";return}
}
$MSExchangeRPCPort = Read-Host "Enter static port configured for Microsoft Exchange RPC (MAPI)"
$MSExchangeABPort = Read-Host "Enter static port configured for Microsoft Exchange Address book service"
#Creating new cluster
Write-Host "Creating NLB Cluster..." -ForegroundColor yellow
New-NlbCluster -ClusterName $ClusterFqdn -InterfaceName $InterfaceName -ClusterPrimaryIP $ClusterPrimaryIP -SubnetMask $ClusterPrimaryIPSubnetMask -OperationMode $OperationMode
#Removing default port rule for the new cluster
Write-Host "Removing default port rule..." -ForegroundColor yellow
Get-NlbClusterPortRule -HostName . | Remove-NlbClusterPortRule -Force
#Adding port rules for Exchange Server 2010 CAS (SMTP, http, POP3, RPC, IMAP4, https, static port for MSExchangeRPC and MSExchangeAB)
Write-Host "Adding port rules for Exchange Server 2010 CAS" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 25 -EndPort 25 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for SMTP (tcp 25)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 80 -EndPort 80 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for http (tcp 80)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 110 -EndPort 110 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for POP3 (tcp 110)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 135 -EndPort 135 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for RPC (tcp 135)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 143 -EndPort 143 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for IMAP4 (tcp 143)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 443 -EndPort 443 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for https (tcp 443)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort $MSExchangeRPCPort -EndPort $MSExchangeRPCPort -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for MSExchange RPC (tcp $MSExchangeRPCPort)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort $MSExchangeABPort -EndPort $MSExchangeABPort -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for MSExchange Address Book service (tcp $MSExchangeABPort)" -ForegroundColor yellow
#Adding additional cluster nodes based on user input
Write-Warning "Before adding additional nodes, make sure that NLB are installed and the NLB-adapter are configured with a static IP-address on the remote node"
$additionalnodes = Read-Host "Add additional nodes to the cluster? Y/N"
if ($additionalnodes -like "y"){
do {
$NodeFqdn = Read-Host "Enter FQDN for the additional node"
$NewNodeInterface = Read-Host "Enter interface name for NLB-adapter on the additional node"
Write-Host "Adding cluster node $NodeFqdn" -ForegroundColor yellow
Get-NlbCluster -HostName . | Add-NlbClusterNode -NewNodeName $NodeFqdn -NewNodeInterface $NewNodeInterface
$additionalnodes = Read-Host "Add additional nodes to the cluster? Y/N"
} until ($additionalnodes -like "n")
}
|
PowerShellCorpus/PoshCode/Send-RTMTask.ps1
|
Send-RTMTask.ps1
|
#——————————————————————————
# Func/Sub Name: Send-RTMTask
# Purpose: Sends a task to the Remember The Milk system via email.
# Arguments Supplied:
# Return Value:
# External Reference:
#——————————————————————————
function Send-RTMTask
{
param( [string]$TaskName=$(Throw "need TaskName"),
$Priority,
$DueDate,
$Repeat,
$TaskEstimate,
$Tags,
$Location,
$URL,
[string]$TaskList,
$Notes
)
Begin
{
@@ # Some Constants
@@ $RTMEmailAddress = ""
@@ $FromEmailAddress = ""
@@ $SMTPServer = ""
$MailClient = New-Object System.Net.Mail.SmtpClient($SMTPServer)
}
Process
{
$FromEmail = New-Object System.Net.Mail.MailAddress($FromEmailAddress )
$ToEmail = New-Object System.Net.Mail.MailAddress($RTMEmailAddress )
$MailMessage = New-Object System.Net.Mail.MailMessage( $FromEmail, $ToEmail)
$MailMessage.Subject = $TaskName
$Body = ""
if ( $Priority -ne $null ) { $Body += "P: $Priority`n" }
if ( $DueDate -ne $null ) { $Body += "Due: $DueDate`n" }
if ( $Repeat -ne $null ) { $Body += "Repeat: $Repeat`n" }
if ( $TaskEstimate -ne $null ) { $Body += "EstimateP: $TaskEstimate`n" }
if ( $Tags -ne $null ) { $Body += "Tags: $Tags`n" }
if ( $Location -ne $null ) { $Body += "Location: $Location`n" }
if ( $URL -ne $null ) { $Body += "URL: $URL`n" }
if ( $TaskList -ne $null ) { $Body += "List: $TaskList`n" }
if ( $Notes -ne $null ) { $Body += "--- `n $Notes" }
$MailMessage.Body = $Body
$MailClient.Send($MailMessage)
}
End
{ }
}
|
PowerShellCorpus/PoshCode/Get-User_3.ps1
|
Get-User_3.ps1
|
function Get-User($user)
{
# this function should be passed the CN of the user to be returned
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))"
$user = $searcher.FindOne()
[System.Collections.Arraylist]$names = $user.Properties.PropertyNames
[System.Collections.Arraylist]$props = $user.Properties.Values
$userobj = New-Object System.Object
for ($i = 0; $i -lt $names.Count)
{
$userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i])
$i++
}
$userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset)
$userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp)
return $userobj
}
|
PowerShellCorpus/PoshCode/Open-Solution.ps1
|
Open-Solution.ps1
|
function Open-Solution([string]$path = ".") {
$sln_files = Get-ChildItem $path -Include *.sln -Recurse
if($sln_files -eq $null) {
Write-Host "No Solution file found"
return
}
if($sln_files.Count) { # There is more than one
do {
Write-Host "Please select file (or Ctrl+C to quit)"
for($i=0;$i -lt $sln_files.Count;$i=$i+1) { Write-Host "($i) - $($sln_files[$i])" }
$idx = Read-Host
$sln = $sln_files[$idx]
}until($sln)
}
else { $sln = $sln_files }
Invoke-Item $sln
}
|
PowerShellCorpus/PoshCode/Finding Old or Unused Ac.ps1
|
Finding Old or Unused Ac.ps1
|
$dcs = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain().DomainControllers | select name
$startdate = get-date('1/1/1601')
$lst = new-Object System.Collections.ArrayList
foreach ($dc in $dcs) {
$root = [ADSI] LDAP://$($dc.Name):389
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=person)(objectClass=user))"
$searcher.PropertiesToLoad.Add("name") | out-null
$searcher.PropertiesToLoad.Add("LastLogon") | out-null
$searcher.PropertiesToLoad.Add("displayName") | out-null
$searcher.PropertiesToLoad.Add("userAccountControl") | out-null
$searcher.PropertiesToLoad.Add("canonicalName") | out-null
$searcher.PropertiesToLoad.Add("title") | out-null
$searcher.PropertiesToLoad.Add("sAMAccountName") | out-null
$searcher.PropertiesToLoad.Add("sn") | out-null
$searcher.PropertiesToLoad.Add("givenName") | out-null
$results = $searcher.FindAll()
foreach ($result in $results)
{
$user = $result.Properties;
$usr = $user | select -property @{name="Name"; expression={$_.name}},
@{name="LastLogon"; expression={$_.lastlogon}},
@{name="DisplayName"; expression={$_.displayname}},
@{name="Disabled"; expression={(($_.useraccountcontrol[0]) -band 2) -eq 2}},
@{name="CanonicalName"; expression={$_.canonicalname}},
@{name="Title"; expression={$_.title}},
@{name="sAMAccountName"; expression={$_.samaccountname}},
@{name="LastName"; expression={$_.sn}},
@{name="FirstName"; expression={$_.givenname}}
$lst.Add($usr) | out-null
}
}
$lst | group name | select-object Name,
@{Expression={ ($_.Group | Measure-Object -property LastLogon -max).Maximum }; Name="LastLogon" },
@{Expression={ ($_.Group | select-object -first 1).DisplayName}; Name="DisplayName" },
@{Expression={ ($_.Group | select-object -first 1).CanonicalName}; Name="CanonicalName" },
@{Expression={ ($_.Group | select-object -first 1).Title}; Name="Title" },
@{Expression={ ($_.Group | select-object -first 1).sAMAccountName}; Name="sAMAccountName" },
@{Expression={ ($_.Group | select-object -first 1).LastName}; Name="LastName" },
@{Expression={ ($_.Group | select-object -first 1).FirstName}; Name="FirstName" },
@{Expression={ ($_.Group | select-object -first 1).Disabled}; Name="Disabled" } |
select-object Name, DisplayName, CanonicalName, Title, sAMAccountName, LastName, FirstName, Disabled,
@{Expression={ $startdate.adddays(($_.LastLogon / (60 * 10000000)) / 1440) }; Name="LastLogon" }
|
PowerShellCorpus/PoshCode/9ef43b00-ae12-4e41-b331-af2bdfba35c1.ps1
|
9ef43b00-ae12-4e41-b331-af2bdfba35c1.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/Set-Watcher.ps1
|
Set-Watcher.ps1
|
###############################################################################
# Use Unregister-Event -SourceIdentifier <name> -Force (to stop an Event).
# Include script in $profile to register all these events. Modify to suit own
# requirements and comment out any of the examples below that are not needed.
# Please visit www.SeaStarDevelopment.Bravehost.com for more utilities.
###############################################################################
# This ACTION will trap Script start/stop events (SourceId = ScriptMonitor); but
# only if started externally via 'powershell.exe -noexit -command & example.ps1'
# NOTE: this duplicates the actions of Script Monitor Service and both should
# not be run together (Uncomment the lines below to start).
###############################################################################
$action = {
$pattern = '^(.*)(\\s+|\\\\)([-_a-z0-9]+\\.(?!(psc1))[a-ehmpstv1]{3,4})\\b'
$script = $msg = 'BLANK'
$e = $Event.SourceEventArgs.NewEvent
$process = $e.TargetInstance.Name
$processID = $e.TargetInstance.ProcessId
$cmdline = $e.TargetInstance.CommandLine
If ($cmdline -match $pattern) {
$script = $matches[3]
$path = $matches[1]
If ($path -match '^.*( sc|/TR ).*$') { #Skip lines with SC or /TR
$script = 'BLANK'
}
}
Switch ($e.__CLASS) {
'__InstanceCreationEvent' {
If ($script -ne 'BLANK') {
$msg = "Script Job: $script ($processID) started."
$time = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$time [$script] start. --> $cmdline"
$ID = "2"
}
}
'__InstanceDeletionEvent' {
If ($script -ne 'BLANK') {
$msg = "Script Job: $script ($processID) ended."
$time = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$time [$script] ended. --> $cmdline"
$ID = "1"
}
}
Default {$_ | Out-Null }
}
If ($cmdline.StartsWith("cscript") -and $cmdline.Contains("//logo")) {
$msg = 'BLANK' #Skip duplicate entry from Notepad Script Editor.
}
If ($msg -ne 'BLANK') {
$file = Join-Path (get-Location) "Monitor.txt"
If (Test-Path $file) {
$tag | Out-File $file -encoding 'Default' -Append
}
Write-LogEvent Scripts $ID $msg
}
}
$query = "SELECT * FROM __InstanceOperationEvent WITHIN 2 WHERE `
TargetInstance ISA 'Win32_Process' AND `
(TargetInstance.Name = 'cmd.exe' OR `
TargetInstance.Name = 'wscript.exe' OR `
TargetInstance.Name = 'Cscript.exe' OR `
TargetInstance.Name = 'mshta.exe')"
#Register-WmiEvent -Query $query -SourceIdentifier ScriptMonitor -Action $action `
# | Out-Null
###############################################################################
#This ACTION will trap any USB insertions (SourceId = USBdevice).
###############################################################################
$action1 = {
$file = 'c:\\Scripts\\AutoAvast.vbs' #Change to run desired script, etc.
$e = $Event.SourceEventArgs.NewEvent
$drive = $e.TargetInstance.DeviceID
$volume = $e.TargetInstance.VolumeName
$free = $e.TargetInstance.FreeSpace
$size = $e.TargetInstance.Size
If ($e.TargetInstance.VolumeSerialNumber -ne "") {
& 'c:\\windows\\system32\\wscript.exe' $file $drive $volume $free $size
}
}
$query1 = "SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE `
TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType = 2"
Register-WmiEvent -Query $query1 -SourceIdentifier USBdevice -Action $action1 `
| Out-Null
###############################################################################
#This ACTION will trap any file downloads (SourceId = Download).
###############################################################################
$action2 = {
$eventLog = "Internet Explorer"
$id = 99
$e = $Event.SourceEventArgs.NewEvent
$drive = $e.TargetInstance.Drive
$file = $e.TargetInstance.FileName + "." + `
$e.TargetInstance.Extension
$path = $e.TargetInstance.Path
$folder = $drive + "\\Downloads"
Switch ($e.TargetInstance.Extension) {
'exe' {$id = 20; break}
'enu' {$id = 21; break}
'html' {$id = 23; break}
'zip' {$id = 24; break}
'rar' {$id = 25; break}
'msi' {$id = 29; break}
Default {$id = 99}
}
$formatString = "{0:##.#}Mb"
$size = $formatString -f ($e.TargetInstance.FileSize/1KB)
$desc = "File $file has been added to the $folder folder; filesize = $size"
Write-LogEvent $eventLog $ID $desc
}
$query2 = "SELECT * FROM __InstanceCreationEvent WITHIN 30 WHERE TargetInstance `
ISA 'CIM_DataFile' AND TargetInstance.Path = '\\\\Downloads\\\\' AND `
(TargetInstance.Drive = 'C:' OR TargetInstance.Drive = 'E:')"
Register-WmiEvent -Query $query2 -SourceIdentifier Download -Action $action2 `
| Out-Null
###############################################################################
#This ACTION will catch Avast Database Update (SourceId = FileWatcher)
#Change to run any script, etc. (Prompter.exe is now included in the Scripting
#Editor download from www.SeaStarDevelopment.Bravehost.com and is used to put
# a message in the notification area). Uncomment the 2 lines below to run.
###############################################################################
$action3 = {
$file = $Event.SourceEventArgs.Name
& 'c:\\Scripts\\prompt.exe' /Notify update /Title Avast Update Service `
/Msg Updating file: $file
}
$folder = "c:\\Program Files\\Alwil Software\\Avast5\\Setup"
$filter = "*.vpx"
$fsw = New-Object -TypeName System.IO.FileSystemWatcher -ArgumentList `
$folder, $filter
$fsw.IncludeSubDirectories = $false
$fsw.EnableRaisingEvents = $true
#Register-ObjectEvent -InputObject $fsw -EventName "Changed" `
# -SourceIdentifier FileWatcher -Action $action3 | Out-Null
###############################################################################
#This ACTION runs Ccleaner and Keylog Backup (SourceId = UnHibernate)
###############################################################################
$action4 = {
$file = "c:\\scripts\\KeylogBackup.vbs"
$args = $Event.SourceEventArgs.NewEvent.EventType #Type 18 = UnHibernate.
& 'c:\\windows\\system32\\wscript.exe' $file $args
& "$env:programfiles\\ccleaner\\ccleaner.exe" /AUTO
}
$query4 = "SELECT * FROM Win32_PowerManagementEvent WHERE EventType = '18'"
Register-WmiEvent -Query $query4 -SourceIdentifier UnHibernate -Action $action4 `
| Out-Null
###############################################################################
#This ACTION will detect Avast Database changes (Updates). Replaces 3 above.
###############################################################################
$action5 = {
& 'c:\\Scripts\\prompt.exe' /Notify update /Title Avast Update Service `
/Msg Starting database update
Write-Eventlog -logname Antivirus -source avast -eventID 90 -entryType `
Information -message "Avast5 Automatic Database Update"
}
$query5 = "SELECT * FROM __InstanceCreationEvent WITHIN 180 WHERE `
TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'avast.setup'"
Register-WmiEvent -Query $query5 -SourceIdentifier Avast -Action $action5 `
| Out-Null
###############################################################################
#This ACTION will detect Windows Media Player & then start ActiveSyncToggle
###############################################################################
$action7 = {
$e = $Event.SourceEventArgs.NewEvent
If (Test-Path "e:\\downloads\\ActiveSyncToggle.exe") {
& 'e:\\downloads\\ActiveSyncToggle.exe'
}
}
$query7 = "SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE `
TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'wmplayer.exe'"
Register-WmiEvent -Query $query7 -SourceIdentifier MediaPlayer -Action $action7 `
| Out-Null
###############################################################################
# This ACTION will detect any changes to the registry HKLM\\Run key.
###############################################################################
$hive = "HKEY_LOCAL_MACHINE"
$keyPath = "SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run"
$action8 = {
$file = 'c:\\Scripts\\HKLMrun.vbs'
& 'c:\\windows\\system32\\wscript.exe' $file
}
$query8 = "SELECT * FROM RegistryKeyChangeEvent WHERE Hive = '$hive' AND KeyPath = '$keyPath'"
Register-WmiEvent -Query $query8 -Namespace 'root\\default' `
-SourceIdentifier HKLMRunKey -Action $action8 | Out-Null
###############################################################################
# To capture scripts started within the current session a 'Run' function (below)
# should be added to the $profile, and each script should then be started with
# Run example.ps1, etc. The $logfile is created by the Script Monitor Service.
#
# Function Run([String]$scriptName = '-BLANK-') {
# $logfile = "$env:programfiles\\Sea Star Development\\" +
# "Script Monitor Service\\ScriptMon.txt"
# $parms = $myInvocation.Line -replace "run(\\s+)$scriptName(\\s*)"
# $script = $scriptName -replace "\\.ps1\\b" #Replace from word end only.
# $script = $script + ".ps1"
# If (Test-Path $pwd\\$script) {
# If(!(Test-Path Variable:\\Session.Script.Job)) {
# Set-Variable Session.Script.Job -value 1 -scope global `
# -description "Script counter"
# }
# $Job = Get-Variable -name Session.Script.Job
# $number = $job.Value.ToString().PadLeft(4,'0')
# $job.Value += 1 #Increment here in case script aborts.
# $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
# $tag = "$startTime [$script] start. --> $($myInvocation.Line)"
# If (Test-Path $logfile) {
# $tag | Out-File $logfile -encoding 'Default' -Append
# }
# Write-LogEvent Scripts 2 "Script Job: $script (PS$number) started."
# Invoke-Expression -command "$pwd\\$script $parms"
# $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
# $tag = "$endTime [$script] ended. --> $($myInvocation.Line)"
# If (Test-Path $logfile) {
# $tag | Out-File $logfile -encoding 'Default' -Append
# }
# Write-LogEvent Scripts 1 "Script Job: $script (PS$number) ended."
# }
# Else {
# Write-Error "$pwd\\$script does not exist."
# }
# }
###############################################################################
|
PowerShellCorpus/PoshCode/Convert-ToCHexString_4.ps1
|
Convert-ToCHexString_4.ps1
|
function Convert-ToCHexString {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true,Mandatory=$true)][string]$str
)
process { ($str.ToCharArray() | %{ "0x{0:X2}" -f [int]$_ }) -join ',' }
}
|
PowerShellCorpus/PoshCode/TabExpansion_3.ps1
|
TabExpansion_3.ps1
|
## Tab-Completion
#################
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $foo[0].<tab>
## $foo[0].n.b<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames expansion
## [Dec<tab>
## [Microsoft.PowerShell.Com<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.Management.Auto<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSourceÅ@Inte<tab>
## iex -Err <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] [-PSProvider] <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Error s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
### Generate ProgIDs list...
if ($_ProgID -eq $null) {
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
[Object[]] $_ProgID = $null
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID += $_i.GetValue("")
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\ProgIDs.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Import-Clixml -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;'
}
### Generate TypeNames list...
if ( $_TypeNames -eq $null ) {
[Object[]] $_TypeNames = $null
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames += $_type.FullName
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\TypeNames.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Import-Clixml -Path $PSHOME\\TypeNames.txt;'
}
if ( $_TypeNames_System -eq $null ) {
[Object[]] $_TypeNames_System = $null
foreach ( $_type in $_TypeNames -like "System.*" )
{
$_TypeNames_System += $_type.Substring(7)
}
'$_TypeNames_System was updated...' | Out-Host
Export-Clixml -InputObject $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Import-Clixml -Path $PSHOME\\TypeNames_System.txt;'
}
### Generate WMIClasses list...
if ( $_WMIClasses -eq $null ) {
[Object[]] $_WMIClasses = $null
foreach ( $_class in gwmi -List )
{
$_WMIClasses += $_class.Name
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt
}
$global:_snapin = $null
# Load Get-PipeLineObject function for $_ and property name expansion.
$_scriptpath = gi $MyInvocation.MyCommand.Path
iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1"))
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
) | sort MemberType,Name -Unique
foreach ($_m in $members)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion...
# e.g. foo[0].a<tab>
'(^.*)(\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)((\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w+\\.)+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[((\\w+\\.?)+)$' {
$_opt = $matches[1] + '*'
foreach ( $_exp in $_TypeNames_System -like $_opt )
{
'[' + $_exp
}
foreach ( $_exp in $_TypeNames -like $_opt )
{
'[' + $_exp
}
break;
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
# expand the parameter sets and emit the matching elements
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
# try to find a matching command...
default {
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$')
{
'['+ $global:_enum + ']'
}
elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' )
#elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' )
{
$_method = $Matches[1]
if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" )
{
$continuous = $true
$_opt = $Matches[5] + '*'
$_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1'
$position = $Matches[1].Split(",").Length
}
else
{
$continuous = $false
$_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*"
$position = $Matches[3].Split(",").Length
}
if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null )
{
$tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }')
}
foreach ( $def in $_mdefs )
{
[void] ($def -match '\\((.*)\\)')
foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] )
{
if ($param -eq $null -or $param -eq "")
{
continue;
}
$type = $param.split()[0]
if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" )
{
continue;
}
$fullname = @($_typenames -like "*$type*")
foreach ( $name in $fullname )
{
if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$global:_enum = $name
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"'
$output | sort
}
}
}
}
if ( $output -ne $null )
{
break;
}
}
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System
$_TypeNames
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0]
if ( $_cmdlet.Name -eq "powershell.exe" )
{
"-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive",
"-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort
break;
}
if ( $_cmdlet.Name -eq "fsutil.exe" )
{
"behavior query", "behavior set", "dirty query", "dirty set",
"file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew",
"fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics",
"hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create",
"quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query",
"reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange",
"usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort
break;
}
if ( $_cmdlet.Name -eq "net.exe" )
{
"ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ",
"HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ",
"SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort
break;
}
if ( $_cmdlet.Name -eq "ipconfig.exe" )
{
"/?", "/all", "/renew", "/release", "/flushdns", "/displaydns",
"/registerdns", "/showclassid", "/setclassid"
break;
}
}
if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' )
{
#$_opt = $Matches[1] + '*'
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2]
$_opt = $Matches[1].Split(" ,")[-1] + '*'
$_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length)
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
$_WMIClasses -like $_opt
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
#$_opt = ($Matches[3] -replace '(^.*\\s*,?\\s*)\\w*$','$1') + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name `
-and "Encoding" -like $_param)
{
"Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -like $_cmdlet.Name )
{
if ( "ComObject" -like $_param )
{
$_ProgID -like $_opt | % { $_ -replace '\\s','` ' }
break;
}
if ( "TypeName" -like $_param )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
}
if ( "New-Item" -eq $_cmdlet.Name )
{
if ( "ItemType" -like $_param )
{
"directory", "file" -like $_opt
break;
}
}
if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name `
-and "PSProvider" -like $_param )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param)
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
}
if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias",
" New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" `
-contains $_cmdlet.Name -and "Scope" -like $_param )
{
"Global", "Local", "Script" -like $_opt
break;
}
if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
$_WMIClasses -like $_opt
break;
}
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name -and "Property" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Select-Object" -eq $_cmdlet.Name )
{
if ( "ExcludeProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "ExpandProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$pattern = $command + "*"
gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/SQLite Read _ Write_1.ps1
|
SQLite Read _ Write_1.ps1
|
# Make sure SQLite.Interop.dll is in the same directory as System.Data.SQLite.dll
$scriptDir = "Path to your SQLite DLL"
Add-Type -Path "$scriptDir\\System.Data.SQLite.dll"
############### SAMPLE USAGE ###################
### Querying:
###
### $readQuery = "SELECT * FROM TABLE"
### $dataArray = $SQLite.querySQLite($readQuery)
###
### Writing:
###
### $writeQuery = "INSERT OR IGNORE INTO TABLE VALUES ('12345', 'TEST');
### UPDATE GAME SET NAME = 'TEST1235' WHERE ID LIKE '12345';"
### $SQLite.writeSQLite($query)
###
################################################
################################################
###
### $catalog contains two properties ID and NAME
### foreach($item in $catalog ){
### $writeQuery = "INSERT OR IGNORE INTO GAME VALUES (`"$($item.ID)`", `"$($item.NAME)`");
### UPDATE GAME SET NAME = `"$($item.NAME)`" WHERE ID LIKE `"$($item.ID)`";"
### $SQLite.writeSQLite($writeQuery)
### }
$SQLite = New-Module {
Function querySQLite {
param([string]$query)
$datatSet = New-Object System.Data.DataSet
### declare location of db file. ###
$database = "$scriptDir\\data"
$connStr = "Data Source = $database"
$conn = New-Object System.Data.SQLite.SQLiteConnection($connStr)
$conn.Open()
$dataAdapter = New-Object System.Data.SQLite.SQLiteDataAdapter($query,$conn)
[void]$dataAdapter.Fill($datatSet)
$conn.close()
return $datatSet.Tables[0].Rows
}
Function writeSQLite {
param([string]$query)
$database = "$scriptDir\\data"
$connStr = "Data Source = $database"
$conn = New-Object System.Data.SQLite.SQLiteConnection($connStr)
$conn.Open()
$command = $conn.CreateCommand()
$command.CommandText = $query
$RowsInserted = $command.ExecuteNonQuery()
$command.Dispose()
}
Export-ModuleMember -Variable * -Function *
} -asCustomObject
|
PowerShellCorpus/PoshCode/Get-GrowthRate_1.ps1
|
Get-GrowthRate_1.ps1
|
function Get-GrowthRate {
param( $Start, $End, $Period )
@@ $rate = [math]::Abs( [math]::Pow( ( $End / $Start ),( 1 / $Period - 1 ) ) - 1 )
"{0:P}" -f $rate
}
|
PowerShellCorpus/PoshCode/Modal File Dialogs.ps1
|
Modal File Dialogs.ps1
|
Add-Type -TypeDefinition @"
using System;
using System.Windows.Forms;
public class Win32Window : IWin32Window
{
private IntPtr _hWnd;
public Win32Window(IntPtr handle)
{
_hWnd = handle;
}
public IntPtr Handle
{
get { return _hWnd; }
}
}
"@ -ReferencedAssemblies "System.Windows.Forms.dll"
$owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.ShowDialog($owner)
|
PowerShellCorpus/PoshCode/New-ISEMenu_1.ps1
|
New-ISEMenu_1.ps1
|
Import-Module ShowUI
Function New-ISEMenu {
New-Grid -AllowDrop:$true -Name "ISEAddonCreator" -columns Auto, * -rows Auto,Auto,Auto,*,Auto,Auto -Margin 5 {
New-Label -Name Warning -Foreground Red -FontWeight Bold -Column 1
($target = New-TextBox -Name txtName -Column 1 -Row ($Row=1))
New-Label "Addon Menu _Name" -Target $target -Row $Row
($target = New-TextBox -Name txtShortcut -Column 1 -Row ($Row+=1))
New-Label "Shortcut _Key" -Row $Row -Target $target
($target = New-TextBox -Name txtScriptBlock -Column 1 -Row ($Row+=1) -MinHeight 141 -MinWidth 336 -AcceptsReturn:$true -HorizontalScrollBarVisibility Auto -VerticalScrollBarVisibility Auto)
New-Label "Script _Block" -Row $Row -Target $target
New-CheckBox "_Add to ISE Profile" -Name chkProfile -Row ($Row+=1)
New-StackPanel -Orientation Horizontal -Column 1 -Row ($Row+=1) -HorizontalAlignment Right {
New-Button "_Save" -Name btnSave -Width 75 -Margin "0,0,5,0" -IsDefault -On_Click {
if ($txtName.Text.Trim() -eq "" -or $txtShortcut.text.Trim() -eq "" -or $txtScriptBlock.text.Trim() -eq "") {
$Warning.Content = "You must supply all parameters"
} else {
$menuItems = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | Select -ExpandProperty DisplayName
if ($menuItems -Contains $txtName.Text) {
$Warning.Content = "Select another Name for the menu"
return
}
try {
$ScriptBlock = [ScriptBlock]::Create($txtScriptBlock.Text)
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add($txtName.Text,$ScriptBlock,$txtShortcut.Text) | Out-Null
}
catch {
$Warning.Content = "Fatal Error Creating MenuItem:`n$_"
return
}
if ($chkProfile.IsChecked) {
$profileText = "`n`#Added by ISE Menu Creator Addon if (`$psISE) { `$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(`"$($txtName.Text)`",`{$ScriptBlock`},`"$($txtShortcut.Text)`") | Out-Null } "
Add-Content -Path $profile -Value $profileText
}
$window.Close()
}
}
New-Button "Cancel" -Name btnCancel -Width 75 -IsCancel
}
} -show
}
# this will add a the "New ISE menu" menu item and load it every time you run this script!
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New ISE menu",{New-ISEMenu},"ALT+M") | Out-Null
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.