full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Find old snapshots.ps1
Find old snapshots.ps1
param ( $Age = 30 ) Connect-VIServer vcenter.domain.com $vm = Get-VM $snapshots = Get-Snapshot -VM $vm Write-Host -ForegroundColor Red "Old snapshots found:" foreach ( $snap in $snapshots ) { if ( $snap.Created -lt (Get-Date).AddDays( -$Age ) ) { Write-Host "Name: " $snap.Name " Size: " $snap.SizeMB " Created: " $snap.Created } }
PowerShellCorpus/PoshCode/Get-Parameter 2.4.ps1
Get-Parameter 2.4.ps1
#Requires -version 2.0 #.Synopsis # Enumerates the parameters of one or more commands #.Notes # With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy # Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186 # Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255 # Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445 # Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446 # Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549 # - Added resolving aliases and avoided empty output # Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344 # Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592 # - Merged Oisin and Hal's code with my own implementation # - Added calculation of dynamic paramters # Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005 # - Now uses FormatData so the output is objects # - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation) # Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007 # - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line) # - Fleshed out and added dates to this version history after Bergle's criticism ;) # Version 2.2 - July 29, 2010 - By Joel Bennett (This Version) # - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo # Version 2.3 - July 29, 2010 - By Joel Bennett (This Version) # - Added a ToString ScriptMethod which allows queries like: # $parameters = Get-Parameter Get-Process; $parameters -match "Name" # Version 2.4 - July 29, 2010 - By Joel Bennett (This Version) # - CHANGED "Name" to CommandName # - ADDED ParameterName parameter to allow filtering parameters # - Fixed bug in 2.3 and 2.2 with dynamic parameters # #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter CommandName # The name of the command to get parameters for #.Parameter ParameterName # Wilcard-enabled filter for parameter names #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [Alias("Name")] [string[]]$CommandName , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] [string[]]$ParameterName="*" , [Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) Function global:Get-Parameter { #.Synopsis # Enumerates the parameters of one or more commands #.Description # Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc. # # By default, formats the output to tables grouped by command and parameter set #.Example # Get-Command Select-Xml | Get-Parameter #.Example # Get-Parameter Select-Xml #.Parameter CommandName # The name of the command to get parameters for #.Parameter ParameterName # Wilcard-enabled filter for parameter names #.Parameter ModuleName # The name of the module which contains the command (this is for scoping) #.Parameter Force # Forces including the CommonParameters in the output [CmdletBinding()] param ( [Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)] [string[]]$CommandName , [Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)] [string[]]$ParameterName="*" , [Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)] $ModuleName , [switch]$Force ) begin { $PropertySet = @( "Name", @{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}}, "Aliases", @{n="Short";e={$_.Name}}, @{n="Type";e={$_.ParameterType.Name}}, @{n="ParameterSet";e={$paramset}}, @{n="Command";e={$command}}, @{n="Mandatory";e={$_.IsMandatory}}, @{n="Provider";e={$_.DynamicProvider}}, @{n="ValueFromPipeline";e={$_.ValueFromPipeline}}, @{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}} ) function Join-Object { Param( [Parameter(Position=0)] $First , [Parameter(ValueFromPipeline=$true,Position=1)] $Second ) begin { [string[]] $p1 = $First | gm -type Properties | select -expand Name } process { $Output = $First | Select $p1 foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) { Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p" } $Output } } } process{ foreach($cmd in $CommandName) { if($ModuleName) { $cmd = "$ModuleName\\$cmd" } $commands = @(Get-Command $cmd) foreach($command in $commands) { # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = @(Get-Command ($command.definition))[0] } if (-not $command) { continue } $Parameters = @{} foreach($provider in Get-PSProvider) { $drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters") [Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values [Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic } foreach($p in $MoreParameters | Where { !$Parameters.ContainsKey( $_.Name ) } ){ $Parameters.($p.Name) = $p } # Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)" if($dynamic) { foreach($d in $dynamic) { if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) { Write-Debug ("ADD:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name).DynamicProvider += $provider.Name } else { Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name) $Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru } } } } ## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else. foreach($p in $($Parameters.Keys)) { $shortest="^" foreach($char in [char[]]$p) { $shortest += $char $Matches = ($Parameters.Keys -match $Shortest).Count Write-Debug "$($shortest.SubString(1)) $Matches" if($Matches -eq 1) { $Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru break } } } Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)" foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){ foreach($parameter in $Parameters.Keys | Sort) { Write-Verbose "Parameter: $Parameter" if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue } if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) { if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet } else { $output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets } Write-Output $Output | Select-Object $PropertySet | ForEach { $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata") $null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx") Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")" $_ } | Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru | Where-Object { $(foreach($pn in $ParameterName){ $_ -like $Pn}) -contains $true } } } } } } } } # Since you can't update format data without a file that has a ps1xml ending, let's make one up... $tempFile = "$([IO.Path]::GetTempFileName()).ps1xml" Set-Content $tempFile @' <?xml version="1.0" encoding="utf-8" ?> <Configuration> <Controls> <Control> <Name>ParameterGroupingFormat</Name> <CustomControl> <CustomEntries> <CustomEntry> <CustomItem> <Frame> <LeftIndent>4</LeftIndent> <CustomItem> <Text>Command: </Text> <ExpressionBinding> <ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock> </ExpressionBinding> <NewLine/> <Text>Set: </Text> <ExpressionBinding> <ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock> </ExpressionBinding> <NewLine/> </CustomItem> </Frame> </CustomItem> </CustomEntry> </CustomEntries> </CustomControl> </Control> </Controls> <ViewDefinitions> <View> <Name>ParameterMetadataEx</Name> <ViewSelectedBy> <TypeName>System.Management.Automation.ParameterMetadataEx</TypeName> </ViewSelectedBy> <GroupBy> <PropertyName>ParameterSet</PropertyName> <CustomControlName>ParameterGroupingFormat</CustomControlName> </GroupBy> <TableControl> <TableHeaders> <TableColumnHeader> <Label>Name</Label> <Width>22</Width> </TableColumnHeader> <TableColumnHeader> <Label>Aliases</Label> <Width>12</Width> </TableColumnHeader> <TableColumnHeader> <Label>Position</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>Mandatory</Label> <Width>9</Width> </TableColumnHeader> <TableColumnHeader> <Label>Pipeline</Label> <Width>8</Width> </TableColumnHeader> <TableColumnHeader> <Label>ByName</Label> <Width>6</Width> </TableColumnHeader> <TableColumnHeader> <Label>Provider</Label> <Width>15</Width> </TableColumnHeader> <TableColumnHeader> <Label>Type</Label> </TableColumnHeader> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>Name</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>Aliases</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Position</PropertyName--> <ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Mandatory</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipeline</PropertyName> </TableColumnItem> <TableColumnItem> <PropertyName>ValueFromPipelineByPropertyName</PropertyName> </TableColumnItem> <TableColumnItem> <!--PropertyName>Provider</PropertyName--> <ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock> </TableColumnItem> <TableColumnItem> <PropertyName>Type</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> </ViewDefinitions> </Configuration> '@ Update-FormatData -Append $tempFile # This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that. Get-Parameter @PSBoundParameters
PowerShellCorpus/PoshCode/Get-MemoryChart_1.ps1
Get-MemoryChart_1.ps1
#.Synopsis # Draw pie charts of server memory usage by process #.Description # Uses PowerBoots to draw a pipe-chart of each computer's memory use. While you wait for that information # to be gathered, it shows you the latest xkcd comic. ##DEPEND-ON -Function Get-Comic http://poshcode.org/1003 # Uses the Transitionals library for nice transitions ##DEPEND-ON -Assembly Transitionals http://www.codeplex.com/transitionals # Uses the Visifire libraries for the charts, of course ##DEPEND-ON -Assembly Transitionals http://visifire.com # Whoops, it's also dependent on Set-AttachedProperty ##DEPEND-ON -Function Set-AttachedProperty http://poshcode.org/1017 # which for some reason isn't in PowerBoots yet! # #.Parameter hosts # The hostnames of the computers you want memory charts for #.Example # Get-MemoryChart localhost # # Returns a pie-chart of the memory on your local PC #.Example # Get-MemoryChart Server01,Server02 # # Returns a pie-chart of the memory on Server01, and Server02 # Note that this requires WMI and authorization... # Param([string[]]$hosts = "localhost") Import-Module PowerBoots if(!(Get-Command Chart -EA SilentlyContinue)) { Add-BootsContentProperty 'DataPoints', 'Series' Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll" 2>$Null Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\Transitionals.dll" } ## And this is how you use a script which might not be there... $comical = Get-Command Get-Comic -EA SilentlyContinue if($comical) { $script:comic = Get-Comic xkcd $image = [system.drawing.image]::fromfile( $comic.FullName ) $script:width = $image.Width $image.Dispose() } #$window = Boots { Image -Source $xkcd -MinHeight 100 } -Popup -Async $limitsize = 10mb $labellimitsize = 15mb $window = Boots { DockPanel { # ListBox -DisplayMember Name -Ov global:list ` # -width 0 # -On_SelectionChanged { $global:container[0].Content = $global:list[0].SelectedItem } # TransitionElement -Transition $(RotateTransition -Angle 45) ` Frame ` -Name TransitionBox -Ov global:container ` -MinWidth 400 -MinHeight 400 -MaxHeight 600 ` -Content { StackPanel { Label -FontSize 42 "Loading ..." if($comical) { Image -Source $comic.FullName -MaxWidth $width } } | Set-AttachedProperty ([System.Windows.Navigation.JournalEntry]::NameProperty) "XKCD Comic" } } -LastChildFill $true } -MinHeight 400 -Async -Popup -Passthru sleep 2; $jobs = @() ForEach($pc in $hosts) { $jobs += gwmi Win32_Process -ComputerName $pc -AsJob; } while($jobs) { $job = Wait-Job -Any $jobs Invoke-BootsWindow $window { # if($list -is [System.Collections.ArrayList]) { # $list = $list[0]; # $list.Padding = "2,2,5,2" # } $name = $($job.Location -Replace "[^a-zA-Z_0-9]" -replace "(^[0-9])",'_$1') # $null = $list.Items.Add( $global:container[0].Content = ` $( Chart { DataSeries -LabelText $job.Location { ForEach($proc in (Receive-Job $job | Sort WorkingSetSize)) { if($proc.WorkingSetSize -gt $limitsize) { DataPoint -YValue $proc.WorkingSetSize -LabelText $proc.Name ` -LabelEnabled $($proc.WorkingSetSize -gt $labellimitsize) ` -ToolTipText "$($proc.Name): #YValue (#Percentage%)" } } } -RenderAs Pie -ShowInLegend $false } -Watermark $false -AnimationEnabled $true -Name $name | Set-AttachedProperty ([System.Windows.Navigation.JournalEntry]::NameProperty) $name ) # $list.SelectedIndex = $list.Items.Count - 1 } $jobs = $jobs -ne $job Remove-Job $job.Id Sleep 5 }
PowerShellCorpus/PoshCode/Get-DiskUsage_1.ps1
Get-DiskUsage_1.ps1
##############################################################################\n##\n## Get-DiskUsage\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\nRetrieve information about disk usage in the current directory and all\nsubdirectories. If you specify the -IncludeSubdirectories flag, this\nscript accounts for the size of subdirectories in the size of a directory.\n\n.EXAMPLE\n\nGet-DiskUsage\nGets the disk usage for the current directory.\n\n.EXAMPLE\n\nGet-DiskUsage -IncludeSubdirectories\nGets the disk usage for the current directory and those below it,\nadding the size of child directories to the directory that contains them.\n\n#>\n\nparam(\n ## Switch to include subdirectories in the size of each directory\n [switch] $IncludeSubdirectories\n)\n\nSet-StrictMode -Version Latest\n\n## If they specify the -IncludeSubdirectories flag, then we want to account\n## for all subdirectories in the size of each directory\nif($includeSubdirectories)\n{\n Get-ChildItem | Where-Object { $_.PsIsContainer } |\n Select-Object Name,\n @{ Name="Size";\n Expression={ ($_ | Get-ChildItem -Recurse |\n Measure-Object -Sum Length).Sum + 0 } }\n}\n## Otherwise, we just find all directories below the current directory,\n## and determine their size\nelse\n{\n Get-ChildItem -Recurse | Where-Object { $_.PsIsContainer } |\n Select-Object FullName,\n @{ Name="Size";\n Expression={ ($_ | Get-ChildItem |\n Measure-Object -Sum Length).Sum + 0 } }\n}
PowerShellCorpus/PoshCode/Transparent Glass Posh.ps1
Transparent Glass Posh.ps1
#include <Misc.au3> #include <Process.au3> #Include <WinAPI.au3> Opt("TrayIconHide",1) Global Const $HSHELL_WINDOWCREATED = 1 Global Const $HSHELL_WINDOWACTIVATED = 4; Global Const $HWND_MESSAGE = -3 Global $bHook = 1 $hGui = GUICreate("", 10, 10, -1, 0,-1,-1,$HWND_MESSAGE) GUIRegisterMsg(_WinAPI_RegisterWindowMessage("SHELLHOOK"), "HookProc") ShellHookWindow($hGui, $bHook) ClearMemory() ;$About = TrayCreateItem("About") TrayCreateItem("") ;$Exit = TrayCreateItem("Exit") While 1 sleep(20000) ;Switch TrayGetMsg() ; Case $About ; MsgBox("","","Glass CMD for Windows Vista/Seven By Komalo - komalo.deviantart.com") ; Case $Exit ; Exit ;EndSwitch WEnd Func HookProc($hWnd, $Msg, $wParam, $lParam) $pname = _ProcessGetName(WinGetProcess($lParam)) If $pname = "cmd.exe" Then EnableBlurBehind($lParam) If @error Then MsgBox(16, "Glass CMD", "You are not running Vista!") ClearMemory() EndIf If $pname = "powershell.exe" Then EnableBlurBehind($lParam) If @error Then MsgBox(16, "Glass CMD", "You are not running Vista!") ClearMemory() EndIf EndFunc Func ShellHookWindow($hWnd, $bFlag) Local $sFunc = 'DeregisterShellHookWindow' If $bFlag Then $sFunc = 'RegisterShellHookWindow' Local $aRet = DllCall('user32.dll', 'int', $sFunc, 'hwnd', $hWnd) Return $aRet[0] EndFunc Func EnableBlurBehind($hWnd) Const $DWM_BB_ENABLE = 0x00000001 $Struct = DllStructCreate("dword;int;ptr;int") DllStructSetData($Struct,1,$DWM_BB_ENABLE) DllStructSetData($Struct,2,"1") DllStructSetData($Struct,4,"1") DllCall("dwmapi.dll","int","DwmEnableBlurBehindWindow","hwnd",$hWnd,"ptr",DllStructGetPtr($Struct)) EndFunc Func ClearMemory() Local $ai_Return = DllCall("psapi.dll", 'int', 'EmptyWorkingSet', 'long', -1) Return $ai_Return[0] EndFunc ;==>_ReduceMemory Func OnAutoItExit() If $hGui Then ShellHookWindow($hGui, 0) EndIf EndFunc ;==>OnAutoItExit
PowerShellCorpus/PoshCode/2c54f592-a435-48e1-9591-e9667f707941.ps1
2c54f592-a435-48e1-9591-e9667f707941.ps1
<# Name: VHDFunctions.psm1 Author: Rich Kusak (rkusak@cbcag.edu) Created: 2009-10-23 LastEdit: 2009-11-02 15:54 Included Functions: Dismount-VHD Initialize-VHD Mount-VHD New-VHD Set-VHDBootConfiguration Test-VHD #> <# .SYNOPSIS Dismount a VHD file from the system. .DESCRIPTION This function wraps the consistancy of PowerShell around the Diskpart utility. A Diskpart script is created to automate the dismount (detach) of a VHD file from the system. Optionally, the VHD file can be deleted following detachment. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER Remove Removes (deletes) the VHD file after dismounting it. .PARAMETER NoConfirm Supresses the delete confirmation prompt. .PARAMETER DiskpartScript Specifies the path location of the Diskpart script file. Default location is $env:SystemDrive This file is deleted at the conclusion of the script. .PARAMETER Rescan Instructs Diskpart to rescan the system for available storage resources. .EXAMPLE Dismount-VHD -Path C:\\test.vhd Dismounts the specified VHD file. .EXAMPLE Dismount-VHD -Path C:\\test.vhd -Remove Dismounts the specified VHD file and then deletes it. .NOTES Name: Dismount-VHD.ps1 Author: Rich Kusak Created: 2009-10-22 LastEdit: 2009-10-26 11:35 #Requires -Version 2.0 #> function Dismount-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [switch]$Remove, [switch]$NoConfirm, [string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } function RemoveVHD { switch ($NoConfirm) { $false { ## Prompt for confirmation to delete the VHD file ## "" ; Write-Warning "Are you sure you want to delete the file ""$Path""?" $Prompt = Read-Host "Type ""YES"" to continue or anything else to break" if ($Prompt -ceq 'YES') { Remove-Item -Path $Path -Force "" ; Write-Host "VHD ""$Path"" deleted!" ; "" } else { "" ; Write-Host "Script terminated without deleting the VHD file." ; "" } } $true { ## Confirmation prompt suppressed ## Remove-Item -Path $Path -Force "" ; Write-Host "VHD ""$Path"" deleted!" ; "" } } } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."} } process{ ## DiskPart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Select VDisk File="$Path"`nDetach VDisk Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart } end { if ($Remove) {RemoveVHD} Remove-Item -Path $DiskpartScript -Force ; "" } } Export-ModuleMember -Function Dismount-VHD <# .SYNOPSIS Initialize a VHD by preparing it for use. .DESCRIPTION This function wraps the consistancy of PowerShell around the Diskpart utility. A Diskpart script is created to automate initializing a VHD. The script creates a partition, assigns a drive letter, and formats a mounted VHD. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER Drive A drive letter to assign to the mounted VHD. If not specified the system will auto assign the next available drive letter. .PARAMETER Label A volume label to assign to the mounted VHD. .PARAMETER DiskpartScript Specifies the path location of the Diskpart script file. Default location is $env:SystemDrive This file is deleted at the conclusion of the script. .PARAMETER Rescan Instructs Diskpart to rescan the system for available storage resources. .EXAMPLE Initialize-VHD C:\\test.vhd X: TestVHD Initializes the VHD at path C:\\test.vhd assign it to drive letter X: and give it the volume label "TestVHD". .NOTES Name: Initialize-VHD Author: Rich Kusak Created: 2009-10-22 LastEdit: 2009-10-26 15:11 #Requires -Version 2.0 #> function Initialize-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)] [string]$Drive, [Parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false)] [string]$Label, [Parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false)] [string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt", [switch]$NoConfirm, [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."} ## Validate -Drive parameter ## if ($Drive) { $Reserved = @('A:','B:','C:') $Reserved += (Get-WmiObject win32_LogicalDisk -Property DeviceID | ForEach-Object {$_.DeviceID}) switch ($Drive) { {($_ -notmatch "^[a-z]$") -and ($_ -notmatch "^[a-z]:$")} {throw "The drive letter ""$_"" is invalid."} {$_ -notmatch ":"} {$Drive += ":"} {$Reserved -contains $Drive} {throw "The drive letter ""$_"" is reserved."} } } if (!$NoConfirm) { "" ; Write-Warning "The VHD ""$Path"" is about to initialized. Any existing data will be destroyed!`nAre you sure you want to continue?" ; "" $Prompt = Read-Host "Type ""YES"" to continue or anything else to break" if ($Prompt -cne 'YES') {Write-Host "Function terminated by user."; "" ; break} } } process { ## Diskpart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Select VDisk File="$Path" Clean Create Partition Primary Format Quick FS=NTFS $(if ($Label) {"Label=""$Label"""}) $(if ($Drive) {"Assign Letter=$Drive"} else {'Assign'}) Detail VDisk Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force } end { InvokeDiskpart Remove-Item -Path $DiskpartScript -Force ; "" Write-Host "The VHD ""$Path"" has been successfully initialized." ; "" } } Export-ModuleMember -Function Initialize-VHD <# .SYNOPSIS Mount a VHD to the system. .DESCRIPTION This function wraps the consistancy of PowerShell around the Diskpart utility. A Diskpart script is created to automate mounting (attach) a VHD file to the system. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER DiskpartScript Specifies the path location of the Diskpart script file. Default location is $env:SystemDrive This file is deleted at the conclusion of the script. .PARAMETER Rescan Instructs Diskpart to rescan the system for available storage resources. .NOTES Name: Mount-VHD.ps1 Author: Rich Kusak Created: 2009-10-22 LastEdit: 2009-10-26 09:25 #Requires -Version 2.0 #> function Mount-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."} } process{ ## Diskpart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Select VDisk File="$Path"`nAttach VDisk Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart } end { Remove-Item -Path $DiskpartScript -Force ; "" Write-Host "The VHD ""$Path"" has been successfully mounted." ; "" } } Export-ModuleMember -Function Mount-VHD <# .SYNOPSIS Create a new VHD file. .DESCRIPTION This function wraps the consistancy of PowerShell around the Diskpart utility. A Diskpart script is created to automate the creation of the VHD. Optionally, the VHD can be mounted immediately following the creation process. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER Maximum The maximum space allocated for the VHD to use. .PARAMETER Fixed Creates a fixed disk VHD file. By default a dynamically expanding VHD file is created. .PARAMETER Mount Mount (attach) the VHD to the system making it available to Windows. .PARAMETER Prepare Prepares the VHD for use by partitioning, Mount (attach) the VHD to the system making it available to Windows. .PARAMETER NoConfirm Supresses the maximum validation warning confirmation prompt. .PARAMETER DiskpartScript Specifies the path location of the Diskpart script file. Default location is $env:SystemDrive This file is deleted at the conclusion of the script. .PARAMETER Rescan Instructs Diskpart to rescan the system for available storage resources. .NOTES Name: New-VHD Author: Rich Kusak Created: 2009-05-27 LastEdit: 2009-10-26 10:06 #Requires -Version 2.0 #> function New-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [int]$Maximum, [switch]$Fixed, [switch]$Mount, [switch]$NoConfirm, [string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } function TestMaximum { ## Validates the -Maximum parameter against the specified disk's available space ## $Drive = Split-Path $Path -Qualifier $LogicalDisk = Get-WmiObject win32_LogicalDisk -Filter "DeviceID = '$Drive'" $FreeSpace = [math]::Truncate(($LogicalDisk.FreeSpace)/1MB) $Percent = [math]::Round(($Maximum/$FreeSpace)*100,0) switch ($Maximum) { {$_ -gt 2088960} {throw "The -Maximum parameter value ""$Maximum"" exceeds the allowable VHD size."} {$_ -ge $FreeSpace -and $Fixed} {throw "The -Maximum parameter value ""$Maximum"" exceeds available disk space."} {$_ -ge $FreeSpace} { "" ; Write-Warning "The VHD maximum size exceeds available disk space." if (!$NoConfirm) { Write-Host "Are you sure you want to continue?" $Prompt = Read-Host "Type ""YES"" to continue or anything else to break" if ($Prompt -cne 'YES') { "" ; Write-Host "Script terminiated by user." ; "" return } } } {$Percent -ge 80} { "" ; Write-Warning "The VHD maximum size is $Percent% of the available disk space." if (!$NoConfirm) { Write-Host "Are you sure you want to continue?" $Prompt = Read-Host "Type ""YES"" to continue or anything else to break" if ($Prompt -cne 'YES') { "" ; Write-Host "Script terminiated by user." ; "" return } } } } ## Validate Operating System Version ## if (Get-WmiObject win32_OperatingSystem -Filter "Version < '6.1'") {throw "The script operation requires at least Windows 7."} } } process { TestMaximum ## Diskpart Script Content ## Here-String statement purposefully not indented ## @" $(if ($Rescan) {'Rescan'}) Create VDisk File="$Path" Maximum=$Maximum $(if ($Fixed) {'Type=Fixed'} else {'Type=Expandable'}) $(if ($Mount) {"Select VDisk File=""$Path""`nAttach VDisk"}) Exit "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart } end { Remove-Item -Path $DiskpartScript -Force ; "" Write-Host "A new VHD has been created at ""$Path""." ; "" if ($Mount) {Write-Host "The VHD has been successfully mounted." ; ""} } } Export-ModuleMember -Function New-VHD <# .SYNOPSIS Set the system boot configuration to boot from a VHD. .DESCRIPTION This function wraps the consistancy of PowerShell around the BCDEdit tool. The Boot Configuration DataStore Editor (BCDEdit) is used to set the necessary boot configuration entry to optionally boot to a VHD during startup. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER Description Description for the boot configuration entry. .EXAMPLE Set-VHDBootConfiguration .NOTES Name: Set-VHDBootConfiguration Author: Rich Kusak Created: 2009-10-22 LastEdit: 2009-10-26 10:14 #Requires -Version 2.0 #> function Set-VHDBootConfiguration { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true)] [string]$Path, [Parameter(Position=1,Mandatory=$true)] [string]$Description ) begin { if (!(Test-Path -Path $Path -Include "*.vhd")) {throw "The path ""$Path"" is invalid or does not contain a VHD file."} $Drive = Split-Path -Path $Path -Qualifier $UnQualifiedPath = Split-Path -Path $Path -NoQualifier } process { $Copy = bcdedit /copy '{current}' /d $Description $CLSID = $Copy | ForEach-Object {$_.Remove(0,37).Replace(".","")} bcdedit /set $CLSID device vhd=[$Drive]""$UnQualifiedPath"" bcdedit /set $CLSID osdevice vhd=[$Drive]""$UnQualifiedPath"" bcdedit /set $CLSID detecthal on New-Object PSObject | Add-Member -MemberType NoteProperty -Name 'Identifier' -Value $CLSID -PassThru | } end { Write-Host "The VHD ""$Path"" has been prepared for boot operation." ; "" } } Export-ModuleMember -Function Set-VHDBootConfiguration <# .SYNOPSIS Test a VHD. .DESCRIPTION This script wraps the consistancy of PowerShell around the Diskpart utility. A Diskpart script is created to automate initializing a VHD. The script creates a partition, assigns a drive letter, and formats a mounted VHD. .PARAMETER Path Specifies the full path to the VHD file. .PARAMETER DiskpartScript Specifies the path location of the Diskpart script file. Default location is $env:SystemDrive This file is deleted at the conclusion of the script. .PARAMETER Rescan Instructs Diskpart to rescan the system for available storage resources. .NOTES Name: Test-VHD.ps1 Author: Rich Kusak Created: 2009-10-23 LastEdit: 2009-10-26 10:17 #Requires -Version 2.0 #> function Test-VHD { [CmdletBinding()] param ( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [string]$Path, [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false)] [string]$DiskpartScript = "$env:SystemDrive\\DiskpartScript.txt", [switch]$Rescan ) begin { function InvokeDiskpart { Diskpart.exe /s $DiskpartScript } if (!(Test-Path -Path $Path -Include "*.vhd")) {throw "The path ""$Path"" is not valid or does not contain a VHD file."} } process { @" Select VDisk File="$Path" Detail VDisk "@ | Out-File -FilePath $DiskpartScript -Encoding ASCII -Force InvokeDiskpart } end { Remove-Item -Path $DiskpartScript -Force ; "" } } Export-ModuleMember -Function Test-VHD
PowerShellCorpus/PoshCode/Logger_1.psm1 0.2.ps1
Logger_1.psm1 0.2.ps1
<# Name : Universal Log4Net Logging Module (Logger.psm1) Version : 0.3 Author : Joel Bennett (MVP) Site : http://www.HuddledMasses.org/ Version History: 0.3 - Cleanupable release. Added Udp, Email, Xml and RollingXml, as well as a "Chainsaw":http`://logging.apache.org/log4j/docs/chainsaw.html logger based on "Szymon Kobalczyk's configuration":http`://geekswithblogs.net/kobush/archive/2005/07/15/46627.aspx. Note: there is a "KNOWN BUG with Log4Net UDP":http`://odalet.wordpress.com/2007/01/13/log4net-ip-parsing-bug-when-used-with-framework-net-20/ which can be patched, but hasn't been released. Added a Close-Logger method to clean up the Xml logger NOTE: the Rolling XML Logger produces invalid XML, and the XML logger only produces valid xml after it's been closed... I did contribute an "XSLT stylesheet for Log4Net":http`://poshcode.org/1746 which you could use as well 0.2 - Configless release. Now configures with inline XML, and supports switches to create "reasonable" default loggers Changed all the functions to Write-*Log so they don't overwrite the cmdlets Added -Logger parameter to take the name of the logger to use (it must be created beforehand via Get-Logger) Created aliases for Write-* to override the cmdlets -- these are easy for users to remove without breaking the module ** NEED to write some docs, but basically, this is stupid simple to use, just: Import-Module Logger Write-Verbose "This message will be saved in your profile folder in a file named PowerShellLogger.log (by default)" To change the defaults for your system, edit the last line in the module!! 0.1 - Initial release. http`://poshcode.org/1744 (Required config: http`://poshcode.org/1743) Uses Log4Net : http`://logging.apache.org/log4net/download.html Documentation: http`://logging.apache.org/log4net/release/sdk/ NOTES: By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host. This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts) To avoid this behavior, remove the aliases after importing it Import-Module Logger; Remove-Item Alias:Write-* Write-Warning "This is your warning" Write-Debug "You should know that..." Write-Verbose "Everything would be logged, otherwise" ***** NOTE: IT ONLY OVERRIDES THE DEFAULTS FOR SCRIPTS ***** It currently has no effect on error/verbose/warning that is logged from cmdlets. #> Add-Type -Path $PSScriptRoot\\log4net.dll function Get-Logger { param( [Parameter(Mandatory=$false)] [string]$LoggerName = "*" , [Parameter(Mandatory=$false)] [ValidateSet("DEBUG","INFO","WARN","ERROR","FATAL","VERBOSE","HOST","WARNING")] [string]$LogLevel = "DEBUG" , [Parameter(Mandatory=$false)] $MessagePattern = "%date %-5level %logger [%property{NDC}] - %message%newline" , [Parameter(Mandatory=$false)] [string]$LogFolder = $PSScriptRoot , [String]$EmailTo , [Switch]$Force , [Switch]$Console , [Switch]$EventLog , [Switch]$Trace , [Switch]$DebugAppender , [Switch]$File , [Switch]$RollingFile , [Switch]$Xml , [Switch]$RollingXml , [Switch]$Udp , [Switch]$Chainsaw ) Remove-Variable Loggers -EA 0 [log4net.LogManager]::GetCurrentLoggers() | Where-Object { $_.Logger.Name -Like $LoggerName } | Tee-Object -Variable Loggers if(!$Loggers -or $Force -and $LoggerName -ne "*") { if($LogLevel -eq "VERBOSE") { $LogLevel = "INFO" } if($LogLevel -eq "HOST") { $LogLevel = "INFO" } if($LogLevel -eq "WARNING") { $LogLevel = "WARN" } $AppenderRefs = '' if($Email) { if(!$PSEmailServer) { throw "You need to specify your SMTP mail server by setting the global $PSEmailServer variable" } $AppenderRefs += "<appender-ref ref=""SmtpAppender"" />`n" $Null,$Domain = $email -split "@",2 } if($EventLog) { $AppenderRefs += "<appender-ref ref=""EventLogAppender"" />`n" } if($Trace) { $AppenderRefs += "<appender-ref ref=""TraceAppender"" />`n" } if($DebugAppender){ $AppenderRefs += "<appender-ref ref=""DebugAppender"" />`n" } if($File) { $AppenderRefs += "<appender-ref ref=""FileAppender"" />`n" } if($RollingFile) { $AppenderRefs += "<appender-ref ref=""RollingFileAppender"" />`n" } if($Udp) { $AppenderRefs += "<appender-ref ref=""UdpAppender"" />`n" } if($Chainsaw) { $AppenderRefs += "<appender-ref ref=""UdpLog4JAppender"" />`n" } if($Xml) { $AppenderRefs += "<appender-ref ref=""XmlAppender"" />`n" } if($RollingXml) { $AppenderRefs += "<appender-ref ref=""RollingXmlAppender"" />`n" } if($Console -or ($AppenderRefs.Length -eq 0)) { $AppenderRefs += "<appender-ref ref=""ColoredConsoleAppender"" />`n" } [log4net.LogManager]::GetLogger($LoggerName) | Tee-Object -Variable Script:Logger [xml]$config = @" <log4net> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="FATAL" /> <foreColor value="Red, HighIntensity" /> <backColor value="White, HighIntensity" /> </mapping> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="DEBUG" /> <foreColor value="Green, HighIntensity" /> </mapping> <mapping> <level value="INFO" /> <foreColor value="Cyan, HighIntensity" /> </mapping> <mapping> <level value="WARN" /> <foreColor value="Yellow, HighIntensity" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" > <applicationName value="$LoggerName" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="TraceAppender" type="log4net.Appender.TraceAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="DebugAppender" type="log4net.Appender.DebugAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="FileAppender" type="log4net.Appender.FileAppender"> <file value="$LogFolder\\$LoggerName.Log" /> <appendToFile value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="XmlAppender" type="log4net.Appender.FileAppender"> <file value="$LogFolder\\$LoggerName.xml" /> <appendToFile value="false" /> <layout type="log4net.Layout.XmlLayout"> <Header value="&lt;?xml version='1.0' ?&gt; &lt;?xml-stylesheet type="text/xsl" href="log4net.xslt"?&gt; &lt;events version='1.2' xmlns='http://logging.apache.org/log4net/schemas/log4net-events-1.2'&gt; "/> <Footer value="&lt;/events&gt;"/> <Prefix value="" /> </layout> </appender> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="$LogFolder\\$LoggerName.Log" /> <appendToFile value="true" /> <maximumFileSize value="100KB" /> <maxSizeRollBackups value="2" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="$MessagePattern" /> </layout> </appender> <appender name="RollingXmlAppender" type="log4net.Appender.RollingFileAppender"> <file value="$LogFolder\\$LoggerName.xml" /> <appendToFile value="true" /> <maximumFileSize value="500KB" /> <maxSizeRollBackups value="2" /> <layout type="log4net.Layout.XmlLayout"> <Prefix value="" /> </layout> </appender> <appender name="UdpAppender" type="log4net.Appender.UdpAppender"> <param name="RemoteAddress" value="localhost" /> <param name="RemotePort" value="8080" /> <param name="Encoding" value="utf-8" /> <layout type="log4net.Layout.XmlLayout"> <param name="Prefix" value="" /> </layout> <param name="threshold" value="DEBUG" /> </appender> <appender name="UdpLog4JAppender" type="log4net.Appender.UdpAppender"> <param name="RemoteAddress" value="127.0.0.1" /> <param name="RemotePort" value="8080" /> <param name="Encoding" value="utf-8" /> <layout type="log4net.Layout.XmlLayoutSchemaLog4j, log4net" /> <param name="threshold" value="DEBUG" /> </appender> <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> <to value="$Email" /> <from value="PoshLogger@$Domain" /> <subject value="PowerShell Logger Message" /> <smtpHost value="$PSEmailServer" /> <bufferSize value="512" /> <lossy value="true" /> <evaluator type="log4net.Core.LevelEvaluator"> <threshold value="WARN"/> </evaluator> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline$MessagePattern%newline%newline" /> </layout> </appender> <root> <level value="DEBUG" /> </root> <logger name="$LoggerName"> <level value="$LogLevel" /> $AppenderRefs </logger> </log4net> "@ [log4net.Config.XmlConfigurator]::Configure( $config.log4net ) } } function Set-Logger { param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [log4net.Core.LogImpl]$Logger ) $script:Logger = $Logger } function Close-Logger { param( [Parameter(Mandatory=$false, ValueFromPipeline=$true)] [log4net.Core.LogImpl]$Logger ) PROCESS { if($Logger) { $Logger.Logger.CloseNestedAppenders() $Logger.Logger.RemoveAllAppenders() } else { [log4net.LogManager]::Shutdown() } } } function Push-LogContext { param( [Parameter(Mandatory=$true)] [string]$Name ) [log4net.NDC]::Push($Name) } function Pop-LogContext { [log4net.NDC]::Pop() } function Write-DebugLog { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message} , [Parameter(Mandatory=$false, Position=99)] ${Logger}) begin { try { if($PSBoundParameters.ContainsKey("Logger")) { if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" } $null = $PSBoundParameters.Remove("Logger") } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $script:logger.debug($Message) #Write-Debug $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Debug .ForwardHelpCategory Cmdlet #> } function Write-VerboseLog { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message} , [Parameter(Mandatory=$false, Position=99)] ${Logger}) begin { try { if($PSBoundParameters.ContainsKey("Logger")) { if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" } $null = $PSBoundParameters.Remove("Logger") } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $script:logger.info($Message) $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Verbose .ForwardHelpCategory Cmdlet #> } function Write-WarningLog { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Msg')] [AllowEmptyString()] [System.String] ${Message} , [Parameter(Mandatory=$false, Position=99)] ${Logger}) begin { try { if($PSBoundParameters.ContainsKey("Logger")) { if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" } $null = $PSBoundParameters.Remove("Logger") } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $script:logger.warn($Message) #Write-Warning $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Warning .ForwardHelpCategory Cmdlet #> } function Write-ErrorLog { [CmdletBinding(DefaultParameterSetName='NoException')] param( [Parameter(ParameterSetName='WithException', Mandatory=$true)] [System.Exception] ${Exception}, [Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Parameter(ParameterSetName='WithException')] [Alias('Msg')] [AllowNull()] [AllowEmptyString()] [System.String] ${Message}, [Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)] [System.Management.Automation.ErrorRecord] ${ErrorRecord}, [Parameter(ParameterSetName='NoException')] [Parameter(ParameterSetName='WithException')] [System.Management.Automation.ErrorCategory] ${Category}, [Parameter(ParameterSetName='WithException')] [Parameter(ParameterSetName='NoException')] [System.String] ${ErrorId}, [Parameter(ParameterSetName='NoException')] [Parameter(ParameterSetName='WithException')] [System.Object] ${TargetObject}, [System.String] ${RecommendedAction}, [Alias('Activity')] [System.String] ${CategoryActivity}, [Alias('Reason')] [System.String] ${CategoryReason}, [Alias('TargetName')] [System.String] ${CategoryTargetName}, [Alias('TargetType')] [System.String] ${CategoryTargetType} , [Parameter(Mandatory=$false, Position=99)] ${Logger}) begin { try { if($PSBoundParameters.ContainsKey("Logger")) { if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" } $null = $PSBoundParameters.Remove("Logger") } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $script:logger.error($Message,$Exception) #Write-Error $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Error .ForwardHelpCategory Cmdlet #> } function Write-HostLog { [CmdletBinding()] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)] [System.Object] ${Object}, [Switch] ${NoNewline}, [System.Object] ${Separator} = $OFS, [System.ConsoleColor] ${ForegroundColor}, [System.ConsoleColor] ${BackgroundColor} , [Parameter(Mandatory=$false, Position=99)] ${Logger}) begin { try { if($PSBoundParameters.ContainsKey("Logger")) { if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" } $null = $PSBoundParameters.Remove("Logger") } $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $script:logger.info(($Object -join $Separator)) #Write-Verbose $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Write-Host .ForwardHelpCategory Cmdlet #> } Set-Alias Write-Debug Write-DebugLog Set-Alias Write-Verbose Write-VerboseLog Set-Alias Write-Warning Write-WarningLog Set-Alias Write-Error Write-ErrorLog #Set-Alias Write-Host Write-HostLog Export-ModuleMember -Function * -Alias * $script:Logger = Get-Logger "PowerShellLogger" -RollingFile -LogFolder (Split-Path $Profile.CurrentUserAllHosts) ## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
PowerShellCorpus/PoshCode/d25bbfc1-3d3f-42bb-a09e-67e69e89a865.ps1
d25bbfc1-3d3f-42bb-a09e-67e69e89a865.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/VMware Lab Manager 4.x.ps1
VMware Lab Manager 4.x.ps1
function Ignore-SslErrors { # Create a compilation environment $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider $Compiler=$Provider.CreateCompiler() $Params=New-Object System.CodeDom.Compiler.CompilerParameters $Params.GenerateExecutable=$False $Params.GenerateInMemory=$True $Params.IncludeDebugInformation=$False $Params.ReferencedAssemblies.Add("System.DLL") > $null $TASource=@' namespace Local.ToolkitExtensions.Net.CertificatePolicy { public class TrustAll : System.Net.ICertificatePolicy { public TrustAll() { } public bool CheckValidationResult(System.Net.ServicePoint sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem) { return true; } } } '@ $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource) $TAAssembly=$TAResults.CompiledAssembly ## We now create an instance of the TrustAll and attach it to the ServicePointManager $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll") [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll } function New-ObjectFromProxy { param($proxy, $proxyAttributeName, $typeName) # Locate the assembly for $proxy $attribute = $proxy | gm | where { $_.Name -eq $proxyAttributeName } $str = "`$assembly = [" + $attribute.TypeName + "].assembly" invoke-expression $str # Instantiate an AuthenticationHeaderValue object. $type = $assembly.getTypes() | where { $_.Name -eq $typeName } return $assembly.CreateInstance($type) } function Connect-LabManager { param ( [string] $server, $credential, [string] $organizationname = "Default", [string] $workspacename = "Main" ) # Log in to Lab Manager's web service. $server = "https://" + $server + "/" $endpoint = $server + "LabManager/SOAP/LabManager.asmx" $proxy = new-webserviceproxy -uri $endpoint -cred $credential # Before continuing we need to add an Authentication Header to $proxy. $authHeader = New-ObjectFromProxy -proxy $proxy -proxyAttributeName "AuthenticationHeaderValue" -typeName "AuthenticationHeader" $authHeader.username = $credential.GetNetworkCredential().UserName $authHeader.password = $credential.GetNetworkCredential().Password $authHeader.organizationname = $organizationname $authHeader.workspacename = $workspacename $proxy.AuthenticationHeaderValue = $authHeader return $proxy } # Examples: # Run this command if your Lab Manager's certificate is untrusted but you want to connect. Ignore-SslErrors # Connect to Lab Manager. $labManager = Connect-LabManager -server "demo.eng.vmware.com" -credential (get-credential) # Find out what operations there are. $labManager | gm | where { $_.MemberType -eq "Method" } # See http://www.vmware.com/pdf/lm30_soap_api_guide.pdf for help on arguments. # List all library configurations. $labManager.ListConfigurations(1) # Find all machines deployed from any library configuration. $labManager.ListConfigurations(1) | foreach { write-host ("For Configuration " + $_.id + ":"); $labManager.ListMachines($_.id) }
PowerShellCorpus/PoshCode/Sync-Time_3.ps1
Sync-Time_3.ps1
function sync-time( [string] $server = "sync-time 0.pool.ntp.org, 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/Save-CurrentFile (ISE).ps1
Save-CurrentFile (ISE).ps1
function Save-CurrentFile ($path) { $psISE.CurrentFile.SaveAs($path) $psISE.CurrentFile.Save([Text.Encoding]::default) } # Save-CurrentFile '.\\Save-CurrentFile.ps1'
PowerShellCorpus/PoshCode/exclude properties_1.ps1
exclude properties_1.ps1
$server = "dcserver1.mafoberg.net" $session = new-pssession -computer $server -cred $creds icm -Session $session -ScriptBlock { import-module activedirectory (get-ADUser -filter "*" -properties GivenName, SurName, EmailAddress | select -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName ) } | select -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName Remove-PSSession $session #####output#### PSComputerName : dcserver1.mafoberg.net RunspaceId : ebb3ebe0-7ad6-4a0e-ab33-63b29fb9890f PSShowComputerName : True DistinguishedName : CN=taland,OU=swteknikere,OU=Teknikere,DC=mafoberg,DC=net EmailAddress : Enabled : True GivenName : Talbe Name : taland ObjectClass : user ObjectGUID : 7a675f74-db4c-4015-9a50-12e2624daf5c SamAccountName : taland SID : S-1-5-21-146981098-1029485922-1443047703-1180 Surname : Andar UserPrincipalName :
PowerShellCorpus/PoshCode/PoshCode ISE Addon.ps1
PoshCode ISE Addon.ps1
if (!(Get-Module WPK)) {Import-Module -global WPK} if (!(Get-Module PoshCode)) {Import-Module -global PoshCode} Function Get-PoshCodePreferences { if (Get-Item $global:xmlPath -ErrorAction SilentlyContinue) { try { $pcPreferences = Import-Clixml -Path $global:xmlPath $global:PCSyntax = $pcPreferences.Syntax $global:PCExpiry = $pcPreferences.Expiry $global:PCAuthor = $pcPreferences.Author } catch { Write-Host "Import-CliXml failed with following error" return } } else { $global:PCSyntax = "posh" $global:PCExpiry = "forever" $global:PCAuthor = "$($env:USERNAME)" } } Function Save-PoshCodePreferences { param($syntax, $expiry, $author) $pcPreferences = New-Object PSObject $pcPreferences | Add-Member -MemberType NoteProperty -Name "Syntax" -Value $syntax $pcPreferences | Add-Member -MemberType NoteProperty -Name "Expiry" -Value $expiry $pcPreferences | Add-Member -MemberType NoteProperty -Name "Author" -Value $author try { Export-Clixml -InputObject $pcPreferences -Path $global:xmlPath -Force } catch { Write-Host "Export-Clixml; failed with the following error" Write-Host $error[0].InnerException return } [system.Windows.Forms.MessageBox]::show('Your preferences have been saved') } function Show-PoshCodeGUI { Get-PoshCodePreferences New-Window -Title "PoshCode addon" -WindowStartupLocation CenterScreen -Width 836 -Height 477 -Show -ResizeMode NoResize -On_Loaded { $txtPasteCode = $Window | Get-ChildControl txtPasteCode $cmbSyntax = $Window | Get-ChildControl cmbSyntax $cmbExpiry = $Window | Get-ChildControl cmbExpiry $txtTitle = $window | Get-ChildControl txtTitle $txtDescription = $window | Get-ChildControl txtDescription $txtAuthor = $window | Get-ChildControl txtAuthor $btnSavePref = $window | Get-ChildControl btnSavePref $btnSubmit = $window | Get-ChildControl btnSubmit } { New-Grid { New-TextBox -Name txtPasteCode -Margin "12,12,0,0" -Height 258 -Width 800 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:SelectedText ` -IsReadOnly -VerticalScrollBarVisibility "Auto" -HorizontalScrollBarVisibility "Auto" New-Label -Name lblLang -Margin "12,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Scripting Language" -FontWeight "Bold" New-ComboBox -Name cmbSyntax -Margin "175,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:cmbSyntaxOptions -SelectedIndex $global:cmbSyntaxOptions.IndexOf($global:PCSyntax) New-Label -Name lblExpiry -Margin "12,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Expires in" -FontWeight "Bold" New-ComboBox -Name cmbExpiry -Margin "175,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:Expiry -SelectedIndex $global:Expiry.IndexOf($global:PCExpiry) New-Label -Name lblTitle -Margin "450,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Title" -FontWeight "Bold" New-TextBox -Name txtTitle -Margin "570,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Label -Name lblAuthor -Margin "450,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Author" -FontWeight "Bold" New-TextBox -Name txtAuthor -Margin "570,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:PCAuthor New-Label -Name lblDescription -Margin "12,361,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Description" -FontWeight "Bold" New-TextBox -Name txtDescription -Margin "175,361,0,0" -Height 35 -Width 590 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Button -Name btnSavePref -Margin "280,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Save Preferences" -On_Click { Save-PasteBinPreferences -Syntax $cmbSyntax.SelectedItem -Expiry $cmbExpiry.SelectedItem -Author $txtAuthor.Text } New-Button -Name btnSubmit -Margin "410,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Submit to PoshCode" -On_Click { $returnUri = $global:SelectedText | New-PoshCode -title $txtTitle.Text ` -description $txtDescription.Text -Author $txtAuthor.Text ` -keep $cmbExpiry.SelectedItem -Language $cmbSyntax.SelectedItem if ($returnUri) { [System.Diagnostics.Process]::Start($returnUri) $window.Close() } else { [system.Windows.Forms.MessageBox]::show('Error occured while uploading to PoshCode') $window.Close() } Write-Host $cmbExpiry.SelectedItem } } } } [System.Collections.ArrayList]$global:cmbSyntaxOptions = "posh","text" [System.Collections.ArrayList]$global:Expiry = "forever","day","month" $global:xmlPath = $("$env:APPDATA\\PoshCodePrefs.xml") if ($host.Name –eq 'Windows PowerShell ISE Host') { $scriptBlock = { if (($psISE.CurrentFile.Editor.SelectedText -ne "")) { $global:SelectedText = $psISE.CurrentFile.Editor.SelectedText } else { if ($psISE.CurrentFile.IsUntitled -or !($psISE.CurrentFile.IsSaved)) { [system.Windows.Forms.MessageBox]::show('You must first save the script or select the contents to upload') return } else { $global:SelectedText = $psISE.CurrentFile.Editor.Text } } Show-PoshCodeGUI } $submenus = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus $menuExists = $false foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to Posh_Code") { $menuExists = $true } } if (!$menuExists) { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Send To Posh_Code",$ScriptBlock,"CTRL+ALT+N") } $ExecutionContext.SessionState.Module.OnRemove = { foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to PPosh_Code") { $submenus.Remove($menuItem) return } } } } else { Write-Host "This module is meant for either ISE or PGSE" return } Export-ModuleMember -Function * -Variable *
PowerShellCorpus/PoshCode/JSON 1.1.ps1
JSON 1.1.ps1
#requires -version 2.0 # Version History: # v 0.5 - First Public version # v 1.0 - Made ConvertFrom-Json work with arbitrary JSON # - switched to xsl style sheets for ConvertTo-JSON # v 1.1 - Changed ConvertFrom-Json to handle single item results # There is no help (yet) because I'm still changing and renaming everything every time I mess with this code # Full RoundTrip capability: # # > ls | ConvertTo-Json | ConvertFrom-Json # > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json # # You may frequently want to use the DEPTH or NoTypeInformation parameters: # # > ConvertTo-Json -Depth 2 -NoTypeInformation # # But then you have to specify the type when you reimport (and you can't do that for deep objects). # This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject). # For Example: # # > PS | Select PM, WS, CPU, ID, ProcessName | # >> ConvertTo-json -NoType | # >> ConvertFrom-json -Type System.Diagnostics.Process Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization $utf8 = [System.Text.Encoding]::UTF8 function Write-String { PARAM( [Parameter()]$stream, [Parameter(ValueFromPipeline=$true)]$string ) PROCESS { $bytes = $utf8.GetBytes($string) $stream.Write( $bytes, 0, $bytes.Length ) } } function Convert-JsonToXml { PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json) BEGIN { $mStream = New-Object System.IO.MemoryStream } PROCESS { $json | Write-String -stream $mStream } END { $mStream.Position = 0 $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max) try { $xml = New-Object Xml.XmlDocument $xml.Load($jsonReader) $xml } finally { $jsonReader.Close() $mStream.Dispose() } } } function Convert-XmlToJson { PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml) PROCESS { $mStream = New-Object System.IO.MemoryStream $jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream) try { $xml.Save($jsonWriter) $bytes = $mStream.ToArray() [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length) } finally { $jsonWriter.Close() $mStream.Dispose() } } } ## Rather than rewriting ConvertTo-Xml ... Function ConvertTo-Json { [CmdletBinding()] Param( [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject , [Parameter(Mandatory=$false)][Int]$Depth=1 , [Switch]$NoTypeInformation ) END { ## You must output ALL the input at once ## ConvertTo-Xml outputs differently if you just have one, so your results would be different $input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson } } Function Convert-CliXmlToJson { PARAM( [Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml ) BEGIN { $xmlToJsonXsl = @' <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- CliXmlToJson.xsl Copyright (c) 2006,2008 Doeke Zanstra Copyright (c) 2009 Joel Bennett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/> <xsl:strip-space elements="*"/> <!--contant--> <xsl:variable name="d">0123456789</xsl:variable> <!-- ignore document text --> <xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/> <!-- string --> <xsl:template match="text()"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="."/> </xsl:call-template> </xsl:template> <!-- Main template for escaping strings; used by above template and for object-properties Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string --> <xsl:template name="escape-string"> <xsl:param name="s"/> <xsl:text>"</xsl:text> <xsl:call-template name="escape-bs-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> <xsl:text>"</xsl:text> </xsl:template> <!-- Escape the backslash (\\) before everything else. --> <xsl:template name="escape-bs-string"> <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,'\\')"> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/> </xsl:call-template> <xsl:call-template name="escape-bs-string"> <xsl:with-param name="s" select="substring-after($s,'\\')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Escape the double quote ("). --> <xsl:template name="escape-quot-string"> <xsl:param name="s"/> <xsl:choose> <xsl:when test="contains($s,'&quot;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&quot;'),'\\&quot;')"/> </xsl:call-template> <xsl:call-template name="escape-quot-string"> <xsl:with-param name="s" select="substring-after($s,'&quot;')"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="$s"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash or double quote here, because they don't replace characters (&#x0; becomes \\t), but they prefix characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be processed first. This function can't do that. --> <xsl:template name="encode-string"> <xsl:param name="s"/> <xsl:choose> <!-- tab --> <xsl:when test="contains($s,'&#x9;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#x9;'),'\\t',substring-after($s,'&#x9;'))"/> </xsl:call-template> </xsl:when> <!-- line feed --> <xsl:when test="contains($s,'&#xA;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#xA;'),'\\n',substring-after($s,'&#xA;'))"/> </xsl:call-template> </xsl:when> <!-- carriage return --> <xsl:when test="contains($s,'&#xD;')"> <xsl:call-template name="encode-string"> <xsl:with-param name="s" select="concat(substring-before($s,'&#xD;'),'\\r',substring-after($s,'&#xD;'))"/> </xsl:call-template> </xsl:when> <xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise> </xsl:choose> </xsl:template> <!-- number (no support for javascript mantise) --> <xsl:template match="text()[not(string(number())='NaN' or (starts-with(.,'0' ) and . != '0'))]"> <xsl:value-of select="."/> </xsl:template> <!-- boolean, case-insensitive --> <xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template> <xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template> <!-- root object(s) --> <xsl:template match="*" name="base"> <xsl:if test="not(preceding-sibling::*)"> <xsl:choose> <xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when> <xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <!-- check type of node --> <xsl:choose> <!-- null nodes --> <xsl:when test="count(child::node())=0">null</xsl:when> <!-- other nodes --> <xsl:otherwise> <xsl:apply-templates select="child::node()"/> </xsl:otherwise> </xsl:choose> <!-- end of type check --> <xsl:if test="following-sibling::*">,</xsl:if> <xsl:if test="not(following-sibling::*)"> <xsl:choose> <xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when> <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- properties of objects --> <xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)&gt;1]"> <xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/> <xsl:if test="not(preceding-sibling::*)"> <xsl:choose> <xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when> <xsl:otherwise> <xsl:text>{</xsl:text> <xsl:if test="../@Type"> <xsl:text>"__type":</xsl:text> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="../@Type"/> </xsl:call-template> <xsl:text>,</xsl:text> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:if> <xsl:choose> <xsl:when test="not(child::node())"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="@Name"/> </xsl:call-template> <xsl:text>:null</xsl:text> </xsl:when> <xsl:when test="$inArray"> <xsl:apply-templates select="child::node()"/> </xsl:when> <!-- <xsl:when test="not(@Name) and not(@Type)"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="local-name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:when> --> <xsl:when test="not(@Name)"> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="local-name()"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:when> <xsl:otherwise> <xsl:call-template name="escape-string"> <xsl:with-param name="s" select="@Name"/> </xsl:call-template> <xsl:text>:</xsl:text> <xsl:apply-templates select="child::node()"/> </xsl:otherwise> </xsl:choose> <xsl:if test="following-sibling::*">,</xsl:if> <xsl:if test="not(following-sibling::*)"> <xsl:choose> <xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when> <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> <!-- convert root element to an anonymous container --> <xsl:template match="/"> <xsl:apply-templates select="node()"/> </xsl:template> </xsl:stylesheet> '@ } PROCESS { if(Get-Member -InputObject $xml -Name root) { Write-Verbose "Ripping to Objects" $xml = $xml.root.Objects } else { Write-Verbose "Was already Objects" } Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl } } Function ConvertFrom-Xml { [CmdletBinding(DefaultParameterSetName="AutoType")] PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)] [Xml.XmlNode] $xml , [Parameter(Mandatory=$true,ParameterSetName="ManualType")] [Type]$Type , [Switch]$ForceType ) PROCESS{ if(Get-Member -InputObject $xml -Name root) { return $xml.root.Objects | } elseif(Get-Member -InputObject $xml -Name Objects) { return $xml.Objects | } $propbag = @{} foreach($name in Get-Member -InputObject $xml -MemberType Property | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) { Write-Verbose "$Name Type: $($xml."$Name".type)" switch( $xml."$Name".type ) { "object" { $propbag."$Name" = ConvertFrom-Xml -Xml $xml."$Name" break } "string" { $propbag."$Name" = $xml."$Name".get_InnerText() $MightBeADate = $xml."$Name".get_InnerText() -as [DateTime] ## Strings that are actually dates (*grumble* JSON is crap) if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) { $propbag."$Name" = $MightBeADate } break } "number" { $number = $xml."$Name".get_InnerText() if($number -eq ($number -as [int])) { $propbag."$Name" = $number -as [int] } elseif($number -eq ($number -as [double])) { $propbag."$Name" = $number -as [double] } else { $propbag."$Name" = $number -as [decimal] } break } "boolean" { $propbag."$Name" = [bool]::parse($xml."$Name".get_InnerText()) } "null" { $propbag."$Name" = $null } default { $propbag."$Name" = $xml."$Name" break } } } if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type } if($ForceType -and $Type) { try { $output = New-Object $Type -Property $propbag } catch { $output = New-Object PSObject -Property $propbag $output.PsTypeNames.Insert(0, $xml.__type) } } else { $output = New-Object PSObject -Property $propbag if($Type) { $output.PsTypeNames.Insert(0, $Type) } } Write-Output $output } } Function ConvertFrom-Json { [CmdletBinding(DefaultParameterSetName="AutoType")] PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)][string]$InputObject , [Parameter(Mandatory=$true,ParameterSetName="ManualType")][Type]$Type , [Switch]$ForceType ) PROCESS { $null = $PSBoundParameters.Remove("InputObject") $xml = (Convert-JsonToXml $InputObject).Root if($xml.Objects) { $xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters }elseif($xml.Item) { $xml.Item | ConvertFrom-Xml @PSBoundParameters } } } ######### ### The JSON library is dependent on Convert-Xml from my Xml script module function Convert-Node { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter Xsl # Specifies an Xml StyleSheet to transform with... [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -ErrorAction 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } New-Alias fromjson ConvertFrom-Json New-Alias tojson ConvertTo-Json #New-Alias ipjs Import-Json #New-Alias epjs Export-Json #Import-Json, Export-Json, Export-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *
PowerShellCorpus/PoshCode/CapsLock Notifier.ps1
CapsLock Notifier.ps1
<# .NOTES Name : CapsLockNotifier.ps1 Author : Bryan Jaudon <bryan.jaudon@gmail.com> Version : 1.0 Date : 10/25/2012 .Description Adds a notification icon to show current CapsLock status. Double clicking or by using the context menu, allows for toggling of the CapsLock status. #> #requires -version 2 param([switch]$Debug) function CheckCapsLock { $CapsLockStatus=[console]::CapsLock Write-Debug "CheckCapsLock - Previous Reading: $Script:PreviousCapsLock - Current Reading: $CapsLockStatus" if ($PreviousCapsLock -ne $CapsLockStatus) { if ($CapsLockStatus -eq $True) { Write-Debug "CheckCapsLock - Update CapsLock NotificationIcon to ON" $NotifyIcon.Icon = $IconOn $NotifyIcon.BalloonTipTitle = "CapsLock is On" $NotifyIcon.Text="CapsLock Status - On" $NotifyIcon.BalloonTipText = "CapsLock status has changed to On." } else { Write-Debug "CheckCapsLock - Update CapsLock NotificationIcon to OFF" $NotifyIcon.Icon = $IconOff $NotifyIcon.BalloonTipTitle = "CapsLock is Off" $NotifyIcon.Text="CapsLock Status - Off" $NotifyIcon.BalloonTipText = "CapsLock status has changed to Off." } Write-Debug "CheckCapsLock - Show NotificationIcon BaloonTip" $NotifyIcon.BalloonTipIcon = "Info" $NotifyIcon.Visible = $True $NotifyIcon.ShowBalloonTip(50000) } $Script:PreviousCapsLock=$CapsLockStatus } function ToggleCapsLock { $wshObject=New-Object -ComObject "WScript.Shell" $wshObject.SendKeys('{CapsLock}') Write-Debug "ToggleCapsLock - wshObject Sendkeys(CapsLock)" } Function Hide-PowerShell { $null = $showWindowAsync::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0) } [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") [void][reflection.assembly]::loadwithpartialname("System.Drawing") [string]$IconOnb64=@" iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAK T2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AU kSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXX Pues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgAB eNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAt AGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3 AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dX Lh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+ 5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk 5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd 0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA 4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzA BhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/ph CJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5 h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+ Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhM WE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQ AkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+Io UspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdp r+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZ D5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61Mb U2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY /R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllir SKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79u p+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6Vh lWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1 mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lO k06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7Ry FDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3I veRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+B Z7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/ 0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5p DoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5q PNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIs OpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5 hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQ rAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9 rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1d T1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aX Dm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7 vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3S PVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKa RptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO 32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21 e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfV P1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i /suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8 IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADq YAAAOpgAABdvkl/FRgAABCBJREFUeNrsl89rFEkUxz+vqnt+7ExYnawYBRcNKHqIaE4bFk97EIx7 cO/+ETl79C8QFpa9rzdZTTAHkcV1EQkEb3oRDSJRJzIzy5j09Mx0V709jN07GScxHhYP64Oioav7 1bff9/u+VS2qyucMw2eOLwA+O4Cg0+l8++LFi186nc73quqBXVWZiVZEUFVEZMf57Lq2tkYQBExO TqKqAlCtVn8/ceLEgjx58uS2c26+UCgwYSYINUQzDDJIYERABCOG2HRJTYJ6BVW8Kvp+jIb3Hucc 3W6Xx48fc/z4cYrFIqpKr9ejXC7/Gmxubn5XrVYpmAI3qzdZD9cJNPiXI2MQEUQEZxzn++c5mZ6k 67t478F7/NDYxq8xqCphGGKtZWtrKwdQLBaJoujHwDknghBowG9f/8bKVyu7cnb478PM9GeINc6/ fCcvyShyzu2UrmSyMv1Xoao458aCFBEC7z1ePYpi1Q6UOUTBcKSSYj6xcXYDAAwAOOfoS5+rG1eJ TLRtEWttrgMMHNEjxBLnvfIxK98TAFXF45l205SDMkmSkCQJIpIDyIa3HrVKaEN6vW7ejsOAgZxW VSVbYxw445zDOYcRQ5RELP+xzLP1Z4QTIbZikbJgKxYtKkE1wBYsnU6Hly9fYoylVCpRLpcJCyET ExO0223a7TbFYjFfJE3TsZ6xrQKlUonr16+TJAnv3r3j6dOnbG1tUalUaDQanD17lpWVFS5dukSn 02FpaYkrV66wuLjIq1evmJ2dZXV1FYBms8nFixc5duwYcRzvWAERIe8C7z2tVou5uTkOHjzI3bt3 WV5e5sGDB7RaLW7cuMGdO3d4+PAhpVKJKIp4vvace/fu0Ww2uXbtGmEYEscxt27dot1uY63NzWhH CoZN5MKFCywtLbGxscGpU6c4d+5cXr75+Xnm5uY4dOgQ+/fvp1AocP/P+5w5c4ZSqcTly5dpNBpM T0+zsLBAHMf5ouMqkFv24uJic9++fbWpqSnCMByU5b2DWWt59OgRMzMzVCqV3N3SNKVQKNDv93PB ZWoffsY5x+bmJm/fvuX169ccPXqUWq2WA4rjuBVkXy8iJEnyQZlmZ2dzPzfGYK1FRHJu/R6seCcN AIMuGH1xOPr9/vaXP/EIN+wD47rAZAj3HPLpVrybBj5agQ8zfuTAMNJmQC7kcQAC730upoyz0STD AzEYEXTkfj4/ooFer8ewzobnBvuOqo+iiPX1daampsbylJVxYMeDRMPCy+aHKykiNBoN6vV6vmVn uYe28F4wOTn5V71e/+nNmzc0Go0PAIwDtNMxbTSyrkrTlCAIKBaLOch+v0+lUrkt9Xr9m9XV1Z9b rdYPqmrZO8V70oC1liiKOHDggNRqtW6aph3AVqvV+6dPn16QL39GXwD87wH8MwBTzNLUBSl3TAAA AABJRU5ErkJggg== "@ $IconOnstream=[System.IO.MemoryStream][System.Convert]::FromBase64String($IconOnb64) $IconOnbmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($IconOnstream) $IconOnhandle=$IconOnbmp.GetHicon() $IconOn=[System.Drawing.Icon]::FromHandle($IconOnhandle) [string]$IconOffb64=@" iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAK T2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AU kSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXX Pues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgAB eNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAt AGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3 AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dX Lh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+ 5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk 5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd 0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA 4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzA BhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/ph CJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5 h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+ Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhM WE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQ AkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+Io UspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdp r+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZ D5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61Mb U2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY /R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllir SKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79u p+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6Vh lWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1 mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lO k06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7Ry FDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3I veRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+B Z7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/ 0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5p DoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5q PNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIs OpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5 hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQ rAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9 rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1d T1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aX Dm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7 vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3S PVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKa RptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO 32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21 e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfV P1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i /suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8 IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADq YAAAOpgAABdvkl/FRgAABBlJREFUeNrsl09rFEkYxn9V1f9mZ+KayYoRcdGAooeI5rRh8bQXMe7B vfshcvbqFxAWlr3rTSUJ5iCyuFlEIsGbXkSDSNRRZmYZk+6e6e6q2sOkm844EyPs4mF9oZima+qt p5/3eZ+uFtZavmRIvnB8BfDFAThRFH3/8uXL36Io+tFaa4BdVZmLVgiBtRYhxMj5/Hd9fR3HcZiY mMBaKwBqtdrtEydOzIunT5/e0VrPeZ6H3LcP6ziQJ9lOIKTsX0uJjGNklmGsBWsx1mK3x2AYY9Ba 0+12efLkCcePH8f3fay19Ho9KpXK787m5uYPtVoN6XnUbt3C3djog8hrJGUfhBBIrUnOnyc7eRLT 7WKMAWMwpbGjvlJircV1XZRSbG1tFQB83ycMw58drbVACKxSfHv9Ot88erRrzf4+fJhkehobx8WT j/KSvERa61HpApnT9F+FtRat9VCQQggcYww2p06p/qJSCXYsyDKQ8l8DAPQBaK0RSULj6lVkGO7Y RClV6EAC9sgRRBQXrfIpK98TAGstGIOemsKpVEjTlDRNEUIUAPKhjEFhUa5Lr9ct2rEMGCjKaq2l 2GMIOKm17jMgJWkY8sfyMhvPnzPmulSVoiIEVaXwraXmOHhKEUURr169QkpFEARUKhVcz2VsbIxO p0On08H3/WKTLMuGesYOBoIg4MaNG6RpyocPH3j27BlbW1tUq1WazSZnz55ldXWVS5cuEUURS0tL XLlyhcXFRV6/fs3MzAxra2sAtFotLl68yLFjx4jjeCQDQgiKLjDG0G63mZ2d5eDBg9y7d4/l5WUe PHhAu93m5s2b3L17l4cPHxIEAWEY8mL9Bffv36fVanHt2jVc1yWOYxYWFuh0OiilCjMaWYKyiVy4 cIGlpSXevXvHqVOnOHfuXEHf3Nwcs7OzHDp0iPHxcTzPY+XPFc6cOUMQBFy+fJlms8nU1BTz8/PE 2z6RO+IggMKyFxcXW/v3769PTk7ium6flm0HU0rx+PFjpqenqVarhbtlWYbneSRJUgguV3v5P1pr Njc3ef/+PW/evOHo0aPU6/UCUBzHbSd/eiEEaZp+RNPMzEzh51JKlFIIIYramj1Y8SgNAP0uGFxY jiRJdi7+zCNc2QeGdYHMEe45xOdb8W4a+CQDH2f8xIFhoM2AQsjDADjGmEJMec0Gk5QHQiKFwA7c L+YHNNDr9SjrrDwH4FhrTRiGbGxsMDk5ObROOY19O+4nKgsvny8zKYSg2WzSaDSKV3aeu/QK7zkT ExN/NRqNX96+fUuz2fwIwDBAo45pg5F3VZZlOI6D7/sFyCRJqFard0Sj0fhubW3t13a7/ZO1VrH3 Eu9JA0opwjDkwIEDol6vd7MsiwBVq9VWTp8+PS++fhl9BfC/B/DPAHixztivq7qsAAAAAElFTkSu QmCC "@ $IconOffstream=[System.IO.MemoryStream][System.Convert]::FromBase64String($IconOffb64) $IconOffbmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($IconOffstream) $IconOffhandle=$IconOffbmp.GetHicon() $IconOff=[System.Drawing.Icon]::FromHandle($IconOffhandle) $form1 = New-Object System.Windows.Forms.form $NotifyIcon= New-Object System.Windows.Forms.NotifyIcon $ContextMenu = New-Object System.Windows.Forms.ContextMenu $MenuItemToggle = New-Object System.Windows.Forms.MenuItem $MenuItemExit = New-Object System.Windows.Forms.MenuItem $Timer = New-Object System.Windows.Forms.Timer $form1.ShowInTaskbar = $false $form1.WindowState = "minimized" $NotifyIcon.ContextMenu = $ContextMenu $NotifyIcon.contextMenu.MenuItems.AddRange($MenuItemToggle) $NotifyIcon.contextMenu.MenuItems.AddRange($MenuItemExit) $NotifyIcon.Visible = $True $NotifyIcon.add_DoubleClick({ Write-Debug "NotifyIcon - DoubleClickEvent: ToggleCapsLock"; ToggleCapsLock }) $Timer.Interval = 1000 $Timer.add_Tick({ CheckCapsLock }) $Timer.start() $MenuItemToggle.Index = 0 $MenuItemToggle.Text = "&Toggle CapsLock" $MenuItemToggle.add_Click({ Write-Debug "NotifyIcon - MenuItemEvent: ToggleCapsLock"; ToggleCapsLock }) $MenuItemExit.Index = 1 $MenuItemExit.Text = "E&xit" $MenuItemExit.add_Click({ Write-Debug "NotifyIcon - ExitEvent"; $Timer.stop(); $NotifyIcon.Visible = $False; $form1.close() }) $script:showWindowAsync = Add-Type -MemberDefinition @" [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); "@ -name Win32ShowWindowAsync -namespace Win32Functions -PassThru if ($host.name -ne "Windows PowerShell ISE Host") { if ($Debug -ne $True) { Hide-PowerShell } else { $DebugPreference="Continue" } } $Script:PreviousCapsLock=[console]::CapsLock if ($Script:PreviousCapsLock -eq $True) { Write-Debug "Initilization - CapsLock On" $NotifyIcon.Icon = $IconOn $NotifyIcon.Text="CapsLock Status - On" } else { Write-Debug "Initilization - CapsLock Off" $NotifyIcon.Icon = $IconOff $NotifyIcon.Text="CapsLock Status - Off" } [void][System.Windows.Forms.Application]::Run($form1)
PowerShellCorpus/PoshCode/Get-UIInput.ps1
Get-UIInput.ps1
function Get-UIInput { #.Synopsis # Prompt the user for input with a pretty dialog #.Parameter PromptText # The text to prompt the user for (an array of one or more strings) #.Example # Get-UIInput "First Name:", "Last Name:", "Age:" Param([string[]]$PromptText = "Please enter your name:") Show-UI -Parameters @(,$PromptText) { Param([string[]]$PromptText) $global:UIInputWindow = $this function global:Get-UIInputOutput { $stack = Select-UIElement $UIInputWindow "Wrapper" $Output = @{} ## Loop through the stack of prompts and get the user's input $inputs = $stack.Children while($inputs.Count) { $label, $value, $inputs = $inputs $Output.($label.Content) = $value.Text } Write-UIOutput $Output } Border -BorderThickness 4 -BorderBrush "#BE8" -Background "#EFC" { Grid -Margin 10 -Name "Wrapper" -Columns Auto,150 -Rows (@("Auto") * ($PromptText.Count + 1)) { ## Loop through the prompts and create input boxes for them for($i=0;$i -lt $PromptText.Count;$i++) { Label -Grid-Row $i $PromptText[$i] TextBox -Grid-Row $i -Grid-Column 1 -Width 150 -On_KeyDown { if($_.Key -eq "Return") { Get-UIInputOutput $UIInputWindow.Close() } } } Button "Ok" -Grid-Row $PromptText.Count -Grid-Column 1 -Width 60 -On_Click { Get-UIInputOutput $UIInputWindow.Close() } } } } -On_Load { (Select-UIElement $this "Wrapper").Children[1].Focus() }` -WindowStyle None -AllowsTransparency ` -On_PreviewMouseLeftButtonDown { if($_.Source -notmatch ".*\\.(TextBox|Button)") { $ShowUI.ActiveWindow.DragMove() } } }
PowerShellCorpus/PoshCode/Get-Parameter_4.ps1
Get-Parameter_4.ps1
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon ) { foreach ($paramset in (Get-Command $Cmdlet).ParameterSets){ $Output = @() foreach ($param in $paramset.Parameters) { if ( !$ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob") { continue } } $process = "" | Select-Object Name, ParameterSet, Aliases, Position, IsMandatory $process.Name = $param.Name if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases if ( $param.Position -lt 0 ) { $process.Position = $null } else { $process.Position = $param.Position } $process.IsMandatory = $param.IsMandatory $output += $process } Write-Output $Output #Write-Host "`n" } }
PowerShellCorpus/PoshCode/VMware Lab Manager _1.x.ps1
VMware Lab Manager _1.x.ps1
function Ignore-SslErrors { # Create a compilation environment $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider $Compiler=$Provider.CreateCompiler() $Params=New-Object System.CodeDom.Compiler.CompilerParameters $Params.GenerateExecutable=$False $Params.GenerateInMemory=$True $Params.IncludeDebugInformation=$False $Params.ReferencedAssemblies.Add("System.DLL") > $null $TASource=@' namespace Local.ToolkitExtensions.Net.CertificatePolicy { public class TrustAll : System.Net.ICertificatePolicy { public TrustAll() { } public bool CheckValidationResult(System.Net.ServicePoint sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem) { return true; } } } '@ $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource) $TAAssembly=$TAResults.CompiledAssembly ## We now create an instance of the TrustAll and attach it to the ServicePointManager $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll") [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll } function New-ObjectFromProxy { param($proxy, $proxyAttributeName, $typeName) # Locate the assembly for $proxy $attribute = $proxy | gm | where { $_.Name -eq $proxyAttributeName } $str = "`$assembly = [" + $attribute.TypeName + "].assembly" invoke-expression $str # Instantiate an AuthenticationHeaderValue object. $type = $assembly.getTypes() | where { $_.Name -eq $typeName } return $assembly.CreateInstance($type) } function Connect-LabManager { param ( [string] $server, $credential, [string] $organizationname = "Default", [string] $workspacename = "Main" ) # Log in to Lab Manager's web service. $server = "https://" + $server + "/" $endpoint = $server + "LabManager/SOAP/LabManager.asmx" $proxy = new-webserviceproxy -uri $endpoint -cred $credential # Before continuing we need to add an Authentication Header to $proxy. $authHeader = New-ObjectFromProxy -proxy $proxy -proxyAttributeName "AuthenticationHeaderValue" -typeName "AuthenticationHeader" $authHeader.username = $credential.GetNetworkCredential().UserName $authHeader.password = $credential.GetNetworkCredential().Password $authHeader.organizationname = $organizationname $authHeader.workspacename = $workspacename $proxy.AuthenticationHeaderValue = $authHeader return $proxy } function Get-LabManagerInternal { param ( [string] $server = $(throw "Parameter -Server [System.String] is required."), $credential = $(get-credential), [string] $organizationname = "Global", [string] $workspacename = "Main" ) $labManagerInternalUri = [System.Uri] "https://$server/LabManager/SOAP/LabManagerInternal.asmx" $proxy = New-WebServiceProxy -Uri $labManagerInternalUri -Credential $credential if ($proxy) { # Before continuing we need to add an Authentication Header to $proxy. $authHeader = New-ObjectFromProxy -proxy $proxy -proxyAttributeName "AuthenticationHeaderValue" -typeName "AuthenticationHeader" $authHeader.username = $credential.GetNetworkCredential().UserName $authHeader.password = $credential.GetNetworkCredential().Password $authHeader.organizationname = $organizationname $authHeader.workspacename = $workspacename $proxy.AuthenticationHeaderValue = $authHeader return $proxy } } # Examples: # Run this command if your Lab Manager's certificate is untrusted but you want to connect. Ignore-SslErrors # Connect to Lab Manager. $labManager = Connect-LabManager -server "demo.eng.vmware.com" -credential (get-credential) # Find out what operations there are. $labManager | gm | where { $_.MemberType -eq "Method" } # See http://www.vmware.com/pdf/lm30_soap_api_guide.pdf for help on arguments. # List all library configurations. $labManager.ListConfigurations(1) # Find all machines deployed from any library configuration. $labManager.ListConfigurations(1) | foreach { write-host ("For Configuration " + $_.id + ":"); $labManager.ListMachines($_.id) } # Internal API Examples: # Connect to Lab Manager Internal API. $labmanagerinternal = Get-LabManagerInternal -server "demo.eng.vmware.com" -organizationname "Default" -workspacename "Main" -credential (get-credential) # Gets all Media images in Lab Manager. $labmanagerinternal.GetAllMedia()
PowerShellCorpus/PoshCode/Colorize Subversion SVN_1.ps1
Colorize Subversion SVN_1.ps1
## SVN STAT colorizer - http://www.overset.com/2008/11/18/colorized-subversion-svn-stat-powershell-function/ function ss () { $c = @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } foreach ( $svno in svn stat ) { @@ $color = $c[$svno.SubString(0,1).ToUpper()] @@ if ( $color ) { @@ write-host $svno -Fore $color } else { write-host $svno } } }
PowerShellCorpus/PoshCode/_4.168.1.1.ps1
_4.168.1.1.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/chkhash_18.ps1
chkhash_18.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/Get-User.ps1
Get-User.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/Test if file is writable_1.ps1
Test if file is writable_1.ps1
function Test-IsWritable(){ <# .Synopsis Command tests if a file is present and writable. .Description Command to test if a file is writeable. Returns true if file can be opened for write access. .Example Test-IsWritable -path $foo Test if file $foo is accesible for write access. .Example $bar | Test-IsWriteable Test if each file object in $bar is accesible for write access. .Parameter Path Psobject containing the path or object of the file to test for write access. #> [CmdletBinding()] param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][psobject]$path) process{ Write-Verbose "Test if file $path is writeable" if (Test-Path -Path $path -PathType Leaf){ Write-Verbose "File is present" $target = Get-Item $path -Force Write-Verbose "File is readable" try{ Write-Verbose "Trying to openwrite" $writestream = $target.Openwrite() Write-Verbose "Openwrite succeded" $writestream.Close() | Out-Null Write-Verbose "Closing file" Remove-Variable -Name writestream Write-Verbose "File is writable" Write-Output $true } catch{ Write-Verbose "Openwrite failed" Write-Verbose "File is not writable" Write-Output $false } Write-Verbose "Tidying up" Remove-Variable -Name target } else{ Write-Verbose "File $path does not exist or is a directory" Write-Output $false } } }
PowerShellCorpus/PoshCode/Convert Raw SID to SID.ps1
Convert Raw SID to SID.ps1
#For intel concerning how to convert raw hex SID to Standard SID got to #http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx #to convert Hex to Dec function Convert-HEXtoDEC { param($HEX) ForEach ($value in $HEX) { [string][Convert]::ToInt32($value,16) } } #to reassort decimal values to correct hex in order to cenvert them function Reassort { param($chaine) $a = $chaine.substring(0,2) $b = $chaine.substring(2,2) $c = $chaine.substring(4,2) $d = $chaine.substring(6,2) $d+$c+$b+$a } # this is the main function # it splits the waxw sid into different parts and then converts the values # finally it brings the converted SID value. # you can supply an array of raw sid function ConvertSID { param($chaine32) foreach($chaine in $chaine32) { [INT]$SID_Revision = $chaine.substring(0,2) [INT]$Identifier_Authority = $chaine.substring(2,2) [INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8))) $chaine1 = $chaine.substring(24,8) $chaine2 = $chaine.substring(32,8) $chaine3 = $chaine.substring(40,8) $chaine4 = $chaine.substring(48,8) [string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1)) [string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2)) [string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3)) [string]$UID=Convert-HextoDEC(Reassort($chaine4)) #"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID "S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID" } }
PowerShellCorpus/PoshCode/Measure-CommandPerforman.ps1
Measure-CommandPerforman.ps1
##############################################################################\n##\n## Measure-CommandPerformance\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\nMeasures the average time of a command, accounting for natural variability by\nautomatically ignoring the top and bottom ten percent.\n\n.EXAMPLE\n\nPS >Measure-CommandPerformance.ps1 { Start-Sleep -m 300 }\n\nCount : 30\nAverage : 312.10155\n(...)\n\n#>\n\nparam(\n ## The command to measure\n [Scriptblock] $Scriptblock,\n\n ## The number of times to measure the command's performance\n [int] $Iterations = 30\n)\n\nSet-StrictMode -Version Latest\n\n## Figure out how many extra iterations we need to account for the outliers\n$buffer = [int] ($iterations * 0.1)\n$totalIterations = $iterations + (2 * $buffer)\n\n## Get the results\n$results = 1..$totalIterations |\n Foreach-Object { Measure-Command $scriptblock }\n\n## Sort the results, and skip the outliers\n$middleResults = $results | Sort TotalMilliseconds |\n Select -Skip $buffer -First $iterations\n\n## Show the average\n$middleResults | Measure-Object -Average TotalMilliseconds
PowerShellCorpus/PoshCode/Test-Prompt_2.ps1
Test-Prompt_2.ps1
$choices = [System.Management.Automation.Host.ChoiceDescription[]]( (New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Choose me!"), (New-Object System.Management.Automation.Host.ChoiceDescription "&No","Pick me!")) $Answer = $host.ui.PromptForChoice('Caption',"Message",$choices,(1)) Write-Output $Answer $fields = new-object "System.Collections.ObjectModel.Collection"[[System.Management.Automation.Host.FieldDescription]]" $f = New-Object System.Management.Automation.Host.FieldDescription "String Field" $f.HelpMessage = "This is the help for the first field" $f.DefaultValue = "Field1" $f.Label = "&Any Text" $fields.Add($f) $f = New-Object System.Management.Automation.Host.FieldDescription "Secure String" $f.SetparameterType( [System.Security.SecureString] ) $f.HelpMessage = "You will get a password input with **** instead of characters" $f.DefaultValue = "Password" $f.Label = "&Password" $fields.Add($f) $f = New-Object System.Management.Automation.Host.FieldDescription "Numeric Value" $f.SetparameterType( [int] ) $f.DefaultValue = "42" $f.HelpMessage = "You need to type a number, or it will re-prompt" $f.Label = "&Number" $fields.Add($f) $results = $Host.UI.Prompt( "Caption", "Message", $fields ) Write-Output $results
PowerShellCorpus/PoshCode/45599912-3e19-46a3-830b-4a7948b8f56d.ps1
45599912-3e19-46a3-830b-4a7948b8f56d.ps1
Function Test-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$true,Position=1)] [string[]]$Name, [Parameter(Mandatory=$true,Position=2)] [string[]]$ComputerName ) Process { $results = @() foreach ($cName in $ComputerName) { foreach ($vName in $Name) { $result = New-Object System.Management.Automation.PSObject $result | Add-Member -NotePropertyName ComputerName -NotePropertyValue $cName $result | Add-Member -NotePropertyName Name -NotePropertyValue $vName Try { $vm = Get-VM -ComputerName $cName -Name $vName -ErrorAction SilentlyContinue if ($vm -ne $null) { $Existence = $true } else { $Existence = $false } } Catch { #Display an error message } $result | Add-Member -NotePropertyName Existence -NotePropertyValue $Existence $results += $result } } return $results } }
PowerShellCorpus/PoshCode/Find-DuplicateSMTP.ps1
Find-DuplicateSMTP.ps1
####################################################################### #### Written By: Kevin Dunn #### #### Date: 1/21/2009 #### #### #### #### FindDuplicateSMTPAddr.ps1 #### #### #### #### Requires Quest Active Directory cmdlets #### #### Requires Excel (tested on 2007) #### ####################################################################### #User defined Variables $SMTPServer = "127.0.0.1" $SenderAddress = "FromAddress@yourdomain.com" $RecipientAddresses = "You@yourdomain.com" $Subject = "Duplicate SMTP Address Report" $Domain = "yourdomain.com" #Set this to a literal path i.e. "C:\\scripts\\" if not running as a .ps1 #This location is where the spreadsheet will be saved to #$ScriptPath = "C:\\Scripts\\" $ScriptPath = ($myInvocation.MyCommand.Path).Replace($myInvocation.MyCommand.Name, "") if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorVariable Err -ErrorAction SilentlyContinue if ($Err) { Write-Host "`tError loading Quest.ActiveRoles.ADManagement" -ForeGroundColor Green exit } } #Gather proxyaddresses information from AD Write-Host "`n`tGathering email addresses from Active Directory" -ForeGroundColor Yellow $Filter = '(|(&(objectClass=user)(homeMDB=*))(&(mailNickName=*)(objectClass=Contact))(&(mailNickName=*)(objectClass=group)))' $MailObjects = get-qadobject -service $Domain -sizeLimit 0 -ldapfilter $Filter -DontUseDefaultIncludedProperties ` -IncludedProperties proxyAddresses | Select proxyAddresses, ClassName $NumberMailobjects = $MailObjects.count Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberMailobjects " -noNewLine -ForeGroundColor Green Write-Host "mail enabled objects" -ForeGroundColor Yellow #Count and Write proxyaddresses information to hashtable Write-Host "`n`tCounting proxyAddresses Data" -ForeGroundColor Yellow $EmailCount = @{} $EmailTypeCount = @{} $EmailDomainCount = @{} $oldPos = $host.UI.RawUI.CursorPosition Foreach ($MailObject in $MailObjects){ $ObjectType = $MailObject.ClassName $MailObject.ProxyAddresses | Foreach { #Count Type of Addresses $Type = [string]$_.split(":")[0] if($EmailTypeCount.ContainsKey($Type) -eq $False) { $EmailTypeCount.Add($Type, 1) } Else { $Count = $EmailTypeCount.Get_Item($Type) $Count++ $EmailTypeCount.Set_Item($Type, $Count) } #Count Unique Email Addresses if($EmailCount.ContainsKey($_) -eq $False) { $EmailCount.Add($_, 1) } Else { $Count = $EmailCount.Get_Item($_) $Count++ $EmailCount.Set_Item($_, $Count) } #Count Mail domains $Domain = [string]$_.Split("@")[1] if($Domain -ne $null) { if($EmailDomainCount.ContainsKey($Domain) -eq $False) { $EmailDomainCount.Add($Domain, 1) } Else { $Count = $EmailDomainCount.Get_Item($Domain) $Count++ $EmailDomainCount.Set_Item($Domain, $Count) } } } #Keep the output refresh from eating CPU $UpdateOutPut = $False If ($NumberAddType -lt $EmailTypeCount.Count){$UpdateOutPut = $True} elseIf ($NumberMailDomains -lt $EmailDomainCount.Count){$UpdateOutPut = $True} elseIf (($EmailCount.Count % 100) -eq 0){$UpdateOutPut = $True} If ($UpdateOutPut -eq $True) { $NumberAddType = $EmailTypeCount.Count $NumberAddresses = $EmailCount.Count $NumberMailDomains = $EmailDomainCount.Count $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberAddresses " -noNewLine -ForeGroundColor Green Write-Host "unique email addresses" -ForeGroundColor Yellow Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberAddType " -noNewLine -ForeGroundColor Green Write-Host "address types" -ForeGroundColor Yellow Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberMailDomains " -noNewLine -ForeGroundColor Green Write-Host "mail domains`n" -ForeGroundColor Yellow } } $EmailDomains = $EmailDomainCount.GetEnumerator() | Sort Key $EmailTypes = $EmailTypeCount.GetEnumerator() | Sort Key #Filter proxyaddresses data for duplicates Write-Host "`n`tFiltering for duplicate email addresses" -ForeGroundColor Yellow $Duplicates = $EmailCount.GetEnumerator() | ? {$_.Value -gt 1} $Duplicates = $Duplicates | Sort $NumberDuplicates = $Duplicates.Count Write-Host "`tFound " -noNewline -ForeGroundColor Yellow Write-Host "$NumberDuplicates " -noNewLine -ForeGroundColor Green Write-Host "duplicate email addresses`n" -ForeGroundColor Yellow #Retrieve additional information about objects with duplicate proxyaddresses Write-Host "`n`tGathering information about the objects with duplicate email addresses" -ForeGroundColor Yellow $DupeOutput = @() $Count = 0 $oldPos = $host.UI.RawUI.CursorPosition $Duplicates | Foreach { $count++ [string]$Email = $_.Key $Filter = "(proxyAddresses=*$Email*)" $ObjectsWithDupes = get-qadobject -service $Domain -ldapFilter $Filter ` -DontUseDefaultIncludedProperties -includedProperties extensionAttribute3 | ` Select DisplayName, samAccountName, DN, ClassName, extensionAttribute3 $ObjectsWithDupes | foreach { $_ | add-member noteproperty -Name "DupeEmailAddress" -Value $Email } $DupeOutput += $ObjectsWithDupes $DupesProcessed = ($DupeOutput | Select DN -Unique).Count $UsersProcessed = ($DupeOutput | ? {$_.Classname -eq "user"} | Select DN -Unique).Count $GroupsProcessed = ($DupeOutput | ? {$_.Classname -eq "group"} | Select DN -Unique).Count $ContactsProcessed = ($DupeOutput | ? {$_.Classname -eq "contact"} | Select DN -Unique).Count $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tProcessed " -noNewline -ForeGroundColor Yellow Write-Host "$DupesProcessed " -noNewLine -ForeGroundColor Green Write-Host "objects and " -noNewLine -ForeGroundColor Yellow Write-Host "$Count" -noNewLine -ForeGroundColor Green Write-Host " addresses" -ForeGroundColor Yellow } $DupeCount = $DupeOutput.count $DupeOutput = $DupeOutput | Sort displayname, ClassName, DupeEmailAddress #Open Excel Write-Host "`n`tGenerating spreadsheet" -ForeGroundColor Yellow $Excel = New-Object -comobject Excel.Application $Excel.Visible = $False $WB = $Excel.Workbooks.Add(1) #Create First Worksheet $EmailParseData = $WB.Worksheets.Item(1) [void]$EmailParseData.Activate() $EmailParseData.Name = "SMTP Data" #Make the top row pretty [void]$Excel.Cells.Item(2,1).Select() $Excel.ActiveWindow.FreezePanes = $True [void]$Excel.Range($Excel.Cells.item((1),(1)),$Excel.cells.item((1),(2))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 [void]$Excel.Range($Excel.Cells.item((1),(4)),$Excel.cells.item((1),(5))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 $Row = 1 #Populate Top row $EmailParseData.Cells.Item($Row,1) = "Domain" $Excel.Columns.item("A:A").ColumnWidth = 45 $EmailParseData.Cells.Item($Row,2) = "Number Of Occurances" $Excel.Columns.item("B:B").ColumnWidth = 23 $EmailParseData.Cells.Item($Row,4) = "Address Type" $Excel.Columns.item("D:D").ColumnWidth = 16 $EmailParseData.Cells.Item($Row,5) = "Number Of Occurances" $Excel.Columns.item("E:E").ColumnWidth = 23 $Row = 2 #Write to first worksheet Write-Host "`n`tWriting Email Domains" -ForeGroundColor Yellow $EmailDomains | Foreach { $EmailParseData.Cells.Item($Row,1) = $_.Key $EmailParseData.Cells.Item($Row,2) = $_.Value $Row++ } Write-Host "`n`tWriting Address Types" -ForeGroundColor Yellow $Row = 2 $EmailTypes | Foreach { $EmailParseData.Cells.Item($Row,4) = $_.Key $EmailParseData.Cells.Item($Row,5) = $_.Value $Row++ } #Add Second Worksheet Write-Host "`n`t`Creating Second Worksheet" -ForeGroundColor Yellow $DupeWS = $Excel.Worksheets.Add() [void]$DupeWS.Activate() $DupeWS.Name = "Duplicate Address Data" $Row = 1 #Make the top row pretty [void]$Excel.Cells.Item(2,1).Select() $Excel.ActiveWindow.FreezePanes = $True [void]$Excel.Range($Excel.Cells.item((1),(1)),$Excel.cells.item((1),(6))).Select() $Excel.Selection.Interior.ColorIndex = 48 [void]$Excel.Selection.Font.Bold $Excel.Selection.Font.Size = 12 $Excel.Selection.HorizontalAlignment = -4108 #Populate data in the top row $DupeWS.Cells.Item($row,1) = "DisplayName" $Excel.Columns.item("A:A").ColumnWidth = 35 $DupeWS.Cells.Item($row,2) = "samAccountName" $Excel.Columns.item("B:B").ColumnWidth = 25 $DupeWS.Cells.Item($row,3) = "DupeEmailAddress" $Excel.Columns.item("C:C").ColumnWidth = 60 $DupeWS.Cells.Item($row,4) = "ClassName" $Excel.Columns.item("D:D").ColumnWidth = 20 $DupeWS.Cells.Item($row,5) = "ExtensionAttribute3" $Excel.Columns.item("E:E").ColumnWidth = 35 $DupeWS.Cells.Item($row,6) = "DN" $Excel.Columns.item("F:F").ColumnWidth = 90 #Begin writing duplicate email address data $row++ Write-Host "`n`tWriting Duplicate Address Data" -ForeGroundColor Yellow $oldPos = $host.UI.RawUI.CursorPosition $DupeOutput | Foreach { $DupeWS.Cells.Item($row,1) = $_.Displayname $DupeWS.Cells.Item($row,2) = $_.Samaccountname $DupeWS.Cells.Item($row,3) = $_.DupeEmailAddress $DupeWS.Cells.Item($row,4) = $_.ClassName $DupeWS.Cells.Item($row,5) = $_.extensionAttribute3 $DupeWS.Cells.Item($row,6) = $_.DN $row++ If (($row % 5) -eq 0) { $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tOutput " -noNewline -ForeGroundColor Yellow Write-Host "$row " -noNewLine -ForeGroundColor Green Write-Host "lines to Excel`n" -ForeGroundColor Yellow } } $host.UI.RawUI.CursorPosition = $oldPos Write-Host "`tOutput " -noNewline -ForeGroundColor Yellow Write-Host "$row " -noNewLine -ForeGroundColor Green Write-Host "lines to Excel" -ForeGroundColor Yellow #Save the spreadsheet and exit Excel $Excel.DisplayAlerts = $False $saveAs = $ScriptPath + "DupeEmailReport." + (get-date).dayofyear + ".xls" write-host "`tSaving Report to: $saveAS`n`n`n" -ForegroundColor Cyan $WB.SaveAs($saveAs, 1) $WB.Close() $Excel.Quit() #Create the message $Body = "`<BR>" +` " Mail Enabled Objects Found`t`t $NumberMailobjects " +` "`<BR>" +` " Unique Email Addresses Found:`t`t $NumberAddresses " + ` "`<BR>" + ` " Duplicated Email Addresses:`t`t $NumberDuplicates " + ` "`<BR><BR>" + ` " Mail Objects Affected:`t`t $DupesProcessed " + ` "`<BR>" + ` " Users Affected:`t`t $UsersProcessed " + ` "`<BR>" + ` " Groups Affected:`t`t $GroupsProcessed " + ` "`<BR>" + ` " Contacts Affected:`t`t $ContactsProcessed " + ` "`<BR><BR>" +` " Number of Address Types:`t`t $NumberAddType " + ` "`<BR>" + ` " Number of Mail Domains:`t`t $NumberMailDomains" $Attachment = new-object System.Net.Mail.Attachment($saveAs) $objMail = new-object System.Net.Mail.MailMessage $objMail.From = $SenderAddress $objMail.Sender = $SenderAddress $objMail.To.Add($RecipientAddresses) $objMail.Subject = $Subject $objMail.Body = $Body $objMail.IsBodyHTML = $true $objMail.Attachments.Add($Attachment) #Send the message $objSMTP = New-Object System.Net.Mail.SmtpClient $objSMTP.Host = $SMTPServer $objSMTP.UseDefaultCredentials = $true $objSMTP.Send($objMail)
PowerShellCorpus/PoshCode/Set-AssemblyBindLogging.ps1
Set-AssemblyBindLogging.ps1
function Set-AssemblyBindLogging { #.Synopsis # Enable or disable Assembly Bind logging for the machine #.Parameter EnableLogging # Whether or not to enable logging. Accepts partial matching of Enable/Disable or True/False or even 1/0 ... #.Parameter LogPath # The location of the folder you want to save fusion logs to. Will be created if it does not already exist # NOTE: If you are DISABLING logging, this folder will be DELETED (if it is empty). [CmdletBinding()] param( [Parameter(Mandatory=$true)] #[ValidateSet("Enable","Disable","True","False","0","1")] [string]$EnableLogging , $LogPath = "C:\\Logs\\Fusion" ) foreach($RegistryRoot in "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion","HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Fusion") { switch -regex ($EnableLogging) { "En?a?b?l?e?|Tr?u?e?|1" { mkdir $LogPath -Force -EA Stop Set-ItemProperty REGISTRY::$RegistryRoot LogPath $LogPath foreach($switch in "LogFailures","ForceLog","LogResourceBinds") { Set-ItemProperty REGISTRY::$RegistryRoot $switch 1 -Type DWord } } "Di?s?a?b?l?e?|Fa?l?s?e?|0" { rmdir $LogPath foreach($switch in "LogPath","LogFailures","ForceLog","LogResourceBinds") { Remove-ItemProperty $switch } } default { throw "Couldn't convert '$EnableLogging' to a valid value. Valid values are: Enable or Disable, True or False, 1 or 0." } } } }
PowerShellCorpus/PoshCode/Get-Process -eq PSList.ps1
Get-Process -eq PSList.ps1
ps | % -b {$arr = @()} -p { $str = "" | select Name, PID, Time $str.Name = $_.ProcessName $str.PID = $_.Id $str.Time = $(try {$_.StartTime} catch {return [DateTime]::MinValue}) $arr += $str } -end {$arr | sort Time | ft -a}
PowerShellCorpus/PoshCode/RESTful Server.ps1
RESTful Server.ps1
# PowerShell RESTful server by Parul Jain paruljain@hotmail.com # Version 0.1 April 4th, 2013 # # Use to offer services to other programs as a simple alternative to remoting and webservice technologies # Does not require a webserver such as IIS. Works on its own! # Single threaded; will process requests in order. If requests take long to execute and hundreds of simultaneous clients are expected # code needs to be re-written to create a new job per request (I will create that version in the future) # Can return plain text, XML, JSON, HTML, etc. XML and JSON are easy to consume from clients. JSON especially with Javascript, JQuery # Inspired by PERL Dancer and Python Flask # # Requires PowerShell v3.0 or better (will work in v2.0 but ConvertTo-Json not available) # # On windows 7, 2008R2 and 2012 run the following command once from an administratively privileged command prompt # This allows your program to listen on port 8000. You can change the port number per your requirements # netsh http add urlacl url=http://+:8000/ user=domain\\user # Start of script $listener = New-Object System.Net.HttpListener $listener.Prefixes.Add('http://+:8000/') # Must exactly match the netsh command above $listener.Start() 'Listening ...' while ($true) { $context = $listener.GetContext() # blocks until request is received $request = $context.Request $response = $context.Response # Equivalent to 'routes' in other frameworks if ($request.Url -match '/date$') { # response to http://myServer:8000/date $response.ContentType = 'text/plain' $message = [System.DateTime]::Now.ToString() } if ($request.Url -match '/date/xml$') { # response to http://myServer:8000/date/xml $response.ContentType = 'text/xml' $hour = [System.DateTime]::Now.Hour $minute = [System.DateTime]::Now.Minute $message = "<?xml version=""1.0""?><Time><Hour>$hour</Hour><Minute>$minute</Minute></Time>" } if ($request.Url -match '/date/json$') { # response to http://myServer:8000/date/json $response.ContentType = 'application/json' $time = '' | select hour, minute $time.hour = [System.DateTime]::Now.Hour $time.minute = [System.DateTime]::Now.Minute $message = $time | ConvertTo-Json } # This will terminate the script. Remove from production! if ($request.Url -match '/end$') { break } [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) $response.ContentLength64 = $buffer.length $output = $response.OutputStream $output.Write($buffer, 0, $buffer.length) $output.Close() } $listener.Stop()
PowerShellCorpus/PoshCode/ELIM (Event Log IM) 1.0.ps1
ELIM (Event Log IM) 1.0.ps1
$ELIMServer = $Env:ComputerName $ELIMChannel = "ELIM" $ELIMUser = $Env:UserName function New-ELIMUser { #.Synopsis # Send a message to the ELIM (Event Log Instant Messaging) Log [CmdletBinding()] param ( # The Computer whose event logs will be used for instant messaging [String]$Server = $ELIMServer, # The Log Name to use for instant messaging [Alias("To")] [String]$Channel = $ELIMChannel, # The "Source" for messages that you will send [Alias("As")] [String]$UserName = $ELIMUser ) New-EventLog -LogName $Channel -Source $UserName -ComputerName $Server -EA 0 -EV Failed if($Failed -and $Failed[0].Exception.Message.StartsWith( "The `"$UserName`" source is already registered" )) { } sleep -milli 500 if(!(Get-EventLog -ComputerName $Server -list |where {$_.Log -eq $Channel })) { throw "Failed to register on server, please check server and username and try again:`n`n$Failed" } Set-ELIMDefaults @PSBoundParameters } function Set-ELIMDefaults { #.Synopsis # Set your default username for the ELIM (Event Log Instant Messaging) Log #.Description # Normally your current computer ($Env:ComputerName), UserName ($Env:UserName), and the "ELIM" log are used unless you overwrite it on the console. # This allows you to override those defaults param ( # The Computer whose event logs will be used for instant messaging [String]$Server = $ELIMServer, # The Log Name to use for instant messaging [Alias("To")] [String]$Channel = $ELIMChannel, # The "Source" for messages that you will send [Alias("As")] [String]$UserName = $ELIMUser ) $script:ELIMServer = $Server $script:ELIMChannel = $Channel $script:ELIMUser = $UserName } function Send-ELIMMessage { #.Synopsis # Send a message to the ELIM (Event Log Instant Messaging) Log [CmdletBinding()] param( # The message to send [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [String]$Message, # The Computer whose event logs will be used for instant messaging [String]$Server = $ELIMServer, # The Log Name to use for instant messaging [Alias("To")] [String]$Channel = $ELIMChannel, # The "Source" for messages that you will send [Alias("As")] [String]$UserName = $ELIMUser ) process { Write-Verbose "Write-EventLog -ComputerName $Server -LogName $Channel -Source $UserName -EventID 1 -Message '$Message'" Write-EventLog -ComputerName $Server -LogName $Channel -Source $UserName -EventID 1 -Message $Message } } Set-Alias Msg Send-ELIMMessage function Start-ELIM { [CmdletBinding()] param( # The Computer whose event logs will be used for instant messaging [String]$Server = $ELIMServer, # The Log Name to use for instant messaging [Alias("To")] [String]$Channel = $ELIMChannel, # The "Source" for messages that you will send [Alias("As")] [String]$UserName = $ELIMUser, # Time stamp format for output $TimeStampFormat = "dd-MM hh:mm:ss", # The default background color for instant messages $Background = "Black", # The highlight color for instant messages $HighlightBackground = "White", # The regular expression for highlighting (defaults to your username) $HighlightRegex = ".*${UserName}.*", # Available colors for user names. You can use any of "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White" -- but you want to exclude any of them which aren't readable. [ConsoleColor[]]$Colors = $("DarkGreen", "DarkCyan", "DarkRed", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White"), [Switch]$Force ) end { Set-ELIMDefaults -Server $Server -Channel $Channel -UserName $UserName try { $exists = [System.Diagnostics.EventLog]::SourceExists($UserName, $Server) } catch {} if(!$exists) { Write-Warning "Your user name ($UserName) doesn't exist on '$Server', you won't be able to send messages until you run New-ELIMUser in an elevated console" } else { $RealChannel = [System.Diagnostics.EventLog]::LogNameFromSourceName($UserName,$Server) if($Channel -ne $RealChannel -and !$Force) { throw "Your username is registered to SEND to '$RealChannel' not '$Channel', if you want to LISTEN to '$Channel' anyway, use -Force" } } $elim = Get-EventLog -ComputerName $Server -list | where { $_.Log -eq $Channel } if(!$elim) { throw "Failed to connect to the '$Channel' channel on the server ($Server)." } else { Register-ObjectEvent $elim EntryWritten -Action { if($Event.Entry.Source -ceq $Event.MessageData.UserName) { return } $Message = "[{0:$($Event.MessageData.TimeStampFormat)}] {1}: {2}" -f $EventArgs.Entry.TimeGenerated, $EventArgs.Entry.Source, $EventArgs.Entry.Message $Color = $Event.MessageData.Colors[(([int[]][char[]]"$($EventArgs.Entry.Source)" | measure -sum ).Sum % $Event.MessageData.Colors.Count)] Write-Host "$(([int[]][char[]]"$($EventArgs.Entry.Source)" | measure -sum ).Sum) % $($Event.MessageData.Colors.Count) = $(([int[]][char[]]"$($EventArgs.Entry.Source)" | measure -sum ).Sum % $Event.MessageData.Colors.Count) = $Color" if($Message -match $Event.MessageData.HighlightRegex) { Write-Host $Message -ForegroundColor $Color -BackgroundColor $Event.MessageData.HighlightBackground } else { Write-Host $Message -ForegroundColor $Color -BackgroundColor $Event.MessageData.Background } } -MessageData @{ Server = $Server Channel = $Channel UserName = $UserName TimeStampFormat = $TimeStampFormat Background = $Background HighlightBackground = $HighlightBackground HighlightRegex = $HighlightRegex Colors = $Colors } } } } Export-ModuleMember -Function * -Alias *
PowerShellCorpus/PoshCode/Added_Deleted AD Objects.ps1
Added_Deleted AD Objects.ps1
#REQUIRES -pssnapin quest.activeroles.admanagement #REQUIRES -pssnapin Pscx begin { # Build variables $strSMTPServer = "192.168.251.144"; $strEmailFrom = "AD_Admin@hfinc.com"; $strEmailTo = "jdelatorre@hfinc.com"; $borders = "=" * 25; [int]$days = -60 function TombStonedObjects { # create Directory Searcher object and set properties to search # for tombstoned objects $ds = New-Object System.DirectoryServices.DirectorySearcher $ds.Tombstone = $TRUE $ds.Filter = "isDeleted=TRUE" # Query for objects and filter for DN $DSResults=$DS.FindAll() | select path # Build simple RegExp to get just Common Name $r=[regex]"(?<=CN=).+(?=\\\\)" $DSR2=$DSResults | % { $r.Matches($_);$script:delCount++} foreach ($DSobject in $DSR2) { $delMessage += "Deleted object: " + $DSobject.value.trim() + "`n" } $delMessage # end function } function AddedComputersAndUsers { # Query AD for Computer and users created in the last 'x' amount of days. $ADObjects=Get-QADObject | ? {$_.type -match ("computer|user")} | ? {$_.whencreated -gt ((get-date).addDays($days))} if ($ADObjects) { foreach ($ADObject in $ADObjects) { switch ($ADObject.Type) { 'user' { $usrCount ++; $ADObject | fl * | Out-Null; #This is needed for some reason some objects are not returned without it $usrMessage += "Display Name: " + $ADobject.displayname + "`n"; $usrMessage += "SAMAccountName: " + $ADObject.get_LogonName() + "`n"; $usrMessage += "Container: " + $ADObject.parentcontainer + "`n"; $usrMessage += "When Created: " + $ADObject.whencreated + "`n"; $usrMessage += "Principal Name: " + $ADObject.userPrincipalName + "`n"; $usrMessage += "Groups: `n"; # Build array of groups and populate $usrMessage variable $groups=$adobject.MemberOf foreach ($group in $groups) { $usrMessage += "$group `n"} $usrMessage += "`n"; } 'computer' { $computerCount ++; $ADObject | fl * | Out-Null; #This is needed for some reason some objects are not returned without it $compMessage += "DNS HostName: " + $ADObject.dnsname + "`n"; $compMessage += "OperatingSystem: " + $ADObject.osName + "`n"; $compMessage += "OS Service Pack: " + $ADObject.osservicepack + "`n"; $compMessage += "Computer Role: " + $ADObject.computerrole + "`n"; $compMessage += "When Created: " + $ADObject.whencreated + "`n"; $compMessage += "Container: " + $ADObject.parentcontainer + "`n"; $compMessage += "`n"; } } } $deletedobjects = TombStonedObjects # Build emailBody with the Usermessage and ComputerMessage variables $script:emailMessage = "AD User/Computer Objects created in the last " + [math]::abs($days) + " day(s).`n"; if ($usrMessage) {$script:emailMessage += "$borders Users $borders`n" + $usrMessage;} if ($compMessage) {$script:emailMessage += "$borders Computers $borders`n" + $compMessage;} if ($deletedobjects) {$script:emailMessage += "$borders Deleted Objects for the last 60 days $borders `n" + $deletedobjects;} $script:emailSubject = "Users Added: " + $usrCount + ". Computers Added: " + $computerCount + ". Objects Deleted: " + $script:delCount + "."; } else { # No users or computers found created in the last 'x' days. $deletedobjects = TombStonedObjects $script:emailSubject = "Users Added: " + $usrCount + ". Computers Added: " + $computerCount + ". Objects Deleted: " + $script:delCount + "."; $script:emailMessage = "No Users or Computers have been added in the last " + [math]::abs($days) + " day(s). `n"; if ($deletedobjects) {$script:emailMessage += "$borders Deleted Objects for the last 60 days $borders `n" + $deletedobjects;} } # end function } # end Begin } process { AddedComputersAndUsers Send-SmtpMail -Subject $script:emailSubject -To $strEmailTo -From $strEmailFrom -SmtpHost $strSMTPServer -Body $script:emailMessage; # end Process }
PowerShellCorpus/PoshCode/Invoke-SqlCmd_3.ps1
Invoke-SqlCmd_3.ps1
####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() $ds.Tables }
PowerShellCorpus/PoshCode/WSUS-Settings.ps1
WSUS-Settings.ps1
#================================================================================================== # File Name : WSUS-Settings.ps1 # Original Author : Kenneth C. Mazie (kcmjr at kcmjr.com) # Description : As written will manually apply all settings associated with a local # : WSUS server. Ideal for use when you need to force a non-domain system # : to point to a domain based WSUS server. # # Notes : Normal operation is with no command line options. This PowerShell script # : was the result of an export of a system registry after being joined to # : a domain and receiveing all WSUS settings from the domain policy. # : Settings "should" mimic those found in the domain policy at: # : "Computer Configuration\\Policies\\Administrative Templates\\Windows Components\\Windows Update" # : On any domain member systems. If the required parent keys do not exist # : it will create them. # : # : The script will set ONE target group and ONE computer at a time. It # : is intended to run locally either manually or as a startup script. # : Primary settings are set as variables, the rest are set in the script body. # : # Warnings : None # : # Legal : Public Domain. Modify and redistribute freely. No rights reserved. # : SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF ANY KIND. # : USE AT YOUR OWN RISK. NO TECHNICAL SUPPORT PROVIDED. # : # Credits : None # : # Last Update by : Kenneth C. Mazie # Version History : v1.0 - 02-19-09 - Original # Change History : v1.1 - # #================================================================================================== Clear-Host #--[ Windows Update Server Info ]-- $TargetGroup = "Computers" $WUServer = "http://192.168.1.10" $WUStatusServer = "http://192.168.1.10" #-[ NOTE: all other settings should be set below ]-- #--[ Setup Windows Updates ]-- Write-Host -backgroundColor white -foregroundcolor blue -object "Setting WSUS Parameters..." if(!( Test-Path 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' )) { New-Item 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -force } New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'ElevateNonAdmins' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'AcceptTrustedPublisherCerts' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'TargetGroupEnabled' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'TargetGroup' -value $TargetGroup -propertyType "String" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'WUServer' -value $WUServer -propertyType "String" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate' -name 'WUStatusServer' -value $WUStatusServer -propertyType "String" -force if(!( Test-Path 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' )) { New-Item 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -force } New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'NoAutoRebootWithLoggedOnUsers' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'NoAUShutdownOption' -value '0' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'NoAUAsDefaultShutdownOption' -value '0' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'DetectionFrequencyEnabled' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'DetectionFrequency' -value '22' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'AutoInstallMinorUpdates' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RebootWarningTimeoutEnabled' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RebootWarningTimeout' -value '5' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RebootRelaunchTimeoutEnabled' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RebootRelaunchTimeout' -value '30' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'IncludeRecommendedUpdates' -value '22' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'AUPowerManagement' -value '0' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'NoAutoUpdate' -value '0' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'AUOptions' -value '4' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'ScheduledInstallDay' -value '4' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'ScheduledInstallTime' -value '3' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'UseWUServer' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RescheduleWaitTimeEnabled' -value '1' -propertyType "DWord" -force New-ItemProperty 'HKLM:\\Software\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU' -name 'RescheduleWaitTime' -value '1' -propertyType "DWord" -force Write-Host -backgroundColor white -foregroundcolor blue -object "Completed..."
PowerShellCorpus/PoshCode/Vim25-less Crazy Magic_1.ps1
Vim25-less Crazy Magic_1.ps1
cls $ws = New-WebServiceProxy -Uri "http://192.168.1.1/sdk/vimService?wsdl" -Namespace "vimService1" ; $ws.Url = "http://192.168.1.1/sdk/vimService"; $ws.UserAgent = "VMware VI Client/4.0.0"; $ws.CookieContainer = New-Object system.net.CookieContainer; $mor_ret = new-object vimService1.ManagedObjectReference; $mor_si = new-object vimService1.ManagedObjectReference; $mor_si.type = "ServiceInstance"; $mor_si.Value = "ServiceInstance"; $mor_sm = new-object vimService1.ManagedObjectReference; $mor_sm.type = "SessionManager"; $mor_sm.Value = "ha-sessionmgr"; $mor_hs = new-object vimService1.ManagedObjectReference; $mor_hs.type = "HostSystem"; $mor_hs.Value = "ha-host"; $us = $ws.Login($mor_sm,"root","root", "en"); write-Host $ws.CurrentTime($mor_si); #$mor_ret = $ws.RebootHost_Task($mor_hs, $true); $ws.Logout($mor_sm);
PowerShellCorpus/PoshCode/Log ports used by applic.ps1
Log ports used by applic.ps1
####################################################################################################################### # File: LogPortsUsedByApplication.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Usage: This scripts collects network connections information in two ways, # # using the netstat -ao command to display hostnames and # # .\\LogPortsUsedByApplication.ps1 $false # # using the netstat -ano command to provide only addresses # # .\\LogPortsUsedByApplication.ps1 $true # # or # # .\\LogPortsUsedByApplication.ps1 # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param( [bool]$Numeric = $true ) cls Set-StrictMode -Version Latest #region logs preparation [string]$netstatParameters = ""; [string]$logfileFull = ""; [string]$logfileSelected = ""; [string]$logfileSqueezed = ""; if ($Numeric){ $logfileFull = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_fullN.txt"; $logfileSelected = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_selectedN.txt"; $logfileSqueezed = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_squeezedN.txt"; $netstatParameters = "-ano";} else { $logfileFull = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_full.txt"; $logfileSelected = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_selected.txt"; $logfileSqueezed = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_squeezed.txt"; $netstatParameters = "-ao";} Remove-Item -Path $logfileFull -Force -ErrorAction:SilentlyContinue; Remove-Item -Path $logfileSelected -Force -ErrorAction:SilentlyContinue; Remove-Item -Path $logfileSqueezed -Force -ErrorAction:SilentlyContinue; $recordsDict = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"; [string]$hostname = $Env:COMPUTERNAME + "`t"; #endregion logs preparation #region settings [String[]]$applications = @( "ServiceName", "GUIApplicationName", "UtilityName" ); #endregion settings #region functions #region function Get-CurrentTime function Get-CurrentTime <# .SYNOPSIS The Get-CurrentTime function is used to write in the timestamp in the log file. .DESCRIPTION The Get-CurrentTime functions is used for getting the current time of operation. As s time source used [System.DateTime]::Now.TimeOfDay property. .EXAMPLE PS C:\\> Get-CurrentTime .OUTPUTS System.String #> { $timeOfDay = [System.DateTime]::Now.TimeOfDay; $time = "$($timeOfDay.Hours):$($timeOfDay.Minutes):$($timeOfDay.Seconds)`t"; return $time;} #endregion function Get-CurrentTime #endregion functions netstat "$($netstatParameters)" 1 | ` %{ if ($_.Length -gt 0){ [string]$currentTime = Get-CurrentTime + "`t"; "$($hostname)$($currentTime)*`t$($_)" >> $logfileFull; for ($private:i = 0; $private:i -lt $applications.Length; $private:i++) { if ((Get-Process $applications[$private:i] -ErrorAction:SilentlyContinue) -ne $null) { if ($_.Contains((Get-Process $applications[$private:i]).Id.ToString())) { "$($hostname)$($currentTime)$($applications[$private:i])`t$($_)" >> $logfileSelected; try{ $recordsDict.Add("$($hostname)`t$($applications[$private:i])`t$($_)", ""); # re-write the squeezed report Remove-Item -Path "$($logfileSqueezed)_previous" ` -Force -ErrorAction:SilentlyContinue; Copy-Item -Path $logfileSqueezed -Destination "$($logfileSqueezed)_previous" Remove-Item -Path $logfileSqueezed -Force -ErrorAction:SilentlyContinue; foreach($key in $recordsDict.Keys) { "$($key)" >> $logfileSqueezed; } } catch{} } } } } }
PowerShellCorpus/PoshCode/Get Network Utilization.ps1
Get Network Utilization.ps1
$cnt = 'Bytes Total/sec' $inst = 'Broadcom NetXtreme Gigabit Ethernet - Packet Scheduler Miniport' $cat = 'Network Interface' $cnt2 = 'Current Bandwidth' $cur = New-Object system.Diagnostics.PerformanceCounter($cat,$cnt,$inst) $max = New-Object system.Diagnostics.PerformanceCounter($cat,$cnt2,$inst) $curnum = $cur.NextValue() $maxnum = $max.NextValue() $util = (( $curnum * 8 ) / $maxnum ) * 100 $util
PowerShellCorpus/PoshCode/New-XVM_3.ps1
New-XVM_3.ps1
#Examples <# New-XVM -Name "WS2012-TestServer01" -SwitchName "Switch(192.168.2.0/24)" -VhdType NoVHD New-XVM -Name "WS2012-TestServer02" -SwitchName "Switch(192.168.2.0/24)" -VhdType ExistingVHD -VhdPath 'D:\\vhds\\WS2012-TestServer02.vhdx' New-XVM -Name "WS2012-TestServer03" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD New-XVM -Name "WS2012-TestServer04" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Fixed -DiskSize 1GB New-XVM -Name "WS2012-TestServer05" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -DiskType Dynamic New-XVM -Name "WS2012-TestServer06" -SwitchName "Switch(192.168.2.0/24)" -VhdType Differencing -ParentVhdPath 'D:\\vhds\\Windows Server 2012 RC Base.vhdx' New-XVM -Name "WS2012-TestServer07" -SwitchName "Switch(192.168.2.0/24)" -VhdType NewVHD -Configuration @{"MemoryStartupBytes"=1GB;"BootDevice"="LegacyNetworkAdapter"} #> Function New-XVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "_AllParameterSets" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { Try { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Invoke-Expression -Command $command } End {} }
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_2.ps1
TabExpansion for V2CTP_2.ps1
## Tab-Completion ################# ## For V2CTP3. ## This won't work on V1 and V2CTP and V2CTP2. ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion ## 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 -Errora s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" } ## $data = Get-Process ## $data[2,4,5] | % { $_.<tab> ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion by -Property parameter ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ## #Parameter expansion for function, filter and script ## man -f<tab> ## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1 ## .\\foobar.ps1 -<tab> -b<tab> ## #Enum expansion for function, filter and scripts ## # this can do continuous enum expansion with comma and no spaces ## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab> ## #Enum expansion for assignment expression ## #needs space(s) after '=' and comma ## #strongly-typed with -as operator and space(s) ## $ErrorActionPreference =<space><tab> ## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3 ## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab> ## #Path expansion with variable and '\\' or '/' ## $PWD\\../../<tab>\\<tab> ## "$env:SystemDrive/pro<tab>/<tab> ## #Operator expansion which starts with '-' ## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2' ## 1..9 -co<tab> 5 ## #Keyword expansion ## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } } ## #Variable name expansion (only global scope) ## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab> ## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab> ## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab> ## Tee-Object -Variable <tab> ## gv pro<tab>,<tab> ## Remove-Variable -Name out<tab>,<tab>,ps<tab> ## ... | ... | tee -v <tab> ## #Alias name expansion ## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab> ## Export-Alias -Name <tab> ## Get-Alias i<tab>,e<tab>,a<tab> ## epal -n for<tab> ## #Property name expansion with -groupBy parameter ## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab> ## ps | ft -g <tab> ## gcm | Format-Wide -GroupBy Par<tab> ## #Type accelerators expansion with no charactors ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\ProgIDs.txt $_ProgID = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") $_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID.Add($_i.GetValue("")) } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose } ### Generate TypeNames list... if ( Test-Path $PSHOME\\TypeNames.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames.txt $_TypeNames = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames.Add($_type.FullName) } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose } if ( Test-Path $PSHOME\\TypeNames_System.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames_System.txt $_TypeNames_System = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\WMIClasses.txt $_WMIClasses = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort iex (@' function prompt { if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru | Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru | Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru | Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru | Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru | Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru | Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru | Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru | Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru | Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru | Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru | Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru | Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru | Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru | Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru | Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru | Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru | Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru | Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru | Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru | Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru | Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru | Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru | Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru | Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru | Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru | Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru | Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru | Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru | Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru | Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru | Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru | Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru | Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru | Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru | Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru | Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru | Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru | Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru | Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru | Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru | Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru | Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru | Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru | Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru | Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru | Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru | Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru | Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru | Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru | Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru | Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru | Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru | Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru | Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru | Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru | Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru | Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru | Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru | Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru | Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru | Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru | Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru | Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru | Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru | Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru | Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru | Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru | Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru | Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru | Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru | Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru | Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru | Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru | Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru | Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru | Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru | Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru | Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru | Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru | Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru | Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru | Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru | Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru | Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru | Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru | Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru | Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru | Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru | Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru | Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru | Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru | Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function TabExpansion { param($line, $lastWord) & { function Write-Members ($sep='.') { 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 '.') { $params = @{view = 'extended','adapted','base'} } else { $params = @{static=$true} } if ( $_val -is [Hashtable] ) { [Object[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } } if ( $_keys -ne $null ) { $_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat}) } else { $_members = (Get-Member @params -InputObject $_val $_pat) } foreach ($_m in $_members | 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 } } } $host.UI.RawUI.WindowTitle = "Windows PowerShell V2 (CTP2)" + $lastword 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 $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[((\\w+\\.?)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ("'`$0'") $fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'") $fse = $fse -replace "''", "'" $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_base + $global:_cmdstack.Pop() } else { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_command = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_command -match '\\{([^\\{\\}]*)$') { $_command = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_command -match '\\(([^()]*)$') { $_command = $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. $_command = $_command.Trim().Split()[0] # now get the info object for it... $_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command)[0] # loop resolving aliases... while ($_command.CommandType -eq 'alias') { $_command = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_command.Definition)[0] } if ( $_command -ne $null ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_command.Parameters.Keys | sort) { if ($_n -like $_pat) { '-' + $_n } } } else { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # Tab complete against history either #<pattern> or #<id> '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;]')[-1] if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' ) { if ( $Matches[6] -ne $nul ) { $brackets = "[]" } '['+ $global:_enum + $brackets + ']' break; } if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' ) { $_pat = $Matches[7] + '*' $_type = @(iex $Matches[1])[0].GetType() if ( $_type.IsEnum ) { $global:_enum = $_type.FullName [Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"' break; } } $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line -match '(function|filter)\\s+(\\w*)$') { $_pat = 'function:\\' + $Matches[2] + '*' Get-ChildItem $_pat| % { $_.Name } break; } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_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 ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { 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 | gm -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { $_cmdlet = [regex]::Split($line, '[|;=]')[-1] if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_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\\.])*)$' ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] 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 ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) $_cmdlet = [regex]::Split($line, '[|;=]')[-1] if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } # parse the script... $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null) if ($_tokens) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Command') { $_cmd = $_lastToken.Content # don't look for paths... if ($_cmd.IndexOfAny('/\\') -eq -1) { # handle parsing errors - the last token string should be the last # string in the line... if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) { $_pat = $_cmd + '*' $_base = $lastword.substring(0, $lastword.length-$_cmd.length) "begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (", "end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ", "param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" ` -like $_pat | % {'{0}{1}' -f $_base,$_ } $ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) | Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ } } } } } } } } }
PowerShellCorpus/PoshCode/Find files not containig.ps1
Find files not containig.ps1
# Find all files which does not contains the text in $Pattern function ssHasNot( [string] $Path="*.txt" ,[string] $pattern="" ) { $has=[string]@(get-childitem $path | ss $pattern | foreach {$_.Path}) get-childitem $path| where {$has.Contains($_.FullName) -eq $false} }
PowerShellCorpus/PoshCode/Simplest animation.ps1
Simplest animation.ps1
[int]$x = 0 [int]$y = 0 [int]$cX = 200 [int]$cY = 200 [int]$rad = 100 [int]$grad = 0 [float]$kfc = 0.5 $tabPag1_OnPaint= { $tmrTim2.Enabled = $false $g = $tabPag1.CreateGraphics() $pen = New-Object Drawing.Pen([Drawing.Brushes]::Red) $g.DrawRectangle($pen, [Convert]::ToInt32($cX - 100), [Convert]::ToInt32($cY - 100), $cX, $cY) $g.FillEllipse([Drawing.Brushes]::Red, [Convert]::ToInt32($cX + $x - 10), ` [Convert]::ToInt32($cY + $y - 10), 20, 20) $g.Dispose() $tmrTim1.Enabled = $true } $tmrTim1_OnTick= { $grad += 5 if ($gard -gt 360) { $grad -= 360 } $x = $rad * [Math]::Cos($grad * [Math]::PI / 180) $y = $kfc * $rad * [Math]::Sin($grad * [Math]::PI / 180) $tabPag1.Invalidate() } $tabPag2_OnPaint= { $tmrTim1.Enabled = $false $g = $tabPag2.CreateGraphics() $brush = New-Object Drawing.SolidBrush Blue $font = New-Object Drawing.Font("Tahoma", (12 + $val), 1) $msg = "Hello from GDI+!" [float]$center = $tabPag2.DisplayRectangle.Width / 2 $size = $g.MeasureString($msg, $font) [float]$swlpos = $center - ($size.Width / 2) $g.DrawString($msg, $font, $brush, $swlpos, 10) $tmrTim2.Enabled = $true } $tmrTim2_OnTick= { $val += 5 if ($val -ge 50) { $val = $null } $tabPag2.Invalidate() } function ShowMainWindow { [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Drawing") [Windows.Forms.Application]::EnableVisualStyles() $frmMain = New-Object Windows.Forms.Form $tabTabs = New-Object Windows.Forms.TabControl $tabPag1 = New-Object Windows.Forms.TabPage $tabPag2 = New-Object Windows.Forms.TabPage $tmrTim1 = New-Object Windows.Forms.Timer $tmrTim2 = New-Object Windows.Forms.Timer #tabTabs $tabTabs.Controls.AddRange(@($tabPag1, $tabPag2)) $tabTabs.Dock = "Fill" #tabPag1 $tabPag1.Text = "Orbital moving" $tabPag1.UseVisualStyleBackColor = $true $tabPag1.Add_Paint($tabPag1_OnPaint) #tabPag2 $tabPag2.Text = "Swelling font" $tabPag2.UseVisualStyleBackColor = $true $tabPag2.Add_Paint($tabPag2_OnPaint) #tmrTim1 $tmrTim1.Interval = 100 $tmrTim1.Add_Tick($tmrTim1_OnTick) #tmrTim2 $tmrTim2.Interval = 100 $tmrTim2.Add_Tick($tmrTim2_OnTick) #frmMain $frmMain.ClientSize = New-Object Drawing.Size(410, 430) $frmMain.Controls.AddRange(@($tabTabs)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.MaximizeBox = $false $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Animation" [void]$frmMain.ShowDialog() } ShowMainWindow
PowerShellCorpus/PoshCode/format-iislog.ps1
format-iislog.ps1
param ( [Parameter( Mandatory=$true, Position = 0, ValueFromPipeline=$true, HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log." )] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter( Mandatory=$true, Position = 1, ValueFromPipeline=$true, HelpMessage="Specifies the desired field names. Must be in the following format: #Fields: fname1 fname2" )] [ValidateNotNullOrEmpty()] [string] $NewPath, [Parameter( Mandatory=$true, Position = 2, ValueFromPipeline=$true, HelpMessage="Specifies the output location for the modified log file." )] [ValidateNotNullOrEmpty()] [string] $OutPath, [Parameter( Position = 3, HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar." )] [ValidateNotNullOrEmpty()] [string] $Delimiter = " ", [Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8 ) begin { $fieldNames = @() $newfieldnames = @() } process { #add headers to new output file (get-content $path)[0..2] | Out-File $outpath -Append -encoding Default $newpath | Out-File $outpath -Append -encoding Default #populate $newfieldnames from the mandatory parameter $newpath $newfieldNames = @($newpath.Substring("#Fields: ".Length).Split($Delimiter)); foreach($line in Get-Content -Path $Path) { # Indentify / parse the log header to determine field names if($line.StartsWith("#Fields: ")) { $fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter)); } # Identify / parse the "non log header" lines to determine field values elseif(-not $line.StartsWith("#")) { $logline = "" $fieldValues = @($line.Split($Delimiter)); #Initialize a hashtable to hold fields and values #Default value is a hyphen #Only fields specified in the $newpath parameter are initialized $output = @{} foreach ($item in $newfieldnames) { switch($item) { "date"{ $output.add("date", "-")} "time"{ $output.add("time", "-")} "s-ip"{ $output.add("s-ip", "-")} "cs-method"{ $output.add("cs-method", "-")} "cs-uri-stem"{ $output.add("cs-uri-stem", "-")} "cs-uri-query"{ $output.add("cs-uri-query", "-")} "s-port"{ $output.add("s-port", "-")} "cs-username"{ $output.add("cs-username", "-")} "c-ip"{ $output.add("c-ip", "-")} "cs-version"{ $output.add("cs-version", "-")} "cs(User-Agent)"{ $output.add("cs(User-Agent)", "-")} "sc-status"{ $output.add("sc-status", "-")} "sc-substatus"{ $output.add("sc-substatus", "-")} "sc-win32-status"{ $output.add("sc-win32-status", "-")} "sc-bytes"{ $output.add("sc-bytes", "-")} "time-taken"{ $output.add("time-taken", "-")} "cs-host"{ $output.add("cs-host", "-")} "cs(Cookie)"{ $output.add("cs(Cookie)", "-")} "cs(Referer)"{ $output.add("cs(Referer)", "-")} "s-sitename"{ $output.add("s-sitename", "-")} "s-computername"{ $output.add("s-computername", "-")} "cs-bytes"{ $output.add("cs-bytes", "-")} } } #Add every field from old log file to the $ouptuts hashtable #Portions of the hash table which are not over written at this point retain the default value (hyphen) for($i = 0; $i -lt $fieldnames.Length; $i++) { $name = $fieldNames[$i] $value = $fieldValues[$i] switch($name) { "date"{ $output['date'] = $value} "time"{ $output['time'] = $value} "s-ip"{ $output['s-ip'] = $value} "cs-method"{ $output['cs-method'] = $value} "cs-uri-stem"{ $output['cs-uri-stem'] = $value} "cs-uri-query"{ $output['cs-uri-query'] = $value} "s-port"{ $output['s-port'] = $value} "cs-username"{ $output['cs-username'] = $value} "c-ip"{ $output['c-ip'] = $value} "cs-version"{ $output['cs-version'] = $value} "cs(User-Agent)"{ $output['cs(User-Agent)'] = $value} "sc-status"{ $output['sc-status'] = $value} "sc-substatus"{ $output['sc-substatus'] = $value} "sc-win32-status"{ $output['sc-win32-status'] = $value} "sc-bytes"{ $output['sc-bytes'] = $value} "time-taken"{ $output['time-taken'] = $value} "cs-host"{ $output['cs-host'] = $value} "cs(Cookie)"{ $output['cs(Cookie)'] = $value} "cs(Referer)"{ $output['cs(Referer)'] = $value} "s-sitename"{ $output['s-sitename'] = $value} "s-computername"{ $output['s-computername'] = $value} "cs-bytes"{ $output['cs-bytes'] = $value} } } #$output $linewriter = $null #Write lines to new log file #Only call upon keys (from output hash) which correspond to desired $newfieldnames as specified in $newpath parameter. #Unwanted fields from old log are inherently dropped #Newly included fields not present in old log are inherently replaced by hypens foreach ($item in $newfieldnames) { $linewriter += $output[$item] $linewriter += " " } $linewriter |%{$_ -replace " $",""}| Out-File $outpath -Append -encoding Default } } } # usage example #.\\import-iislog-final.ps1 "C:\\Old Logs\\u_ex120218.log" "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\u_ex120218.log" #foreach ($log in (gci "c:\\Old Logs")) {.\\import-iislog-final.ps1 $log.fullname "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\$log"}
PowerShellCorpus/PoshCode/Get- ExchangeMBStore.ps1
Get- ExchangeMBStore.ps1
Param ( [Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)] [alias("Name","ComputerName")]$Computer=@("xcserver01") ) process{ $XCinfo = GetXCDatabases $Computer $XCMaintInfo = GetMBStoreMaintenance $Computer foreach ($DB in $XCinfo){ try{ $DB.WhiteSpace = $XCMaintInfo[$DB.MB].WhiteSpace $DB.RetainedMailbox = $XCMaintInfo[$DB.MB].RetainedMailbox $DB.RetainedMailboxSize = $XCMaintInfo[$DB.MB].RetainedMailboxSize $DB.DeletedMailbox = $XCMaintInfo[$DB.MB].DeletedMailbox $DB.DeletedMailboxSize = $XCMaintInfo[$DB.MB].DeletedMailboxSize $DB.DeletedItems = $XCMaintInfo[$DB.MB].DeletedItems $DB.DeletedItemsSize = $XCMaintInfo[$DB.MB].DeletedItemsSize } catch{ Write-Error $("For " + $Computer + ": " + $($error[0])) } } $Global:XCserverInfo += $XCinfo | select Server, StorageGroup, DatabaseName, Path, FileSize, DeletedMailbox, DeletedMailboxSize, RetainedMailbox, RetainedMailboxSize, DeletedItems, DeletedItemsSize } begin{ $Global:XCserverInfo = @() $Quote = [char]34 Function GetADSIObject ($Name){ write-verbose "get ADSI information for $Name" $root = [ADSI]'LDAP://RootDSE' $cfConfigRootpath = "LDAP://" + $root.ConfigurationNamingContext.tostring() $configRoot = [ADSI]$cfConfigRootpath $searcher = new-object System.DirectoryServices.DirectorySearcher($configRoot) $searcher.Filter = '(&(objectCategory=msExchExchangeServer)(cn=' + $Name + '))' $searchres = $searcher.FindOne() $snServerEntry = New-Object System.DirectoryServices.directoryentry $snServerEntry = $searchres.GetDirectoryEntry() $adsiServer = [ADSI]('LDAP://' + $snServerEntry.DistinguishedName) return $adsiserver } Function GetXCDatabases($XCservername){ $XCDatabases = @() $XCserver = GetADSIObject $XCservername write-verbose "get XC DB information for $($XCserver.Name)" $dfsearcher = new-object System.DirectoryServices.DirectorySearcher($XCserver) #get all standard mailstores $dfsearcher.Filter = "(objectCategory=msExchPrivateMDB)" $srSearchResults = $dfsearcher.FindAll() #get all public folder stores $dfsearcher.Filter = "(objectCategory=msExchPublicMDB)" $srSearchResults += $dfsearcher.FindAll() foreach ($srSearchResult in $srSearchResults){ $msMailStore = $srSearchResult.GetDirectoryEntry() $msMailStoreFileName = $msMailStore.msExchEDBFile $Filter = $msMailStoreFileName -replace '\\\\','\\\\' write-verbose "getting details for $Filter thru WMI" $msMailStoreFile = (Gwmi -computername $XCservername -class CIM_DataFile -filter "Name = '$Filter'") $sgStorageGroup = $msMailStore.psbase.Parent #skip recovery databases if ($sgStorageGroup.msExchESEParamBaseName -ne "R00"){ $XCdatabase = New-Object PSObject -Property @{ Server = [string] $XCservername StorageGroup = [string] $sgStorageGroup.Name DataBaseName = [string] $msMailStore.Name MB = "$($sgStorageGroup.Name)\\$($msMailStore.Name)" Path = [string] $msMailStoreFileName FileSize = "$([math]::round($msMailStoreFile.FileSize/1048576,0)) MB" WhiteSpace = "" RetainedMailbox = "" RetainedMailboxSize = "" DeletedMailbox = "" DeletedMailboxSize = "" DeletedItems = "" DeletedItemsSize = "" } } write-verbose "retrieved information for $($XCdatabase.MB)" $XCDatabases += $XCdatabase } return $XCdatabases | sort MB } Function GetMBStoreMaintenance ($Computername){ $MBMaintInfo = @{} $WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::UtcNow.AddDays(-1)) $Filter = "Logfile='Application' and SourceName = 'MSExchangeIS Mailbox Store' and TimeWritten >='" + $WmidtQueryDT + "'" $Events = (Get-WmiObject -Computername $ComputerName -class Win32_NTLogEvent -Filter $Filter | sort $_.TimeWritten -Descending) foreach ($Event in $Events){ write-verbose "getting details of Event $($Event.Eventcode)" switch ($Event.Eventcode){ '1207'{ #Cleanup Item Recovery $itemsremovedStart = $Event.Insertionstrings[0] $itemsremovedSizeStart = $Event.Insertionstrings[1] $itemsremovedEnd = $Event.Insertionstrings[2] $itemsremovedSizeEnd = $Event.Insertionstrings[3] $MB = $Event.Insertionstrings[4] write-verbose "For: $MB Item Cleanup details" write-verbose "Begin: $itemsremovedStart items with a total size of $itemsremovedStartSize KB" write-verbose "End: $itemsremovedEnd items with a total size of $itemsremovedEndSize KB" if (-not $MBMaintInfo.ContainsKey($MB)){ $MBMaintInfo.add($MB,@{}) $MBMaintInfo.$MB.Name = $MB } if (-not $MBMaintInfo.$MB.ContainsKey("DeletedItems")){$MBMaintInfo.$MB.Add("DeletedItems",$itemsremovedEnd)} if (-not $MBMaintInfo.$MB.ContainsKey("DeletedItemsSize")){$MBMaintInfo.$MB.Add("DeletedItemsSize","$itemsremovedSizeEnd KB")} } '1221'{ #Online Defrag Whitespace $WhiteSpace = $Event.Insertionstrings[0] $MB = $Event.Insertionstrings[1] write-verbose "For: $MB Online Defrag details" write-verbose "Defrag has freed up $WhiteSpace MB" if (-not $MBMaintInfo.ContainsKey($MB)){ $MBMaintInfo.add($MB,@{}) $MBMaintInfo.$MB.Name = $MB } if (-not $MBMaintInfo.$MB.ContainsKey("WhiteSpace")){$MBMaintInfo.$MB.Add("WhiteSpace","$WhiteSpace MB")} } '9535'{ #Cleanup Deleted Mailboxes $mbremoved = $Event.Insertionstrings[0] $mbremovedSize = $Event.Insertionstrings[1] $mbretained = $Event.Insertionstrings[2] $mbretainedSize = $Event.Insertionstrings[3] $MB = $Event.Insertionstrings[4] write-verbose "For: $MB Mailbox Cleanup details" write-verbose "Removed: $mbremoved mailboxes with a total size of $mbremovedSize KB" write-verbose "Retained: $mbretained mailboxes with a total size of $mbretainedSize KB" if (-not $MBMaintInfo.ContainsKey($MB)){ $MBMaintInfo.add($MB,@{}) $MBMaintInfo.$MB.Name = $MB } if (-not $MBMaintInfo.$MB.ContainsKey("DeletedMailbox")){$MBMaintInfo.$MB.Add("DeletedMailbox",$mbremoved)} if (-not $MBMaintInfo.$MB.ContainsKey("DeletedMailboxSize")){$MBMaintInfo.$MB.Add("DeletedMailboxSize","$mbremovedSize KB")} if (-not $MBMaintInfo.$MB.ContainsKey("RetainedMailbox")){$MBMaintInfo.$MB.Add("RetainedMailbox",$mbretained)} if (-not $MBMaintInfo.$MB.ContainsKey("RetainedMailboxSize")){$MBMaintInfo.$MB.Add("RetainedMailboxSize","$mbretainedSize KB")} } 'default'{write-verbose "event $($Event.Eventcode) not defined"} } } return $MBMaintInfo | Sort Name } } end{ $Global:XCserverInfo | sort Server, StorageGroup, DatabaseName }
PowerShellCorpus/PoshCode/Get-WMIVersions_2.ps1
Get-WMIVersions_2.ps1
#Requires -Version 2 param ( $Credential, $ComputerName ) # The official way to detect .NET versions is to look at their known location on the hard drive as per # this article: http://msdn.microsoft.com/en-us/kb/kb00318785.aspx # thanks to David M (http://twitter.com/makovec) for the WQL $query = "select name from win32_directory where name like 'c:\\\\windows\\\\microsoft.net\\\\framework\\\\v%'" $res = Get-WmiObject -query $query -Credential $Credential -ComputerName $ComputerName | ForEach-Object { Split-Path $_.name -Leaf } | # returns directories Where-Object { $_ -like 'v*' } | # only include those that start with v ForEach-Object { [system.version]( $_ -replace "^v" ) } # remove "v" from the string and convert to version object # Create hashtable with computername and version details $prop = @{ ComputerName = $ComputerName V1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 0 } ) { $true } } V1_1Present = &{ if ( $res | Where-Object { $_.Major -eq 1 -and $_.Minor -eq 1 } ) { $true } } V2Present = &{ if ( $res | Where-Object { $_.Major -eq 2 -and $_.Minor -eq 0 } ) { $true } } V3_5Present = &{ if ( $res | Where-Object { $_.Major -eq 3 -and $_.Minor -eq 5 } ) { $true } } V4Present = &{ if ( $res | Where-Object { $_.Major -eq 4 -and $_.Minor -eq 0 } ) { $true } } VersionDetails = $res } # Create and output PSobject using hashtable New-Object PSObject -Property $prop
PowerShellCorpus/PoshCode/Get-WebFile _1.1.ps1
Get-WebFile _1.1.ps1
## Get-WebFile.ps1 (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## - added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## #function wget { param( $url = (Read-Host "The URL to download"), $fileName ) $req = [System.Net.HttpWebRequest]::Create($url); $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName)) { # if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not ))) [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($res.StatusCode -eq 200) { $reader = new-object System.IO.StreamReader $res.GetResponseStream() $writer = new-object System.IO.StreamWriter $fileName # TODO: stick this in a loop and give progress reports $writer.Write($reader.ReadToEnd()) $reader.Close(); $writer.Close(); } $res.Close(); ls $fileName #}
PowerShellCorpus/PoshCode/PS2WCF_6.ps1
PS2WCF_6.ps1
<# .SYNOPSIS Functions to call WCF Services With PowerShell. .NOTES Version 1.2 11.02.2012 Requires Powershell v2 and .NET 3.5 Original version by Christian Glessner Blog: http://www.iLoveSharePoint.com Twitter: http://twitter.com/cglessner Codeplex: http://codeplex.com/iLoveSharePoint PowerShell v2.0 modification by Justin Dearing Blog: http://justaprogrammer.net Twitter: http://twitter.com/zippy1981 .LINK Blog describing original version: http://www.ilovesharepoint.com/2008/12/call-wcf-services-with-powershell.html Authoritative version of this fork: https://github.com/justaprogrammer/PowerShellWCF Posted to PoshCode.org http://poshcode.org/?lang=&q=PS2WCF #> # load WCF assemblies Add-Type -AssemblyName "System.ServiceModel" Add-Type -AssemblyName "System.Runtime.Serialization" <# .SYNOPSIS Get metadata of a service .DESCRIPTION Parses a wsdl or mex and generates a WsdlImporter object from it. .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc/mex' .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc' -HttpGet .EXAMPLE Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc?wsdl' -HttpGet #> function global:Get-WsdlImporter([CmdletBinding()][Parameter(Mandatory=$true, ValueFromPipeline=$true)][string]$WsdlUrl, [switch]$HttpGet) { if($HttpGet) { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet } else { $local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange } $mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient([Uri]$WsdlUrl, $mode); $mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue $metadataSet = $mexClient.GetMetadata() $wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet) return $wsdlImporter } <# .SYNOPSIS Generate wcf proxy types .DESCRIPTION Examines a web services meta data (wsdl or mex) and generates the types for the client proxy, as well as request and response contracts. .EXAMPLE $proxyType = Get-WcfProxyType $wsdlImporter $endpoints = $wsdlImporter.ImportAllEndpoints(); $proxy = New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address); #> function global:Get-WcfProxyType( [CmdletBinding()] [Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter, [Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl, [string] $proxyPath ) { switch ($PsCmdlet.ParameterSetName) { "WsdlUrl" { $WsdlImporter = Get-WsdlImporter $WsdlUrl trap [Exception] { $WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet continue } break } "WsdlImporter" { break } } $generator = new-object System.ServiceModel.Description.ServiceContractGenerator foreach($contractDescription in $wsdlImporter.ImportAllContracts()) { [void]$generator.GenerateServiceContractType($contractDescription) } $parameters = New-Object System.CodeDom.Compiler.CompilerParameters if($proxyPath -eq $null) { $parameters.GenerateInMemory = $true } else { $parameters.OutputAssembly = $proxyPath } $providerOptions = New-Object "Collections.Generic.Dictionary[String,String]" [void]$providerOptions.Add("CompilerVersion","v3.5") $compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions) $result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit); if($result.Errors.Count -gt 0) { throw "Proxy generation failed" } return $result.CompiledAssembly.GetTypes() | Where-Object {$_.BaseType.IsGenericType -and $_.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" } } <# .SYNOPSIS Generate wcf proxy .DESCRIPTION Generate wcf proxy in a manner similar to a Get-WebServiceProxy .EXAMPLE $proxy = Get-WcfProxy 'http://localhost.fiddler:14232/EchoService.svc/mex' $proxy.Echo("Justin Dearing"); .EXAMPLE $proxy = Get-WcfProxy 'net.tcp://localhost:8732/EchoService/mex' 'net.tcp://localhost:8732/EchoService/' (New-Object System.ServiceModel.NetTcpBinding) $proxy.Echo("Justin Dearing"); #> function global:Get-WcfProxy( [CmdletBinding()] [Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $WsdlImporter, [Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $WsdlUrl, [Parameter(Position=1, Mandatory=$false)][string] $EndpointAddress = $null, [Parameter(Position=2, Mandatory=$false)][System.ServiceModel.Channels.Binding] $Binding = $null ) { if ($Binding -ne $null -and [string]::IsNullOrEmpty($EndpointAddress)) { throw New-Object ArgumentNullException '$EndPointAddress', 'You cannot set $Binding without setting $EndpointAddress.' } switch ($PsCmdlet.ParameterSetName) { "WsdlUrl" { $WsdlImporter = Get-WsdlImporter $WsdlUrl trap [Exception] { $WsdlImporter = Get-WsdlImporter $WsdlUrl -HttpGet continue } break } } $proxyType = Get-WcfProxyType $wsdlImporter; if ([string]::IsNullOrEmpty($EndpointAddress)) { $endpoints = $WsdlImporter.ImportAllEndpoints(); $Binding = $endpoints[0].Binding; $EndpointAddress = $endpoints[0].Address; } return New-Object $proxyType($Binding, $EndpointAddress); }
PowerShellCorpus/PoshCode/USB Script backup_3.ps1
USB Script backup_3.ps1
<# .SYNOPSIS Backup-ToUSB.ps1 (Version 2.2, 9 Jan 2012) .DESCRIPTION This script will backup recently changed *.ps1,*.psm1,*.psd1 files from any selected folder (default is $pwd) to any number of inserted USB devices, on which an archive folder 'PSarchive' will be created if it does not already exist. As a USB hard disk is a Type 3 device (similar to the system disk), use the -Unit D switch (drive letter 'D' for example) to distinguish such a unit and add it to the list of selected devices. .EXAMPLE Invoke-Expression ".\\Backup-ToUsb.ps1 -Unit D $args" Add this line in 'function Backup' in $profile and it will add the USB Hard Disk 'D' as the standard backup device. .EXAMPLE .\\Backup-ToUSB.ps1 -type ps1 -v Select *.ps1 files to be archived. 'Verbose' will display the name of each file processed. Using the '-Debug' switch shows the time difference that has tagged any file for archive. .NOTES The author may be contacted via www.SeaStarDevelopment.Bravehost.com #> param ([String]$types = 'ps1', [String]$folder = $pwd, [String]$unit = $null, [Switch]$debug, [Switch]$verbose) if ($verbose) { $verbosePreference = 'Continue' } if ($debug) { $debugPreference = 'Continue' } $drive = '-<BLANK>-' if ($types -notmatch '^ps1|psd1|psm1|ps\\*$') { #Adjust to suit. Write-Warning "Invalid filetype ($types): ps1, psm1, psd1 only." exit 1 } if (!(Test-path $folder -pathType Container )) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$folder is not a directory - resubmit." exit 3 } $filter = 'DriveType = 2' if ($unit -match '^[d-z]$') { #Allow any single letter drive unit here. $filter = "DriveType = 2 OR (DriveType = 3 AND DeviceID = '" + "$unit" + ":')" } function copyFile ([string]$value) { Copy-Item -Path $value -Destination $newFolder -Force Write-Verbose "--> Archiving file: $value" $SCRIPT:files++ } Get-WMIObject Win32_LogicalDisk -filter $filter | Select-Object VolumeName, DriveType, FreeSpace, DeviceID | Where-Object {$_.VolumeName -ne $null} | foreach { $vol = $_.VolumeName $drive = $_.DeviceID + '\\' $type = $_.DriveType [int]$free = $_.FreeSpace / 1MB Write-Verbose "Scanning USB devices - Drive = [$drive] Name = $vol, Free = $free Mb" if (!(Test-Path $drive)) { Write-Warning "Error on drive $drive - restart." [System.Media.SystemSounds]::Hand.Play() exit 4 } [int]$SCRIPT:files = 0 #Reset counter for each new drive. $newFolder = $drive + "PSarchive" #Check if folder exists. if (!(Test-Path $newFolder)) { New-Item -path ($drive) -name PSarchive -type directory | Out-Null } (Get-ChildItem $folder -filter "*.$types") | foreach { $checkFile = Join-Path ($drive + 'PSArchive') $_ if (Test-path $checkFile) { $lwtHdd = $_.LastWriteTime #HDD time last written. $lwtUsb = (Get-Item $checkFile).LastWriteTime if ($lwtHdd -gt $lwtUsb) { Write-Debug "(HDD) $lwtHdd (USB) $LwtUsb $_" copyFile $_ } } else { #New file, so archive it anyway. Write-Debug "(HDD) $($_.LastWriteTime) (USB Archiving new file) $_" copyFile $_ } } $print = "Backup to USB drive [{0}] (Volume = {2}) completed; {1} files copied." -f $drive, $SCRIPT:files, $vol Write-Host "--> $print" } if ($drive -eq '-<BLANK>-') { [System.Media.SystemSounds]::Asterisk.Play() Write-Warning "No USB drive detected - Insert a device and resubmit." }
PowerShellCorpus/PoshCode/Get-AclMisconfiguration..ps1
Get-AclMisconfiguration..ps1
##############################################################################\n##\n## Get-AclMisconfiguration\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\nDemonstration of functionality exposed by the Get-Acl cmdlet. This script\ngoes through all access rules in all files in the current directory, and\nensures that the Administrator group has full control of that file.\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Get all files in the current directory\nforeach($file in Get-ChildItem)\n{\n ## Retrieve the ACL from the current file\n $acl = Get-Acl $file\n if(-not $acl)\n {\n continue\n }\n\n $foundAdministratorAcl = $false\n\n ## Go through each access rule in that ACL\n foreach($accessRule in $acl.Access)\n {\n ## If we find the Administrator, Full Control access rule,\n ## then set the $foundAdministratorAcl variable\n if(($accessRule.IdentityReference -like "*Administrator*") -and\n ($accessRule.FileSystemRights -eq "FullControl"))\n {\n $foundAdministratorAcl = $true\n }\n }\n\n ## If we didn't find the administrator ACL, output a message\n if(-not $foundAdministratorAcl)\n {\n "Found possible ACL Misconfiguration: $file"\n }\n}
PowerShellCorpus/PoshCode/Out-Balloon.ps1
Out-Balloon.ps1
<# .Synopsis Makes a baloon tip in the notification area .Description With just a few arguments, it is easy to make some text appear in a little balloon. You can specify an icon file (*.ico) with the -icon argument, if you don't then the embedded ! icon is used. It's blue. out-balloon accepts pipeline input, strings only please. It blocks for the duration of the balloon display, 3 seconds by default. Simple fixes for this are welcome. timeout should be an integer value. INSTALLATION: um, save this text in a file named out-balloon.ps1 in your path .Example out-balloon "hey, your job is done." -icon "C:\\Program Files\\Microsoft Office\\Office12\\MYSL.ICO" "job done." | out-balloon #> param( [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)] [Alias('output')] [string]$text, [string]$icon, [int32]$timeout = 3 ) begin { $not = new-object System.Windows.Forms.NotifyIcon if ($icon -eq $null) { #create icon object from embedded string $qmark_icon_string = ` "AAABAAEAgIAAAAEAIAAoCAEAFgAAACgAAACAAAAAAAEAAAEAIAAAAAAAAAgBAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAANHR0gfT09Qp1NTVOtXV1kbW1tdS19fYYNfX2G7X19h619fYetfX2G7W1tdg1dXW" + ` "UtTU1UbT09Q60dHSKdDQ0QcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0tLT" + ` "DNXV1j/Y2Nho29vbjd3d3bPf39/b4ODh/OLi4//j4+T/5OTl/+Xl5v/m5uf/5ubn/+bm5//m5u" + ` "f/5ubn/+Xl5v/k5OX/4+Pk/+Li4//g4OH/39/f/N3d3dvb29uz2NjYjdXV1mjS0tM/0NDRDAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANLS0wjW1t" + ` "dA2tragd7e3sPh4eL55OTl/+fn6P/p6er/7Ozt/+7u7//w8PD/8vLy//Pz8//09PT/9fX1//b2" + ` "9v/29vb/9vb2//b29v/29vb/9fX1//T09P/z8/P/8vLy//Dw8P/u7u//7Ozt/+np6v/n5+j/5O" + ` "Tl/+Hh4v/e3t752traw9bW14HS0tNAz8/QCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1NTVE9nZ" + ` "2Wrd3d274eHi9uXl5v/p6er/7e3u//Dw8P/z8/P/9vb2//n5+f/8/Pz//v7+//7+/v/+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/8" + ` "/Pz/+fn5//b29v/z8/P/8PDw/+3t7v/p6er/5eXm/+Hh4v/d3d322dnZu9TU1WrPz9ATAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADS0tMH2N" + ` "jYUt3d3a/i4uP55+fo/+zs7f/w8PD/9PT0//j4+P/8/Pz//v7+//7+/v/+/v7//v7+//7+/v/+" + ` "/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//" + ` "7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//Pz8//j4+P/09PT/8PDw/+zs7f/n5+j/" + ` "4uLj/93d3fnY2Niv0tLTUs3NzgcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV" + ` "1dYl29vbl+Dg4e7m5uf/7Ozt//Hx8f/29vb/+/v7//7+/v/+/v7//v7+//7+/v/+/v7//v7+//" + ` "7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/" + ` "/v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v" + ` "/+/v7/+/v7//b29v/x8fH/7Ozt/+bm5//g4OH/29vb7tXV1pfQ0NElAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAADW1tcs3d3dpePj5Pzp6er/7+/v//X19f/7+/v//v7+//7+/v/+/v7//v7+//7+/v/+/v7/" + ` "/v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v" + ` "/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+" + ` "//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/7+/v/9fX1/+/v7//p6er/4+Pk/93d3fzW1t" + ` "el0NDRLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAADW1tcz3t7ereTk5f3r6+z/8fHx//j4+P/+/v7//v7+//7+/v/+/v7//v7+//7+/v" + ` "/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/vz/+fPr" + ` "//Dk0f/p1rj/4sqk/92/kf/dv5H/4sqk/+nWuP/w5NH/+fPr//7+/P/+/v7//v7+//7+/v/+/v" + ` "7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//j4" + ` "+P/x8fH/6+vs/+Tk5f/e3t791tbXrdDQ0TMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAADV1dYf3d3druTk5f7r6+z/8vLy//n5+f/+/v7//v7+//7+/v/+/v7//v7+" + ` "//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//Ln1v/bvY7/yp5Z/76GMP+2dh" + ` "T/sm0D/7FsAP+ybQD/sm0A/7JtAP+ybQD/sm0A/7JtAP+ybQD/sm0A/7JtAP+xbAD/sWwA/7Jt" + ` "A/+1dhT/voYw/8qdWf/bvY7/8ufW//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/5+fn/8vLy/+vr7P/k5OX/3d3d/tXV1q7Ozs8fAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAADT09QG29vbeuLi4/Xq6uv/8vLy//n5+f/+/v7//v7+//7+/v/+/v" + ` "7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/0697/1K93/72FL/+xbgf/sGwA/7Bs" + ` "AP+xbAD/sWwA/7JtAP+ybQD/sm0A/7JuAP+ybgD/sm4A/7JuAP+ybgD/sm4A/7JuAP+ybgD/sm" + ` "4A/7JtAP+ybQD/sm0A/7FsAP+xbAD/sGwA/7BsAP+vawD/sW4H/72EL//Trnf/9Ove//7+/v/+" + ` "/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/+fn5//Ly8v/q6uv/4uLj/9" + ` "vb2/XT09R6zMzNBgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2NjYQ+Dg4dfo6On/8PDw//j4+P/+/v7//v7+//7+" + ` "/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+/+/iz//FlUv/sW8K/69qAP+vawD/r2" + ` "sA/7BsAP+xbAD/sWwA/7JtAP+ybQD/sm4A/7JuAP+ybgD/s24A/7NuAP+zbgD/s24A/7NuAP+z" + ` "bgD/s24A/7NuAP+zbgD/sm4A/7JuAP+ybgD/sm0A/7JtAP+xbAD/sWwA/7BsAP+vawD/r2sA/6" + ` "9qAP+uaQD/sW8K/8WVS//v4s///v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/" + ` "/v7+//j4+P/w8PD/6Ojp/+Dg4f/Y2NjX0NDRQwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1NTVDt3d3aLk5OX/7e3u//b29v/+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/+PPr/86mav+zdBT/rmkA/65pAP+v" + ` "agD/r2sA/7BsAP+wbAD/sWwA/7FsAP+ybQD/sm0A/7BsAP+wawD/r2oA/65oAP+taAD/rWgA/6" + ` "xnAP+sZwD/rGYA/6xmAP+sZwD/rGcA/61oAP+taAD/rmgA/69qAP+vawD/sGwA/7JsAP+xbAD/" + ` "sWwA/7BsAP+wbAD/r2sA/69qAP+uaQD/rmkA/61pAP+ycxT/zqZq//jz6//+/v7//v7+//7+/v" + ` "/+/v7//v7+//7+/v/+/v7//v7+//7+/v/29vb/7e3u/+Tk5f/d3d3/1NTVosvLzA4AAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANfX2DDg4OHa6enq//Ly8v/7" + ` "+/v//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/7+HN/7yFMv+saAD/rWkA/6" + ` "1pAP+uaQD/r2oA/69rAP+wbAD/sGwA/7BrAP+vagD/rWgA/6xmAP+rZgD/q2YA/6xnAP+sZwD/" + ` "rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6tmAP" + ` "+rZgD/q2YA/6xmAP+taAD/rmkA/69rAP+wbAD/r2sA/69qAP+uaQD/rWkA/61pAP+saAD/rGcA" + ` "/7uEMv/v4c3//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/7+/v/8vLy/+np6v/g4O" + ` "H/19fY2s/P0DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADb29to4+Pk9+" + ` "3t7v/29vb//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/69zE/7mAK/+sZwD/" + ` "rGgA/6xoAP+taQD/rmkA/69qAP+vawD/rmkA/61oAP+sZgD/q2YA/6xnAP+sZwD/rGcA/6xnAP" + ` "+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA" + ` "/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+rZgD/q2YA/6xmAP+taAD/rmkA/69qAP+uaQ" + ` "D/rWkA/6xoAP+saAD/rGcA/6pmAP+5gCv/69zE//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+" + ` "/v/+/v7/9vb2/+3t7v/j4+T/29vb99HR0moAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADT09QP" + ` "3d3dqubm5//w8PD/+vr6//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/7eDL/7Z6JP" + ` "+qZQD/q2YA/6xnAP+saAD/rWkA/65pAP+uaQD/rWgA/6tmAP+sZwD/rGcA/6xnAP+sZwD/rGcA" + ` "/6xnAP+sZwD/rGcA/6xnAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saA" + ` "D/rGgA/6xoAP+saAD/rGgA/6xoAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xn" + ` "AP+rZgD/q2YA/61oAP+taAD/rWkA/6xoAP+sZwD/q2YA/6plAP+pZAD/tnok/+3gy//+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/+/v7/+vr6//Dw8P/m5uf/3d3d/9PT1KrKyssPAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAA1dXWHN/f4NTp6er/8/Pz//39/f/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//Pr3" + ` "/8OUTf+pZAD/qmUA/6pmAP+sZwD/rGgA/6xoAP+saAD/rGYA/6tmAP+sZwD/rGcA/6xnAP+sZw" + ` "D/rGcA/6xnAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xo" + ` "AP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rG" + ` "cA/6xnAP+sZwD/rGcA/6xnAP+sZwD/q2YA/6tmAP+rZgD/q2cA/6xoAP+sZwD/qmYA/6plAP+p" + ` "ZAD/qGQA/8OTTf/8+vf//v7+//7+/v/+/v7//v7+//7+/v/+/v7//f39//Pz8//p6er/39/g/9" + ` "XV1tTMzM0cAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAANfX2Cjh4eLh6+vs//X19f/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v" + ` "7//v7+/9q8kf+raAf/qGQA/6lkAP+qZQD/q2YA/6xnAP+sZwD/q2YA/6xnAP+sZwD/rGcA/6xn" + ` "AP+sZwD/rGcA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rWkA/61pAP+taQD/rW" + ` "kA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rGgA/6xoAP+s" + ` "aAD/rGgA/6xoAP+saAD/rGgA/6xoAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6xnAP+rZgD/q2YA/6" + ` "tmAP+rZgD/qmUA/6lkAP+oZAD/qGMA/6pnB//avJH//v7+//7+/v/+/v7//v7+//7+/v/+/v7/" + ` "/v7+//X19f/r6+z/4eHi/9fX2OHNzc4oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAADY2Ng34uLj7O3t7v/39/f//v7+//7+/v/+/v7//v7+//7+" + ` "/v/+/v7//v7+//jy6f+1eib/qGMA/6hkAP+pZAD/qmUA/6pmAP+rZgD/q2YA/6xnAP+sZwD/rG" + ` "cA/6xnAP+sZwD/rGgA/6xoAP+saAD/rGgA/6xoAP+saAD/rWkA/61pAP+taQD/rWkA/61pAP+t" + ` "aQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/6" + ` "1pAP+taQD/rWkA/61pAP+taQD/rWkA/6xoAP+saAD/rGgA/6xoAP+saAD/rGgA/6xnAP+sZwD/" + ` "rGcA/6xnAP+sZwD/q2YA/6tmAP+qZgD/qmUA/6lkAP+oZAD/qGMA/6diAP+0eib/+PLp//7+/v" + ` "/+/v7//v7+//7+/v/+/v7//v7+//f39//t7e7/4uLj/9jY2OzOzs83AAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2dnZSePj5PTu7u//+Pj4//7+/v/+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/kz7D/qWYG/6diAP+oYwD/qGQA/6lkAP+qZQD/q2YA/6xnAP+s" + ` "ZwD/rGcA/6xnAP+sZwD/rGgA/6xoAP+saAD/rGgA/6xoAP+taQD/rWkA/61pAP+taQD/rWkA/6" + ` "1pAP+taQD/rWkA/65pAP+uaQD/rmkA/65pAP+uaQD/rmkA/65pAP+uaQD/rmkA/65pAP+uaQD/" + ` "rmkA/65pAP+uaQD/rmkA/61pAP+taQD/rWkA/61pAP+taQD/rWkA/61pAP+taQD/rGgA/6xoAP" + ` "+saAD/rGgA/6xoAP+sZwD/rGcA/6xnAP+sZwD/rGcA/6tmAP+rZgD/qWQA/6hkAP+oYwD/p2IA" + ` "/6ZhAP+oZQb/5M+w//7+/v/+/v7//v7+//7+/v/+/v7//v7+//j4+P/u7u//4+Pk/9nZ2fTOzs" + ` "9JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANnZ2Unj4+T67u7v//n5+f/+" + ` "/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7/x5td/6VgAP+mYQD/p2IA/6hjAP+oZAD/qmUA/6" + ` "tmAP+sZwD/rGcA/6xnAP+sZwD/rGgA/6xoAP+saAD/rGgA/61pAP+taQD/rWkA/61pAP+taQD/" + ` "rWkA/61pAP+uaQD/rmkA/65pAP+uaQD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP" + ` "+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/rmkA/65pAP+uaQD/rmkA/61pAP+taQD/rWkA" + ` "/61pAP+taQD/rWkA/61pAP+saAD/rGgA/6xoAP+saAD/rGcA/6xnAP+sZwD/rGcA/6tmAP+rZg" + ` "D/qWUA/6hjAP+nYgD/pmEA/6VgAP+kXwD/x5td//7+/v/+/v7//v7+//7+/v/+/v7//v7+//n5" + ` "+f/u7u//4+Pk/9nZ2frOzs9JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADY2Ng34+Pk9O" + ` "7u7//6+vr//v7+//7+/v/+/v7//v7+//7+/v/+/v7/+vbv/7J2If+lYAD/pmEA/6diAP+nYgD/" + ` "qWQA/6tmAP+sZwD/rGcA/6xnAP+sZwD/rGgA/6xoAP+saAD/rGgA/61pAP+taQD/rWkA/61pAP" + ` "+taQD/rmkA/65pAP+uaQD/rmkA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA" + ` "/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vag" + ` "D/rmkA/65pAP+uaQD/rmkA/61pAP+taQD/rWkA/61pAP+taQD/rGgA/6xoAP+saAD/rGgA/6xn" + ` "AP+sZwD/rGcA/6xnAP+rZgD/q2YA/6hjAP+nYgD/pmEA/6VgAP+kXwD/sXYh//r27//+/v7//v" + ` "7+//7+/v/+/v7//v7+//r6+v/u7u//4+Pk/9jY2PTNzc43AAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "19fYKeLi4+zu7u//+fn5//7+/v/+/v7//v7+//7+/v/+/v7//v7+//bu4/+raxD/pF8A/6VgAP" + ` "+mYQD/p2IA/6pkAP+rZgD/rGcA/6xnAP+sZwD/rGgA/6xoAP+saAD/rGgA/61pAP+taQD/rWkA" + ` "/61pAP+taQD/rmkA/65pAP+uaQD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vag" + ` "D/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69q" + ` "AP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+uaQD/rmkA/65pAP+taQD/rWkA/61pAP+taQD/rW" + ` "kA/6xoAP+saAD/rGgA/6xoAP+sZwD/rGcA/6xnAP+rZgD/q2YA/6lkAP+mYQD/pWAA/6RfAP+k" + ` "XwD/qmoQ//bu4//+/v7//v7+//7+/v/+/v7//v7+//n5+f/u7u//4uLj/9fX2OzMzM0pAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAANXV1hvh4eLh7e3u//j4+P/+/v7//v7+//7+/v/+/v7//v7+//7+/v/w5NL/qGUJ" + ` "/6RfAP+kXwD/pWAA/6dhAP+qZQD/rGcA/6xnAP+sZwD/rGcA/6xoAP+saAD/rGgA/61pAP+taQ" + ` "D/rWkA/61pAP+taQD/rmkA/65pAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69q" + ` "AP+vagD/r2oA/69rAP+vawD/r2sA/69rAP+vawD/r2sA/69rAP+vawD/r2sA/69rAP+vawD/r2" + ` "sA/69rAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA/65pAP+u" + ` "aQD/rWkA/61pAP+taQD/rWkA/61pAP+saAD/rGgA/6xoAP+sZwD/rGcA/6xnAP+sZwD/q2YA/6" + ` "llAP+mYAD/pF8A/6RfAP+jXgD/p2QJ//Dk0v/+/v7//v7+//7+/v/+/v7//v7+//j4+P/t7e7/" + ` "4eHi/9XV1uHKyssbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAADT09QO39/g1Ovr7P/39/f//v7+//7+/v/+/v7//v7+//7+/v/+/v" + ` "7/6Na9/6VhBP+jXgD/pF8A/6RfAP+mYQD/q2UA/6xnAP+sZwD/rGcA/6xoAP+saAD/rGgA/6xo" + ` "AP+taQD/rWkA/61pAP+taQD/rmkA/65pAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2" + ` "oA/69rAP+vawD/r2sA/69rAP+vawD/sGsA/7BrAP+wawD/sGsA/7BrAP+wawD/sGsA/7BrAP+w" + ` "awD/sGsA/7BrAP+wawD/sGsA/69rAP+vawD/r2sA/69rAP+vawD/r2oA/69qAP+vagD/r2oA/6" + ` "9qAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+taQD/rWkA/61pAP+saAD/rGgA/6xoAP+saAD/" + ` "rGcA/6xnAP+sZwD/q2YA/6tlAP+lYAD/pF8A/6NeAP+iXQD/pWAE/+jWvf/+/v7//v7+//7+/v" + ` "/+/v7//v7+//f39//r6+z/39/g/9PT1NTIyMkOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN3d3anp6er/9fX1//7+/v/+/v7//v7+//7+" + ` "/v/+/v7//v7+/+jWvf+kXgL/ol0A/6NeAP+kXwD/pmEA/6tmAP+sZwD/rGcA/6xnAP+saAD/rG" + ` "gA/6xoAP+taQD/rWkA/61pAP+taQD/rmkA/65pAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+v" + ` "agD/r2sA/69rAP+vawD/sGsA/7V1Ef+2dxT/tHIV/7JwFv+ycRb/snEW/7JxFv+ycRb/snEW/7" + ` "JxFv+ycRb/snEW/7JxFv+ycRb/snEW/7JxFv+ycRb/snAW/7JwFv+ycBb/snAW/7FuE/+qZAP/" + ` "qmQD/69rAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/rmkA/65pAP+taQD/rWkA/61pAP" + ` "+taQD/rGgA/6xoAP+saAD/rGcA/6xnAP+sZwD/q2YA/6tlAP+mYQD/o14A/6JdAP+iXAD/o14C" + ` "/+jWvf/+/v7//v7+//7+/v/+/v7//v7+//X19f/p6er/3d3d/9HR0qkAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADb29tp5ubn//Pz8//+/v7//v" + ` "7+//7+/v/+/v7//v7+//7+/v/u4tH/pGAE/6JcAP+iXQD/o14A/6ZhAP+rZgD/rGcA/6xnAP+s" + ` "ZwD/rGgA/6xoAP+saAD/rWkA/61pAP+taQD/rmkA/65pAP+vagD/r2oA/69qAP+vagD/r2oA/6" + ` "9qAP+vagD/r2sA/69rAP+wawD/sGsA/7BrAP+wbAD/9Ora////////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "//////697g/28WKP9vFij/r2oA/69rAP+vawD/r2oA/69qAP+vagD/r2oA/69qAP+vagD/r2oA" + ` "/65pAP+uaQD/rWkA/61pAP+taQD/rGgA/6xoAP+saAD/rGcA/6xnAP+sZwD/q2YA/6tmAP+lYA" + ` "D/ol0A/6JcAP+hXAD/o18E/+7i0f/+/v7//v7+//7+/v/+/v7//v7+//Pz8//m5uf/29vb/8/P" + ` "0GkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA19fYMePj5Pfw" + ` "8PD//f39//7+/v/+/v7//v7+//7+/v/+/v7/9Ozh/6ViCP+hXAD/olwA/6JdAP+mYQD/q2YA/6" + ` "xnAP+sZwD/rGcA/6xoAP+saAD/rGgA/61pAP+taQD/rWkA/65pAP+uaQD/r2oA/69qAP+vagD/" + ` "r2oA/69qAP+vagD/r2sA/69rAP+wawD/sGsA/7BsAP+wbAD/sGwA/7BsAP/06tr///////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////////////r3uD/bxYo/28WKP+vawD/sGsA/7BrAP+vawD/r2sA/69qAP+vag" + ` "D/r2oA/69qAP+vagD/r2oA/65pAP+uaQD/rWkA/61pAP+taQD/rGgA/6xoAP+saAD/rGcA/6xn" + ` "AP+sZwD/q2YA/6tmAP+lYAD/olwA/6FcAP+gWwD/pWEI//Ts4f/+/v7//v7+//7+/v/+/v7//f" + ` "39//Dw8P/j4+T/19fY98vLzDEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN" + ` "TU1Q3g4OHa7e3u//r6+v/+/v7//v7+//7+/v/+/v7//v7+//r28f+oZxD/oFsA/6FcAP+iXAD/" + ` "pWAA/6tmAP+sZwD/rGcA/6xoAP+saAD/rGgA/61pAP+taQD/rWkA/61pAP+uaQD/r2oA/69qAP" + ` "+vagD/r2oA/69qAP+vagD/r2sA/69rAP+wawD/sGsA/7BsAP+wbAD/sGwA/7FsAP+xbAD/sWwA" + ` "//Tq2v////////////////////////////////////////////////////////////////////" + ` "///////////////////////////////////////+ve4P9vFij/bxYo/69rAP+wbAD/sGwA/7Br" + ` "AP+wawD/r2sA/69rAP+vagD/r2oA/69qAP+vagD/r2oA/69qAP+uaQD/rWkA/61pAP+taQD/rW" + ` "kA/6xoAP+saAD/rGgA/6xnAP+sZwD/q2YA/6tmAP+lXwD/oVwA/6BbAP+gWgD/p2YQ//r28f/+" + ` "/v7//v7+//7+/v/+/v7/+vr6/+3t7v/g4OH/1NTV2sfHyA0AAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAA3d3dounp6v/29vb//v7+//7+/v/+/v7//v7+//7+/v/+/v7/r3Ih/6BaAP" + ` "+gWwD/oVwA/6ReAP+rZgD/rGcA/6xnAP+saAD/rGgA/6xoAP+taQD/rWkA/61pAP+uaQD/rmkA" + ` "/69qAP+vagD/r2oA/69qAP+vagD/r2sA/69rAP+wawD/sGsA/7BsAP+wbAD/sWwA/7FsAP+xbA" + ` "D/sWwA/7FsAP+xbAD/9Ora////////////////////////////////////////////////////" + ` "////////////////////////////////////////////////////////697g/28WKP9vFij/sG" + ` "sA/7FsAP+xbAD/sGwA/7BsAP+wawD/sGsA/69rAP+vawD/r2oA/69qAP+vagD/r2oA/69qAP+u" + ` "aQD/rmkA/61pAP+taQD/rWkA/6xoAP+saAD/rGgA/6xnAP+sZwD/q2YA/6tmAP+jXgD/oFsA/6" + ` "BaAP+fWQD/rXEh//7+/v/+/v7//v7+//7+/v/+/v7/9vb2/+np6v/d3d3/0NDRogAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAANjY2ETk5OX/8vLy//7+/v/+/v7//v7+//7+/v/+/v7//v7+" + ` "/8aaYP+fWQD/oFoA/6BbAP+jXgD/q2UA/6xnAP+sZwD/rGgA/6xoAP+saAD/rWkA/61pAP+taQ" + ` "D/rmkA/65pAP+vagD/r2oA/69qAP+vagD/r2oA/69rAP+wawD/sGsA/7BsAP+wbAD/sWwA/7Fs" + ` "AP+xbAD/sWwA/7FsAP+xbQD/sW0A/7FtAP/06tr///////////////////////////////////" + ` "/////////////////////////////////////////////////////////////////////////r" + ` "3uD/bxYo/28WKP+wawD/sWwA/7FsAP+xbAD/sWwA/7BsAP+wbAD/sGsA/7BrAP+vawD/r2oA/6" + ` "9qAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+taQD/rWkA/6xoAP+saAD/rGgA/6xnAP+sZwD/" + ` "q2YA/6tlAP+iXQD/oFoA/59ZAP+eWAD/xZpg//7+/v/+/v7//v7+//7+/v/+/v7/8vLy/+Tk5f" + ` "/Y2Nj/zMzNRAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADT09QG4ODh1+3t7v/7+/v//v7+//7+/v/+/v" + ` "7//v7+//7+/v/izrD/n1kA/59ZAP+gWgD/oVwA/6plAP+sZwD/rGcA/6xnAP+saAD/rGgA/61p" + ` "AP+taQD/rWkA/65pAP+uaQD/r2oA/69qAP+vagD/r2oA/69rAP+vawD/sGsA/7BrAP+wbAD/sG" + ` "wA/7FsAP+xbAD/sWwA/7FsAP+xbQD/sW0A/7JtAP+ybQD/sm0A//Tq2v//////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////+ve4P9vFij/bxYo/7BsAP+xbQD/sWwA/7FsAP+xbAD/sWwA/7BsAP+wbAD/" + ` "sGsA/7BrAP+vawD/r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+taQD/rWkA/6xoAP" + ` "+saAD/rGcA/6xnAP+sZwD/q2YA/6llAP+hWwD/n1kA/55YAP+eWQD/4s2w//7+/v/+/v7//v7+" + ` "//7+/v/7+/v/7e3u/+Dg4f/T09TXxsbHBgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANvb23ro6On/9vb2//7+" + ` "/v/+/v7//v7+//7+/v/+/v7/+PLr/6JeB/+eWAD/n1kA/6BaAP+oYwD/rGcA/6xnAP+sZwD/rG" + ` "gA/6xoAP+taQD/rWkA/61pAP+uaQD/r2oA/69qAP+vagD/r2oA/69qAP+vawD/r2sA/7BrAP+w" + ` "bAD/sGwA/7FsAP+xbAD/sWwA/7FsAP+xbQD/sW0A/7JtAP+ybQD/sm4A/7JuAP+ybgD/9Ora//" + ` "//////////////////////////////////////////////////////////////////////////" + ` "////////////////////////////////697g/28WKP9vFij/sWwA/7JtAP+xbQD/sW0A/7FsAP" + ` "+xbAD/sWwA/7FsAP+wbAD/sGwA/7BrAP+vawD/r2sA/69qAP+vagD/r2oA/69qAP+vagD/rmkA" + ` "/61pAP+taQD/rWkA/6xoAP+saAD/rGcA/6xnAP+sZwD/q2YA/6djAP+fWQD/nlgA/51YAP+hXg" + ` "f/+PLr//7+/v/+/v7//v7+//7+/v/29vb/6Ojp/9vb2//Ozs96AAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV1dYg4u" + ` "Lj9fDw8P/+/v7//v7+//7+/v/+/v7//v7+//7+/v+vdCb/nVgA/55YAP+fWQD/pWAA/6xnAP+s" + ` "ZwD/rGcA/6xoAP+saAD/rWkA/61pAP+taQD/rmkA/69qAP+vagD/r2oA/69qAP+vagD/r2sA/7" + ` "BrAP+wawD/sGwA/7BsAP+xbAD/sWwA/7FsAP+xbQD/sW0A/7JtAP+ybQD/sm4A/7JuAP+ybgD/" + ` "s24A/7NuAP/06tr///////////////////////////////////////////////////////////" + ` "/////////////////////////////////////////////////r3uD/bxYo/28WKP+xbQD/sm4A" + ` "/7JtAP+ybQD/sW0A/7FtAP+xbAD/sWwA/7FsAP+wbAD/sGwA/7BrAP+wawD/r2sA/69qAP+vag" + ` "D/r2oA/69qAP+vagD/rmkA/61pAP+taQD/rWkA/6xoAP+saAD/rGcA/6xnAP+sZwD/q2YA/6Rf" + ` "AP+eWAD/nVgA/5xXAP+vcyb//v7+//7+/v/+/v7//v7+//7+/v/w8PD/4uLj/9XV1vXIyMkgAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAN3d3a/q6uv/+Pj4//7+/v/+/v7//v7+//7+/v/+/v7/2LuT/5xXAP+dWAD/nlgA/6" + ` "FbAP+rZgD/rGcA/6xnAP+saAD/rGgA/6xoAP+taQD/rWkA/65pAP+uaQD/r2oA/69qAP+vagD/" + ` "r2oA/69rAP+wawD/sGsA/7BsAP+xbAD/sWwA/7FsAP+xbAD/sW0A/7JtAP+ybQD/sm4A/7JuAP" + ` "+zbgD/s24A/7NuAP+zbgD/s24A//Tq2v//////////////////////////////////////////" + ` "/////////////////////////////////////////////////////////////////+ve4P9vFi" + ` "j/bxYo/7JtAP+zbgD/sm4A/7JuAP+ybQD/sm0A/7FtAP+xbAD/sWwA/7FsAP+xbAD/sGwA/7Br" + ` "AP+wawD/r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+taQD/rGgA/6xoAP+saAD/rG" + ` "cA/6xnAP+rZgD/q2YA/6FbAP+dWAD/nFcA/5xWAP/XupP//v7+//7+/v/+/v7//v7+//j4+P/q" + ` "6uv/3d3d/9DQ0a8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAADW1tc05OTl//Ly8v/+/v7//v7+//7+/v/+/v7//v7+//z49f+gXAf/" + ` "nFYA/5xXAP+eWQD/qmQA/6xnAP+sZwD/rGgA/6xoAP+saAD/rWkA/61pAP+uaQD/rmkA/69qAP" + ` "+vagD/r2oA/69qAP+vawD/sGsA/7BrAP+wbAD/sWwA/7FsAP+xbAD/sW0A/7FtAP+ybQD/sm0A" + ` "/7JuAP+ybgD/s24A/7NuAP+zbgD/s24A/7RvAP+0bwD/9eva//////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "////////697g/28WKP9vFij/sm0A/7NuAP+zbgD/sm4A/7JuAP+ybQD/sm0A/7FtAP+xbQD/sW" + ` "wA/7FsAP+xbAD/sGwA/7BrAP+wawD/r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+t" + ` "aQD/rGgA/6xoAP+saAD/rGcA/6xnAP+rZgD/qWQA/51YAP+cVgD/m1UA/6BcB//8+PX//v7+//" + ` "7+/v/+/v7//v7+//Ly8v/k5OX/1tbX/8nJyjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN7e3q/r6+z/+fn5//7+/v/+/v7//v7+//7+/v" + ` "/+/v7/vYxM/5tVAP+cVgD/nFcA/6VgAP+sZwD/rGcA/6xnAP+saAD/rGgA/61pAP+taQD/rWkA" + ` "/65pAP+vagD/r2oA/69qAP+vagD/r2sA/7BrAP+wawD/sGwA/7FsAP+xbAD/sWwA/7FtAP+xbQ" + ` "D/sm0A/7JuAP+ybgD/s24A/7NuAP+zbgD/s24A/7RvAP+0bwD/tG8A/7RvAP/169r/////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////////////r3uD/bxYo/28WKP+zbgD/s24A/7NuAP+zbgD/s24A/7JuAP+y" + ` "bgD/sm0A/7FtAP+xbQD/sWwA/7FsAP+xbAD/sGwA/7BrAP+wawD/r2sA/69qAP+vagD/r2oA/6" + ` "9qAP+uaQD/rWkA/61pAP+taQD/rGgA/6xoAP+sZwD/rGcA/6xnAP+rZgD/pF8A/5xWAP+bVQD/" + ` "m1UA/7yLTP/+/v7//v7+//7+/v/+/v7/+fn5/+vr7P/e3t7/0NDRrwAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADW1tcs5OTl/vLy8v/+/v7//v7+" + ` "//7+/v/+/v7//v7+/+zey/+cVgD/m1UA/5xWAP+fWgD/q2YA/6xnAP+sZwD/rGgA/6xoAP+taQ" + ` "D/rWkA/61pAP+uaQD/r2oA/69qAP+vagD/r2oA/69rAP+wawD/sGsA/7BsAP+xbAD/sWwA/7Fs" + ` "AP+xbQD/sm0A/7JtAP+ybgD/sm4A/7NuAP+zbgD/s24A/7RvAP+0bwD/tG8A/7RvAP+1cAD/tX" + ` "AA//Xr2v//////////////////////////////////////////////////////////////////" + ` "/////////////////////////////////////////+ve4P9vFij/bxYo/7NuAP+0bwD/tG8A/7" + ` "NuAP+zbgD/s24A/7JuAP+ybgD/sm0A/7JtAP+xbQD/sWwA/7FsAP+xbAD/sGwA/7BrAP+wawD/" + ` "r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rWkA/61pAP+taQD/rGgA/6xoAP+sZwD/rGcA/6tmAP" + ` "+rZgD/n1kA/5tVAP+bVQD/m1UA/+zey//+/v7//v7+//7+/v/+/v7/8vLy/+Tk5f/W1tf+ycnK" + ` "LAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN3d3abr6+" + ` "z/+fn5//7+/v/+/v7//v7+//7+/v/+/v7/rHAj/5tVAP+bVQD/nFYA/6hjAP+sZwD/rGcA/6xo" + ` "AP+saAD/rGgA/61pAP+taQD/rmkA/69qAP+vagD/r2oA/69qAP+vawD/sGsA/7BrAP+wbAD/sW" + ` "wA/7FsAP+xbAD/sW0A/7JtAP+ybQD/sm4A/7NuAP+zbgD/s24A/7NuAP+0bwD/tG8A/7RvAP+1" + ` "cAD/tXAA/7VwAP+1cAD/9eva//////////////////////////////////////////////////" + ` "//////////////////////////////////////////////////////////697g/28WKP9vFij/" + ` "tG8A/7RvAP+0bwD/tG8A/7NuAP+zbgD/s24A/7NuAP+ybgD/sm0A/7JtAP+xbQD/sWwA/7FsAP" + ` "+xbAD/sGwA/7BrAP+wawD/r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rWkA/61pAP+saAD/rGgA" + ` "/6xoAP+sZwD/rGcA/6tmAP+nYgD/m1UA/5tVAP+aVAD/q3Aj//7+/v/+/v7//v7+//7+/v/5+f" + ` "n/6+vs/93d3f/Q0NGmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AADV1dYl4+Pk/PHx8f/+/v7//v7+//7+/v/+/v7//v7+/+jYwf+aVAD/m1UA/5tVAP+iXAD/rG" + ` "cA/6xnAP+sZwD/rGgA/6xoAP+taQD/rWkA/65pAP+uaQD/r2oA/69qAP+vagD/r2sA/69rAP+w" + ` "awD/sGwA/7FsAP+xbAD/sWwA/7FtAP+ybQD/sm0A/7JuAP+zbgD/s24A/7NuAP+0bwD/tG8A/7" + ` "RvAP+0bwD/tXAA/7VwAP+1cAD/tXAA/7ZxAP/169r/////////////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/r3uD/bxYo/28WKP+0bwD/tXAA/7RvAP+0bwD/tG8A/7RvAP+zbgD/s24A/7NuAP+ybgD/sm0A" + ` "/7JtAP+xbQD/sWwA/7FsAP+xbAD/sGwA/7BrAP+vawD/r2sA/69qAP+vagD/r2oA/65pAP+uaQ" + ` "D/rWkA/61pAP+saAD/rGgA/6xnAP+sZwD/rGcA/6tmAP+hWwD/m1UA/5pUAP+ZUwD/6NjB//7+" + ` "/v/+/v7//v7+//7+/v/x8fH/4+Pk/9XV1vzHx8glAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAANvb25Xp6er/+Pj4//7+/v/+/v7//v7+//7+/v/+/v7/rnMq/5lTAP+a" + ` "VAD/m1UA/6lkAP+sZwD/rGcA/6xoAP+saAD/rWkA/61pAP+taQD/rmkA/69qAP+vagD/r2oA/6" + ` "9qAP+vawD/sGsA/7BsAP+xbAD/sWwA/7FsAP+xbQD/sm0A/7JtAP+ybgD/s24A/7NuAP+zbgD/" + ` "tG8A/7RvAP+0bwD/tXAA/7VwAP+1cAD/tXAA/7ZxAP+2cQD/tnEA//Xr2v////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////+ve4P9vFij/bxYo/7RvAP+1cAD/tXAA/7VwAP+0bwD/tG8A/7RvAP+zbg" + ` "D/s24A/7NuAP+ybgD/sm0A/7JtAP+xbQD/sWwA/7FsAP+xbAD/sGwA/7BrAP+vawD/r2oA/69q" + ` "AP+vagD/r2oA/65pAP+taQD/rWkA/61pAP+saAD/rGgA/6xnAP+sZwD/q2YA/6hkAP+aVAD/mV" + ` "MA/5hSAP+tcyr//v7+//7+/v/+/v7//v7+//j4+P/p6er/29vb/83NzpUAAAAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAADS0tMH4ODh7e/v7//+/v7//v7+//7+/v/+/v7//v7+/+" + ` "vey/+ZUgD/mVMA/5pUAP+hWwD/rGcA/6xnAP+sZwD/rGgA/6xoAP+taQD/rWkA/65pAP+vagD/" + ` "r2oA/69qAP+vagD/r2sA/7BrAP+wbAD/sGwA/7FsAP+xbAD/sW0A/7JtAP+ybQD/sm4A/7NuAP" + ` "+zbgD/s24A/7RvAP+0bwD/tG8A/7VwAP+1cAD/tXAA/7ZxAP+2cQD/tnEA/7ZxAP+2cQD/9eva" + ` "//////////////////////////////////////////////////////////////////////////" + ` "//////////////////////////////////697g/28WKP9vFij/tXAA/7ZxAP+1cAD/tXAA/7Vw" + ` "AP+0bwD/tG8A/7RvAP+zbgD/s24A/7NuAP+ybgD/sm0A/7JtAP+xbQD/sWwA/7FsAP+wbAD/sG" + ` "wA/7BrAP+vawD/r2oA/69qAP+vagD/r2oA/65pAP+taQD/rWkA/6xoAP+saAD/rGcA/6xnAP+s" + ` "ZwD/q2YA/6BbAP+ZUwD/mFIA/5hRAP/r3sv//v7+//7+/v/+/v7//v7+/+/v7//g4OH/0tLT7c" + ` "TExQcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANjY2FLm5uf/9fX1//7+/v/+/v7/" + ` "/v7+//7+/v/+/v7/sHcw/5hSAP+ZUwD/mlQA/6ljAP+sZwD/rGcA/6xoAP+saAD/rWkA/61pAP" + ` "+taQD/rmkA/69qAP+vagD/r2oA/69rAP+wawD/sGsA/7BsAP+xbAD/sWwA/7FtAP+xbQD/sm0A" + ` "/7JuAP+zbgD/s24A/7NuAP+0bwD/tG8A/7RvAP+1cAD/tXAA/7VwAP+2cQD/tnEA/7ZxAP+2cQ" + ` "D/tnEA/7ZxAP/169r/////////////////////////////////////////////////////////" + ` "///////////////////////////////////////////////////r3uD/bxYo/28WKP+1cAD/tn" + ` "EA/7ZxAP+1cAD/tXAA/7VwAP+0bwD/tG8A/7RvAP+zbgD/s24A/7NuAP+ybgD/sm0A/7FtAP+x" + ` "bQD/sWwA/7FsAP+wbAD/sGsA/7BrAP+vawD/r2oA/69qAP+vagD/rmkA/61pAP+taQD/rWkA/6" + ` "xoAP+saAD/rGcA/6xnAP+rZgD/qGMA/5lTAP+YUgD/l1EA/7B3MP/+/v7//v7+//7+/v/+/v7/" + ` "9fX1/+bm5//Y2Nj/ysrLUgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3d3dr+zs7f" + ` "/7+/v//v7+//7+/v/+/v7//v7+//fx6f+YUgD/mFIA/5lTAP+fWQD/rGcA/6xnAP+sZwD/rGgA" + ` "/6xoAP+taQD/rWkA/65pAP+vagD/r2oA/69qAP+vagD/r2sA/7BrAP+wbAD/sWwA/7FsAP+xbA" + ` "D/sW0A/7JtAP+ybgD/s24A/7NuAP+zbgD/tG8A/7RvAP+0bwD/tXAA/7VwAP+1cAD/tnEA/7Zx" + ` "AP+2cQD/tnEA/7ZxAP+3cgD/t3IA//Xr2v////////////////////////////////////////" + ` "///////////////////////////////////////////////////////////////////+ve4P9v" + ` "Fij/bxYo/7VwAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7VwAP+0bwD/tG8A/7RvAP+zbgD/s24A/7" + ` "NuAP+ybgD/sm0A/7FtAP+xbAD/sWwA/7FsAP+wbAD/sGsA/69rAP+vagD/r2oA/69qAP+vagD/" + ` "rmkA/61pAP+taQD/rGgA/6xoAP+sZwD/rGcA/6xnAP+rZgD/n1kA/5hSAP+XUQD/mFEA//fx6f" + ` "/+/v7//v7+//7+/v/7+/v/7Ozt/93d3f/Pz9CvAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ` "ANTU1RPi4uP58fHx//7+/v/+/v7//v7+//7+/v/+/v7/xpxn/5dQAP+XUQD/mFIA/6hiAP+sZw" + ` "D/rGcA/6xoAP+saAD/rWkA/61pAP+taQD/rmkA/69qAP+vagD/r2oA/69rAP+wawD/sGwA/7Bs" + ` "AP+xbAD/sWwA/7FtAP+ybQD/sm4A/7JuAP+zbgD/s24A/7RvAP+0bwD/tG8A/7VwAP+1cAD/tX" + ` "AA/7ZxAP+2cQD/tnEA/7ZxAP+3cgD/t3IA/7dyAP+3cgD/9eva////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "//////////697g/28WKP9vFij/tnAA/7ZxAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7VwAP+0bwD/" + ` "tG8A/7RvAP+zbgD/s24A/7JuAP+ybgD/sm0A/7FtAP+xbAD/sWwA/7BsAP+wbAD/sGsA/69rAP" + ` "+vagD/r2oA/69qAP+uaQD/rWkA/61pAP+taQD/rGgA/6xoAP+sZwD/rGcA/6tmAP+nYgD/l1EA" + ` "/5dQAP+WTwD/xZxn//7+/v/+/v7//v7+//7+/v/x8fH/4uLj/9TU1fnFxcYTAAAAAAAAAAAAAA" + ` "AAAAAAAAAAAAAAAAAA2dnZaufn6P/29vb//v7+//7+/v/+/v7//v7+//7+/v+iYBP/l1AA/5dR" + ` "AP+bVQD/q2YA/6xnAP+sZwD/rGgA/6xoAP+taQD/rWkA/65pAP+vagD/r2oA/69qAP+vagD/r2" + ` "sA/7BrAP+wbAD/sWwA/7FsAP+xbQD/sm0A/7JtAP+ybgD/s24A/7NuAP+0bwD/tG8A/7RvAP+1" + ` "cAD/tXAA/7VwAP+2cQD/tnEA/7ZxAP+2cQD/t3IA/7dyAP+3cgD/t3IA/7dyAP/169r///////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////////////////r3uD/bxYo/28WKP+2cAD/t3IA/7ZxAP+2cQD/tnEA/7ZxAP" + ` "+1cAD/tXAA/7VwAP+0bwD/tG8A/7RvAP+zbgD/s24A/7JuAP+ybQD/sm0A/7FtAP+xbAD/sWwA" + ` "/7BsAP+wawD/r2sA/69qAP+vagD/r2oA/69qAP+uaQD/rWkA/61pAP+saAD/rGgA/6xnAP+sZw" + ` "D/q2YA/6tmAP+aVAD/l1AA/5ZPAP+hYBP//v7+//7+/v/+/v7//v7+//b29v/n5+j/2dnZ/8rK" + ` "y2oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADd3d297Ozt//v7+//+/v7//v7+//7+/v/+/v7/7d" + ` "/N/5ZPAP+XUAD/l1EA/6JdAP+taAH/snIS/61pAf+saAD/rWkA/61pAP+taQD/rmkA/69qAP+v" + ` "agD/r2oA/69rAP+wawD/sGwA/7FsAP+xbAD/sWwA/7FtAP+ybQD/sm4A/7NuAP+zbgD/s24A/7" + ` "RvAP+0bwD/tXAA/7VwAP+1cAD/tnEA/7ZxAP+2cQD/tnEA/7dyAP+3cgD/t3IA/7dyAP+3cgD/" + ` "uHMA//Xr2v////////////////////////////////////////////////////////////////" + ` "///////////////////////////////////////////+ve4P9vFij/bxYo/7ZwAP+3cgD/t3IA" + ` "/7ZxAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7VwAP+0bwD/tG8A/7NuAP+zbgD/s24A/7JuAP+ybQ" + ` "D/sW0A/7FsAP+xbAD/sWwA/7BsAP+wawD/r2sA/69qAP+vagD/r2oA/65pAP+taQD/rWkA/61p" + ` "AP+saAD/rGgA/61oAf+ychL/rGcB/6FcAP+XUAD/lk8A/5VPAP/s383//v7+//7+/v/+/v7/+/" + ` "v7/+zs7f/d3d3/z8/QvQAAAAAAAAAAAAAAAAAAAAAAAAAA0tLTCOHh4vfw8PD//v7+//7+/v/+" + ` "/v7//v7+//7+/v+4h0r/lU8A/5ZPAP+XUAD/qWQA/61oAv+5fyj/snIR/6xoAP+taQD/rWkA/6" + ` "5pAP+vagD/r2oA/69qAP+vagD/r2sA/7BrAP+wbAD/sWwA/7FsAP+xbQD/sm0A/7JuAP+ybgD/" + ` "s24A/7NuAP+0bwD/tG8A/7VwAP+1cAD/tXAA/7ZxAP+2cQD/tnEA/7ZxAP+3cgD/t3IA/7dyAP" + ` "+3cgD/uHMA/7hzAP+5cwD/9eva////////////////////////////////////////////////" + ` "////////////////////////////////////////////////////////////697g/28WKP9vFi" + ` "j/tnAA/7dyAP+3cgD/t3IA/7ZxAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7VwAP+0bwD/tG8A/7Nu" + ` "AP+zbgD/sm4A/7JuAP+ybQD/sW0A/7FsAP+xbAD/sGwA/7BrAP+vawD/r2oA/69qAP+vagD/r2" + ` "oA/65pAP+taQD/rWkA/6xoAP+saAD/snER/7l/KP+sZwL/qGQA/5ZPAP+VTwD/lE4A/7iHSv/+" + ` "/v7//v7+//7+/v/+/v7/8PDw/+Hh4v/S0tP3xMTFCAAAAAAAAAAAAAAAAAAAAADW1tdB5eXm//" + ` "T09P/+/v7//v7+//7+/v/+/v7//v7+/5xZCv+VTwD/lk8A/51WAP+sZwD/sG4M/72FMv+4fiX/" + ` "rGgA/61pAP+taQD/rmkA/69qAP+vagD/r2oA/69rAP+wawD/sGwA/7FsAP+xbAD/sWwA/7FtAP" + ` "+ybQD/sm4A/7NuAP+zbgD/tG8A/7RvAP+0bwD/tXAA/7VwAP+2cQD/tnEA/7ZxAP+2cQD/t3IA" + ` "/7dyAP+3cgD/t3IA/7hzAP+4cwD/uXMA/7lzAP/169r///////////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///r3uD/bxYo/28WKP+3cQD/t3IA/7dyAP+3cgD/t3IA/7ZxAP+2cQD/tnEA/7ZxAP+1cAD/tX" + ` "AA/7RvAP+0bwD/tG8A/7NuAP+zbgD/sm4A/7JtAP+xbQD/sWwA/7FsAP+xbAD/sGwA/7BrAP+v" + ` "awD/r2oA/69qAP+vagD/rmkA/61pAP+taQD/rGgA/6xoAP+4fSX/vYUy/7BuDP+rZgD/nFUA/5" + ` "VPAP+UTgD/nFgK//7+/v/+/v7//v7+//7+/v/09PT/5eXm/9bW1//IyMlBAAAAAAAAAAAAAAAA" + ` "AAAAANra2oPp6er/+Pj4//7+/v/+/v7//v7+//7+/v/z6d7/lE4A/5VPAP+WTwD/o10A/61oAf" + ` "+2eB3/vYYz/7yEL/+xcQ3/rWkA/65pAP+uaQD/r2oA/69qAP+vagD/r2sA/7BrAP+wbAD/sWwA" + ` "/7FsAP+xbQD/sm0A/7JuAP+zbgD/s24A/7NuAP+0bwD/tG8A/7VwAP+1cAD/tnEA/7ZxAP+2cQ" + ` "D/tnEA/7dyAP+3cgD/t3IA/7dyAP+4cwD/uXMA/7lzAP+5cwD/uXMA//Xr2v//////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////////+ve4P9vFij/bxYo/7hxAP+4cwD/t3IA/7dyAP+3cgD/t3IA/7ZxAP+2" + ` "cQD/tnEA/7ZxAP+1cAD/tXAA/7RvAP+0bwD/s24A/7NuAP+zbgD/sm4A/7JtAP+xbQD/sWwA/7" + ` "FsAP+wbAD/sGsA/69rAP+vagD/r2oA/69qAP+uaQD/rmkA/61pAP+taQD/sHAN/7yEL/+9hTP/" + ` "tngd/6xnAf+iXQD/lU8A/5ROAP+UTQD/8+ne//7+/v/+/v7//v7+//j4+P/p6er/2tra/8zMzY" + ` "MAAAAAAAAAAAAAAAAAAAAA3t7exe3t7v/8/Pz//v7+//7+/v/+/v7//v7+/8uld/+UTQD/lE4A" + ` "/5VPAP+oYwD/rWgC/7uBLP+9hjP/vYYy/7l+JP+uagH/rmkA/69qAP+vagD/r2oA/69rAP+waw" + ` "D/sGwA/7BsAP+xbAD/sWwA/7FtAP+ybQD/sm4A/7NuAP+zbgD/tG8A/7RvAP+1cAD/tXAA/7Vw" + ` "AP+2cQD/tnEA/7ZxAP+3cgD/t3IA/7dyAP+3cgD/uHMA/7lzAP+5cwD/uXMA/7l0AP+5dAD/9e" + ` "va////////////////////////////////////////////////////////////////////////" + ` "////////////////////////////////////697g/28WKP9vFij/uHEA/7lzAP+4cwD/t3IA/7" + ` "dyAP+3cgD/t3IA/7ZxAP+2cQD/tnEA/7VwAP+1cAD/tXAA/7RvAP+0bwD/s24A/7NuAP+ybgD/" + ` "sm0A/7FtAP+xbAD/sWwA/7BsAP+wbAD/sGsA/69rAP+vagD/r2oA/69qAP+uaQD/rWkA/65qAf" + ` "+4fST/vYYy/72FM/+7gSz/rGcC/6djAP+UTgD/lE0A/5NMAP/LpXf//v7+//7+/v/+/v7//Pz8" + ` "/+3t7v/e3t7/0NDRxQAAAAAAAAAAAAAAANLS0wzh4eL68PDw//7+/v/+/v7//v7+//7+/v/+/v" + ` "7/rXMv/5RNAP+UTgD/mFIA/6tmAP+vbAj/vYUz/72GM/+9hjP/vIUv/7JyEP+uaQD/r2oA/69q" + ` "AP+vagD/r2sA/7BrAP+wbAD/sWwA/7FsAP+xbQD/sm0A/7JuAP+ybgD/s24A/7NuAP+0bwD/tG" + ` "8A/7VwAP+1cAD/tnEA/7ZxAP+2cQD/tnEA/7dyAP+3cgD/t3IA/7hzAP+4cwD/uXMA/7lzAP+5" + ` "dAD/uXQA/7p1AP/269r///////////////////////////////////////////////////////" + ` "/////////////////////////////////////////////////////r3uD/bxYo/28WKP+4cQD/" + ` "uXMA/7hzAP+4cwD/t3IA/7dyAP+3cgD/tnEA/7ZxAP+2cQD/tnEA/7VwAP+1cAD/tG8A/7RvAP" + ` "+zbgD/s24A/7JuAP+ybgD/sm0A/7FtAP+xbAD/sWwA/7BsAP+wawD/r2sA/69qAP+vagD/r2oA" + ` "/65pAP+taQD/snIQ/7yEL/+9hjP/vYUz/72FM/+uawj/qmYA/5dRAP+UTQD/k0wA/6xzL//+/v" + ` "7//v7+//7+/v/+/v7/8PDw/+Hh4v/S0tP6w8PEDAAAAAAAAAAA1dXWQOTk5f/z8/P//v7+//7+" + ` "/v/+/v7//v7+//7+/v+aVQf/k0wA/5RNAP+dVwD/rGcA/7NzFf+9hjP/vYYz/76HM/+9hjL/uX" + ` "8m/69qAv+vagD/r2oA/69qAP+vawD/sGsA/7BsAP+xbAD/sWwA/7FtAP+ybQD/sm4A/7NuAP+z" + ` "bgD/tG8A/7RvAP+1cAD/tXAA/7VwAP+2cQD/tnEA/7ZxAP+3cgD/t3IA/7dyAP+3cgD/uHMA/7" + ` "lzAP+5cwD/uXQA/7l0AP+2cQD/s24A//Tq2v//////////////////////////////////////" + ` "/////////////////////////////////////////////////////////////////////+ve4P" + ` "9vFij/bxYo/7hyAP+5cwD/uXMA/7hzAP+3cgD/t3IA/7dyAP+3cgD/tnEA/7ZxAP+2cQD/tXAA" + ` "/7VwAP+1cAD/tG8A/7RvAP+zbgD/s24A/7JuAP+ybQD/sW0A/7FsAP+xbAD/sGwA/7BrAP+vaw" + ` "D/r2oA/69qAP+vagD/rmkA/65qAv+5fyb/vYYy/72GM/+9hjP/vYUz/7NzFf+rZgD/nFYA/5NM" + ` "AP+TTAD/mVQH//7+/v/+/v7//v7+//7+/v/z8/P/5OTl/9XV1v/GxsdAAAAAAAAAAADY2Nho5+" + ` "fo//b29v/+/v7//v7+//7+/v/+/v7/7+XW/5JLAP+TTAD/lE0A/6NdAP+sZwD/t3sh/72GM/+9" + ` "hjP/vocz/76HM/+9hS//tncX/69qAP+vagD/r2sA/7BrAP+wbAD/sGwA/7FsAP+xbAD/sW0A/7" + ` "JtAP+ybgD/s24A/7NuAP+0bwD/tG8A/7VwAP+1cAD/tnEA/7ZxAP+2cQD/tnEA/7dyAP+3cgD/" + ` "t3IA/7hzAP+5cwD/t3EA/7JtAP+uaQD/qmUA/6lkAP+qZQD/8+na//////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "////////////697g/28WKP9vFij/qWQA/65pAP+ybQD/t3EA/7hzAP+3cgD/t3IA/7dyAP+2cQ" + ` "D/tnEA/7ZxAP+2cQD/tXAA/7VwAP+0bwD/tG8A/7NuAP+zbgD/sm4A/7JtAP+xbQD/sWwA/7Fs" + ` "AP+wbAD/sGwA/7BrAP+vawD/r2oA/69qAP+vagD/tnYX/7yFL/++hzP/vYYz/72GM/+9hTP/t3" + ` "sh/6tmAP+iXQD/k0wA/5JLAP+SSgD/7+TW//7+/v/+/v7//v7+//b29v/n5+j/2NjY/8nJymgA" + ` "AAAAAAAAANvb24/p6er/+fn5//7+/v/+/v7//v7+//7+/v/Ts43/kksA/5NMAP+TTAD/qGIA/6" + ` "1oAf+7gSz/vYYz/72GM/++hzP/vocz/76GMv+9gyv/sm8J/69qAP+vawD/sGsA/7BsAP+xbAD/" + ` "sWwA/7FtAP+ybQD/sm4A/7NuAP+zbgD/s24A/7RvAP+0bwD/tXAA/7VwAP+2cQD/tnEA/7ZxAP" + ` "+3cgD/t3IA/7dyAP+3cgD/smwA/6xmAP+oYwD/qGMA/6hkAP+oZAD/qWQA/6lkAP/z6dr/////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////////////////r3uD/bxYo/28WKP+nYwD/qGMA/6hjAP+nYgD/rGYA/7Fs" + ` "AP+2cQD/t3IA/7dyAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7RvAP+0bwD/s24A/7NuAP+zbgD/sm" + ` "4A/7JtAP+xbQD/sWwA/7FsAP+wbAD/sGsA/69rAP+vagD/r2oA/7JvCf+8giv/vYYy/76HM/+9" + ` "hjP/vYYz/72FM/+7gSz/rGcB/6diAP+TTAD/kksA/5JKAP/Ts43//v7+//7+/v/+/v7/+fn5/+" + ` "np6v/b29v/zMzNjwAAAAAAAAAA3d3dtuzs7f/8/Pz//v7+//7+/v/+/v7//v7+/76QWf+SSgD/" + ` "kksA/5RNAP+rZgD/rmoF/72FM/+9hjP/vYYz/76HM/++hzP/vocz/7+HMf+6fSH/sGsC/69rAP" + ` "+wawD/sGwA/7FsAP+xbAD/sW0A/7JtAP+ybgD/s24A/7NuAP+0bwD/tG8A/7VwAP+1cAD/tnEA" + ` "/7ZxAP+2cQD/tnEA/7dyAP+0bwD/rWcA/6ZhAP+mYQD/pmEA/6diAP+nYgD/qGMA/6hjAP+oZA" + ` "D/qGQA//Pp2v//////////////////////////////////////////////////////////////" + ` "/////////////////////////////////////////////+ve4P9vFij/bxYo/6diAP+nYgD/p2" + ` "IA/6ZhAP+mYQD/pWAA/6ZhAP+sZwD/tG8A/7ZxAP+2cQD/tnEA/7ZxAP+1cAD/tXAA/7RvAP+0" + ` "bwD/s24A/7NuAP+ybgD/sm0A/7FtAP+xbAD/sWwA/7BsAP+wawD/r2sA/69qAP+wawL/un0h/7" + ` "6GMf++hzP/vocz/72GM/+9hjP/vYUz/72FM/+taQX/qmYA/5NMAP+SSgD/kUkA/72PWf/+/v7/" + ` "/v7+//7+/v/8/Pz/7Ozt/93d3f/Ozs+2AAAAAAAAAADf39/c7u7v//7+/v/+/v7//v7+//7+/v" + ` "/+/v7/rXMx/5JKAP+SSwD/l1AA/6tmAP+wbw3/vYUz/72GM/+9hjP/vocz/76HM/++hzP/v4gz" + ` "/76FLv+2dhX/sGwB/7BrAP+wbAD/sWwA/7FsAP+xbQD/sm0A/7JuAP+zbgD/s24A/7RvAP+0bw" + ` "D/tXAA/7VwAP+2cQD/tnEA/7ZxAP+ybQD/qmUA/6RfAP+kXwD/pF8A/6VgAP+lYAD/pmEA/6Zh" + ` "AP+nYgD/p2IA/6hjAP+oYwD/8+na//////////////////////////////////////////////" + ` "//////////////////////////////////////////////////////////////697g/28WKP9v" + ` "Fij/pmEA/6ZhAP+mYQD/pWAA/6VgAP+kXwD/pF8A/6RfAP+kXwD/qWQA/7FsAP+2cQD/tnEA/7" + ` "VwAP+1cAD/tG8A/7RvAP+zbgD/s24A/7JuAP+ybQD/sW0A/7FsAP+xbAD/sGwA/7BrAP+vawD/" + ` "sGsB/7Z2Ff++hS7/vocz/76HM/++hzP/vYYz/72GM/+9hTP/vYUz/69uDf+qZgD/lk8A/5JKAP" + ` "+RSQD/rHMx//7+/v/+/v7//v7+//7+/v/u7u//39/f/9DQ0d0AAAAA0dHSB+Dg4fzw8PD//v7+" + ` "//7+/v/+/v7//v7+//7+/v+fXRX/kUkA/5JKAP+aVAD/rGcA/7NzFP+9hjP/vYYz/76HM/++hz" + ` "P/vocz/7+IM/+/iDP/v4cy/72DK/+zcgz/sGsA/7BsAP+xbAD/sWwA/7FtAP+ybQD/sm4A/7Nu" + ` "AP+zbgD/tG8A/7RvAP+1cAD/tXAA/7ZxAP+zbQD/qGMA/6JdAP+jXgD/o14A/6RfAP+kXwD/pF" + ` "8A/6VgAP+lYAD/pmEA/6ZhAP+mYQD/p2IA/6diAP/z6dr/////////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////r3uD/bxYo/28WKP+lYAD/pmEA/6VgAP+lYAD/pF8A/6RfAP+kXwD/o14A/6NeAP+iXQD/" + ` "ol0A/6hiAP+ybQD/tXAA/7VwAP+0bwD/tG8A/7NuAP+zbgD/sm4A/7JtAP+xbQD/sWwA/7FsAP" + ` "+wbAD/sGsA/69rAP+zcQz/vYMr/7+HMv+/iDP/vocz/76HM/++hzP/vYYz/72GM/+9hTP/s3MU" + ` "/6tmAP+aUwD/kUkA/5BIAP+fXRX//v7+//7+/v/+/v7//v7+//Dw8P/g4OH/0dHS/MLCwwfT09" + ` "Qo4uLj//Ly8v/+/v7//v7+//7+/v/+/v7//v7+/5VPBP+RSQD/kkoA/55YAP+sZwD/tXgc/72G" + ` "M/+9hjP/vocz/76HM/++hzP/v4gz/7+IM/+/iDP/v4cx/7yAJf+ycAf/sWwA/7FsAP+xbQD/sm" + ` "0A/7JuAP+zbgD/s24A/7NuAP+0bwD/tG8A/7VwAP+zbgD/qWQA/6FcAP+iXAD/olwA/6JdAP+j" + ` "XgD/o14A/6RfAP+kXwD/pF8A/6RfAP+lYAD/pWAA/6VgAP+mYQD/pmEA//Po2v////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////////+ve4P9vFij/bxYo/6RfAP+lYAD/pF8A/6RfAP+kXwD/pF8A/6NeAP" + ` "+jXgD/ol0A/6JcAP+iXAD/oVwA/6FcAP+oYwD/s24A/7RvAP+0bwD/s24A/7NuAP+zbgD/sm4A" + ` "/7JtAP+xbQD/sWwA/7FsAP+wbAD/sm8H/7uAJf+/hzH/v4gz/7+IM/++hzP/vocz/76HM/+9hj" + ` "P/vYYz/72FM/+1eBz/q2YA/55XAP+RSQD/kEgA/5RPBP/+/v7//v7+//7+/v/+/v7/8vLy/+Li" + ` "4//T09T/xMTFKNTU1Tnj4+T/8/Pz//7+/v/+/v7//v7+//7+/v/+/vz/kEgA/5BIAP+RSQD/oV" + ` "sA/6xnAP+4fCP/vYYz/72GM/++hzP/vocz/76HM/+/iDP/v4gz/7+IM/+/iTP/v4cw/7p+H/+y" + ` "bgT/sWwA/7FtAP+ybQD/sm4A/7NuAP+zbgD/tG8A/7RvAP+1cAD/rWcA/6JbAP+gWwD/oFsA/6" + ` "FcAP+iXAD/olwA/6JdAP+iXQD/o14A/6NeAP+kXwD/pF8A/6RfAP+kXwD/pWAA/6VgAP+lYAD/" + ` "8+ja//////////////////////////////////////////////////////////////////////" + ` "//////////////////////////////////////697g/28WKP9vFij/o14A/6RfAP+kXwD/pF8A" + ` "/6NeAP+jXgD/ol0A/6JdAP+iXAD/olwA/6FcAP+gWwD/oFsA/6BaAP+iWwD/rWcA/7RvAP+0bw" + ` "D/s24A/7NuAP+ybgD/sm0A/7FtAP+xbAD/sWwA/7FuBP+6fR//vocw/7+IM/+/iDP/v4gz/76H" + ` "M/++hzP/vocz/72GM/+9hjP/vYUz/7h8I/+rZgD/oFsA/5BIAP+PSAD/kEgA//7+/P/+/v7//v" + ` "7+//7+/v/z8/P/4+Pk/9TU1f/FxcY51dXWReTk5f/09PT//v7+//7+/v/+/v7//v7+//fy6/+P" + ` "SAD/kEgA/5FJAP+jXQD/rGcA/7l/KP+9hjP/vYYz/76HM/++hzP/vocz/7+IM/+/iDP/v4gz/7" + ` "+JM//AiTP/v4cv/7l7Gv+ybgP/sW0A/7JtAP+ybgD/s24A/7NuAP+0bwD/sWwA/6ReAP+fWQD/" + ` "n1kA/6BaAP+gWwD/oFsA/6FcAP+hXAD/olwA/6JcAP+iXQD/ol0A/6NeAP+jXgD/pF8A/6RfAP" + ` "+kXwD/pF8A/6RfAP/y6Nr/////////////////////////////////////////////////////" + ` "///////////////////////////////////////////////////////r3uD/bxYo/28WKP+jXg" + ` "D/pF8A/6NeAP+jXgD/ol0A/6JdAP+iXAD/olwA/6FcAP+hXAD/oFsA/6BbAP+gWgD/n1kA/59Z" + ` "AP+eWAD/o14A/7FsAP+zbgD/s24A/7JuAP+ybQD/sW0A/7FsAP+ybgP/uHsa/7+GL/+/iTP/v4" + ` "gz/7+IM/+/iDP/vocz/76HM/++hzP/vYYz/72GM/+9hTP/uX8o/6tmAP+iXQD/kEgA/49IAP+P" + ` "RwD/9/Hp//7+/v/+/v7//v7+//T09P/k5OX/1dXW/8fHyEXW1tdS5eXm//X19f/+/v7//v7+//" + ` "7+/v/+/v7/7uLS/49HAP+PSAD/kEgA/6ReAP+sZwD/uoAq/72GM/+9hjP/vocz/76HM/++hzP/" + ` "v4gz/7+IM/+/iDP/v4kz/8CJM//AiTP/v4Yt/7h5Fv+ybwP/sm0A/7JuAP+zbgD/s24A/61oAP" + ` "+fWQD/nVgA/55YAP+fWQD/n1kA/6BaAP+gWgD/oFsA/6FcAP+hXAD/olwA/6JcAP+iXQD/ol0A" + ` "/6JdAP+jXgD/o14A/6RfAP+kXwD/pF8A//Lo2v////////////////////////////////////" + ` "///////////////////////////////////////////////////////////////////////+ve" + ` "4P9vFij/bxYo/6JdAP+jXgD/ol0A/6JdAP+iXQD/olwA/6JcAP+hXAD/oVwA/6BbAP+gWgD/oF" + ` "oA/59ZAP+fWQD/nlgA/51YAP+dWAD/nlkA/6xnAP+zbgD/sm4A/7JtAP+xbQD/sm4D/7h5Fv++" + ` "hi3/wIkz/7+JM/+/iDP/v4gz/7+IM/++hzP/vocz/76HM/+9hjP/vYYz/72FM/+6gCr/q2YA/6" + ` "NeAP+PSAD/j0cA/49HAP/u4tL//v7+//7+/v/+/v7/9fX1/+Xl5v/W1tf/x8fIUtfX2F/m5uf/" + ` "9vb2//7+/v/+/v7//v7+//7+/v/k0rv/j0cA/49IAP+QSAD/pV8A/6xnAP+7gi3/vYYz/72GM/" + ` "++hzP/vocz/76HM/+/iDP/v4gz/7+IM/+/iTP/wIkz/8CJM//BiTP/v4Us/7d4FP+zbwP/sm4A" + ` "/7NtAP+nYQD/nFYA/5xXAP+dWAD/nVgA/55YAP+eWAD/n1kA/6BaAP+gWgD/oFsA/6BbAP+hXA" + ` "D/oVwA/6JcAP+iXAD/ol0A/6JdAP+iXQD/o14A/6NeAP+jXgD/8uja////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "//////////////697g/28WKP9vFij/oVwA/6JdAP+iXQD/olwA/6JcAP+hXAD/oVwA/6BbAP+g" + ` "WwD/oFoA/6BaAP+fWQD/nlgA/55YAP+dWAD/nVgA/5xXAP+cVgD/nFYA/6ZgAP+ybQD/sm0A/7" + ` "JvA/+3dxT/v4Us/8CJM//AiTP/v4kz/7+IM/+/iDP/v4gz/76HM/++hzP/vocz/72GM/+9hjP/" + ` "vYUz/7uCLf+rZgD/pF8A/49IAP+PRwD/jkYA/+TSu//+/v7//v7+//7+/v/29vb/5ubn/9fX2P" + ` "/IyMlf19fYbObm5//29vb//v7+//7+/v/+/v7//v7+/9zDpv+ORgD/j0cA/49IAP+mYQD/rGcA" + ` "/7yDL/+9hjP/vYYz/76HM/++hzP/vocz/7+IM/+/iDP/v4gz/7+JM//AiTP/wIkz/8GJM//BiT" + ` "L/v4Ys/7h4FP+ybgP/oVsA/5tVAP+cVgD/nFYA/5xXAP+cVwD/nVgA/55YAP+eWAD/n1kA/59Z" + ` "AP+gWgD/oFoA/6BbAP+gWwD/oVwA/6FcAP+iXAD/olwA/6JcAP+iXQD/ol0A/6JdAP/y6Nr///" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////////////////////r3uD/bxYo/28WKP+hWwD/olwA/6JcAP+hXAD/oVwA/6" + ` "BbAP+gWwD/oFoA/6BaAP+fWQD/n1kA/55YAP+eWAD/nVgA/5xXAP+cVwD/nFYA/5xWAP+bVQD/" + ` "m1UA/6FbAP+ybQP/t3gU/7+FLP/BiTL/wIkz/8CJM/+/iTP/v4gz/7+IM/+/iDP/vocz/76HM/" + ` "++hzP/vYYz/72GM/+9hTP/vIMv/6tmAP+lYQD/j0cA/45GAP+ORQD/3MOm//7+/v/+/v7//v7+" + ` "//b29v/m5uf/19fY/8jIyWzX19h55ubn//b29v/+/v7//v7+//7+/v/+/v7/1LWR/45GAP+PRw" + ` "D/j0cA/6hiAP+sZwD/vIQx/72GM/+9hjP/vocz/76HM/++hzP/v4gz/7+IM/+/iDP/v4kz/8CJ" + ` "M//AiTP/wYkz/8GJM//BijL/vYMr/6ZmFf+cVwT/m1UA/5tVAP+bVQD/nFYA/5xXAP+cVwD/nV" + ` "gA/51YAP+eWAD/nlgA/59ZAP+gWgD/oFoA/6BaAP+gWwD/oFsA/6FcAP+hXAD/olwA/6JcAP+i" + ` "XAD/olwA//Lo2v////////////////////////////////////////////////////////////" + ` "///////////////////////////////////////////////+ve4P9vFij/bxYo/6FbAP+hXAD/" + ` "oVwA/6BbAP+gWwD/oFoA/6BaAP+gWgD/n1kA/55YAP+eWAD/nVgA/51YAP+cVwD/nFcA/5xWAP" + ` "+bVQD/m1UA/5tVAP+aVAD/nFcE/6VlFf+8gyv/wYky/8GJM//AiTP/wIkz/7+JM/+/iDP/v4gz" + ` "/7+IM/++hzP/vocz/76HM/+9hjP/vYYz/72FM/+8hDH/q2YA/6diAP+PRwD/jkYA/45FAP/UtZ" + ` "H//v7+//7+/v/+/v7/9vb2/+bm5//X19j/yMjJedfX2Hnm5uf/9vb2//7+/v/+/v7//v7+//7+" + ` "/v/UtZH/jkUA/45GAP+PRwD/qGIA/6xnAP+8hDH/vYYz/72GM/++hzP/vocz/76HM/+/iDP/v4" + ` "gz/7+IM/+/iTP/wIkz/8CJM//BiTP/wYkz/76GM/+vdjP/q3Es/6RkGP+cWAb/m1UA/5tVAP+b" + ` "VQD/nFYA/5xWAP+cVwD/nVgA/51YAP+eWAD/nlgA/59ZAP+fWQD/oFoA/6BaAP+gWgD/oFsA/6" + ` "BbAP+hXAD/oVwA/6FcAP+iXAD/8uja////////////////////////////////////////////" + ` "////////////////////////////////////////////////////////////////697g/28WKP" + ` "9vFij/oFsA/6BbAP+gWwD/oFoA/6BaAP+gWgD/n1kA/59ZAP+eWAD/nlgA/51YAP+dWAD/nFcA" + ` "/5xWAP+cVgD/m1UA/5tVAP+bVQD/mlQA/5xYBv+jYxj/qnAs/652M/+9hTP/wYkz/8CJM//AiT" + ` "P/v4kz/7+IM/+/iDP/v4gz/76HM/++hzP/vocz/72GM/+9hjP/vYUz/7yEMf+rZgD/p2IA/45G" + ` "AP+ORQD/jUQA/9S1kf/+/v7//v7+//7+/v/29vb/5ubn/9fX2P/IyMl519fYbObm5//29vb//v" + ` "7+//7+/v/+/v7//v7+/9zDpv+ORQD/jkUA/45GAP+mYAD/rGcA/7uCLv+9hjP/vYYz/76HM/++" + ` "hzP/vocz/7+IM/+/iDP/v4gz/7+JM//AiTP/wIkz/8GJM/+9hTP/rnUz/611M/+tdTP/rHIu/6" + ` "VnHP+dWQj/nFYB/5tVAP+bVQD/nFYA/5xWAP+cVwD/nFcA/51YAP+dWAD/nlgA/55YAP+fWQD/" + ` "n1kA/6BaAP+gWgD/oFoA/6BbAP+gWwD/oFsA/6FcAP/y6Nr///////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////r3uD/bxYo/28WKP+fWgD/oFoA/6BaAP+gWgD/n1kA/59ZAP+eWAD/nlgA/51YAP+dWA" + ` "D/nFcA/5xXAP+cVgD/nFYA/5tVAP+bVQD/m1UA/5tVAf+dWQj/pGYc/6txLv+tdTP/rHQz/651" + ` "M/+9hTP/wIkz/8CJM/+/iTP/v4gz/7+IM/+/iDP/vocz/76HM/++hzP/vYYz/72GM/+9hTP/u4" + ` "Iu/6tmAP+lYAD/jkUA/45FAP+NRAD/3MOm//7+/v/+/v7//v7+//b29v/m5uf/19fY/8jIyWzW" + ` "1tdf5eXm//X19f/+/v7//v7+//7+/v/+/v7/5NK7/41EAP+ORQD/jkYA/6VfAP+sZwD/u4Es/7" + ` "2GM/+9hjP/vocz/76HM/++hzP/v4gz/7+IM/+/iDP/v4kz/8CJM//AiTP/vYUz/651M/+sczP/" + ` "rHQz/611M/+tdTP/rHMw/6ZpIf+fXQ3/nFYC/5tVAP+bVQD/m1UA/5xWAP+cVgD/nFcA/5xXAP" + ` "+dWAD/nVgA/55YAP+eWAD/n1kA/59ZAP+fWQD/oFoA/6BaAP+gWgD/oFsA//Lo2v//////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "///////////////////////+ve4P9vFij/bxYo/59ZAP+fWQD/n1kA/59ZAP+eWAD/nlgA/51Y" + ` "AP+dWAD/nFcA/5xXAP+cVgD/nFYA/5tVAP+bVQD/m1UA/5tVAP+bVQL/nlwN/6ZpIf+sczD/rX" + ` "Uz/6x0M/+sczP/rHMz/610M/+8hTP/wIkz/7+JM/+/iDP/v4gz/7+IM/++hzP/vocz/76HM/+9" + ` "hjP/vYYz/72FM/+7gSz/q2YA/6RfAP+ORQD/jUQA/4xDAP/k0rv//v7+//7+/v/+/v7/9fX1/+" + ` "Xl5v/W1tf/x8fIX9XV1lLk5OX/9PT0//7+/v/+/v7//v7+//7+/v/u4tL/jEMA/41EAP+ORQD/" + ` "o10A/6xnAP+6fyn/vYYz/72GM/++hzP/vocz/76HM/+/iDP/v4gz/7+IM/+/iTP/wIkz/72GM/" + ` "+sdDP/q3Iz/6xzM/+sczP/rHQz/6x0M/+tdTP/rXUy/6ltJ/+iYRP/nFcF/5tVAP+bVQD/m1UA" + ` "/5xWAP+cVgD/nFcA/5xXAP+cVwD/nVgA/51YAP+eWAD/nlgA/55YAP+fWQD/n1kA/59ZAP+gWg" + ` "D/8ufa////////////////////////////////////////////////////////////////////" + ` "////////////////////////////////////////697g/28WKP9vFij/nlgA/55YAP+eWAD/nl" + ` "gA/51YAP+dWAD/nFcA/5xXAP+cVwD/nFYA/5xWAP+bVQD/m1UA/5tVAP+aVAD/nFcF/6FgE/+p" + ` "bSf/rHQy/6x0M/+sdDP/rHMz/6xzM/+rcjP/qnIz/6tzM/+9hTP/v4kz/7+IM/+/iDP/v4gz/7" + ` "6HM/++hzP/vocz/72GM/+9hjP/vYUz/7p/Kf+rZgD/o10A/41EAP+MQwD/jEMA/+7i0//+/v7/" + ` "/v7+//7+/v/09PT/5OTl/9XV1v/Hx8hS1NTVRePj5P/z8/P//v7+//7+/v/+/v7//v7+//fx6/" + ` "+MQwD/jUQA/41EAP+iWwD/rGcA/7l+J/+9hjP/vYYz/76HM/++hzP/vocz/7+IM/+/iDP/v4gz" + ` "/7+JM/++hzP/rXUz/6pxM/+qcjP/q3Iz/6tyM/+sczP/rHQz/6x0M/+tdTP/rXUz/6txLP+lZh" + ` "v/nlsL/5xWAv+bVQD/m1UA/5tVAP+cVgD/nFYA/5xXAP+cVwD/nFcA/51YAP+dWAD/nVgA/55Y" + ` "AP+eWAD/nlgA/59ZAP/y59r///////////////////////////////////////////////////" + ` "/////////////////////////////////////////////////////////r3uD/bxYo/28WKP+d" + ` "VwD/nVgA/51YAP+dWAD/nFcA/5xXAP+cVwD/nFYA/5xWAP+bVQD/m1UA/5tVAP+bVQD/m1UC/5" + ` "5bC/+kZRv/qnAs/611M/+sdDP/rHQz/6xzM/+rcjP/q3Iz/6pyM/+qcTP/qnEz/610M/++hzP/" + ` "v4gz/7+IM/+/iDP/vocz/76HM/++hzP/vYYz/72GM/+9hTP/uX4n/6tmAP+hWwD/jUQA/4xDAP" + ` "+LQgH/9/Hp//7+/v/+/v7//v7+//Pz8//j4+T/1NTV/8XFxkXT09Q54uLj//Ly8v/+/v7//v7+" + ` "//7+/v/+/v7//v79/4xCAP+MQwD/jUQA/59YAP+sZwD/t3si/72GM/+9hjP/vocz/76HM/++hz" + ` "P/v4gz/7+IM/+/iDP/vogz/651M/+qcTP/qnEz/6pxM/+qcjP/q3Iz/6tyM/+sczP/rHMz/6x0" + ` "M/+tdTP/rXUz/610Mf+obCX/omET/51ZB/+cVgH/m1UA/5tVAP+bVQD/nFYA/5xWAP+cVgD/nF" + ` "cA/5xXAP+dWAD/nVgA/51YAP+dWAD/nlgA//Hn2v//////////////////////////////////" + ` "/////////////////////////////////////////////////////////////////////////+" + ` "ve4P9vFij/bxYo/5xXAP+dWAD/nFcA/5xXAP+cVgD/nFYA/5xWAP+bVQD/m1UA/5tVAP+bVQD/" + ` "m1UB/51ZB/+hYBP/qGwl/6xzMf+tdTP/rHQz/6xzM/+sczP/q3Iz/6tyM/+qcjP/qnEz/6pxM/" + ` "+qcTP/qXAz/651M/++hzP/v4gz/7+IM/++hzP/vocz/76HM/+9hjP/vYYz/72FM/+3eyL/q2YA" + ` "/55YAP+MQwD/i0IA/4xBAv/+/v3//v7+//7+/v/+/v7/8vLy/+Li4//T09T/xMTFOdHR0ijg4O" + ` "H/8PDw//7+/v/+/v7//v7+//7+/v/+/v7/kUkF/4tCAP+MQwD/mlMA/6xnAP+1dxv/vYYz/72G" + ` "M/++hzP/vocz/76HM/+/iDP/v4gz/7+IM/+yeTP/qXAz/6lwM/+qcTP/qnEz/6pxM/+qcjP/qn" + ` "Iz/6tyM/+sczP/rHMz/6x0M/+sdDP/rXUz/611M/+rcS3/pmgf/6BfEP+cVwX/m1UA/5tVAP+b" + ` "VQD/m1UA/5xWAP+cVgD/nFYA/5xXAP+cVwD/nFcA/5xXAP+dWAD/8efa//////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "////////////////697g/28WKP9vFij/m1YA/5xXAP+cVgD/nFYA/5xWAP+bVQD/m1UA/5tVAP" + ` "+bVQD/mlQA/5xXBf+gXhD/pmgf/6pwLf+tdTP/rHQz/6x0M/+sczP/rHMz/6tyM/+qcjP/qnIz" + ` "/6pxM/+qcTP/qnEz/6lwM/+pcDP/qG8z/7J5M/+/iDP/v4gz/76HM/++hzP/vocz/72GM/+9hj" + ` "P/vYUz/7V3G/+rZgD/mVIA/4tCAP+LQgH/kUkH//7+/v/+/v7//v7+//7+/v/w8PD/4ODh/9HR" + ` "0v/CwsMo0NDRB9/f3/zu7u///v7+//7+/v/+/v7//v7+//7+/v+bWBf/i0IB/4xDAP+VTQD/q2" + ` "YA/7JyE/+9hTP/vYYz/72GM/++hzP/vocz/76HM/+/iDP/t38z/6huM/+obzP/qXAz/6lwM/+q" + ` "cTP/qnEz/6pxM/+qcjP/qnIz/6tyM/+rcjP/rHMz/6x0M/+sdDP/rXUz/611M/+tdTL/qnAr/6" + ` "VnHP+gXQ7/nFcF/5tVAP+bVQD/m1UA/5tVAP+bVQD/nFYA/5xWAP+cVgD/nFYA/5xXAP/x59r/" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////////////////////r3uD/bxYo/28WKP+bVQD/nFYA/5tVAP+bVQD/m1UA" + ` "/5tVAP+bVQD/mlQA/5xXBf+gXQ7/pGYc/6pwK/+sdDL/rXUz/6x0M/+sdDP/rHMz/6tyM/+rcj" + ` "P/qnIz/6pyM/+qcTP/qnEz/6pxM/+pcDP/qXAz/6hvM/+objP/qG4z/7d/M/++hzP/vocz/76H" + ` "M/+9hjP/vYYz/72FM/+9hTP/sXET/6pmAP+VTQD/i0IB/4tBA/+aWBj//v7+//7+/v/+/v7//v" + ` "7+/+7u7//f39//0NDR/MHBwgcAAAAA3d3d3Ozs7f/8/Pz//v7+//7+/v/+/v7//v7+/6lvNP+L" + ` "QQL/i0IB/5FIAP+rZgD/sG0L/72FM/+9hjP/vYYz/76HM/++hzP/vocz/7yEM/+pbzP/p20z/6" + ` "huM/+obzP/qG8z/6lwM/+qcTP/qnEz/6pxM/+qcTP/qnIz/6tyM/+rcjP/rHMz/6xzM/+sdDP/" + ` "rHQz/611M/+tdTP/rXUy/6pvKv+kZhz/oF8Q/51ZB/+cVgH/m1UA/5tVAP+bVQD/m1UA/5tVAP" + ` "+cVgD/nFYA//Hn2v//////////////////////////////////////////////////////////" + ` "/////////////////////////////////////////////////+ve4P9vFij/bxYo/5pUAP+bVQ" + ` "D/m1UA/5tVAP+bVQD/m1UB/51ZB/+gXhD/pGYc/6pvKv+sdDL/rXUz/6x0M/+sdDP/rHMz/6xz" + ` "M/+rcjP/q3Iz/6pyM/+qcTP/qnEz/6pxM/+qcTP/qXAz/6hvM/+obzP/qG4z/6dtM/+nbTP/qG" + ` "4z/7uDM/++hzP/vocz/72GM/+9hjP/vYUz/72FM/+vbQv/qmYA/5BHAP+LQQL/ikEE/6lvNP/+" + ` "/v7//v7+//7+/v/8/Pz/7Ozt/93d3f/Ozs/dAAAAAAAAAADb29u26enq//n5+f/+/v7//v7+//" + ` "7+/v/+/v7/u4xa/4pBBP+LQQL/jEMA/6tlAP+taQT/vYUy/72GM/+9hjP/vocz/76HM/++hzP/" + ` "q3Iz/6ZtM/+nbTP/p20z/6huM/+obzP/qG8z/6lwM/+pcDP/qnEz/6pxM/+qcTP/qnIz/6pyM/" + ` "+rcjP/q3Iz/6xzM/+sczP/rHQz/6x0M/+tdTP/rXUz/611Mv+rcSz/pmgf/6JhFP+fXAz/nFcE" + ` "/5tVAP+bVQD/m1UA/5tVAP+bVQD/8efa//////////////////////////////////////////" + ` "//////////////////////////////////////////////////////////////////697g/28W" + ` "KP9vFij/mlQA/5tVAP+aVAD/nFcE/59cDP+hYBT/pmgf/6txLP+sdDL/rXUz/6x0M/+sdDP/rH" + ` "Mz/6xzM/+rcjP/q3Iz/6pyM/+qcjP/qnEz/6pxM/+qcTP/qXAz/6lwM/+obzP/qG8z/6huM/+n" + ` "bTP/p20z/6ZtM/+mbTP/q3Iz/76HM/++hzP/vYYz/72GM/+9hTP/vYUy/6xoBP+qZQD/jEIB/4" + ` "pBBP+KQQT/uoxb//7+/v/+/v7//v7+//n5+f/p6er/29vb/8zMzbYAAAAAAAAAANjY2I/n5+j/" + ` "9vb2//7+/v/+/v7//v7+//7+/v/RsY7/ikEE/4tBBP+LQQL/pV8A/61oAf+6gSv/vYYz/72GM/" + ` "++hzP/vocz/7R7M/+mbTP/pm0z/6ZtM/+nbTP/p20z/6huM/+objP/qG8z/6lwM/+pcDP/qnEz" + ` "/6pxM/+qcTP/qnEz/6pyM/+qcjP/q3Iz/6tyM/+sczP/rHMz/6x0M/+sdDP/rXUz/611M/+tdT" + ` "P/rHMv/6htJv+kZhz/omET/59cDP+cWAb/nFYB/5tVAP/x59r/////////////////////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////r3uD/bxYo/28WKP+bVwb/n1wM/6FgE/+kZhz/qG0m/6tyL/+tdTP/rXUz/6x0M/+s" + ` "dDP/rHMz/6xzM/+rcjP/q3Iz/6pyM/+qcjP/qnEz/6pxM/+qcTP/qnEz/6lwM/+pcDP/qG8z/6" + ` "huM/+objP/p20z/6dtM/+mbTP/pm0z/6ZtM/+mbDP/s3sz/76HM/+9hjP/vYYz/72FM/+6gSv/" + ` "rGcB/6VfAP+LQQT/ikEE/4lABv/RsI///v7+//7+/v/+/v7/9vb2/+fn6P/Y2Nj/ycnKjwAAAA" + ` "AAAAAA1dXWaOTk5f/z8/P//v7+//7+/v/+/v7//v7+/+7k1/+JQAX/ikEE/4tBA/+dVgD/rGcA" + ` "/7Z5H/+9hjP/vYYz/76HM/+7hDP/pmwz/6ZsM/+mbTP/pm0z/6ZtM/+mbTP/p20z/6huM/+obj" + ` "P/qG8z/6hvM/+pcDP/qnEz/6pxM/+qcTP/qnEz/6pyM/+qcjP/q3Iz/6tyM/+sczP/rHMz/6xz" + ` "M/+sdDP/rHQz/611M/+tdTP/rXUz/611Mv+sci7/qG0m/6VnHv+jYxb/oF8Q//Lo3P////////" + ` "//////////////////////////////////////////////////////////////////////////" + ` "/////////////////////////+ve4P9vFij/bxYo/6RmHv+obSb/rHIu/6x0Mv+tdTP/rXUz/6" + ` "x0M/+sdDP/rHMz/6xzM/+sczP/q3Iz/6tyM/+qcjP/qnIz/6pxM/+qcTP/qnEz/6pxM/+pcDP/" + ` "qG8z/6hvM/+objP/qG4z/6dtM/+mbTP/pm0z/6ZtM/+mbTP/pmwz/6VrM/+mbDP/u4Qz/72GM/" + ` "+9hjP/vYUz/7Z5H/+rZgD/nVYB/4pBBP+JQAb/iT8H/+7k1//+/v7//v7+//7+/v/z8/P/5OTl" + ` "/9XV1v/GxsdoAAAAAAAAAADS0tNA4eHi//Dw8P/+/v7//v7+//7+/v/+/v7//v7+/5FKDv+JQA" + ` "X/ikEE/5VNAv+rZgD/snIT/72FM/+9hjP/vYYz/61zM/+lajP/pWsz/6ZsM/+mbDP/pm0z/6Zt" + ` "M/+mbTP/p20z/6dtM/+objP/qG8z/6hvM/+pcDP/qXAz/6pxM/+qcTP/qnEz/6pxM/+qcjP/qn" + ` "Iz/6tyM/+rcjP/q3Iz/6xzM/+sczP/rHQz/6x0M/+sdDP/rXUz/611M/+tdTP/rXUz/610Mf+r" + ` "cSz/8+rg//////////////////////////////////////////////////////////////////" + ` "//////////////////////////////////////////697g/28WKP9vFij/rHMz/611M/+tdTP/" + ` "rHQz/6x0M/+sdDP/rHMz/6xzM/+rcjP/q3Iz/6tyM/+qcjP/qnIz/6pxM/+qcTP/qnEz/6pxM/" + ` "+pcDP/qXAz/6hvM/+obzP/qG4z/6dtM/+nbTP/pm0z/6ZtM/+mbTP/pmwz/6ZsM/+lazP/pWoz" + ` "/6VqM/+scjP/vYYz/72FM/+9hTP/sXET/6pmAP+VTQL/iUAF/4k/CP+RSg///v7+//7+/v/+/v" + ` "7//v7+//Dw8P/h4eL/0tLT/8PDxEAAAAAAAAAAANDQ0Qze3t767e3u//z8/P/+/v7//v7+//7+" + ` "/v/+/v7/p2w0/4lACP+JQAX/jUQD/6tmAP+uawf/vIQx/72GM/+3fzP/pGkz/6VqM/+lajP/pW" + ` "sz/6ZsM/+mbDP/pm0z/6ZtM/+mbTP/p20z/6dtM/+objP/qG4z/6hvM/+obzP/qXAz/6lwM/+q" + ` "cTP/qnEz/6pxM/+qcTP/qnIz/6pyM/+rcjP/q3Iz/6tyM/+sczP/rHMz/6xzM/+sdDP/rHQz/6" + ` "x0M/+sdDP/rX
PowerShellCorpus/PoshCode/New Switch and Portgroup.ps1
New Switch and Portgroup.ps1
get-vc vcservername Get-VMHost | New-VirtualSwitch -Name SwitchName Get-VMHost | Get-VirtualSwitch -Name SwitchName | New-VirtualPortGroup -Name portgroupname -VLANID vlan_number
PowerShellCorpus/PoshCode/Write-DataTable_3.ps1
Write-DataTable_3.ps1
####################### <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an objects properties. .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-Alias | Out-DataTable This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable .NOTES Adapted from script by Marc van Orsouw see link Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 v1.3 - Chad Miller - Correct issue with setting datatype on empty properties .LINK http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx #> function Out-DataTable { [CmdletBinding()] param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject) Begin { $dt = new-object Data.datatable $First = $true } Process { foreach ($object in $InputObject) { $DR = $DT.NewRow() foreach($property in $object.PsObject.get_properties()) { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $property.Name.ToString() if ($property.value) { $Col.DataType = $property.value.gettype() } $DT.Columns.Add($Col) } if ($property.IsArray) { $DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 } else { $DR.Item($property.Name) = $property.value } } $DT.Rows.Add($DR) $First = $false } } End { Write-Output @(,($dt)) } } #Out-DataTable
PowerShellCorpus/PoshCode/Get-DomainPasswordPolicy.ps1
Get-DomainPasswordPolicy.ps1
function Get-DomainPasswordPolicy { $domain = [ADSI]"WinNT://$env:userdomain" $Name = @{Name="DomainName";Expression={$_.Name}} $MinPassLen = @{Name="Minimum Password Length (Chars)";Expression={$_.MinPasswordLength}} $MinPassAge = @{Name="Minimum Password Age (Days)";Expression={$_.MinPasswordAge.value/86400}} $MaxPassAge = @{Name="Maximum Password Age (Days)";Expression={$_.MaxPasswordAge.value/86400}} $PassHistory = @{Name="Enforce Password History (Passwords remembered)";Expression={$_.PasswordHistoryLength}} $AcctLockoutThreshold = @{Name="Account Lockout Threshold (Invalid logon attempts)";Expression={$_.MaxBadPasswordsAllowed}} $AcctLockoutDuration = @{Name="Account Lockout Duration (Minutes)";Expression={if ($_.AutoUnlockInterval.value -eq -1) {'Account is locked out until administrator unlocks it.'} else {$_.AutoUnlockInterval.value/60}}} $ResetAcctLockoutCounter = @{Name="Reset Account Lockout Counter After (Minutes)";Expression={$_.LockoutObservationInterval.value/60}} $domain | Select-Object $Name,$MinPassLen,$MinPassAge,$MaxPassAge,$PassHistory,$AcctLockoutThreshold,$AcctLockoutDuration,$ResetAcctLockoutCounter }
PowerShellCorpus/PoshCode/Custom Accelerators CTP3.ps1
Custom Accelerators CTP3.ps1
#requires -version 2.0 ## Custom Accelerators for PowerShell 2 (CTP3) #################################################################################################### ## A script module for CTP3 which allows the user to create their own custom type accelerators. ## Thanks to "Oisin Grehan for the discovery":http://www.nivot.org/2008/12/25/ListOfTypeAcceleratorsForPowerShellCTP3.aspx. #################################################################################################### ## Revision History ## v1.0 - Modularization, by Joel 'Jaykul' Bennett #################################################################################################### # get a reference to the Type $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list [System.Collections.Generic.List``1] $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator list, glist [System.Collections.Generic.List``1] Creates two accelerators for the generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] PARAM( [Parameter(Position=0)] [string[]]$Accelerator , [Parameter(Position=1)] [type]$Type ) PROCESS { # add a user-defined accelerator foreach($a in $Accelerator) { $xlr8r::Add( $a, $Type) } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator string Returns the KeyValue pair for the accelerator definition(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pair for the matching accelerator definitions .Parameter Accelerator One or more short form accelerators to search for Accepts Wildcards. .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] PARAM( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key")] [string[]]$Accelerator , [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value")] [type[]]$Type ) PROCESS { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int [Int64] Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] PARAM( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key")] [string[]]$Accelerator ) PROCESS { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($_.Key)] for type [$($_.Value.FullName)]", "Removing alias [$($_.Key)] for type [$($_.Value.FullName)]?", "Remove Alias" )) { # remove a user-defined accelerator $xlr8r::remove($_.Key) } } } } } }
PowerShellCorpus/PoshCode/8c4d244d-22ac-4bfe-8ddf-c0a5ee0b552c.ps1
8c4d244d-22ac-4bfe-8ddf-c0a5ee0b552c.ps1
function out-default() { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [System.Management.Automation.PSObject] ${InputObject}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer) -and $outBuffer -gt 1024) { $PSBoundParameters['OutBuffer'] = 1024 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline() $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) if ($last_output -eq $null) { $last_output = @() } if ($last_output.Length -lt 10) { $last_output += $_ } else { $null, $last_output = $last_output $last_output += $_ } } catch { throw } } end { try { $steppablePipeline.End() $global:last_output = $last_output } catch { throw } } <# .ForwardHelpTargetName Out-Default .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/PoshCode/Invoke-RemoteExpression..ps1
Invoke-RemoteExpression..ps1
##############################################################################\n##\n## Invoke-RemoteExpression\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\nInvoke a PowerShell expression on a remote machine. Requires PsExec from\nhttp://live.sysinternals.com/tools/psexec.exe. If the remote machine\nsupports PowerShell version two, use PowerShell remoting instead.\n\n.EXAMPLE\n\nInvoke-RemoteExpression \\\\LEE-DESK { Get-Process }\nRetrieves the output of a simple command from a remote machine\n\n.EXAMPLE\n\n(Invoke-RemoteExpression \\\\LEE-DESK { Get-Date }).AddDays(1)\nInvokes a command on a remote machine. Since the command returns one of\nPowerShell's primitive types (a DateTime object,) you can manipulate\nits output as an object afterward.\n\n.EXAMPLE\n\nInvoke-RemoteExpression \\\\LEE-DESK { Get-Process } | Sort Handles\nInvokes a command on a remote machine. The command does not return one of\nPowerShell's primitive types, but you can still use PowerShell's filtering\ncmdlets to work with its structured output.\n\n#>\n\nparam(\n ## The computer on which to invoke the command.\n $ComputerName = "\\\\$ENV:ComputerName",\n\n ## The scriptblock to invoke on the remote machine.\n [Parameter(Mandatory = $true)]\n [ScriptBlock] $ScriptBlock,\n\n ## The username / password to use in the connection\n $Credential,\n\n ## Determines if PowerShell should load the user's PowerShell profile\n ## when invoking the command.\n [switch] $NoProfile\n)\n\nSet-StrictMode -Version Latest\n\n## Prepare the command line for PsExec. We use the XML output encoding so\n## that PowerShell can convert the output back into structured objects.\n## PowerShell expects that you pass it some input when being run by PsExec\n## this way, so the 'echo .' statement satisfies that appetite.\n$commandLine = "echo . | powershell -Output XML "\n\nif($noProfile)\n{\n $commandLine += "-NoProfile "\n}\n\n## Convert the command into an encoded command for PowerShell\n$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptblock)\n$encodedCommand = [Convert]::ToBase64String($commandBytes)\n$commandLine += "-EncodedCommand $encodedCommand"\n\n## Collect the output and error output\n$errorOutput = [IO.Path]::GetTempFileName()\n\nif($Credential)\n{\n ## This lets users pass either a username, or full credential to our\n ## credential parameter\n $credential = Get-Credential $credential\n $networkCredential = $credential.GetNetworkCredential()\n $username = $networkCredential.Username\n $password = $networkCredential.Password\n\n $output = psexec $computername /user $username /password $password `\n /accepteula cmd /c $commandLine 2>$errorOutput\n}\nelse\n{\n $output = psexec /acceptEula $computername `\n cmd /c $commandLine 2>$errorOutput\n}\n\n## Check for any errors\n$errorContent = Get-Content $errorOutput\nRemove-Item $errorOutput\nif($errorContent -match "(Access is denied)|(failure)|(Couldn't)")\n{\n $OFS = "`n"\n $errorMessage = "Could not execute remote expression. "\n $errorMessage += "Ensure that your account has administrative " +\n "privileges on the target machine.`n"\n $errorMessage += ($errorContent -match "psexec.exe :")\n\n Write-Error $errorMessage\n}\n\n## Return the output to the user\n$output
PowerShellCorpus/PoshCode/Custom Speech Commands.ps1
Custom Speech Commands.ps1
@@#Filename commands.ps1 import-module "G:\\Documents\\Speech Macros\\custom.psm1" import-module "G:\\Documents\\Speech Macros\\alice.psm1" Add-SpeechCommands @{ "test command" = { Say $(Respond "3:2,4:0-2") } " * the percentages * " = { Say $(Percentages) } " * star date * " = { Say "Current, Star date, $("$((Get-Date).year).$([math]::round($((Get-Date).dayofyear)/365, 2)*100)" -replace "([A-Za-z0-9.]){1}","`$1 " -replace "\\.","point")" } " * mail * " = { Start-Process "https://mail.google.com" } "Google * please" = { $term = $_ -replace "$Computer(.+?)Google (.+?) please", '$2'; Start-Process "http://www.google.com/search?q=$term" } "What * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What is * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What time * " = { Say "It is $(Get-Date -f "h:mm tt")" } " * some music * " = { Start-Process "grooveshark.exe" } "What * date today" = { Say $(Get-Date -f "dddd, MMMM dd") } #list processes "What's running?" = { $proc = ps | sort ws -desc Say $("$($proc.Count) processes, including $($proc[0].name), which is using " + "$([int]($proc[0].ws/1mb)) megabytes of memory") } #Word Definition " * the definition for * please" = {$define = $_ -replace "$Computer(.+?)the definition for (.+?) please", '$2' ;$outtext = Get-Definition("$define");Say "Definitions for $define, , , $outtext"} } -Computer "alice" -Verbose #eof @@#Filename custom.psm1 function Get-Definition($word) { #.Synopsis # Polls wiktionary for top text definitons for a given $word input #.Description # This Function parses the top $lines definitions for a given # $term into one string formatted for speech synthesis # # Say "Sure" if($word -match " "){Say "Fail, one word at a time please"; break} $page = "http://simple.wiktionary.org/wiki/$word" $ie = new-object -com "InternetExplorer.Application" $ie.visible = $false $ie.navigate($page) while($ie.busy){Start-Sleep 1} $output = " " $lines = 0 for($d=0;$d -le $lines;$d++) { ## grab the definition strings from each table $ol = @($ie.Document.getElementsByTagName("ol"))[0] $li = @($ol.getElementsByTagName("li"))[$d] $def = @($li.innerHTML) $output += "$def" if($d -lt $lines){ $output += ", or, " } } $ie.Quit() $closeIE = [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($ie) Remove-Variable ie return Clean-String($output) } function Clean-String([string]$str){ #.Synopsis # Cleans string from web (most concerned about x/html tags) #.Description # Cleans input string of xml tags # returns $str # # $str = $str -replace "\\<[^<]*\\>", " " $str = $str.replace("&nbsp", "") return $str } function Respond($in, [string]$del = ","){ #.Synopsis # Recursive. # Returns a random response from $responses via the three dimensional array of choices: $choices[<groups>][<dimensions>][<values>] # This function takes in a string indicating which responses from the $responses array # to to choose from. It supports ranges (-) and direct selections (/) in each seed separated by (,). #.Description # the idea here is to respond based on this format: $in = "3:2,4:1-2,0/2-4/6:1" # where 3:2 is a direct seed, 4:1-2 is a range seed (from 4:1 to 4:2), # and 0/2-4/6:1 combines the two (effectively adds 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the choices) # In heap, the above example would effectively add 3:2, 4:1, 4:2, 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the # available choices, and will appear as $choices(@($xs(3),$ys(2)),@($xs(4),$ys(1,2)),@($xs(0,2,3,4,6),$ys(1))) # switch -wildcard ($del){ "`,"{ if($in -match "`,"){ #if more than one coordset, handle each $coordsets = $in -split "`," #split coordsets apart foreach($coordset in $coordsets){ $choices += ,(Respond $coordset "`:") } } else{ #else pass the string to the next step, $choices = ,(Respond $in "`:") } $choice = $choices[(get-random -min 0 -max $choices.count)] #choose one of the groups randomly $responses[$choice[0]][$choice[1]];#pass response out of the function } "`:"{ $coords = $in -split "`:" #split coordset apart foreach ($coord in $coords){ if(($coord -match "`/")-or($coord -match "`-")){ #if there's an or operator or a range $dimensions += ,(Respond $coord "`/") # handle them, and add all values (in array) to this dimension (split fails elegantly) } else{ $dimensions += ,$coord #else just add the coord value (in an array) via comma operator } } $dimensions #pass dimensions out dimensions is two dimensional array } "`/"{ $ranges = $in -split "`/" #split ORs apart (if theres not OR, the string is still added to $ranges[0]) foreach($range in $ranges){ if($range -match "`-"){#if theres a range to handle, do so foreach ($val in (Respond $range "`-")){ $orVals += ,$val #append all values in returned range array to new array } } else{# else just append the value to teh new array $orVals += ,$range } } ,($orVals | get-random) #pass out single element array of random value from vals array } "`-"{ $vals = $in -split "`-" #split ranges apart $vals[0]..$vals[1] # pass out array containing all values in range } } } $responses = (#Response Array (##0-correct "Right", "Correct" ), (##1-incorrect "Wrong", "Incorrect" ), (##2-positive "Yes", "Aye", "I'll give it a shot" ), (##3-negative "No", "Negative", "Not going to happen" ), (##4-affirmation "Sure", "OK", "Lets See" ), (##5-retort "your mom", "your face" ), (##6-insult "You\\'re dumb", "you fail" ), (##7-eager "I'm ready", "Lets check it out" ), (##8-apprehensive "I don't know", "Just a seck" ), (##9-neutral "oh", "Hum" ) ) function Percentages { #.Synopsis # Specific speech command that reads back # remaining percentages of year, month, week, and day #.Description # Pretty self explanitory, basic maths, elucidatory var names # # $date = get-date #capture date object $daysInYear = [int]$(if([datetime]::IsLeapYear($date.year)){366}else{365}) #if leap year, 366, else 365 $daysInMonth = [int]$([datetime]::DaysInMonth($date.year, $date.month)) #capture days in month $dayOfYear = [int]$date.dayofyear #days past (including today) $dayOfMonth = [int]$date.day #days past (including today) $hoursOfDay = [int]$date.hour #hours past (including current) $minutesOfHour = [int]$date.minute #minutes past (including current) switch ($date.dayofweek.toString()){ #assumes start of week is sunday Sunday { [int]$dayOfWeek="1"; break } Monday { [int]$dayOfWeek="2"; break } Tuesday { [int]$dayOfWeek="3"; break } Wednesday { [int]$dayOfWeek="4"; break } Thursday { [int]$dayOfWeek="5"; break } Friday { [int]$dayOfWeek="6"; break } Saturday { [int]$dayOfWeek="7"; break } } $percentYearGone = $dayOfYear/$daysInYear #days of this year (including today) divided by total days in this year $percentMonthGone = ((($dayOfMonth*24)-24)+$hoursOfDay)/($daysInMonth*24) #hours of this month divided by total hours in this month $percentWeekGone = ((($dayOfWeek*24)-24)+$hoursOfDay)/(7*24) #hours of this week divided by total hours in a week $percentDayGone = ((($hoursOfDay*60)-60)+$minutesOfDay)/(24*60) #minutes of today divided by total minutes in a day $percentYearLeft = [math]::round((1-$percentYearGone)*100,1) #opposite percentages rounded to one decimal place $percentMonthLeft = [math]::round((1-$percentMonthGone)*100,1) #^ $percentWeekLeft = [math]::round((1-$percentWeekGone)*100,1) #^ $percentDayLeft = [math]::round((1-$percentDayGone)*100,1) #^ $str = "" $str += "There's " $str += $percentYearLeft $str += "% of this year, " $str += $percentMonthLeft $str += "% of this month, " $str += $percentWeekLeft $str += "% of this week, and " $str += $percentDayLeft $str += "% of today remaining, what will you do with it?" return $str } #eof
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_3.ps1
Send-HTMLFormattedEmail_3.ps1
#------------------------------------------------- # Send-HTMLFormattedEmail #------------------------------------------------- # Usage: Used to send an HTML Formatted Email that is based on an XSLT template. #------------------------------------------------- function Send-HTMLFormattedEmail{ param ( [string] $To, [string] $ToDisName, [string] $BCC, [string] $From, [string] $FromDisName, [string] $Subject, [string] $Content, [string] $Relay, [string] $XSLPath) try { # Load XSL Argument List $XSLArg = New-Object System.Xml.Xsl.XsltArgumentList $XSLArg.Clear() $XSLArg.AddParam("To", $Null, $ToDisName) $XSLArg.AddParam("Content", $Null, $Content) # Load Documents $BaseXMLDoc = New-Object System.Xml.XmlDocument $BaseXMLDoc.LoadXml("<root/>") $XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform $XSLTrans.Load($XSLPath) #Perform XSL Transform $FinalXMLDoc = New-Object System.Xml.XmlDocument $MemStream = New-Object System.IO.MemoryStream $XMLWriter = [System.Xml.XmlWriter]::Create($MemStream) $XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter) $XMLWriter.Flush() $MemStream.Position = 0 # Load the results $FinalXMLDoc.Load($MemStream) $Body = $FinalXMLDoc.Get_OuterXML() # Create from, To, BCC and the message strucures $MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName $MessTo = New-Object System.Net.Mail.Mailaddress $To $MessBCC = New-Object System.Net.Mail.Mailaddress $BCC $Message = New-Object System.Net.Mail.MailMessage $MessFrom, $MessTo # Populate message $Message.Subject = $Subject $Message.Body = $Body $Message.IsBodyHTML = $True # Add BCC $Message.BCC.Add($MessBCC) # Create SMTP Client $Client = New-Object System.Net.Mail.SmtpClient $Relay # Send The Message $Client.Send($Message) } catch { return $Error[0] } } ### XSLT Template Example <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output media-type="xml" omit-xml-declaration="yes" /> <xsl:param name="To"/> <xsl:param name="Content"/> <xsl:template match="/"> <html> <head> <title>My First Formatted Email</title> </head> <body> <div width="400px"> <p>Dear <xsl:value-of select="$To" />,</p> <p></p> <p><xsl:value-of select="$Content" /></p> <p></p> <p><strong>Please do not respond to this email!</strong><br /> An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p> <p></p> <Address> Many thanks from your:<br /> Really Cool IT Team<br /> </Address> </div> </body> </html> </xsl:template> </xsl:stylesheet>
PowerShellCorpus/PoshCode/forever.ps1
forever.ps1
forever
PowerShellCorpus/PoshCode/powertab patch.ps1
powertab patch.ps1
# When in the cert provider - objects returned by gci must be completed by a particular member (not by ToString). # This can be done more generically but for now this is super handy to complete with these types $firstChildType = $childitems[0].GetType() if ($firstChildType -is [Microsoft.Powershell.Commands.X509StoreLocation]) { $childitems = childitems | % { $_.Location } } if ($firstChildType -is [System.Security.Cryptography.X509Certificates.X509Store]) { $childitems = childitems | % { $_.Name } } if ($firstChildType -is [Microsoft.Win32.RegistryKey]) { # registry provider returns full path names - split by \\ and take the final item. $childitems = childitems | % { $_.Name.Split("\\")[-1] } }
PowerShellCorpus/PoshCode/Citrix License Info.ps1
Citrix License Info.ps1
########################################### # Licence Checking Script for Citrix # # Virtu-Al - http://teckinfo.blogspot.com/ ########################################### param( [string] $sendmailsched ) Function Sendemail ($LicTypeText, $InstalledLicNum, $InUseNum, $PercentageNum) { #Email options for automated emailed report $smtpServer = "mysmtpserver.co.uk" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "someone@mydomain.co.uk" $msg.To.Add("me@mydomain.co.uk") $msg.Subject = "Citrix License Server Stats" $msg.Body = "The below is the current status of the license server:`n`nLicense Type: $LicTypeText`n`nInstalled Licences: $InstalledLicNum`n`nLicences In Use: $InUseNum`n`nPercentage: $PercentageNum%" $smtp.Send($msg) } # Set licence server and temporary file $licserver = "mylicserver.mydomain.co.uk" $tempfile = "c:\\lictest.txt" # Retrieve web page into a text file $webClient = New-Object System.Net.WebClient $webClient.credentials = New-Object system.net.networkcredential("usernametoaccesssite", "Password") $webadd = "http://$licserver/lmc/current_usage/currentUsage.jsp" $webClient.DownloadString($webadd) > $tempfile # Find Line numbers of text $Myline = Select-String -Path "$tempfile" -pattern "Enterprise" $LicTypeLine = $Myline.LineNumber - 1 $InstalledLicLine = $LicTypeLine + 3 $InUseLine = $InstalledLicLine + 1 $PercentageLine = $LicTypeLine +6 # Read line for Installed Licences $LicTypeRAW = @(gc $tempfile)[$LicTypeLine] $LicTypeText = [regex]::match($LicTypeRAW,'(?<=).+(?=)').value #Write "License Type: $LicTypeText" # Read line for Installed Licences $InstalledLicRAW = @(gc $tempfile)[$InstalledLicLine] $InstalledLicNum = [regex]::match($InstalledLicRAW,'(?<=).+(?=)').value #Write "Installed Licences: $InstalledLicNum" # Read line for Licences in use $InUseRAW = @(gc $tempfile)[$InUseLine] $InUseNum = [regex]::match($InUseRAW,'(?<=).+(?=)').value #Write "Licences In Use: $InUseNum" # Read Percentage used line $PercentageRAW = @(gc $tempfile)[$PercentageLine] $PercentageNum = [regex]::match($PercentageRAW,'[0-9]+').value #Write "Percentage: $PercentageNum%" # Check the usage and send an email if over 90% if ($PercentageNum -lt 90) { } else { Sendemail $LicTypeText $InstalledLicNum $InUseNum $PercentageNum } if ($sendmailsched -eq "send") { Sendemail $LicTypeText $InstalledLicNum $InUseNum $PercentageNum } # Remove the temporary contents file Remove-Item $tempfile
PowerShellCorpus/PoshCode/New-SQLComputerLogin_1.ps1
New-SQLComputerLogin_1.ps1
# Depends on Invoke-SQLCmd2 http://poshcode.org/2950 # Depends on Get-ADComputer http://poshcode.org/3009 function New-SqlComputerLogin { #.Synopsis # Creates a Login on the specified SQL server for a computer account #.Example # New-SqlComputerLogin -SQL DevDB2 -Computer BuildBox2 -Force # # Specifying the Force parameter causes us to lookup the SID and remove a duplicate entry (in case your computer had an account before under another name). [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0)] [String]$SQLServer, [Parameter(ValueFromPipelineByPropertyName=$true, Position=1)] [String]$ComputerName, [Switch]$Force ) process { # Import-Module QAD, SQLPS -DisableNameChecking $Computer = Get-ADComputer $ComputerName #$NTAccountName = $Computer.NTAccountName #if(!$SID) { $SID = $Computer.SID.ToString() } invoke-sqlcmd2 -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS" -ErrorVariable SqlError -ErrorAction SilentlyContinue ## If this principal already exists, fail, or clean it out and recreate it: if($SqlError[0].Exception.Message.EndsWith("already exists.")) { if(!$Force) { Write-Error $SqlError[0].Exception } else { $ExistingAccount = invoke-sqlcmd2 -ServerInstance $SQLServer -Query "select name, sid, create_date from sys.server_principals where type IN ('U','G')" | add-member -membertype ScriptProperty SSDL { new-object security.principal.securityidentifier $this.SID, 0 } -passthru | where-object {$_.SSDL -eq $Computer.SID} invoke-sqlcmd2 -ServerInstance $SQLServer -Query "DROP LOGIN [$($ExistingAccount.Name)]" -ErrorAction Stop invoke-sqlcmd2 -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS" } } }}
PowerShellCorpus/PoshCode/SetDefaultPrinter_1.ps1
SetDefaultPrinter_1.ps1
<# .SYNOPSIS Sets the Default Printer for any user on any machine in active directory. .DESCRIPTION Search AD for Computername; Select User Account and Printer and make that printer the default printer for that user on that computer. .PARAMETER Hostnme This parameter is required and should reflect the computer name (or names) you wish to inventory. This is basically a search criteria because the first thing the script will do is search Active Directory for computer names matching this input. .NOTES Author: Brad Blaylock Version: 3.2 Date: October 3, 2011 Contact: brad.blaylock@gmail.com Details: This Script accepts an AD Query (Computername) in the form of an entire computer name or partial computername as in sbcomp* or *2471wk1 and will find any listed computers that match the criteria in AD. This list will be presented to the user. The user will select the computer they are needing, and click [LOAD]. Load will find all user accounts that have ever had a profile on that computer; Load will also list all printers installed on that computer. The user will then select the user account and printer and click [Set Default]. SetDefault will make the selected printer default for the selected user on the selected computer. 3.0 -If the selected user is not logged into the selected computer at the time, SetDefault will Load the selected user's NTUSER.DAT registry Hive and make the selected changes offline. 3.2 -Added Current User Display Issues: None Discovered as of Yet. } #> #~~~~~~~~Global \\ Script Variables~~~~~~# $Script:ping = new-object System.Net.NetworkInformation.Ping $Script:tcpClient = New-Object System.Net.Sockets.TcpClient $Script:Search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”) $Script:hku = 2147483651 $Script:hklm = 2147483650 $Script:UserPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList" $Script:PrinterPath = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Printers" $Script:domain = $env:USERDOMAIN #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #~~~~~~~~~~~CUSTOM FUNCTIONS~~~~~~~~~~~~# function Test-Alive($comp) { $stat=$ping.Send("$comp") $reply = $stat.status trap { $False continue; } if($reply -eq "Success") {$True} } function Ping-Port([string]$server, [int]$port) { trap { $False continue; } $tcpClient.Connect($server,$port) if ($tcpClient.Connected) {$True} } Function ADSearch { $Input = $Args[0] $Search.filter = “(&(objectClass=Computer)(Name=$Input))” $Results = $Search.Findall() foreach ($i in $Results) { $Item = $i.properties $lbxServers.Items.Add("$($Item.cn)") } } function LoadUsers { $UserWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Accounts = $UserWMI.EnumKey($hklm,$UserPath) foreach ($Account in $Accounts.snames) { $User = $UserWMI.GetStringValue($hklm,"$UserPath\\$Account","ProfileImagePath") $UserName = ($User.svalue).split("\\")[2] $cbxUserAccount.Items.Add($Username) } $currentuser = (gwmi win32_ComputerSystem -computername $Computer | select UserName).UserName $tbxCurrentUser.Text = $currentuser } Function LoadPrinters { $PrinterWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Printers = $PrinterWMI.EnumKey($hklm,$PrinterPath) foreach ($Printer in $Printers.snames) { $Print = $PrinterWMI.GetStringValue($hklm,"$PrinterPath\\$Printer","Name") $PrinterName = $Print.svalue $cbxPrinter.Items.Add($PrinterName) } } Function SetWithLocalRegHive { #<# #Test OS Version (2000, XP or Vista\\7\\8) $ostest = (gwmi win32_operatingsystem -computername $Computer | select Version | %{$_ -replace "@{Version=", ""} | %{$_ -replace "}", ""}) $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) Switch -wildcard ($ostest) { "5.0*" {$tbxStatus.Text = "Windows 2000"; $profileroot = "Documents and Settings"} "5.1*" {$tbxStatus.Text = "Windows XP"; $profileroot = "Documents and Settings"} "6.0*" {$tbxStatus.Text = "Windows Vista"; $profileroot = "Users" } "6.1*" {$tbxStatus.Text = "Windows 7"; $profileroot = "Users"} } Reg Load HKLM\\TemporaryHive \\\\$Computer\\C$\\$profileroot\\$UserName\\NTUSER.DAT $LocalDefPrinter = (New-Object -ComObject Wscript.shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device") $localDetailsTest = Test-Path "HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices" If (!$LocalDetailsTest) { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "Incomplete User Profile" } Else { $LocalDefPrinterDetails = (New-Object -ComObject Wscript.Shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices\\$PrinterName") $LocalDefaultPrinter = ($LocalDefPrinter).split(",")[0] $Localspool = ($LocalDefPrinterDetails).split(",")[0] $LocalPort = ($LocalDefPrinterDetails).split(",")[1] $LocalNewDefPrinter = $PrinterName + "," + $Localspool + "," + $LocalPort (New-Object -comobject Wscript.Shell).regWrite("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device", "$LocalNewDefPrinter", "REG_SZ") Reg Unload HKLM\\TemporaryHive $tbxStatus.Text = "Default Printer Changed!" } } Function SetDefaultPrinter { Get-service -ComputerName $Computer -Include 'RemoteRegistry' | Start-Service $ntAccount = new-object System.Security.Principal.NTAccount($domain, $UserName) $sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]) $ActionPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows" $DevicesPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices" $ActionWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $DefPrinter = $ActionWMI.GetStringValue($hku,"$ActionPath","Device") $DefPrinterDetails = $ActionWMI.GetStringValue($hku,"$DevicesPath","$PrinterName") $testRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hku,$Computer) $testReg = $testRegKey.OpenSubKey("$sid") If (!$testReg) { SetWithLocalRegHive } Else { $DefaultPrinter = ($DefPrinter.svalue).split(",")[0] $spool = ($DefPrinterDetails.svalue).split(",")[0] $Port = ($DefPrinterDetails.svalue).split(",")[1] $NewDefPrinter = $PrinterName + "," + $spool + "," + $Port $ActionWMI.SetStringValue($HKU,"$ActionPath","Device","$NewDefPrinter") #SET THE DEFAULT PRINTER# $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Default Printer Changed!" } $cbxUserAccount.ResetText() $cbxPrinter.ResetText() } #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.8.0 # Generated On: 2/28/2011 11:35 AM # Generated By: bwblaylock ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms.VisualStyles") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() #endregion #region Generated Form Objects $FrmMain = New-Object System.Windows.Forms.Form $pgbProgress = New-Object System.Windows.Forms.ProgressBar $lblPrinter = New-Object System.Windows.Forms.Label $lblUserAccount = New-Object System.Windows.Forms.Label $lblSearch = New-Object System.Windows.Forms.Label $btnSearch = New-Object System.Windows.Forms.Button $tbxSearch = New-Object System.Windows.Forms.TextBox $btnClose = New-Object System.Windows.Forms.Button $btnLoad = New-Object System.Windows.Forms.Button $tbxServer = New-Object System.Windows.Forms.TextBox $tbxStatus = New-Object System.Windows.Forms.TextBox $tbxCurrentUser = New-Object System.Windows.Forms.TextBox $lbxServers = New-Object System.Windows.Forms.ListBox $btnSetDefault = New-Object System.Windows.Forms.Button $cbxPrinter = New-Object System.Windows.Forms.ComboBox $cbxUserAccount = New-Object System.Windows.Forms.ComboBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $btnClose_OnClick= { $FrmMain.Close() } $lbxServers.add_SelectedIndexChanged({ $tbxStatus.Text = $Null $tbxStatus.Refresh() $tbxServer.Text = $lbxServers.SelectedItem $tbxServer.Refresh() $tbxCurrentUser.Text = $null $tbxCurrentUser.Refresh() $cbxPrinter.Items.clear() $cbxPrinter.Text = $null $cbxPrinter.Refresh() $cbxUserAccount.Items.clear() $cbxUserAccount.Text = $null $cbxUserAccount.Refresh() }) $btnLoad_OnClick= { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,255,0) $tbxStatus.Text = "Loading..." $tbxStatus.Refresh() $Computer = $tbxServer.Text If (Test-Alive $Computer) { if ( (ping-port $Computer 135) -and (ping-port $Computer 445) ) { LoadUsers $Computer LoadPrinters $Computer $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Ready..." } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "RPC Server Not Available" } } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "Server Offline" } $pgbProgress.Visible = $False } $btnSetDefault_OnClick= { $Script:Computer = $tbxServer.Text $Script:UserName = $cbxUserAccount.SelectedItem $Script:PrinterName = $cbxPrinter.SelectedItem SetDefaultPrinter } $btnSearch_OnClick= { $lbxServers.Items.Clear() $Criteria = $tbxSearch.Text ADSearch $Criteria } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $FrmMain.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code #Main Form $FrmMain.CancelButton = $btnClose $FrmMain.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $FrmMain.Text = "Set Default Printer" $FrmMain.Name = "FrmMain" $FrmMain.KeyPreview = $True $FrmMain.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 439 $System_Drawing_Size.Height = 272 $FrmMain.ClientSize = $System_Drawing_Size $FrmMain.AcceptButton = $btnSearch $FrmMain.FormBorderStyle = 2 #Search Label $lblSearch.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 14 $lblSearch.Size = $System_Drawing_Size $lblSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 9 $lblSearch.Location = $System_Drawing_Point $lblSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $lblSearch.Name = "lblSearch" $FrmMain.Controls.Add($lblSearch) #Printer Label $lblPrinter.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 12 $lblPrinter.Size = $System_Drawing_Size $lblPrinter.Text = "Printer:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 185 $lblPrinter.Location = $System_Drawing_Point $lblPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $lblPrinter.Name = "lblPrinter" $FrmMain.Controls.Add($lblPrinter) #UserAccount Label $lblUserAccount.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 13 $lblUserAccount.Size = $System_Drawing_Size $lblUserAccount.Text = "User Account:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 145 $lblUserAccount.Location = $System_Drawing_Point $lblUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $lblUserAccount.Name = "lblUserAccount" $FrmMain.Controls.Add($lblUserAccount) #Progress Bar $pgbProgress.DataBindings.DefaultDataSourceUpdateMode = 0 $pgbProgress.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $pgbProgress.ForeColor = [System.Drawing.Color]::FromArgb(255,0,255,0) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 191 $System_Drawing_Size.Height = 8 $pgbProgress.Size = $System_Drawing_Size $pgbProgress.Step = 1 $pgbProgress.TabIndex = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 246 $System_Drawing_Point.Y = 105 $pgbProgress.Location = $System_Drawing_Point $pgbProgress.Style = [System.Windows.Forms.ProgressBarStyle]::Marquee #2 $pgbProgress.MarqueeAnimationSpeed = 50 $pgbProgress.Visible = $False $pgbProgress.Name = "pgbProgress" $FrmMain.Controls.Add($pgbProgress) #Status Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxStatus.Size = $System_Drawing_Size $tbxStatus.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxStatus.TextAlign = 2 $tbxStatus.BorderStyle = 0 $tbxStatus.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,0) $tbxStatus.Name = "tbxStatus" $tbxStatus.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 88 $tbxStatus.Location = $System_Drawing_Point $tbxStatus.TabIndex = 20 $FrmMain.Controls.Add($tbxStatus) #Server Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxServer.Size = $System_Drawing_Size $tbxServer.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxServer.TextAlign = 2 $tbxServer.BorderStyle = 0 $tbxServer.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,1) $tbxServer.Name = "tbxServer" $tbxServer.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 32 $tbxServer.Location = $System_Drawing_Point $tbxServer.TabIndex = 19 $FrmMain.Controls.Add($tbxServer) #CurrentUser Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxCurrentUser.Size = $System_Drawing_Size $tbxCurrentUser.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxCurrentUser.TextAlign = 2 $tbxCurrentUser.BorderStyle = 0 $tbxCurrentUser.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Italic') #0,3,1) $tbxCurrentUser.Name = "tbxCurrentUser" $tbxCurrentUser.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 60 $tbxCurrentUser.Location = $System_Drawing_Point $tbxCurrentUser.TabIndex = 20 $FrmMain.Controls.Add($tbxCurrentUser) #Search Button $btnSearch.TabIndex = 2 $btnSearch.Name = "btnSearch" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnSearch.Size = $System_Drawing_Size $btnSearch.UseVisualStyleBackColor = $True $btnSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 180 $System_Drawing_Point.Y = 26 $btnSearch.Location = $System_Drawing_Point $btnSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSearch.add_Click($btnSearch_OnClick) $FrmMain.Controls.Add($btnSearch) #Load Button $btnLoad.TabIndex = 4 $btnLoad.Name = "btnLoad" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnLoad.Size = $System_Drawing_Size $btnLoad.UseVisualStyleBackColor = $True $btnLoad.Text = "Load" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 310 $System_Drawing_Point.Y = 120 $btnLoad.Location = $System_Drawing_Point $btnLoad.DataBindings.DefaultDataSourceUpdateMode = 0 $btnLoad.add_Click($btnLoad_OnClick) $FrmMain.Controls.Add($btnLoad) #Close Button $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 351 $System_Drawing_Point.Y = 236 $btnClose.Location = $System_Drawing_Point $btnClose.DataBindings.DefaultDataSourceUpdateMode = 0 $btnClose.DialogResult = 2 $btnClose.add_Click($btnClose_OnClick) $FrmMain.Controls.Add($btnClose) #SetDefault Button $btnSetDefault.TabIndex = 7 $btnSetDefault.Name = "btnSetDefault" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnSetDefault.Size = $System_Drawing_Size $btnSetDefault.UseVisualStyleBackColor = $True $btnSetDefault.Text = "Set Default" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 236 $btnSetDefault.Location = $System_Drawing_Point $btnSetDefault.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSetDefault.add_Click($btnSetDefault_OnClick) $FrmMain.Controls.Add($btnSetDefault) #Search Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 161 $System_Drawing_Size.Height = 20 $tbxSearch.Size = $System_Drawing_Size $tbxSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxSearch.Name = "tbxSearch" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 29 $tbxSearch.Location = $System_Drawing_Point $tbxSearch.TabIndex = 1 $FrmMain.Controls.Add($tbxSearch) $btnClose.TabIndex = 8 $btnClose.Name = "btnClose" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnClose.Size = $System_Drawing_Size $btnClose.UseVisualStyleBackColor = $True $btnClose.Text = "Close" #Servers Listbox #$lbxServers.UseCompatibleStateImageBehavior = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 227 $System_Drawing_Size.Height = 205 $lbxServers.Size = $System_Drawing_Size $lbxServers.DataBindings.DefaultDataSourceUpdateMode = 0 $lbxServers.Name = "lbxServers" #$lbxServers.View = 3 $lbxServers.TabIndex = 3 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 55 $lbxServers.Location = $System_Drawing_Point $FrmMain.Controls.Add($lbxServers) #Printer Combobox $cbxPrinter.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxPrinter.Size = $System_Drawing_Size $cbxPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxPrinter.Name = "cbxPrinter" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 200 $cbxPrinter.Location = $System_Drawing_Point $cbxPrinter.TabIndex = 6 $FrmMain.Controls.Add($cbxPrinter) #UserAccount Combobox $cbxUserAccount.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxUserAccount.Size = $System_Drawing_Size $cbxUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxUserAccount.Name = "cbxUserAccount" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 161 $cbxUserAccount.Location = $System_Drawing_Point $cbxUserAccount.TabIndex = 5 $FrmMain.Controls.Add($cbxUserAccount) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $FrmMain.WindowState #Init the OnLoad event to correct the initial state of the form $FrmMain.add_Load($OnLoadForm_StateCorrection) #Show the Form $FrmMain.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/8b815eb7-c620-4159-b0fc-435ceeca036b.ps1
8b815eb7-c620-4159-b0fc-435ceeca036b.ps1
# Add the Active Directory bits and not complain if they're already there Import-Module ActiveDirectory -ErrorAction SilentlyContinue # set default password # change pass@word1 to whatever you want the account passwords to be $defpassword = (ConvertTo-SecureString "pass@word1" -AsPlainText -force) # Get domain DNS suffix $dnsroot = '@' + (Get-ADDomain).dnsroot # Import the file with the users. You can change the filename to reflect your file $users = Import-Csv .\\users.csv foreach ($user in $users) { if ($user.manager -eq "") # In case it's a service account or a boss { try { New-ADUser -SamAccountName $user.SamAccountName -Name ($user.FirstName + " " + $user.LastName) ` -DisplayName ($user.FirstName + " " + $user.LastName) -GivenName $user.FirstName -Surname $user.LastName ` -EmailAddress ($user.SamAccountName + $dnsroot) -UserPrincipalName ($user.SamAccountName + $dnsroot) ` -Title $user.title -Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires $true ` -AccountPassword $defpassword -PassThru ` } catch [System.Object] { Write-Output "Could not create user $($user.SamAccountName), $_" } } else { try { New-ADUser -SamAccountName $user.SamAccountName -Name ($user.FirstName + " " + $user.LastName) ` -DisplayName ($user.FirstName + " " + $user.LastName) -GivenName $user.FirstName -Surname $user.LastName ` -EmailAddress ($user.SamAccountName + $dnsroot) -UserPrincipalName ($user.SamAccountName + $dnsroot) ` -Title $user.title -manager $user.manager ` -Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires $true ` -AccountPassword $defpassword -PassThru ` } catch [System.Object] { Write-Output "Could not create user $($user.SamAccountName), $_" } } # Put picture part here. $filename = "$($user.SamAccountName).jpg" Write-Output $filename if (test-path -path $filename) { Write-Output "Found picture for $($user.SamAccountName)" $photo = [byte[]](Get-Content $filename -Encoding byte) Set-ADUser $($user.SamAccountName) -Replace @{thumbnailPhoto=$photo} } }
PowerShellCorpus/PoshCode/New-UrlFile.ps1
New-UrlFile.ps1
function New-UrlFile { param( $URL = "http://www.google.com") $UrlFile = [system.io.Path]::ChangeExtension([system.io.Path]::GetTempFileName(),".url") $UrlFileContents = ` "[InternetShortcut]", "URL=$URL" Write-Host $URL $UrlFileContents | Set-Content -Path $UrlFile Get-Item $UrlFile }
PowerShellCorpus/PoshCode/Get-PrivateKeyPath.ps1
Get-PrivateKeyPath.ps1
#requires -Version 2.0 function Get-PrivateKeyPath { param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [System.Security.Cryptography.X509Certificates.X509Certificate2] [ValidateScript( { ( $_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2] ) } ) ] $Certificate, [string] [ValidateSet('TrustedPublisher','Remote Desktop','Root','REQUEST','TrustedDevices','CA','Windows Live ID Token Issuer','AuthRoot','TrustedPeople','AddressBook','My','SmartCardRoot','Trust','Disallowed')] $StoreName = 'My', [string] [ValidateSet('LocalMachine','CurrentUser')] $StoreScope = 'CurrentUser' ) begin { Add-Type -AssemblyName System.Security } process { if ($Certificate.PrivateKey -eq $null){Write-Error ("Certificate doesn't have Private Key") -ErrorAction:Stop} Switch ($StoreScope) { "LocalMachine" { $PrivateKeysPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::CommonApplicationData) + "\\Microsoft\\Crypto\\RSA\\MachineKeys" } "CurrentUser" { $PrivateKeysPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::ApplicationData) + "\\Microsoft\\Crypto\\RSA" } } $PrivateKeyPath = $PrivateKeysPath + "\\" + $Certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName $PrivateKeyPath } end { } }
PowerShellCorpus/PoshCode/Invoke-PoshCode.ps1
Invoke-PoshCode.ps1
# .Summary # Download and execute a script block from PoshCode.org # .Description # Download the code for a PoshCode script based on search of by specific index. # Execute the code as a script block, passing arguments to it. # # Note: this is scary, and you should only use it if you really know what you're doing ;) By invoking the downloaded code as a script block, we effenctively bypass the execution policy... # # Depends on the PoshCode module from http://poshcode.org/PoshCode.psm1 # # .Parameter SearchTerms # The terms to use when searching, or the Id of the spu # .Parameter ArgumentList # The arguments to be passed to the Invoked script # .Example # Invoke-PoshCode Test-Port localhost 80 # # Search for "Test-Port" and invoke the first result with the parameters "localhost" and 80 # .Example # Invoke-PoshCode 85 localhost 80 # # Fetch http://poshcode.org/get/85 and invoke it with the parameters "localhost" and 80 # .Example # Invoke-PoshCode 85 -ArgumentList @{srv="localhost";port="80"} # # Fetch http://poshcode.org/get/85 and invoke it with the parameters srv = "localhost" and port = 80 function Invoke-PoshCode { param( [Parameter(Mandatory=$true, Position=1)]$SearchTerms, [Parameter(Position=2, ValueFromRemainingArguments=$true)]$ArgumentList) Write-Verbose "Searching for: $SearchTerms" if($SearchTerms -is [int]) { $Code = Get-PoshCode -Id $SearchTerms -Passthru } else { $Code = Get-PoshCode -Query $SearchTerms | Select -First 1 | Get-PoshCode -Passthru } Invoke-Command -ScriptBlock ([ScriptBlock]::Create($Code)) -ArgumentList $ArgumentList }
PowerShellCorpus/PoshCode/Get-Credential.ps1
Get-Credential.ps1
function Get-Credential{ PARAM([String]$Title, [String]$Message, [String]$Domain, [String]$UserName, [switch]$Console) ## Carefully EA=SilentlyContinue and check for $True because by default it's MISSING (not False, as you might expect) $cp = (Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds ConsolePrompting -ea "SilentlyContinue").ConsolePrompting -eq $True if($Console -and !$cp) { Set-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds" ConsolePrompting $True } elseif(!$Console -and $Console.IsPresent -and $cp) { Set-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds" 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) ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True) Set-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds" ConsolePrompting $cp }
PowerShellCorpus/PoshCode/Get-MacAddressOui_1.ps1
Get-MacAddressOui_1.ps1
function Get-MacAddressOui { <# .SYNOPSIS Gets a MAC address OUI (Organizationally Unique Identifier). .DESCRIPTION The Get-MacAddressOui function retrieves the MAC address OUI reference list maintained by the IEEE standards website and returns the name of the company to which the MAC address OUI is assigned. .PARAMETER MacAddress Specifies the MAC address for which the OUI should be retrieved. .EXAMPLE Get-MacAddressOui 00:02:B3:FF:FF:FF Returns the MAC address OUI and the company assigned that idenifier. .INPUTS System.String .OUTPUTS PSObject .NOTES Name: Get-MacAddressOui Author: Rich Kusak (rkusak@hotmail.com) Created: 2011-09-01 LastEdit: 2011-09-06 19:09 Version: 1.0.3.0 .LINK http://standards.ieee.org/develop/regauth/oui/oui.txt .LINK about_regular_expressions #> [CmdletBinding()] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateScript({ # Builds regex patterns for the 4 MAC address hex formats $patterns = @(':', '-', $null) | ForEach {"^([0-9a-f]{2}$_){5}([0-9a-f]{2})$"} $patterns += '^([0-9a-f]{4}\\.){2}([0-9a-f]{4})$' if ($_ -match ($patterns -join '|')) {$true} else { throw "The argument '$_' does not match a valid MAC address format." } })] [string]$MacAddress ) begin { $uri = 'http://standards.ieee.org/develop/regauth/oui/oui.txt' $webClient = New-Object System.Net.WebClient try { Write-Debug "Performing operation 'DownloadString' on target '$uri'." $ouiReference = $webClient.DownloadString($uri) } catch { throw $_ } $properties = 'MacAddress', 'OUI', 'Company' } # begin process { $oui = ($MacAddress -replace '\\W').Remove(6) $regex = "($oui)\\s*\\(base 16\\)\\s*(.+)" New-Object PSObject -Property @{ 'MacAddress' = $MacAddress 'OUI' = $oui 'Company' = [regex]::Match($ouiReference, $regex, 'IgnoreCase').Groups[2].Value } | Select $properties } # process } # function Get-MacAddressOui
PowerShellCorpus/PoshCode/Add-UniqueEndings.ps1
Add-UniqueEndings.ps1
## Add-UniqueEndings ## Takes an array of strings and forces them to be unique by adding _<number> tails to duplicates. #################################################################################################### ## Usage: ## $$: (Add-UniqueEndings "one","two","three","one","two","one","one_5").ToString() ## one, two, three, one_1, two_1, one_2, one_3 ## ## $$: ("one","two","three","one","two","one","one_5" | Add-UniqueEndings).ToString() ## one, two, three, one_1, two_1, one_2, one_3 #################################################################################################### ## History: ## v1 - adds tails _ until the string is unique ## v2 - adds number tails _1 instead ## v2.5 - works with the array passed as an argument (default is on the pipeline) #################################################################################################### function Add-UniqueEndings { BEGIN { if($args.Count) { $args[0] | Add-UniqueEndings } else { $uniques = @{} $collect = @() } } PROCESS { if($_){ $item = "$_" -replace "(.*)_\\d+",'$1' $collect += $item $uniques.$item += 1 } } END { if(!$args.Count -and $collect.Count) { [Array]::Reverse($collect) $collect = $collect | % { if($uniques.$_-- -eq 1){ $_ } else { "$_$('_')$($uniques.$_)" } } [Array]::Reverse($collect) $collect } } }
PowerShellCorpus/PoshCode/$env_PATH permanently.ps1
$env_PATH permanently.ps1
#requires -version 2 param( [string] $AddedFolder, [bool] $ApplyImmediately = $true ) $environmentRegistryKey = 'Registry::HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment' $oldPath = (Get-ItemProperty -Path $environmentRegistryKey -Name PATH).Path # See if a new folder has been supplied. if (!$AddedFolder) { Write-Warning 'No Folder Supplied. $ENV:PATH Unchanged' return } if ($ENV:PATH | Select-String -SimpleMatch $AddedFolder) { Write-Warning 'Folder already within $ENV:PATH' return } $newPath = $oldPath + ’;’ + $AddedFolder Set-ItemProperty -Path $environmentRegistryKey -Name PATH -Value $newPath if ($ApplyImmediately) { if (-not ("Win32.NativeMethods" -as [Type])) { # import sendmessagetimeout from win32 Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @" [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult); "@ } $HWND_BROADCAST = [IntPtr] 0xffff; $WM_SETTINGCHANGE = 0x1a; $result = [UIntPtr]::Zero # notify all windows of environment block change [Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref] $result); }
PowerShellCorpus/PoshCode/a4d96102-d5a8-4437-b3e0-568a0936fcbf.ps1
a4d96102-d5a8-4437-b3e0-568a0936fcbf.ps1
# The $test variable can be pretty much whatever you want it to be, or with a little adjustment it isn't even necessary. # I just wanted to set it up like this for the $match variable later on $test=(get-folder testing|get-vm) #$data and the csv is where all the information lies that this script/s pulls $data=import-csv book1.csv $hostcredential=Get-Credential "Host Credentials" $guestcredential=Get-Credential "Guest Credentials" #Line row, row line, same thing in a spreadsheet. I just wish I knew more of those basic understood variables such as $line. # If anyone knows a good listing please let me know foreach ($line in $data) { #For each of the VMs in $test it checks to see if there is a listing for that vm name in the excel spreadsheet. $match=$test|?{$line.guestname -eq $_.name} IF($match) { #Oh invoke-vmscript how I both love and hate you. This calls for the execution of the script works2.ps1 script locally on the remote computer invoke-vmscript -vm $match.name -scripttext '&"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" "C:\\Power\\works2.ps1"' -scripttype "powershell" -hostcredential $hostcredential -guestcredential $guestcredential -confirm } }
PowerShellCorpus/PoshCode/Get-SerialNumber.ps1
Get-SerialNumber.ps1
function Get-SerialNumber { param([VMware.VimAutomation.Types.VMHost[]]$InputObject = $null) process { $hView = $_ | Get-View -Property Hardware $serviceTag = $hView.Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.IdentifierType.Key -eq "ServiceTag" } $assetTag = $hView.Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.IdentifierType.Key -eq "AssetTag" } $obj = New-Object psobject $obj | Add-Member -MemberType NoteProperty -Name VMHost -Value $_ $obj | Add-Member -MemberType NoteProperty -Name ServiceTag -Value $serviceTag.IdentifierValue $obj | Add-Member -MemberType NoteProperty -Name AssetTag -Value $assetTag.IdentifierValue Write-Output $obj } }
PowerShellCorpus/PoshCode/Start-RDP_2.ps1
Start-RDP_2.ps1
######################################################################################################################## # NAME # Start-RDP # # SYNOPSIS # Opens a remote desktop connection to another computer. # # SYNTAX # Start-RDP [[-Server] <string>] [[-Width] <int>] [[-Height] <int>] # Start-RDP -Path <string> [[-Width] <int>] [[-Height] <int>] # # DETAILED DESCRIPTION # The Start-RDP cmdlet opens a new Remote Desktop connection using the Microsoft Terminal Services Client. # Connection settings can be specified by argument or read from a standard RDP file. # # PARAMETERS # -Server <string> # Specifies the name of the server to connect to. May also include an IP address, domain, and/or port. # # Required? false # Position? 1 # Default value # Accept pipeline input? true # Accept wildcard characters? false # # -Width <int> # Specifies the desired width of the resolution for the connection (for non-full screen connections). # # Required? false # Position? 2 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Height <int> # Specifies the desired height of the resolution for the connection (for non-full screen connections). # # Required? false # Position? 3 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Path <string> # Specifies the path to an RDP file to connect with (resolution settings can be overridden using the # -Width and -Height parameters. # # Required? false # Position? 4 # Default value # Accept pipeline input? true # Accept wildcard characters? false # # -Console <SwitchParameter> # Connect to a Windows Server 2003 console session. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Admin <SwitchParameter> # Connect to a Windows Server 2008 administrator session. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Fullscreen <SwitchParameter> # Open connection in full screen mode. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Public <SwitchParameter> # Run Remote Desktop in public mode. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # -Span <SwitchParameter> # Span the Remote Desktop connection across multiple monitors. Each monitor must have the same height # and be arranged vertically. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # INPUT TYPE # String,System.IO.FileInfo # # RETURN TYPE # # # NOTES # # -------------------------- EXAMPLE 1 -------------------------- # # C:\\PS>Start-RDP # # # This command opens the Terminal Services Client connection dialog to specify a connection. # # # -------------------------- EXAMPLE 2 -------------------------- # # C:\\PS>Start-RDP -Server myserver -Width 1024 -Height 768 # # # This command opens a new Remote Desktop connection to the server named "myserver" in a window with 1024x768 resolution. # # # -------------------------- EXAMPLE 3 -------------------------- # # C:\\PS>Start-RDP -Server myserver -Fullscreen # # # This command opens a new full screen Remote Desktop connection to the server named "myserver". # # # -------------------------- EXAMPLE 4 -------------------------- # # C:\\PS>Start-RDP -Path C:\\myserver.rdp # # # This command opens a new Remote Desktop connection using the specified RDP file. # # #Function global:Start-RDP { param( [string]$Server = "", [int]$Width = "", [int]$Height = "", [string]$Path = "", [switch]$Console, [switch]$Admin, [switch]$Fullscreen, [switch]$Public, [switch]$Span ) begin { $arguments = "" $dimensions = "" $processed = $false if ($admin) { $arguments += "/admin " } elseif ($console) { $arguments += "/console " } if ($fullscreen) { $arguments += "/f " } if ($public) { $arguments += "/public " } if ($span) { $arguments += "/span " } if ($width -and $height) { $dimensions = "/w:$width /h:$height" } } process { Function script:executePath([string]$path) { Invoke-Expression "mstsc.exe '$path' $dimensions $arguments" } Function script:executeArguments([string]$Server) { Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments" } if ($_) { if ($_ -is [string]) { if ($_ -imatch '\\.rdp$') { if (Test-Path $_) { executePath $_ $processed = $true } else { throw "Path does not exist." } } else { executeArguments $_ $processed = $true } } elseif ($_ -is [System.IO.FileInfo]) { if (Test-Path $_.FullName) { executePath $_.FullName $processed = $true } else { throw "Path does not exist." } } elseif ($_.Path) { if (Test-Path $_.Path) { executePath $_.Path $processed = $true } else { throw "Path does not exist." } } elseif ($_.DnsName) { executeArguments $_.DnsName $processed = $true } elseif ($_.Server) { executeArguments $_.Server $processed = $true } elseif ($_.ServerName) { executeArguments $_.ServerName $processed = $true } elseif ($_.Name) { executeArguments $_.Name $processed = $true } } } end { if ($path) { if (Test-Path $path) { Invoke-Expression "mstsc.exe '$path' $dimensions $arguments" } else { throw "Path does not exist." } } elseif ($server) { Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments" } elseif (-not $processed) { Invoke-Expression "mstsc.exe $dimensions $arguments" } } #}
PowerShellCorpus/PoshCode/ESXiMgmt module.ps1
ESXiMgmt module.ps1
####################################################################################################################### # File: ESXiMgmt.psm1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### Set-StrictMode -Version Latest #region initialization # Initailize PowerCLI environment if ((Get-PSSnapin VMware.VimAutomation.Core) -ne $null -and ` (Get-PSSnapin VMware.VimAutomation.Core).Name.Length -gt 0) { Remove-PSSnapin VMware.VimAutomation.Core; } Add-PSSnapin VMware.VimAutomation.Core; # x86 if ($Env:PROCESSOR_ARCHITECTURE -eq 'x86'){ . "$env:ProgramFiles\\VMware\\Infrastructure\\vSphere PowerCLI\\Scripts\\Initialize-PowerCLIEnvironment.ps1" } # x64 if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64'){ . "${env:ProgramFiles(x86)}\\VMware\\Infrastructure\\vSphere PowerCLI\\Scripts\\Initialize-PowerCLIEnvironment.ps1" } # It is recommended to put plink.exe in the directory this module resides # plink.exe can be taken from this link # http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe if (Test-Path -Path ($PSScriptRoot + '\\plink.exe')){ [string]$script:plinkPath = $PSScriptRoot + '\\plink.exe'; } #endregion initialization #region private functions #region function Get-CurrentTime function Get-CurrentTime <# .SYNOPSIS The Get-CurrentTime function is used to write in the timestamp in the log file. .DESCRIPTION The Get-CurrentTime functions is used for getting the current time of operation. As s time source used [System.DateTime]::Now.TimeOfDay property. .EXAMPLE PS C:\\> Get-CurrentTime .OUTPUTS System.String #> { $timeOfDay = [System.DateTime]::Now.TimeOfDay; $time = "$($timeOfDay.Hours):$($timeOfDay.Minutes):$($timeOfDay.Seconds)`t"; return $time;} #endregion function Get-CurrentTime #endregion private functions #region public functions #region function Connect-ESXi function Connect-ESXi <# .SYNOPSIS Connects to a single ESXi you are planning to work with. .DESCRIPTION The Connect-ESXi function is intended to be the first the user runs while working with this module. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER Port Default value is 443. See the Connect-VIServer description. .PARAMETER Protocol Default value is HTTPS. See the Connect-VIServer description. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER DatastoreName The name of the datastore you work with. .PARAMETER Drive The name that will represents the content of the datastore. .EXAMPLE PS C:\\> Connect-ESXi -Server 192.168.1.1 -Port 443 -Protocol HTTPS -User root -Password 123 -DatastoreName datastore1 -Drive server1 .INPUTS System.String, System.Int32 .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$false)] [int]$Port = 443, [Parameter(Mandatory=$false)] [string]$Protocol = 'HTTPS', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$DatastoreName, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Drive ) [string]$script:pwd = $Password; [VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl]$script:esxiserver = ` Connect-VIServer -Server $Server ` -User $User -Password $Password ` -Protocol $Protocol -Port $Port; [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]$script:vmhost = ` Get-VMHost -Server $script:esxiserver; [VMware.VimAutomation.ViCore.Impl.V1.DatastoreManagement.DatastoreImpl]$script:datastore = ` Get-Datastore -Server $script:esxiserver -Name $DatastoreName; try{New-DatastoreDrive -Datastore $script:datastore -Name $Drive; [string]$script:dsdrive = $Drive;}catch{} } #endregion function Connect-ESXi #region function Disconnect-ESXi function Disconnect-ESXi <# .SYNOPSIS Disconnects the latest connected ESXi server. .DESCRIPTION The function cleans up the variable that stores VIServer object of the server you connected. .EXAMPLE PS C:\\> Disconnect-ESXi .INPUTS None .OUTPUTS None #> { Disconnect-VIServer -Server $script:esxiserver -Force:$true; } #endregion function Disconnect-ESXi #region function Invoke-ESXiCommand function Invoke-ESXiCommand <# .SYNOPSIS Runs a command or a semicolon-separated sequence of commands on an ESXi server. .DESCRIPTION This function runs plink.exe with the command supplied and optionally suppressses the console window. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Command The string that plink.exe runs on a server. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER ShowWindow Enables or disables appearance of the plink.exe console window. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> Invoke-ESXiCommand -Server 192.168.1.1 ` -User root -Password 123 ` -Command 'ls ~; sleep 10s; exit;' ` -PathToPlink 'C:\\plink.exe' ` -ShowWindow $true -OperationTimeout 10; .INPUTS System.String, System.Int32, System.Boolean .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Command, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$PathToPlink, [Parameter(Mandatory=$false)] [bool]$ShowWindow = $true, [Parameter(Mandatory=$false)] [int]$OperationTimeout = 2 ) try{ [string[]]$private:connectArgs = ` @( "-ssh $($User)@$($Server) -pw $($Password) $($Command) " ); if ($ShowWindow){ Start-Process -FilePath $PathToPlink ` -ArgumentList $private:connectArgs; } else{ Start-Process -FilePath $PathToPlink ` -ArgumentList $private:connectArgs -NoNewWindow; } sleep -Seconds $OperationTimeout; }catch{}; } #endregion function Invoke-ESXiCommand #region function New-ESXiFSDirectory function New-ESXiFSDirectory <# .SYNOPSIS Creates a directory on the datastore file system. .DESCRIPTION This function creates a directory and is a cane. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Path The absolute path to the folder which a new folder will be created within. .PARAMETER Name The name for a new folder. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> New-ESXiFSDirectory -Server 192.168.1.1 ` -User root -Password 123 ` -Path "/vmfs/volumes/datastore3" -Name foldername ` -PathToPlink C:\\plink.exe -OperationTimeout 20; .INPUTS System.String, System.Int32 .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Path, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 2 ) if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} [string]$private:commandToRun = "`"cd $($Path);mkdir $($Name);exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $false -OperationTimeout $OperationTimeout; } #endregion function New-ESXiFSDirectory #region function Register-ESXiVM function Register-ESXiVM <# .SYNOPSIS Register an VMX file. .DESCRIPTION this function register a new virtual machine specified as a full path to its .vmx file. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Path The full path to a VMX file. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> Register-ESXiVM -Server 192.168.1.1 ` -User root -Password 123 ` -Path "/vmfs/volumes/datastore3/vmname/vmname.vmx" ` -PathToPlink C:\\plink.exe; .INPUTS System.String, System.Int32 .OUTPUTS System.String #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Path, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 20 ) if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} [string]$private:commandToRun = "`"/bin/vim-cmd solo/registervm $($Path);exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $false -OperationTimeout $OperationTimeout; } #endregion function Register-ESXiVM #region function Start-ESXiVM function Start-ESXiVM <# .SYNOPSIS Starts a powered off orsuspended virtual machine. .DESCRIPTION This function is intended to start a new virtual machine as well as an existing one. In case the machine is generated from an image, it also answer the question whether the machine was copied or moved. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Id The Id of a virtual machine that is generated by the server that hosts it. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> Start-ESXiVM -Server 192.168.1.1 ` -User root -Password 123 ` -Id 504 ` -PathToPlink C:\\plink.exe; .INPUTS System.String, System.Int32 .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [int]$Id, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 10 ) if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} [string]$private:commandToRun = "`"/bin/vim-cmd vmsvc/power.on $($Id.ToString());exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $true -OperationTimeout $OperationTimeout; try{Get-VM -Id $Id; if ((Get-VM -Id $Id).PowerState -eq ` [VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState]::PoweredOff){ [string]$private:commandToRun = "`"/bin/vim-cmd vmsvc/message $($Id.ToString()) 0 2;exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $true -OperationTimeout 2;} }catch{ [string]$private:commandToRun = "`"/bin/vim-cmd vmsvc/message $($Id.ToString()) 0 2;exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $true -OperationTimeout 2; } } #endregion function Start-ESXiVM #region function Stop-ESXiVM function Stop-ESXiVM <# .SYNOPSIS Powers off (or what is set for this option on your server) a virtual machine. .DESCRIPTION This funciton simply 'presses' the red button. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Id The Id of a virtual machine that is generated by the server that hosts it. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> Stop-ESXiVM -Server 192.168.1.1 ` -User root -Password 123 ` -Id (Get-ESXiVMId $vm); .INPUTS System.String, System.Int32 .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [int]$Id, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 60 ) if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} [string]$private:commandToRun = "`"/bin/vim-cmd vmsvc/power.off $($Id.ToString());exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $true -OperationTimeout $OperationTimeout; } #endregion function Stop-ESXiVM #region function Suspend-ESXiVM function Suspend-ESXiVM <# .SYNOPSIS Puts a virtual machine into a suspended state. .DESCRIPTION This function 'presses' the yellow button. .PARAMETER Server The name of IP address of the server you work with. It's also used further as an user@server combination. .PARAMETER User Username that is often root. It's also used further as an user@server combination. .PARAMETER Password Password to connect to a ESXi. It's also used as a parameter for plink. .PARAMETER Id The Id of a virtual machine that is generated by the server that hosts it. .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> Suspend-ESXiVM -Server 192.168.1.1 ` -User root -Password 123 ` -Id $private:vmId ` -PathToPlink C:\\plink.exe; .INPUTS System.String, System.Int32 .OUTPUTS None #> { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Server, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$User, [AllowEmptyString()] [string]$Password = '', [Parameter(Mandatory=$true)] [int]$Id, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 60 ) if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} [string]$private:commandToRun = "`"/bin/vim-cmd vmsvc/power.suspend $($Id.ToString());exit;`""; Invoke-ESXiCommand -Server $Server -User $User -Password $Password ` -Command $private:commandToRun -PathToPlink $PathToPlink ` -ShowWindow $true -OperationTimeout $OperationTimeout; } #endregion function Suspend-ESXiVM #region function Get-ESXiVMId function Get-ESXiVMId <# .SYNOPSIS Returns the Id of a virtual machine. .DESCRIPTION This function receives a virtual machine object and extract the Id property. .PARAMETER VM The VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl object. .EXAMPLE PS C:\\> [int]$private:vmId = ` Get-ESXiVMId -VM (Get-VM -Name $VMName); .INPUTS VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl .OUTPUTS System.Int32 #> ( [CmdletBinding()] [OutputType([System.Int32])] [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$VM ) { #[int]$private:vmId = [System.Text.RegularExpressions.Regex]::Match( ` # (Get-VM -Name $private:currentVMName).Id.ToString(), "(?<=[-]).*").Value [int]$private:vmId = [System.Text.RegularExpressions.Regex]::Match( ` $VM.Id.ToString(), "(?<=[-]).*").Value; return $private:vmId; } #endregion function Get-ESXiVMId #region function Get-ESXiVMName function Get-ESXiVMName <# .SYNOPSIS Returns the name of a virtual machine that contains a guest with name given. .DESCRIPTION This function enumerates all the virtual machines hosted on a server in order to get the name that has the corresponding virtual machine. .PARAMETER VMHostname Ths name(s) of the guest host(s). .EXAMPLE PS C:\\> $vmname = Get-ESXiVMName -VMHostname 'B45E19A64B5E418' .INPUTS System.String[] .OUTPUTS System.String #> ( [CmdletBinding()] [OutputType([System.String])] [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string[]]$VMHostname ) { [System.Collections.ArrayList]$vmnames = ` New-Object System.Collections.ArrayList; [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl[]]$vmss = ` Get-VM *; for ([int]$private:i = 0; $private:i -lt $VMHostname.Length; $private:i++) { [bool]$addEmptyName = $true; foreach($vm in $vmss) { if ($vm.Name -ne $null -and ` $vm.Guest -ne $null -and ` $vm.Guest.HostName -ne $null -and ` $vm.Guest.HostName.Length -gt 0){ if ($vm.Guest.HostName.toUpper() -eq ` $VMHostname[$private:i].toUpper() -or ` $vm.Guest.HostName.toUpper().Contains($VMHostname[$private:i].toUpper())) { $null = $vmnames.Add($vm.Name); $addEmptyName = $false; break; } } } # } if ($addEmptyName){$vmnames.Add("");} } return $vmnames; } #endregion function Get-ESXiVMName #region function New-ESXiVMs function New-ESXiVMs <# .SYNOPSIS Generates a bunch of virtual machines. .DESCRIPTION This function generates new virtual machine by copying the existing virtual machine files, replacing the name of the original machine with the name that's provided and copying the result to the server the module connected.. .PARAMETER TemplateVMName The name of the virtual machine used as a template. .PARAMETER Count The number of virtual machines you need. .PARAMETER Logname The full path to the log file. .PARAMETER NewVMName The base name of new virtual machines. Virtual machines will be named in the follwing order: newvm_1 newvm_2 ... newvm_20. .PARAMETER BasePath The path in the local file system where the template resides. the hardcoded values are basepath\\hdd - the folder where the virtual disk(s) <templatevm>-flat.vmdk, <templatevm>-<number>delta.vmdk, <templatevm>-Snapshot<number>.vmsn (snapshot of a machine that was turned on) are stored. In short, the files of megabyte of gigabyte size. basepath\\template - the folder where the rest of files (namely, <templatevm>.vmx, <templatevm>.vmxf, <templatevm>.vmsd, <templatevm>.vmdk (the header), <templatevm>-<number>.vmdk, <templatevm>-Snapshot<number>.vmsn (snapshot of a machine that was turned off) ) reside, in other words, the files the size of which are measured in kilobytes .PARAMETER PathToPlink Used if for some reason you don't want to put plink.exe in the module folder. .PARAMETER OperationTimeout The time that the module sleeps before start next operation. .EXAMPLE PS C:\\> New-ESXiVMs -TemplateVMName 'template XP SP2 Sv' -Count 20 ` -Logname "C:\\VMTests\\20VMs.txt" -NewVMName 'XPSP2a' ` -BasePath 'C:\\VMTests\\xpsp2'; .INPUTS System.String, System.Int32 .OUTPUTS None #> ( [CmdletBinding()] [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$TemplateVMName, [Parameter(Mandatory=$true)] [int]$Count = 1, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Logname, [Parameter(Mandatory=$true)] [string]$NewVMName = 'newVM_', [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$BasePath, [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$PathToPlink, [int]$OperationTimeout = 600 ) { if ($PathToPlink.Length -lt 1){$PathToPlink = $script:plinkPath;} # the need in storaging a template VM on a host is deprecated # if we used traditional PowerCLI cmdlets, it would be easy to read properties from a template # or use a template and put the data to a new machine or even create one from template #[VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$script:templateVM = ` # Get-VM -Server $script:esxiserver -Name $TemplateVMName; #if ($script:templateVM -eq $null) #{ # Write-Error "Couldn`'t get the '$($TemplateVMName)' virtual machine on the $($script:esxiserver) host."; # return; #} for ($private:i = 0; $private:i -lt $Count; $private:i++) { [string]$private:currentVMName = $NewVMName + ($private:i + 1).ToString(); "$(Get-CurrentTime)Start creating the virtual machine '$($private:currentVMName)'" >> $Logname; #region #Unsupported for the ESXi host: # $private:newvm = New-VM -VM $script:templateVM ` # -Name $private:currentVMName ` # -Datastore $script:datastore ` # -VMHost $script:vmhost; #endregion #Unsupported for the ESXi host: #region #Unsupported for the ESXi host: # $private:newvm = New-VM ` # -Name $private:currentVMName ` # -Datastore $script:datastore ` # -VMHost $script:vmhost; # ` # #-MemoryMB $script:templateVM.MemoryMB ` # #-NumCpu $script:templateVM.NumCpu #endregion #Unsupported for the ESXi host: New-Item -Path "$($BasePath)\\$($private:currentVMName)" -type directory -Force; [string]$templateStorage = $BasePath + "\\template"; [string]$hddStorage = $BasePath + "\\hdd"; Get-ChildItem -LiteralPath $templateStorage | ` %{[string]$currentFile = $_.FullName; [string]$newFile = ` $currentFile.ToLower().Replace("$($templateStorage)\\$($TemplateVMname)".ToLower(), ` "$($BasePath)\\$($private:currentVMName)\\$($private:currentVMName)"); "Changing $($currentFile) to $($newFile)" >> $Logname; Copy-Item -Path $currentFile -Destination $newFile; (Get-Content $newFile) | %{ $_ -replace $TemplateVMname, $private:currentVMName; } | ` Set-Content -Path $newFile;} New-ESXiFSDirectory -Server $script:esxiserver.Name -User $script:esxiserver.User -Password $script:pwd ` -Path "/vmfs/volumes/$($script:datastore.Name)" -Name $private:currentVMName ` -PathToPlink $PathToPlink -OperationTimeout 20; "$(Get-CurrentTime)Copying the config files '$($private:currentVMName)'" >> $Logname; Copy-DatastoreItem -Item "$($BasePath)\\$($private:currentVMName)\\$($private:currentVMName)*.*" ` -Destination "$($script:dsdrive):\\$($private:currentVMName)\\"; "$(Get-CurrentTime)Copying the virtual drive image(s) '$($private:currentVMName)'" >> $Logname; Get-ChildItem -Path "$($hddStorage)" | %{[string]$private:newFileName = $_.Name.Replace($TemplateVMname, $private:currentVMName); Copy-DatastoreItem -Item $_.FullName ` -Destination "$($script:dsdrive):\\$($private:currentVMName)\\$($private:newFileName)";} #region #Unsupported for the ESXi host: # $private:newvm = ` # New-VM -VMHost $script:vmhost ` # -VMFilePath "$($script:dsdrive):\\$($private:currentVMName)\\$($private:currentVMName).vmx"; #endregion #Unsupported for the ESXi host: #region #Unsupported for the ESXi host: # Copy-HardDisk -HardDisk $vm.HardDisks[0] ` # -DestinationPath "[$($DatastoreName)] $($private:currentVMName)/" # Copy-DatastoreItem -Item "$($script:dsdrive):\\templXPSP3\\templXPSP3.vmdk" -Destination "$($script:dsdrive):\\3\\1.vmdk" #endregion #Unsupported for the ESXi host: "$(Get-CurrentTime)Registering the VM '$($private:currentVMName)'" >> $Logname; Register-ESXiVM -Server $script:esxiserver.Name -User $script:esxiserver.User -Password $script:pwd ` -Path "/vmfs/volumes/$($script:datastore.Name)/$($private:currentVMName)/$($private:currentVMName).vmx" ` -PathToPlink $PathToPlink; [int]$private:vmId = Get-ESXiVMId -VM (Get-VM -Name $private:currentVMName); #region #Unsupported for the ESXi host: # Start-VM -VM (Get-VM -Name $private:currentVMName) -RunAsync; #endregion #Unsupported for the ESXi host: "$(Get-CurrentTime)Starting the VM '$($private:currentVMName)'" >> $Logname; Start-ESXiVM -Server $script:esxiserver.Name -User $script:esxiserver.User -Password $script:pwd ` -Id $private:vmId ` -PathToPlink $PathToPlink; #region #Unsupported for the ESXi host: # Set-VMQuestion -VMQuestion (Get-VM XPSP3_2 | Get-VMQuestion) -Option 'I copied it' -Confirm:$false #endregion #Unsupported for the ESXi host: sleep -Seconds $OperationTimeout; #region #Unsupported for the ESXi host: # Get-VM $private:currentVMName | Suspend-VMGuest #endregion #Unsupported for the ESXi host: Suspend-ESXiVM -Server $script:esxiserver.Name -User $script:esxiserver.User -Password $script:pwd ` -Id $private:vmId ` -PathToPlink $PathToPlink; } } #endregion function New-ESXiVMs #endregion public functions # Tested functions Export-ModuleMember -Function Connect-ESXi, Invoke-ESXiCommand, New-ESXiFSDirectory; Export-ModuleMember -Function Register-ESXiVM, Start-ESXiVM, Suspend-ESXiVM, New-ESXiVMs; Export-ModuleMember -Function Get-ESXiVMId, Get-ESXiVMName, Disconnect-ESXi, Stop-ESXiVM;
PowerShellCorpus/PoshCode/finddupe_3.ps1
finddupe_3.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 <directory1> <directory2> ... <directoryN>" $matches = 0 # initialize number of matches for summary. if ($args.count -eq 0) { $files = (dir -recurse | ? {$_.psiscontainer -ne $true})} else {$files = (dir $args -recurse | ? {$_.psiscontainer -ne $true})} 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++ $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/Custom Speech Commands_1.ps1
Custom Speech Commands_1.ps1
#Filename commands.ps1 import-module "G:\\Documents\\Speech Macros\\custom.psm1" import-module "G:\\Documents\\Speech Macros\\alice.psm1" Add-SpeechCommands @{ "test command" = { Say $(Respond "3:2,4:0-2") } " * the percentages * " = { Say $(Percentages) } " * star date * " = { Say "Current, Star date, $("$((Get-Date).year).$([math]::round($((Get-Date).dayofyear)/365, 2)*100)" -replace "([A-Za-z0-9.]){1}","`$1 " -replace "\\.","point")" } " * mail * " = { Start-Process "https://mail.google.com" } "Google * please" = { $term = $_ -replace "$Computer(.+?)Google (.+?) please", '$2'; Start-Process "http://www.google.com/search?q=$term" } "What * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What is * time * " = { Say "It is $(Get-Date -f "h:mm tt")" } "What time * " = { Say "It is $(Get-Date -f "h:mm tt")" } " * some music * " = { Start-Process "grooveshark.exe" } "What * date today" = { Say $(Get-Date -f "dddd, MMMM dd") } #list processes "What's running?" = { $proc = ps | sort ws -desc Say $("$($proc.Count) processes, including $($proc[0].name), which is using " + "$([int]($proc[0].ws/1mb)) megabytes of memory") } #Word Definition " * the definition for * please" = {$define = $_ -replace "$Computer(.+?)the definition for (.+?) please", '$2' ;$outtext = Get-Definition("$define");Say "Definitions for $define, , , $outtext"} } -Computer "alice" -Verbose #eof #Filename custom.psm1 function Get-Definition($word) { #.Synopsis # Polls wiktionary for top text definitons for a given $word input #.Description # This Function parses the top $lines definitions for a given # $term into one string formatted for speech synthesis # # Say "Sure" if($word -match " "){Say "Fail, one word at a time please"; break} $page = "http://simple.wiktionary.org/wiki/$word" $ie = new-object -com "InternetExplorer.Application" $ie.visible = $false $ie.navigate($page) while($ie.busy){Start-Sleep 1} $output = " " $lines = 0 for($d=0;$d -le $lines;$d++) { ## grab the definition strings from each table $ol = @($ie.Document.getElementsByTagName("ol"))[0] $li = @($ol.getElementsByTagName("li"))[$d] $def = @($li.innerHTML) $output += "$def" if($d -lt $lines){ $output += ", or, " } } $ie.Quit() $closeIE = [System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($ie) Remove-Variable ie $Clean-String($output) } function Clean-String([string]$str){ #.Synopsis # Cleans string from web (most concerned about x/html tags) #.Description # Cleans input string of xml tags # returns $str # # $str = $str -replace "\\<[^<]*\\>", " " $str = $str.replace("&nbsp", "") $str } function Respond($in, [string]$del = ","){ #.Synopsis # Recursive. # Returns a random response from $responses via the three dimensional array of choices: $choices[<groups>][<dimensions>][<values>] # This function takes in a string indicating which responses from the $responses array # to to choose from. It supports ranges (-) and direct selections (/) in each seed separated by (,). #.Description # the idea here is to respond based on this format: $in = "3:2,4:1-2,0/2-4/6:1" # where 3:2 is a direct seed, 4:1-2 is a range seed (from 4:1 to 4:2), # and 0/2-4/6:1 combines the two (effectively adds 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the choices) # In heap, the above example would effectively add 3:2, 4:1, 4:2, 0:1, 2:1, 3:1, 4:1, 5:1, 6:1 to the # available choices, and will appear as $choices(@($xs(3),$ys(2)),@($xs(4),$ys(1,2)),@($xs(0,2,3,4,6),$ys(1))) # switch -wildcard ($del){ "`,"{ if($in -match "`,"){ #if more than one coordset, handle each $coordsets = $in -split "`," #split coordsets apart foreach($coordset in $coordsets){ $choices += ,(Respond $coordset "`:") } } else{ #else pass the string to the next step, $choices = ,(Respond $in "`:") } $choice = $choices[(get-random -min 0 -max $choices.count)] #choose one of the groups randomly $responses[$choice[0]][$choice[1]];#pass response out of the function } "`:"{ $coords = $in -split "`:" #split coordset apart foreach ($coord in $coords){ if(($coord -match "`/")-or($coord -match "`-")){ #if there's an or operator or a range $dimensions += ,(Respond $coord "`/") # handle them, and add all values (in array) to this dimension (split fails elegantly) } else{ $dimensions += ,$coord #else just add the coord value (in an array) via comma operator } } $dimensions #pass dimensions out dimensions is two dimensional array } "`/"{ $ranges = $in -split "`/" #split ORs apart (if theres not OR, the string is still added to $ranges[0]) foreach($range in $ranges){ if($range -match "`-"){#if theres a range to handle, do so foreach ($val in (Respond $range "`-")){ $orVals += ,$val #append all values in returned range array to new array } } else{# else just append the value to teh new array $orVals += ,$range } } ,($orVals | get-random) #pass out single element array of random value from vals array } "`-"{ $vals = $in -split "`-" #split ranges apart $vals[0]..$vals[1] # pass out array containing all values in range } } } $responses = (#Response Array (##0-correct "Right", "Correct" ), (##1-incorrect "Wrong", "Incorrect" ), (##2-positive "Yes", "Aye", "I'll give it a shot" ), (##3-negative "No", "Negative", "Not going to happen" ), (##4-affirmation "Sure", "OK", "Lets See" ), (##5-retort "your mom", "your face" ), (##6-insult "You\\'re dumb", "you fail" ), (##7-eager "I'm ready", "Lets check it out" ), (##8-apprehensive "I don't know", "Just a seck" ), (##9-neutral "oh", "Hum" ) ) function Percentages { #.Synopsis # Specific speech command that reads back # remaining percentages of year, month, week, and day #.Description # Pretty self explanitory, basic maths, elucidatory var names # # $date = get-date #capture date object $daysInYear = [int]$(if([datetime]::IsLeapYear($date.year)){366}else{365}) #if leap year, 366, else 365 $daysInMonth = [int]$([datetime]::DaysInMonth($date.year, $date.month)) #capture days in month $dayOfYear = [int]$date.dayofyear #days past (including today) $dayOfMonth = [int]$date.day #days past (including today) $hoursOfDay = [int]$date.hour #hours past (including current) $minutesOfHour = [int]$date.minute #minutes past (including current) switch ($date.dayofweek.toString()){ #assumes start of week is sunday Sunday { [int]$dayOfWeek="1"; break } Monday { [int]$dayOfWeek="2"; break } Tuesday { [int]$dayOfWeek="3"; break } Wednesday { [int]$dayOfWeek="4"; break } Thursday { [int]$dayOfWeek="5"; break } Friday { [int]$dayOfWeek="6"; break } Saturday { [int]$dayOfWeek="7"; break } } $percentYearGone = $dayOfYear/$daysInYear #days of this year (including today) divided by total days in this year $percentMonthGone = ((($dayOfMonth*24)-24)+$hoursOfDay)/($daysInMonth*24) #hours of this month divided by total hours in this month $percentWeekGone = ((($dayOfWeek*24)-24)+$hoursOfDay)/(7*24) #hours of this week divided by total hours in a week $percentDayGone = ((($hoursOfDay*60)-60)+$minutesOfDay)/(24*60) #minutes of today divided by total minutes in a day $percentYearLeft = [math]::round((1-$percentYearGone)*100,1) #opposite percentages rounded to one decimal place $percentMonthLeft = [math]::round((1-$percentMonthGone)*100,1) #^ $percentWeekLeft = [math]::round((1-$percentWeekGone)*100,1) #^ $percentDayLeft = [math]::round((1-$percentDayGone)*100,1) #^ $str = "" $str += "There's " $str += $percentYearLeft $str += "% of this year, " $str += $percentMonthLeft $str += "% of this month, " $str += $percentWeekLeft $str += "% of this week, and " $str += $percentDayLeft $str += "% of today remaining, what will you do with it?" $str } #eof
PowerShellCorpus/PoshCode/Set Single email .ps1
Set Single email .ps1
# Very simple script to use in Exchange 2007 with a dead simple task # Create an email enabled user with the local Email Address Policy Disabled with a SINGLE email address # Attached to it # # This can be used in an environment where you may have multiple email addresses but don't want an account picking # up multiple email addresses or more explicitly where an email account should have only ONE address and it may not be the standard # If you are hosting multiple domains on your server. IE ABCCORPORATION.COM may have a private address for their website called # @hotwebsitestuff.com. # # What this script will do after creating the address is purge all email addresses in the Proxy list and # Replace it with just the one # # Questions and details just email sean@energizeit.ca # # # Obtain FirstName, Last Name and designed email address # # $FirstName=READ-HOST 'Enter First Name ' $LastName=READ-HOST 'Enter Last Name' # # Email address is in the form of name@domain.xxx and does not need to contain quotes or 'SMTP:' # $EmailAddress=READ-HOST 'E-mail Address reqd ' # # Password for the account # $Password=READ-HOST 'DefaultPassword' -assecurestring # # Script will generate the needed fields from provided data. Name is "FirstName Lastname" # Alias is "Firstname.Lastname" # Account will be created in a fictional OU in Active Directory "Contoso.Local" # With a default UPN of "firstname.lastname@contoso.local" # $Name=$FirstName+' '+$LastName $Alias=$Firstname+'.'+$LastName $OU='Contoso.local/Offices/Seattle' $UPN=$Alias+'@contoso.local' # # Information will echo to the screen # $FirstName $LastName $EmailAddress $Password $Name $Alias $OU $UPN # # Create New Mailbox on Exchange 2007 server. This is the standard New-Mailbox commandlet automatically generated by Exchange 2007 # With Hardcoded fields replaced by variables # New-Mailbox -Name $Name -Alias $Alias -OrganizationalUnit $OU -UserPrincipalName $UPN -SamAccountName $Firstname -FirstName $FirstName -Initials '' -LastName $Lastname -Password $Password -ResetPasswordOnNextLogon $false -Database 'OUREXCHANGESERVER\\First Storage Group\\Mailbox Database' # # If you find the mailbox doesn't appear immediately, you may have to do a "start-sleep 2" in Powershell V2 to make the script pause # for two seconds # # Read the information about the mailbox in Quest and disable EmailAddressPolicy # get-mailbox $Alias | Set-Mailbox -EmailAddressPolicyEnabled $False # # Assign Mailbox Object to a variable "$MailboxUser" # Using the "Clear()" Method purge the Property "EmailAddresses" within # $mailboxuser=get-mailbox $Alias $mailboxuser.EmailAddresses.Clear() # # Add back in the ONE address you want # $mailboxuser.EmailAddresses.Add($EmailAddress) # # and then Set those changes back to the mailbox # $mailboxuser | set-mailbox
PowerShellCorpus/PoshCode/ProcuriosJSON.psm1.ps1
ProcuriosJSON.psm1.ps1
function ConvertFrom-Json { param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [Alias("Json")] [string[]] $InputObject, [switch]$AsPSObject = $false ) Process { $output = [procurios.Public.JSON]::JsonDecode( $InputObject ) if ( $AsPSObject ) { $output | ForEach-Object { New-Object PSObject -Property $_ } } else { Write-Output $output } } } #REGION IMPORT CSHARP TYPES # Source from: http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html Add-Type @" using System; //using System.Data; using System.Collections; using System.Globalization; using System.Text; namespace Procurios.Public { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> public class JSON { public const int TOKEN_NONE = 0; public const int TOKEN_CURLY_OPEN = 1; public const int TOKEN_CURLY_CLOSE = 2; public const int TOKEN_SQUARED_OPEN = 3; public const int TOKEN_SQUARED_CLOSE = 4; public const int TOKEN_COLON = 5; public const int TOKEN_COMMA = 6; public const int TOKEN_STRING = 7; public const int TOKEN_NUMBER = 8; public const int TOKEN_TRUE = 9; public const int TOKEN_FALSE = 10; public const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 2000; protected static JSON instance = new JSON(); /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected int lastErrorIndex = -1; protected string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> public static object JsonDecode(string json) { // save the string for debug information JSON.instance.lastDecode = json; if (json != null) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = JSON.instance.ParseValue(charArray, ref index, ref success); if (success) { JSON.instance.lastErrorIndex = -1; } else { JSON.instance.lastErrorIndex = index; } return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string JsonEncode(object json) { StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); bool success = JSON.instance.SerializeValue(json, builder); return (success ? builder.ToString() : null); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool LastDecodeSuccessful() { return (JSON.instance.lastErrorIndex == -1); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int GetLastErrorIndex() { return JSON.instance.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string GetLastErrorSnippet() { if (JSON.instance.lastErrorIndex == -1) { return ""; } else { int startIndex = JSON.instance.lastErrorIndex - 5; int endIndex = JSON.instance.lastErrorIndex + 15; if (startIndex < 0) { startIndex = 0; } if (endIndex >= JSON.instance.lastDecode.Length) { endIndex = JSON.instance.lastDecode.Length - 1; } return JSON.instance.lastDecode.Substring(startIndex, endIndex - startIndex + 1); } } protected Hashtable ParseObject(char[] json, ref int index) { Hashtable table = new Hashtable(); int token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == JSON.TOKEN_NONE) { return null; } else if (token == JSON.TOKEN_COMMA) { NextToken(json, ref index); } else if (token == JSON.TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index); if (name == null) { return null; } // : token = NextToken(json, ref index); if (token != JSON.TOKEN_COLON) { return null; } // value bool success = true; object value = ParseValue(json, ref index, ref success); if (!success) { return null; } table[name] = value; } } return table; } protected ArrayList ParseArray(char[] json, ref int index) { ArrayList array = new ArrayList(); // [ NextToken(json, ref index); bool done = false; while (!done) { int token = LookAhead(json, index); if (token == JSON.TOKEN_NONE) { return null; } else if (token == JSON.TOKEN_COMMA) { NextToken(json, ref index); } else if (token == JSON.TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { bool success = true; object value = ParseValue(json, ref index, ref success); if (!success) { return null; } array.Add(value); } } return array; } protected object ParseValue(char[] json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case JSON.TOKEN_STRING: return ParseString(json, ref index); case JSON.TOKEN_NUMBER: return ParseNumber(json, ref index); case JSON.TOKEN_CURLY_OPEN: return ParseObject(json, ref index); case JSON.TOKEN_SQUARED_OPEN: return ParseArray(json, ref index); case JSON.TOKEN_TRUE: NextToken(json, ref index); return Boolean.Parse("TRUE"); case JSON.TOKEN_FALSE: NextToken(json, ref index); return Boolean.Parse("FALSE"); case JSON.TOKEN_NULL: NextToken(json, ref index); return null; case JSON.TOKEN_NONE: break; } success = false; return null; } protected string ParseString(char[] json, ref int index) { string s = ""; char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s += '"'; } else if (c == '\\\\') { s += '\\\\'; } else if (c == '/') { s += '/'; } else if (c == 'b') { s += '\\b'; } else if (c == 'f') { s += '\\f'; } else if (c == 'n') { s += '\\n'; } else if (c == 'r') { s += '\\r'; } else if (c == 't') { s += '\\t'; } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // fetch the next 4 chars char[] unicodeCharArray = new char[4]; Array.Copy(json, index, unicodeCharArray, 0, 4); // parse the 32 bit hex into an integer codepoint uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if (!complete) { return null; } return s; } protected double ParseNumber(char[] json, ref int index) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; char[] numberCharArray = new char[charLength]; Array.Copy(json, index, numberCharArray, 0, charLength); index = lastIndex + 1; return Double.Parse(new string(numberCharArray), CultureInfo.InvariantCulture); } protected int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) { if (" \\t\\n\\r".IndexOf(json[index]) == -1) { break; } } } protected int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) { return JSON.TOKEN_NONE; } char c = json[index]; index++; switch (c) { case '{': return JSON.TOKEN_CURLY_OPEN; case '}': return JSON.TOKEN_CURLY_CLOSE; case '[': return JSON.TOKEN_SQUARED_OPEN; case ']': return JSON.TOKEN_SQUARED_CLOSE; case ',': return JSON.TOKEN_COMMA; case '"': return JSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return JSON.TOKEN_NUMBER; case ':': return JSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return JSON.TOKEN_FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return JSON.TOKEN_TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return JSON.TOKEN_NULL; } } return JSON.TOKEN_NONE; } protected bool SerializeObjectOrArray(object objectOrArray, StringBuilder builder) { if (objectOrArray is Hashtable) { return SerializeObject((Hashtable)objectOrArray, builder); } else if (objectOrArray is ArrayList) { return SerializeArray((ArrayList)objectOrArray, builder); } else { return false; } } protected bool SerializeObject(Hashtable anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while (e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if (!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected bool SerializeArray(ArrayList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for (int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if (!first) { builder.Append(", "); } if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected bool SerializeValue(object value, StringBuilder builder) { if (value is string) { SerializeString((string)value, builder); } else if (value is Hashtable) { SerializeObject((Hashtable)value, builder); } else if (value is ArrayList) { SerializeArray((ArrayList)value, builder); } else if (IsNumeric(value)) { SerializeNumber(Convert.ToDouble(value), builder); } else if ((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if ((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } else if (value == null) { builder.Append("null"); } else { return false; } return true; } protected void SerializeString(string aString, StringBuilder builder) { builder.Append("\\""); char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if (c == '"') { builder.Append("\\\\\\""); } else if (c == '\\\\') { builder.Append("\\\\\\\\"); } else if (c == '\\b') { builder.Append("\\\\b"); } else if (c == '\\f') { builder.Append("\\\\f"); } else if (c == '\\n') { builder.Append("\\\\n"); } else if (c == '\\r') { builder.Append("\\\\r"); } else if (c == '\\t') { builder.Append("\\\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append("\\""); } protected void SerializeNumber(double number, StringBuilder builder) { builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture)); } /// <summary> /// Determines if a given object is numeric in any way /// (can be integer, double, etc). C# has no pretty way to do this. /// </summary> protected bool IsNumeric(object o) { try { Double.Parse(o.ToString()); } catch (Exception) { return false; } return true; } } } "@ #ENDREGION Export-ModuleMember ConvertFrom-Json
PowerShellCorpus/PoshCode/Deny-PendingRequest.ps1
Deny-PendingRequest.ps1
##################################################################### # Deny certificate request.ps1 # Version 1.0 # # Denies certificate request from a pending request # # For this function to succeed, the certificate request must be pending # # Vadims Podans (c) 2010 # http://en-us.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Deny-PendingRequest { [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFomPipeline = $true)] [string]$CAConfig, [Parameter(Mandatory = $true)] [int]$RequestID ) try {$CertAdmin = New-Object -ComObject CertificateAuthority.Admin} catch {Write-Warning "Unable to instantiate ICertAdmin2 object!"; return} try {$CertAdmin.DenyRequest($CAConfig,$RequestID)} catch {$_; return} Write-Host "Successfully denied request '$RequestID'" }
PowerShellCorpus/PoshCode/Explorer Style Script.ps1
Explorer Style Script.ps1
$nul = "<NULL>" $type = "Directory", "File" function Show-Error([string]$mes) { [Windows.Forms.MessageBox]::Show($mes, "Error", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Exclamation ) } function Add-RootsTree { [IO.Directory]::GetLogicalDrives() | % { $nod = $tvRoots.Nodes.Add($_) $nod.Nodes.Add($nul) } } function Add-Folders { $_.Node.Nodes.Clear() try { foreach ($i in [IO.Directory]::GetDirectories($_.Node.FullPath)) { $node = $_.Node.Nodes.Add([IO.Path]::GetFileName($i)) $node.Tag = $type[0] $node.Nodes.Add($nul) } } catch { Show-Error $_.Exception.Message } } function Add-Files { try { foreach ($i in [IO.Directory]::GetFiles($_.Node.FullPath)) { $node = $_.Node.Nodes.Add([IO.Path]::GetFileName($i)) $node.Tag = $type[1] } } catch {} } $tvRoots_AfterSelect= { switch ($_.Node.Tag) { $type[0] { $sbPnl_2.Text = $type[0]; break } $type[1] { $sbPnl_2.Text = $type[1]; break } } } $tvRoots_BeforeExpand= { Add-Folders Add-Files } function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() $ico = [Drawing.Icon]::ExtractAssociatedIcon(($PSHome + '\\powershell.exe')) $frmMain = New-Object Windows.Forms.Form $tvRoots = New-Object Windows.Forms.TreeView $sbPanel = New-Object Windows.Forms.StatusBar $sbPnl_1 = New-Object Windows.Forms.StatusBarPanel $sbPnl_2 = New-Object Windows.Forms.StatusBarPanel # #tvRoots # $tvRoots.Dock = "Fill" $tvRoots.Add_AfterSelect($tvRoots_AfterSelect) $tvRoots.Add_BeforeExpand($tvRoots_BeforeExpand) # #sbPanel # $sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2)) $sbPanel.ShowPanels = $true $sbPanel.SizingGrip = $false # #sbPnl_1 # $sbPnl_1.AutoSize = "Spring" $sbPnl_1.Text = "Follow me at @gregzakharov" # #sbPnl_2 # $sbPnl_2.Alignment = "Center" $sbPnl_2.AutoSize = "Contents" $sbPnl_2.Text = "Not clicked item yet" # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(350, 350) $frmMain.Controls.AddRange(@($tvRoots, $sbPanel)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.Icon = $ico $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Explorer Style Script" $frmMain.Add_Load({Add-RootsTree}) [void]$frmMain.ShowDialog() } frmMain_Show
PowerShellCorpus/PoshCode/Get-HexDump.ps1
Get-HexDump.ps1
<# Required v2.0 Using examples: PS C:\\> gi .\\foo | hex -b 150 Dumps first 150 bytes of foo. PS C:\\> hex .\\foo -b 150 It's equal first command. #> function Get-HexDump { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [string]$FileName, [Parameter(Position=1, Mandatory=$false)] [int]$Bytes = -1 ) $ofs = '' Get-Content -ea 0 -enc Byte $FileName -re 16 -to $Bytes | % { $hex = ''; $hex += $_ | % {' ' + ('{0:x}' -f $_).PadLeft(2, "0")} $chr = ''; $chr += $_ | % {if ([char]::IsLetterOrDigit($_)) {[char]$_} else {'.'}} '{0, -49} {1}' -f $hex, $chr } } Set-Alias hex Get-HexDump
PowerShellCorpus/PoshCode/Mailbox User_Update.ps1
Mailbox User_Update.ps1
#Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms v1.0.1.0 # Generated On: 5/10/2010 9:28 AM # Generated By: Bernard Chouinard berchouinard@gmail.com # This script requires Powershell v2 # This powershell script creates a gui form that will search for a mailbox user in # Active directory and display it's properties and allow for changes to be # made. The script uses the Exchange cmdlet get-user, set-user, # get-mailbox and set-mailbox. This script has been tested in Exchange 2010, # it should also work for Exchange 2007. # The iso_3166-1_list_en.xml file is needed to populate the country list # it is available at this web site # http://www.iso.org/iso/country_codes/iso_3166_code_lists.htm # the script is hard coded to look for iso_3166-1_list_en.xml in the c:\\scripts directory. # The countrycombobox can also be populated using the .Items.add instead of # using the xml file. ######################################################################## #region Import the Assembles [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $UserUpdate = New-Object System.Windows.Forms.Form $Pages = New-Object System.Windows.Forms.TabControl $Search_User = New-Object System.Windows.Forms.TabPage $statusBar = New-Object System.Windows.Forms.StatusBar $lblTip = New-Object System.Windows.Forms.Label $btnClose = New-Object System.Windows.Forms.Button $btnProperties = New-Object System.Windows.Forms.Button $btnReset = New-Object System.Windows.Forms.Button $btnfind = New-Object System.Windows.Forms.Button $ListUsers = New-Object System.Windows.Forms.ListBox $NameSearch = New-Object System.Windows.Forms.TextBox $lblselectuser = New-Object System.Windows.Forms.Label $UserName = New-Object System.Windows.Forms.Label $User_Properties = New-Object System.Windows.Forms.TabPage $comboBoxCountry = New-Object System.Windows.Forms.ComboBox $textBoxCustomAttribute5 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute5 = New-Object System.Windows.Forms.Label $lblcountry = New-Object System.Windows.Forms.Label $textBoxpostalcode = New-Object System.Windows.Forms.TextBox $lblpostalcode = New-Object System.Windows.Forms.Label $textBoxStorProv = New-Object System.Windows.Forms.TextBox $lblStorProv = New-Object System.Windows.Forms.Label $textBoxcity = New-Object System.Windows.Forms.TextBox $lblcity = New-Object System.Windows.Forms.Label $textBoxStreetAddress = New-Object System.Windows.Forms.TextBox $lblStreetAddress = New-Object System.Windows.Forms.Label $textBoxassistantphone = New-Object System.Windows.Forms.TextBox $lblassistantphone = New-Object System.Windows.Forms.Label $textBoxoffice = New-Object System.Windows.Forms.TextBox $lbloffice = New-Object System.Windows.Forms.Label $textBoxotherTelephone = New-Object System.Windows.Forms.TextBox $lblotherTelephone = New-Object System.Windows.Forms.Label $textBoxCustomAttribute10 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute10 = New-Object System.Windows.Forms.Label $textBoxpager = New-Object System.Windows.Forms.TextBox $lblpager = New-Object System.Windows.Forms.Label $textBoxOtherHomePhone = New-Object System.Windows.Forms.TextBox $lblOtherHomePhone = New-Object System.Windows.Forms.Label $textBoxmobile = New-Object System.Windows.Forms.TextBox $lblmobile = New-Object System.Windows.Forms.Label $textBoxfax = New-Object System.Windows.Forms.TextBox $lblFax = New-Object System.Windows.Forms.Label $textBoxHomePhone = New-Object System.Windows.Forms.TextBox $lblHomePhone = New-Object System.Windows.Forms.Label $textboxPhone = New-Object System.Windows.Forms.TextBox $lblPhone = New-Object System.Windows.Forms.Label $textBoxCustomAttribute6 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute6 = New-Object System.Windows.Forms.Label $textBoxCustomAttribute8 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute8 = New-Object System.Windows.Forms.Label $textBoxCustomAttribute4 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute4 = New-Object System.Windows.Forms.Label $textboxDepartment = New-Object System.Windows.Forms.TextBox $lblDepartment = New-Object System.Windows.Forms.Label $textBoxCustomAttribute3 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute3 = New-Object System.Windows.Forms.Label $textBoxCustomAttribute7 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute7 = New-Object System.Windows.Forms.Label $textBoxCompany = New-Object System.Windows.Forms.TextBox $lblCompany = New-Object System.Windows.Forms.Label $textBoxCustomAttribute1 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute1 = New-Object System.Windows.Forms.Label $textBoxAlias = New-Object System.Windows.Forms.TextBox $lblAlias = New-Object System.Windows.Forms.Label $textBoxEmail = New-Object System.Windows.Forms.TextBox $lblemail = New-Object System.Windows.Forms.Label $textBoxCustomAttribute2 = New-Object System.Windows.Forms.TextBox $lblCustomAttribute2 = New-Object System.Windows.Forms.Label $textBoxUPN = New-Object System.Windows.Forms.TextBox $lblUPN = New-Object System.Windows.Forms.Label $btnclose1 = New-Object System.Windows.Forms.Button $btnnamesearchagain = New-Object System.Windows.Forms.Button $btnupdate = New-Object System.Windows.Forms.Button $textBoxTitle = New-Object System.Windows.Forms.TextBox $lblTitle = New-Object System.Windows.Forms.Label $textBoxInitials = New-Object System.Windows.Forms.TextBox $lblInitials = New-Object System.Windows.Forms.Label $textBoxFirstName = New-Object System.Windows.Forms.TextBox $lblFirstName = New-Object System.Windows.Forms.Label $textBoxLastName = New-Object System.Windows.Forms.TextBox $lblLastName = New-Object System.Windows.Forms.Label $textBoxDisplayName = New-Object System.Windows.Forms.TextBox $lbldisplayName = New-Object System.Windows.Forms.Label #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. #Clicking the find button will search for a mailbox user using the get-mailbox cmdlet #search progress is shown the status bar $btnFind_OnClick= { $StatusBar.text = "Search for " + $NameSearch.text + " in progress, please wait" $user=get-mailbox -anr $NameSearch.text | Sort-Object | select Displayname $ListUsers.Items.Clear() if ($user -ne $Null){ foreach ($name in $user) { $listUsers.Items.add($name.displayname) } } Else{ [Windows.Forms.MessageBox]::Show("User not found, please try another search") } $StatusBar.text = "Ready" } #clicking the reset button clears the namesearch box and the list of users #from the previous search $btnreset_OnClick= { $NameSearch.Clear() $ListUsers.Items.Clear() } #Clicking on the properties button will get the properties for the mailbox user #using the get-mailbox cmdlet, if no user is selected a pop-up message #will be displayed. $btnProperties_OnClick= { Try { $SelectedUser = $listUsers.SelectedItem.ToString() If ($SelectedUser -ne $Null) { $MailboxUser = Get-User $SelectedUser $MailboxUser1 = Get-Mailbox $SelectedUser $textBoxdisplayName.text = $MailboxUser.displayName $textBoxlastName.text = $MailboxUser.lastName $textBoxfirstName.text = $MailboxUser.firstName $textBoxInitials.text = $MailboxUser.Initials $textBoxTitle.text = $MailboxUser.Title $textBoxUPN.text = $MailboxUser.UserPrincipalName $textBoxUPN.ReadOnly = $True $textBoxEmail.text = $MailboxUser1.PrimarySmtpAddress $textBoxEmail.ReadOnly = $True $textBoxCustomAttribute2.text = $MailboxUser1.CustomAttribute2 $textBoxAlias.text = $MailboxUser1.Alias $textBoxCustomAttribute1.text = $MailboxUser1.CustomAttribute1 $textBoxCustomAttribute5.text = $MailboxUser1.CustomAttribute5 $textBoxCompany.text = $MailboxUser.Company $textBoxCustomAttribute7.text = $MailboxUser1.CustomAttribute7 $textBoxCustomAttribute3.text = $MailboxUser1.CustomAttribute3 $textboxDepartment.text = $MailboxUser.Department $textBoxCustomAttribute4.text = $MailboxUser1.CustomAttribute4 $textBoxCustomAttribute8.text = $MailboxUser1.CustomAttribute8 $textBoxCustomAttribute6.text = $MailboxUser1.CustomAttribute6 $textboxPhone.text = $MailboxUser.Phone $textBoxHomePhone.text = $MailboxUser.HomePhone $textBoxfax.text = $MailboxUser.Fax $textBoxmobile.text = $MailboxUser.MobilePhone $textBoxOtherHomePhone.text = $MailboxUser.OtherHomePhone $textBoxpager.text = $MailboxUser.Pager $textBoxCustomAttribute10.text = $MailboxUser1.CustomAttribute10 $textBoxotherTelephone.text = $MailboxUser.OtherTelephone $textBoxoffice.text = $MailboxUser.Office $textBoxassistantphone.text = $MailboxUser.TelephoneAssistant $textBoxStreetAddress.text = $MailboxUser.StreetAddress $textBoxcity.text = $MailboxUser.City $textBoxStorProv.text = $MailboxUser.StateOrProvince $textBoxpostalcode.text = $MailboxUser.Postalcode $comboBoxcountry.text = $MailboxUser.CountryOrRegion $Pages.SelectTab($User_Properties) } } Catch { [Windows.Forms.MessageBox]::Show("You have not selected a user in the list, please select a user and try again") } } #Clicking the close button will close the form $btnClose_OnClick= { $UserUpdate.Close() } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $form1.WindowState = $InitialFormWindowState } #$handler_TabPage:_Click= #{ #TODO: Place custom script here #} #Clicking the search another user button will perform a new search $btnnamesearchagain_OnClick= { $Pages.SelectTab($Search_User) $NameSearch.Clear() $ListUsers.Items.Clear() } #Clicking the Update button will update all of the mailbox user attributes that were modified #by using the set-user and the set-mailbox cmdlet $btnupdate_OnClick= { $UPN = $textBoxUPN.text $Array = @() if ($textBoxdisplayName.modified -eq $true) { $Array += "-DisplayName " + "`"" + $textBoxdisplayName.text + "`"" } if ($textBoxlastName.modified -eq $True) { $Array += "-LastName " + "`"" + $textBoxlastName.text + "`"" } if ($textBoxfirstName.modified -eq $True) { $Array += "-FirstName " + "`"" + $textBoxfirstName.text + "`"" } if ($textBoxInitials.modified -eq $true) { $Array += "-Initials " + "`"" + $textBoxInitials.text + "`"" } if ($textBoxTitle.modified -eq $True) { $Array += "-Title " + "`"" + $textBoxTitle.text + "`"" } if ($textBoxCompany.modified -eq $true) { $Array += "-Company " + "`"" + $textBoxCompany.text + "`"" } if ($textboxDepartment.modified -eq $True) { $Array += "-Department " + "`"" + $textboxDepartment.text + "`"" } if ($textboxPhone.modified -eq $True) { $Array += "-Phone " + "`"" + $textboxPhone.text + "`"" } if ($textBoxHomePhone.modified -eq $true) { $Array += "-HomePhone " + "`"" + $textBoxHomePhone.text + "`"" } if ($textBoxfax.modified -eq $True) { $Array += "-Fax " + "`"" + $textBoxfax.text + "`"" } if ($textBoxmobile.modified -eq $true) { $Array += "-MobilePhone " + "`"" + $textBoxmobile.text + "`"" } if ($textBoxOtherHomePhone.modified -eq $True) { if ($textBoxOtherHomePhone.text -eq ""){ $Array += "-OtherHomePhone " + '$Null' } else { $Array += "-OtherHomePhone " + "`"" + $textBoxOtherHomePhone.text + "`"" } } if ($textBoxpager.modified -eq $True) { $Array += "-Pager " + "`"" + $textBoxpager.text + "`"" } if ($textBoxotherTelephone.modified -eq $true) { if ($textBoxotherTelephone.text -eq ""){ $Array += "-OtherTelephone " + '$Null' } else { $Array += "-OtherTelephone " + "`"" + $textBoxotherTelephone.text + "`"" } } if ($textBoxoffice.modified -eq $True) { $Array += "-Office " + "`"" + $textBoxoffice.text + "`"" } if ($textBoxassistantphone.modified -eq $true) { $Array += "-TelephoneAssistant " + "`"" + $textBoxassistantphone.text + "`"" } if ($textBoxStreetAddress.modified -eq $True) { $Array += "-StreetAddress " + "`"" + $textBoxStreetAddress.text + "`"" } if ($textBoxcity.modified -eq $True) { $Array += "-City " + "`"" + $textBoxcity.text + "`"" } if ($textBoxStorProv.modified -eq $true) { $Array += "-StateOrProvince " + "`"" + $textBoxStorProv.text + "`"" } if ($textBoxpostalcode.modified -eq $True) { $Array += "-PostalCode " + "`"" + $textBoxpostalcode.text + "`"" } If ($comboBoxcountry_SelectionChanged -eq "True") { $Array += "-CountryOrRegion " + "`"" + $comboboxcountry.Text + "`"" } $Array1 = @() if ($textBoxCustomAttribute2.modified -eq $true) { $Array1 += "-CustomAttribute2 " + "`"" + $textBoxCustomAttribute2.text + "`"" } if ($textBoxAlias.modified -eq $True) { $Array1 += "-Alias " + "`"" + $textBoxAlias.text + "`"" } if ($textBoxCustomAttribute1.modified -eq $True) { $Array1 += "-CustomAttribute1 " + "`"" + $textBoxCustomAttribute1.text + "`"" } if ($textBoxCustomAttribute5.modified -eq $true) { $Array1 += "-CustomAttribute5 " + "`"" + $textBoxCustomAttribute5.text + "`"" } if ($textBoxCustomAttribute7.modified -eq $True) { $Array1 += "-CustomAttribute7 " + "`"" + $textBoxCustomAttribute7.text + "`"" } if ($textBoxCustomAttribute3.modified -eq $true) { $Array1 += "-CustomAttribute3 " + "`"" + $textBoxCustomAttribute3.text + "`"" } if ($textBoxCustomAttribute4.modified -eq $True) { $Array1 += "-CustomAttribute4 " + "`"" + $textBoxCustomAttribute4.text + "`"" } if ($textBoxCustomAttribute8.modified -eq $True) { $Array1 += "-CustomAttribute8 " + "`"" + $textBoxCustomAttribute8.text + "`"" } if ($textBoxCustomAttribute6.modified -eq $true) { $Array1 += "-CustomAttribute6 " + "`"" + $textBoxCustomAttribute6.text + "`"" } if ($textBoxCustomAttribute10.modified -eq $True) { $Array1 += "-CustomAttribute10 " + "`"" + $textBoxCustomAttribute10.text + "`"" } try { if ($Array -ne $null) { $setuser = 'Set-user -identity ' + $upn + " " + $array + ' -EA Stop' Invoke-expression $setuser } if ($Array1 -ne $null) { $setmailbox = 'Set-Mailbox -Identity ' + $UPN + " " + $Array1 + ' -EA Stop' Invoke-expression $setmailbox } [Windows.Forms.MessageBox]::Show("The mailbox user has been updated sucessfully") } catch { [Windows.Forms.MessageBox]::Show("An error has occured while trying to update the user data, please ensure you have the proper rights to modify this specific mailbox user.") } } $comboBoxcountry_SelectedValueChanged= { $comboBoxcountry_SelectionChanged = $True } #Clicking the close button closes the form $btnclose1_OnClick= { $UserUpdate.Close() } #Makes the search tip visible on mouse over of the namesearch box $NameSearch_ShowTip= { $lbltip.visible = $true } #Hides the seach tip $NameSearch_HideTip= { $lbltip.visible = $false } #---------------------------------------------- #region Generated Form Code $UserUpdate.BackColor = [System.Drawing.Color]::FromArgb(255,49,106,197) $UserUpdate.Text = 'User Update Utility' $UserUpdate.Name = 'UserUpdate' $UserUpdate.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 539 $System_Drawing_Size.Height = 566 $UserUpdate.ClientSize = $System_Drawing_Size $Pages.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 538 $System_Drawing_Size.Height = 556 $Pages.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 0 $System_Drawing_Point.Y = -2 $Pages.Location = $System_Drawing_Point $Pages.DataBindings.DefaultDataSourceUpdateMode = 0 $Pages.Name = 'Pages' $Pages.SelectedIndex = 0 $UserUpdate.Controls.Add($Pages) $Search_User.BackColor = [System.Drawing.Color]::FromArgb(255,135,206,250) $Search_User.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 530 $System_Drawing_Size.Height = 507 $Search_User.Size = $System_Drawing_Size $Search_User.Text = 'Search_User' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 4 $System_Drawing_Point.Y = 22 $Search_User.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 3 $System_Windows_Forms_Padding.Bottom = 3 $System_Windows_Forms_Padding.Left = 3 $System_Windows_Forms_Padding.Right = 3 $System_Windows_Forms_Padding.Top = 3 $Search_User.Padding = $System_Windows_Forms_Padding $Search_User.Name = 'Search_User' $Search_User.DataBindings.DefaultDataSourceUpdateMode = 0 $Search_User.add_Click($handler_TabPage:_Click) $Pages.Controls.Add($Search_User) $statusbar.Name = "statusbar" $statusbar.Text = "Ready" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 539 $System_Drawing_Size.Height = 22 $statusbar.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 0 $System_Drawing_Point.Y = 544 $statusbar.Location = $System_Drawing_Point $statusbar.DataBindings.DefaultDataSourceUpdateMode = 0 $statusbar.TabIndex = 10 $statusbar.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0) $Search_User.Controls.Add($statusbar) $lblTip.TabIndex = 9 $lblTip.BackColor = [System.Drawing.Color]::FromArgb(0,255,255,255) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 340 $System_Drawing_Size.Height = 76 $lblTip.Size = $System_Drawing_Size $lblTip.Text = 'Please enter at least 3 characters for the search, the search will be performed on the following attributes: CN, Display Name, Alias, First Name, Last Name.' $lblTip.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0) $lblTip.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 100 $System_Drawing_Point.Y = 283 $lblTip.Location = $System_Drawing_Point $lblTip.DataBindings.DefaultDataSourceUpdateMode = 0 $lblTip.Name = 'lblTip' $lbltip.visible = $False $Search_User.Controls.Add($lblTip) $btnClose.TabIndex = 7 $btnClose.Name = 'btnClose' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnClose.Size = $System_Drawing_Size $btnClose.UseVisualStyleBackColor = $True $btnClose.Text = 'Close' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 450 $System_Drawing_Point.Y = 167 $btnClose.Location = $System_Drawing_Point $btnClose.DataBindings.DefaultDataSourceUpdateMode = 0 $btnClose.add_Click($btnClose_OnClick) $Search_User.Controls.Add($btnClose) $btnProperties.TabIndex = 6 $btnProperties.Name = 'btnProperties' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnProperties.Size = $System_Drawing_Size $btnProperties.UseVisualStyleBackColor = $True $btnProperties.Text = 'Properties' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 365 $System_Drawing_Point.Y = 167 $btnProperties.Location = $System_Drawing_Point $btnProperties.DataBindings.DefaultDataSourceUpdateMode = 0 $btnProperties.add_Click($btnProperties_OnClick) $Search_User.Controls.Add($btnProperties) $btnReset.TabIndex = 5 $btnReset.Name = 'btnReset' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnReset.Size = $System_Drawing_Size $btnReset.UseVisualStyleBackColor = $True $btnReset.Text = 'Reset' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 450 $System_Drawing_Point.Y = 31 $btnReset.Location = $System_Drawing_Point $btnReset.DataBindings.DefaultDataSourceUpdateMode = 0 $btnReset.add_Click($btnReset_OnClick) $Search_User.Controls.Add($btnReset) $btnfind.TabIndex = 4 $btnfind.Name = 'btnfind' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnfind.Size = $System_Drawing_Size $btnfind.UseVisualStyleBackColor = $True $btnfind.Text = 'Find' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 365 $System_Drawing_Point.Y = 31 $btnfind.Location = $System_Drawing_Point $btnfind.DataBindings.DefaultDataSourceUpdateMode = 0 $btnfind.add_Click($btnfind_OnClick) $Search_User.Controls.Add($btnfind) $ListUsers.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 234 $System_Drawing_Size.Height = 95 $ListUsers.Size = $System_Drawing_Size $ListUsers.DataBindings.DefaultDataSourceUpdateMode = 0 $ListUsers.Name = 'ListUsers' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 118 $System_Drawing_Point.Y = 95 $ListUsers.Location = $System_Drawing_Point $ListUsers.TabIndex = 3 $UserUpdate.KeyPreview = $True $ListUsers.Add_Keydown({if ($_.KeyCode -eq "Enter"){$btnProperties.performClick()}}) $Search_User.Controls.Add($ListUsers) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 234 $System_Drawing_Size.Height = 20 $NameSearch.Size = $System_Drawing_Size $NameSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $NameSearch.Name = 'NameSearch' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 118 $System_Drawing_Point.Y = 33 $NameSearch.Location = $System_Drawing_Point $NameSearch.TabIndex = 2 $NameSearch.add_MouseLeave($NameSearch_HideTip) $NameSearch.add_MouseEnter($NameSearch_ShowTip) $UserUpdate.KeyPreview = $True $NameSearch.Add_Keydown({if ($_.KeyCode -eq "Enter"){$btnfind.performClick()}}) $Search_User.Controls.Add($NameSearch) $lblselectuser.TabIndex = 1 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 73 $System_Drawing_Size.Height = 23 $lblselectuser.Size = $System_Drawing_Size $lblselectuser.Text = 'Select User' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 41 $System_Drawing_Point.Y = 129 $lblselectuser.Location = $System_Drawing_Point $lblselectuser.DataBindings.DefaultDataSourceUpdateMode = 0 $lblselectuser.Name = 'label2' $Search_User.Controls.Add($lblselectuser) $UserName.TabIndex = 0 $UserName.TextAlign = 2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 102 $System_Drawing_Size.Height = 28 $UserName.Size = $System_Drawing_Size $UserName.Text = 'Enter Name to search' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 31 $UserName.Location = $System_Drawing_Point $UserName.DataBindings.DefaultDataSourceUpdateMode = 0 $UserName.Name = 'UserName' $Search_User.Controls.Add($UserName) $User_Properties.BackColor = [System.Drawing.Color]::FromArgb(255,135,206,250) $User_Properties.TabIndex = 1 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 530 $System_Drawing_Size.Height = 530 $User_Properties.Size = $System_Drawing_Size $User_Properties.Text = 'User_Properties' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 4 $System_Drawing_Point.Y = 22 $User_Properties.Location = $System_Drawing_Point $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding $System_Windows_Forms_Padding.All = 3 $System_Windows_Forms_Padding.Bottom = 3 $System_Windows_Forms_Padding.Left = 3 $System_Windows_Forms_Padding.Right = 3 $System_Windows_Forms_Padding.Top = 3 $User_Properties.Padding = $System_Windows_Forms_Padding $User_Properties.Name = 'User_Properties' $User_Properties.DataBindings.DefaultDataSourceUpdateMode = 0 $Pages.Controls.Add($User_Properties) $comboBoxCountry.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 320 $System_Drawing_Size.Height = 21 $comboBoxCountry.Size = $System_Drawing_Size $comboBoxCountry.DataBindings.DefaultDataSourceUpdateMode = 0 #Uncomment the next 2 line if not using the xml file #$comboBoxCountry.Items.Add('CANADA') | Out-null #$comboBoxCountry.Items.Add('UNITED STATES') | Out-null #Comment the next 4 lines if not using the xml file [xml]$getcountrylist = Get-Content c:\\Scripts\\iso_3166-1_list_en.xml $countries = $getcountrylist.'ISO_3166-1_List_en'.'ISO_3166-1_Entry' | %{$_.'ISO_3166-1_Country_name'} | Select-Object -unique $comboBoxCountry.Name = 'comboBoxCountry' $comboBoxcountry.Items.AddRange($countries) | Out-Null $comboBoxcountry.add_SelectionChangeCommitted($comboBoxcountry_SelectedValueChanged) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 474 $comboBoxCountry.Location = $System_Drawing_Point $comboBoxCountry.TabIndex = 65 $User_Properties.Controls.Add($comboBoxCountry) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute5.Size = $System_Drawing_Size $textBoxCustomAttribute5.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute5.Name = 'textBoxCustomAttribute5' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 162 $textBoxCustomAttribute5.Location = $System_Drawing_Point $textBoxCustomAttribute5.TabIndex = 21 $User_Properties.Controls.Add($textBoxCustomAttribute5) $lblCustomAttribute5.TabIndex = 20 $lblCustomAttribute5.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute5.Size = $System_Drawing_Size $lblCustomAttribute5.Text = 'CustomAttribute5:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 158 $lblCustomAttribute5.Location = $System_Drawing_Point $lblCustomAttribute5.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute5.Name = 'lblCustomAttribute5' $User_Properties.Controls.Add($lblCustomAttribute5) $lblcountry.TabIndex = 62 $lblcountry.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblcountry.Size = $System_Drawing_Size $lblcountry.Text = 'Country:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 470 $lblcountry.Location = $System_Drawing_Point $lblcountry.DataBindings.DefaultDataSourceUpdateMode = 0 $lblcountry.Name = 'lblcountry' $User_Properties.Controls.Add($lblcountry) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxpostalcode.Size = $System_Drawing_Size $textBoxpostalcode.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxpostalcode.Name = 'textBoxpostalcode' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 448 $textBoxpostalcode.Location = $System_Drawing_Point $textBoxpostalcode.TabIndex = 63 $User_Properties.Controls.Add($textBoxpostalcode) $lblpostalcode.TabIndex = 62 $lblpostalcode.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblpostalcode.Size = $System_Drawing_Size $lblpostalcode.Text = 'Postal Code:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 444 $lblpostalcode.Location = $System_Drawing_Point $lblpostalcode.DataBindings.DefaultDataSourceUpdateMode = 0 $lblpostalcode.Name = 'lblpostalcode' $User_Properties.Controls.Add($lblpostalcode) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxStorProv.Size = $System_Drawing_Size $textBoxStorProv.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxStorProv.Name = 'textBoxStorProv' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 422 $textBoxStorProv.Location = $System_Drawing_Point $textBoxStorProv.TabIndex = 59 $User_Properties.Controls.Add($textBoxStorProv) $lblStorProv.TabIndex = 58 $lblStorProv.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblStorProv.Size = $System_Drawing_Size $lblStorProv.Text = 'State or Province:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 418 $lblStorProv.Location = $System_Drawing_Point $lblStorProv.DataBindings.DefaultDataSourceUpdateMode = 0 $lblStorProv.Name = 'lblStorProv' $User_Properties.Controls.Add($lblStorProv) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxcity.Size = $System_Drawing_Size $textBoxcity.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxcity.Name = 'textBoxcity' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 422 $textBoxcity.Location = $System_Drawing_Point $textBoxcity.TabIndex = 61 $User_Properties.Controls.Add($textBoxcity) $lblcity.TabIndex = 60 $lblcity.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblcity.Size = $System_Drawing_Size $lblcity.Text = 'City:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 418 $lblcity.Location = $System_Drawing_Point $lblcity.DataBindings.DefaultDataSourceUpdateMode = 0 $lblcity.Name = 'lblcity' $User_Properties.Controls.Add($lblcity) $textBoxStreetAddress.Multiline = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxStreetAddress.Size = $System_Drawing_Size $textBoxStreetAddress.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxStreetAddress.ScrollBars = 2 $textBoxStreetAddress.Name = 'textBoxStreetAddress' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 396 $textBoxStreetAddress.Location = $System_Drawing_Point $textBoxStreetAddress.TabIndex = 55 $User_Properties.Controls.Add($textBoxStreetAddress) $lblStreetAddress.TabIndex = 54 $lblStreetAddress.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblStreetAddress.Size = $System_Drawing_Size $lblStreetAddress.Text = 'Street Address:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 392 $lblStreetAddress.Location = $System_Drawing_Point $lblStreetAddress.DataBindings.DefaultDataSourceUpdateMode = 0 $lblStreetAddress.Name = 'lblStreetAddress' $User_Properties.Controls.Add($lblStreetAddress) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxassistantphone.Size = $System_Drawing_Size $textBoxassistantphone.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxassistantphone.Name = 'textBoxassistantphone' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 396 $textBoxassistantphone.Location = $System_Drawing_Point $textBoxassistantphone.TabIndex = 57 $User_Properties.Controls.Add($textBoxassistantphone) $lblassistantphone.TabIndex = 56 $lblassistantphone.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblassistantphone.Size = $System_Drawing_Size $lblassistantphone.Text = 'Assistant Phone:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 392 $lblassistantphone.Location = $System_Drawing_Point $lblassistantphone.DataBindings.DefaultDataSourceUpdateMode = 0 $lblassistantphone.Name = 'lblassistantphone' $User_Properties.Controls.Add($lblassistantphone) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxoffice.Size = $System_Drawing_Size $textBoxoffice.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxoffice.Name = 'textBoxoffice' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 370 $textBoxoffice.Location = $System_Drawing_Point $textBoxoffice.TabIndex = 51 $User_Properties.Controls.Add($textBoxoffice) $lbloffice.TabIndex = 50 $lbloffice.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lbloffice.Size = $System_Drawing_Size $lbloffice.Text = 'Office:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 366 $lbloffice.Location = $System_Drawing_Point $lbloffice.DataBindings.DefaultDataSourceUpdateMode = 0 $lbloffice.Name = 'lbloffice' $User_Properties.Controls.Add($lbloffice) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxotherTelephone.Size = $System_Drawing_Size $textBoxotherTelephone.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxotherTelephone.Name = 'textBoxotherTelephone' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 370 $textBoxotherTelephone.Location = $System_Drawing_Point $textBoxotherTelephone.TabIndex = 53 $User_Properties.Controls.Add($textBoxotherTelephone) $lblotherTelephone.TabIndex = 52 $lblotherTelephone.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblotherTelephone.Size = $System_Drawing_Size $lblotherTelephone.Text = 'Other Telephone:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 366 $lblotherTelephone.Location = $System_Drawing_Point $lblotherTelephone.DataBindings.DefaultDataSourceUpdateMode = 0 $lblotherTelephone.Name = 'lblotherTelephone' $User_Properties.Controls.Add($lblotherTelephone) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute10.Size = $System_Drawing_Size $textBoxCustomAttribute10.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute10.Name = 'textBoxCustomAttribute10' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 344 $textBoxCustomAttribute10.Location = $System_Drawing_Point $textBoxCustomAttribute10.TabIndex = 47 $User_Properties.Controls.Add($textBoxCustomAttribute10) $lblCustomAttribute10.TabIndex = 46 $lblCustomAttribute10.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 102 $System_Drawing_Size.Height = 23 $lblCustomAttribute10.Size = $System_Drawing_Size $lblCustomAttribute10.Text = 'CustomAttribute10:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 340 $lblCustomAttribute10.Location = $System_Drawing_Point $lblCustomAttribute10.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute10.Name = 'lblCustomAttribute10' $User_Properties.Controls.Add($lblCustomAttribute10) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxpager.Size = $System_Drawing_Size $textBoxpager.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxpager.Name = 'textBoxpager' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 344 $textBoxpager.Location = $System_Drawing_Point $textBoxpager.TabIndex = 49 $User_Properties.Controls.Add($textBoxpager) $lblpager.TabIndex = 48 $lblpager.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblpager.Size = $System_Drawing_Size $lblpager.Text = 'Pager:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 340 $lblpager.Location = $System_Drawing_Point $lblpager.DataBindings.DefaultDataSourceUpdateMode = 0 $lblpager.Name = 'lblpager' $User_Properties.Controls.Add($lblpager) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxOtherHomePhone.Size = $System_Drawing_Size $textBoxOtherHomePhone.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxOtherHomePhone.Name = 'textBoxOtherHomePhone' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 318 $textBoxOtherHomePhone.Location = $System_Drawing_Point $textBoxOtherHomePhone.TabIndex = 43 $User_Properties.Controls.Add($textBoxOtherHomePhone) $lblOtherHomePhone.TabIndex = 42 $lblOtherHomePhone.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 106 $System_Drawing_Size.Height = 23 $lblOtherHomePhone.Size = $System_Drawing_Size $lblOtherHomePhone.Text = 'Other Home Phone:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 4 $System_Drawing_Point.Y = 314 $lblOtherHomePhone.Location = $System_Drawing_Point $lblOtherHomePhone.DataBindings.DefaultDataSourceUpdateMode = 0 $lblOtherHomePhone.Name = 'lblOtherHomePhone' $User_Properties.Controls.Add($lblOtherHomePhone) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxmobile.Size = $System_Drawing_Size $textBoxmobile.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxmobile.Name = 'textBoxmobile' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 318 $textBoxmobile.Location = $System_Drawing_Point $textBoxmobile.TabIndex = 45 $User_Properties.Controls.Add($textBoxmobile) $lblmobile.TabIndex = 44 $lblmobile.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblmobile.Size = $System_Drawing_Size $lblmobile.Text = 'Mobile:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 314 $lblmobile.Location = $System_Drawing_Point $lblmobile.DataBindings.DefaultDataSourceUpdateMode = 0 $lblmobile.Name = 'lblmobile' $User_Properties.Controls.Add($lblmobile) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 139 $System_Drawing_Size.Height = 20 $textBoxfax.Size = $System_Drawing_Size $textBoxfax.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxfax.Name = 'textBoxfax' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 292 $textBoxfax.Location = $System_Drawing_Point $textBoxfax.TabIndex = 39 $User_Properties.Controls.Add($textBoxfax) $lblFax.TabIndex = 38 $lblFax.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblFax.Size = $System_Drawing_Size $lblFax.Text = 'Fax:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 288 $lblFax.Location = $System_Drawing_Point $lblFax.DataBindings.DefaultDataSourceUpdateMode = 0 $lblFax.Name = 'lblFax' $User_Properties.Controls.Add($lblFax) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxHomePhone.Size = $System_Drawing_Size $textBoxHomePhone.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxHomePhone.Name = 'textBoxHomePhone' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 292 $textBoxHomePhone.Location = $System_Drawing_Point $textBoxHomePhone.TabIndex = 41 $User_Properties.Controls.Add($textBoxHomePhone) $lblHomePhone.TabIndex = 40 $lblHomePhone.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblHomePhone.Size = $System_Drawing_Size $lblHomePhone.Text = 'Home Phone:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 288 $lblHomePhone.Location = $System_Drawing_Point $lblHomePhone.DataBindings.DefaultDataSourceUpdateMode = 0 $lblHomePhone.Name = 'lblHomePhone' $User_Properties.Controls.Add($lblHomePhone) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textboxPhone.Size = $System_Drawing_Size $textboxPhone.DataBindings.DefaultDataSourceUpdateMode = 0 $textboxPhone.Name = 'textboxPhone' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 266 $textboxPhone.Location = $System_Drawing_Point $textboxPhone.TabIndex = 35 $User_Properties.Controls.Add($textboxPhone) $lblPhone.TabIndex = 34 $lblPhone.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblPhone.Size = $System_Drawing_Size $lblPhone.Text = 'Business:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 262 $lblPhone.Location = $System_Drawing_Point $lblPhone.DataBindings.DefaultDataSourceUpdateMode = 0 $lblPhone.Name = 'lblPhone' $User_Properties.Controls.Add($lblPhone) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute6.Size = $System_Drawing_Size $textBoxCustomAttribute6.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute6.Name = 'textBoxCustomAttribute6' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 266 $textBoxCustomAttribute6.Location = $System_Drawing_Point $textBoxCustomAttribute6.TabIndex = 37 $User_Properties.Controls.Add($textBoxCustomAttribute6) $lblCustomAttribute6.TabIndex = 36 $lblCustomAttribute6.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute6.Size = $System_Drawing_Size $lblCustomAttribute6.Text = 'CustomAttribute6:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 262 $lblCustomAttribute6.Location = $System_Drawing_Point $lblCustomAttribute6.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute6.Name = 'lblCustomAttribute6' $User_Properties.Controls.Add($lblCustomAttribute6) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute8.Size = $System_Drawing_Size $textBoxCustomAttribute8.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute8.Name = 'textBoxCustomAttribute8' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 240 $textBoxCustomAttribute8.Location = $System_Drawing_Point $textBoxCustomAttribute8.TabIndex = 31 $User_Properties.Controls.Add($textBoxCustomAttribute8) $lblCustomAttribute8.TabIndex = 30 $lblCustomAttribute8.TextAlign = 16 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 23 $lblCustomAttribute8.Size = $System_Drawing_Size $lblCustomAttribute8.Text = 'CustomAttribute8:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 236 $lblCustomAttribute8.Location = $System_Drawing_Point $lblCustomAttribute8.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute8.Name = 'lblCustomAttribute8' $User_Properties.Controls.Add($lblCustomAttribute8) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute4.Size = $System_Drawing_Size $textBoxCustomAttribute4.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute4.Name = 'textBoxCustomAttribute4' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 240 $textBoxCustomAttribute4.Location = $System_Drawing_Point $textBoxCustomAttribute4.TabIndex = 33 $User_Properties.Controls.Add($textBoxCustomAttribute4) $lblCustomAttribute4.TabIndex = 32 $lblCustomAttribute4.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute4.Size = $System_Drawing_Size $lblCustomAttribute4.Text = 'CustomAttribute4:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 236 $lblCustomAttribute4.Location = $System_Drawing_Point $lblCustomAttribute4.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute4.Name = 'lblCustomAttribute4' $User_Properties.Controls.Add($lblCustomAttribute4) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textboxDepartment.Size = $System_Drawing_Size $textboxDepartment.DataBindings.DefaultDataSourceUpdateMode = 0 $textboxDepartment.Name = 'textboxDepartment' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 214 $textboxDepartment.Location = $System_Drawing_Point $textboxDepartment.TabIndex = 27 $User_Properties.Controls.Add($textboxDepartment) $lblDepartment.TabIndex = 26 $lblDepartment.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblDepartment.Size = $System_Drawing_Size $lblDepartment.Text = 'Department:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 210 $lblDepartment.Location = $System_Drawing_Point $lblDepartment.DataBindings.DefaultDataSourceUpdateMode = 0 $lblDepartment.Name = 'lblDepartment' $User_Properties.Controls.Add($lblDepartment) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute3.Size = $System_Drawing_Size $textBoxCustomAttribute3.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute3.Name = 'textBoxCustomAttribute3' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 214 $textBoxCustomAttribute3.Location = $System_Drawing_Point $textBoxCustomAttribute3.TabIndex = 29 $User_Properties.Controls.Add($textBoxCustomAttribute3) $lblCustomAttribute3.TabIndex = 28 $lblCustomAttribute3.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute3.Size = $System_Drawing_Size $lblCustomAttribute3.Text = 'CustomAttribute3:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 210 $lblCustomAttribute3.Location = $System_Drawing_Point $lblCustomAttribute3.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute3.Name = 'lblCustomAttribute3' $User_Properties.Controls.Add($lblCustomAttribute3) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute7.Size = $System_Drawing_Size $textBoxCustomAttribute7.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute7.Name = 'textBoxCustomAttribute7' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 188 $textBoxCustomAttribute7.Location = $System_Drawing_Point $textBoxCustomAttribute7.TabIndex = 23 $User_Properties.Controls.Add($textBoxCustomAttribute7) $lblCustomAttribute7.TabIndex = 22 $lblCustomAttribute7.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute7.Size = $System_Drawing_Size $lblCustomAttribute7.Text = 'CustomAttribute7:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 184 $lblCustomAttribute7.Location = $System_Drawing_Point $lblCustomAttribute7.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute7.Name = 'lblCustomAttribute7' $User_Properties.Controls.Add($lblCustomAttribute7) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCompany.Size = $System_Drawing_Size $textBoxCompany.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCompany.Name = 'textBoxCompany' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 188 $textBoxCompany.Location = $System_Drawing_Point $textBoxCompany.TabIndex = 25 $User_Properties.Controls.Add($textBoxCompany) $lblCompany.TabIndex = 24 $lblCompany.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCompany.Size = $System_Drawing_Size $lblCompany.Text = 'Company:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 184 $lblCompany.Location = $System_Drawing_Point $lblCompany.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCompany.Name = 'lblCompany' $User_Properties.Controls.Add($lblCompany) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute1.Size = $System_Drawing_Size $textBoxCustomAttribute1.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute1.Name = 'textBoxCustomAttribute1' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 162 $textBoxCustomAttribute1.Location = $System_Drawing_Point $textBoxCustomAttribute1.TabIndex = 19 $User_Properties.Controls.Add($textBoxCustomAttribute1) $lblCustomAttribute1.TabIndex = 18 $lblCustomAttribute1.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute1.Size = $System_Drawing_Size $lblCustomAttribute1.Text = 'CustomAttribute1:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 158 $lblCustomAttribute1.Location = $System_Drawing_Point $lblCustomAttribute1.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute1.Name = 'lblCustomAttribute1' $User_Properties.Controls.Add($lblCustomAttribute1) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxAlias.Size = $System_Drawing_Size $textBoxAlias.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxAlias.Name = 'textBoxAlias' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 136 $textBoxAlias.Location = $System_Drawing_Point $textBoxAlias.TabIndex = 15 $User_Properties.Controls.Add($textBoxAlias) $lblAlias.TabIndex = 14 $lblAlias.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblAlias.Size = $System_Drawing_Size $lblAlias.Text = 'Email Alias:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 132 $lblAlias.Location = $System_Drawing_Point $lblAlias.DataBindings.DefaultDataSourceUpdateMode = 0 $lblAlias.Name = 'lblAlias' $User_Properties.Controls.Add($lblAlias) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 254 $System_Drawing_Size.Height = 20 $textBoxEmail.Size = $System_Drawing_Size $textBoxEmail.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxEmail.Name = 'textBoxEmail' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 58 $textBoxEmail.Location = $System_Drawing_Point $textBoxEmail.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0) $textBoxEmail.TabIndex = 5 $User_Properties.Controls.Add($textBoxEmail) $lblemail.TabIndex = 4 $lblemail.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblemail.Size = $System_Drawing_Size $lblemail.Text = 'E-Mail:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 57 $lblemail.Location = $System_Drawing_Point $lblemail.DataBindings.DefaultDataSourceUpdateMode = 0 $lblemail.Name = 'lblemail' $User_Properties.Controls.Add($lblemail) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxCustomAttribute2.Size = $System_Drawing_Size $textBoxCustomAttribute2.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxCustomAttribute2.Name = 'textBoxCustomAttribute2' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 136 $textBoxCustomAttribute2.Location = $System_Drawing_Point $textBoxCustomAttribute2.TabIndex = 17 $User_Properties.Controls.Add($textBoxCustomAttribute2) $lblCustomAttribute2.TabIndex = 16 $lblCustomAttribute2.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblCustomAttribute2.Size = $System_Drawing_Size $lblCustomAttribute2.Text = 'CustomAttribute2:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 132 $lblCustomAttribute2.Location = $System_Drawing_Point $lblCustomAttribute2.DataBindings.DefaultDataSourceUpdateMode = 0 $lblCustomAttribute2.Name = 'lblCustomAttribute2' $User_Properties.Controls.Add($lblCustomAttribute2) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 254 $System_Drawing_Size.Height = 20 $textBoxUPN.Size = $System_Drawing_Size $textBoxUPN.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxUPN.Name = 'textBoxUPN' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 32 $textBoxUPN.Location = $System_Drawing_Point $textBoxUPN.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0) $textBoxUPN.TabIndex = 3 $User_Properties.Controls.Add($textBoxUPN) $lblUPN.TabIndex = 2 $lblUPN.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblUPN.Size = $System_Drawing_Size $lblUPN.Text = 'UPN:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 32 $lblUPN.Location = $System_Drawing_Point $lblUPN.DataBindings.DefaultDataSourceUpdateMode = 0 $lblUPN.Name = 'lblUPN' $User_Properties.Controls.Add($lblUPN) $btnclose1.TabIndex = 68 $btnclose1.Name = 'btnclose1' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnclose1.Size = $System_Drawing_Size $btnclose1.UseVisualStyleBackColor = $True $btnclose1.Text = 'Close' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 448 $System_Drawing_Point.Y = 501 $btnclose1.Location = $System_Drawing_Point $btnclose1.DataBindings.DefaultDataSourceUpdateMode = 0 $btnclose1.add_Click($btnclose1_OnClick) $User_Properties.Controls.Add($btnclose1) $btnnamesearchagain.TabIndex = 67 $btnnamesearchagain.Name = 'btnnamesearchagain' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 103 $System_Drawing_Size.Height = 23 $btnnamesearchagain.Size = $System_Drawing_Size $btnnamesearchagain.UseVisualStyleBackColor = $True $btnnamesearchagain.Text = 'Find Another user' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 326 $System_Drawing_Point.Y = 501 $btnnamesearchagain.Location = $System_Drawing_Point $btnnamesearchagain.DataBindings.DefaultDataSourceUpdateMode = 0 $btnnamesearchagain.add_Click($btnnamesearchagain_OnClick) $User_Properties.Controls.Add($btnnamesearchagain) $btnupdate.TabIndex = 66 $btnupdate.Name = 'btnupdate' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnupdate.Size = $System_Drawing_Size $btnupdate.UseVisualStyleBackColor = $True $btnupdate.Text = 'Update' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 235 $System_Drawing_Point.Y = 501 $btnupdate.Location = $System_Drawing_Point $btnupdate.DataBindings.DefaultDataSourceUpdateMode = 0 $btnupdate.add_Click($btnupdate_OnClick) $User_Properties.Controls.Add($btnupdate) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxTitle.Size = $System_Drawing_Size $textBoxTitle.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxTitle.Name = 'textBoxTitle' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 110 $textBoxTitle.Location = $System_Drawing_Point $textBoxTitle.TabIndex = 13 $User_Properties.Controls.Add($textBoxTitle) $lblTitle.TabIndex = 12 $lblTitle.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblTitle.Size = $System_Drawing_Size $lblTitle.Text = 'Title:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 106 $lblTitle.Location = $System_Drawing_Point $lblTitle.DataBindings.DefaultDataSourceUpdateMode = 0 $lblTitle.Name = 'lblTitle' $User_Properties.Controls.Add($lblTitle) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxInitials.Size = $System_Drawing_Size $textBoxInitials.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxInitials.Name = 'textBoxInitials' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 110 $textBoxInitials.Location = $System_Drawing_Point $textBoxInitials.TabIndex = 11 $User_Properties.Controls.Add($textBoxInitials) $lblInitials.TabIndex = 10 $lblInitials.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblInitials.Size = $System_Drawing_Size $lblInitials.Text = 'Initials:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 106 $lblInitials.Location = $System_Drawing_Point $lblInitials.DataBindings.DefaultDataSourceUpdateMode = 0 $lblInitials.Name = 'lblInitials' $User_Properties.Controls.Add($lblInitials) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxFirstName.Size = $System_Drawing_Size $textBoxFirstName.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxFirstName.Name = 'textBoxFirstName' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 369 $System_Drawing_Point.Y = 84 $textBoxFirstName.Location = $System_Drawing_Point $textBoxFirstName.TabIndex = 9 $User_Properties.Controls.Add($textBoxFirstName) $lblFirstName.TabIndex = 8 $lblFirstName.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblFirstName.Size = $System_Drawing_Size $lblFirstName.Text = 'First Name:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 263 $System_Drawing_Point.Y = 80 $lblFirstName.Location = $System_Drawing_Point $lblFirstName.DataBindings.DefaultDataSourceUpdateMode = 0 $lblFirstName.Name = 'lblFirstName' $User_Properties.Controls.Add($lblFirstName) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $textBoxLastName.Size = $System_Drawing_Size $textBoxLastName.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxLastName.Name = 'textBoxLastName' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 84 $textBoxLastName.Location = $System_Drawing_Point $textBoxLastName.TabIndex = 7 $User_Properties.Controls.Add($textBoxLastName) $lblLastName.TabIndex = 6 $lblLastName.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lblLastName.Size = $System_Drawing_Size $lblLastName.Text = 'Last Name:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 80 $lblLastName.Location = $System_Drawing_Point $lblLastName.DataBindings.DefaultDataSourceUpdateMode = 0 $lblLastName.Name = 'lblLastName' $User_Properties.Controls.Add($lblLastName) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 409 $System_Drawing_Size.Height = 20 $textBoxDisplayName.Size = $System_Drawing_Size $textBoxDisplayName.DataBindings.DefaultDataSourceUpdateMode = 0 $textBoxDisplayName.Name = 'textBoxDisplayName' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 114 $System_Drawing_Point.Y = 6 $textBoxDisplayName.Location = $System_Drawing_Point $textBoxDisplayName.TabIndex = 1 $User_Properties.Controls.Add($textBoxDisplayName) $lbldisplayName.TabIndex = 0 $lbldisplayName.TextAlign = 64 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $lbldisplayName.Size = $System_Drawing_Size $lbldisplayName.Text = 'DisplayName:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 8 $System_Drawing_Point.Y = 3 $lbldisplayName.Location = $System_Drawing_Point $lbldisplayName.DataBindings.DefaultDataSourceUpdateMode = 0 $lbldisplayName.Name = 'lbldisplayName' $User_Properties.Controls.Add($lbldisplayName) #endregion Generated Form Code $UserUpdate.TopMost = $True #Show the Form $UserUpdate.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/1027025e-d46a-4d37-a5b0-b1c76068dc6b.ps1
1027025e-d46a-4d37-a5b0-b1c76068dc6b.ps1
# Code to auto update the Address policy, GAL, OAB and storage groups and mailbox databases of an Exchange 2007 server by John McLear # This code is good for hosting providers or people who wish to use lots of storage groups and mailbox databases. # # Thanks to Joel Bennett (Jaykul) for general scripting help and the friendly folks in #powershell - freenode # # I rewrote this and didnt test before publishing so there may be some syntax errors. # # Created 07/09/2008 ################################################################################################################################# param([string]$fullname, [string]$mail2, [string]$typeofcustomer) # PRE REQ - Create a container in your address lists called "Generic Address Book" or something similar - this is where we will store address lists! - Create a public folder database on your MB server - In $publicfolderDatabase our example is in storage group sg0 called Public Folder. # We need to set some things manually too! $yourinternaldomain = "domain.com" # ie contoso.com $OABDistributionServer = "CASserver" # Your CAS server responsible for OAB distribution $MailboxServer = "MBserver" # Shortname of your MailboxServer $PublicFolderDatabase = $MailboxServer + '\\sg0\\Public Folder' # The Path to your public folder used for Address List distribution $LogFilePath = "d:\\Program Files\\Microsoft\\Exchange Server\\Mailbox\\First Storage Group\\" # Where we will put the log files $AdminName = "CN=Servers,CN=Exchange Administrative Group (TESTING23TESTY),CN=Administrative Groups,CN=Contoso,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" # This needs to be changed echo "Fullname: $fullname" # full name of customer - this must be a unique value) echo "Domain name: $mail2" # customers domain name ie fraggle.com echo "Type of customer (1 is basic, 2 is standard, 3 is premium): $typeofcustomer" # Basically a premium customer will get their own mailboxdatabase - a basic or standard will share in one big database (know why before you use this!) echo "Your internal domain: $yourinternaldomain" # The internal domain you set # Lets go! ###################### Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin # Loads exchange snap ins new-AcceptedDomain -Name $mail2 -DomainName $mail2 -DomainType 'Authoritative' # Creates an accepted domain new-EmailAddressPolicy -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain # Creates a new address policy giving - you may wish to modify this to suit set-EmailAddressPolicy -Identity $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain # Modifies the new address policy giving - you may wish to modify this to suit - Why modify? You may wish to update this at some point and its best practice to have a set command imho new-GlobalAddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname # Create a new GAL new-AddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Container '\\Generic Address Book' # Create a new address list in the Generic Address Book container - Modify your container to suit! $fullname2 = '\\Generic Address book\\' + $fullname # You may wish to modify the above to suit $OABPoint = $OABdistributionServer + '\\OAB (Default Web Site)' # You may wish to modify the above line to suit but I doubt it. new-OfflineAddressBook -Name $fullname -Server $pinkyring -AddressLists $fullname2 -PublicFolderDistributionEnabled $false -VirtualDirectories $OABPoint # Create a new Offline Address Book Set-OfflineAddressBook -Identity $fullname -versions Version3, Version4 -PublicFolderDistributionEnabled $true -AddressLists $fullname2 # Set the OAB to V3, 4 and Public folder distribution. Update-EmailAddressPolicy -Identity $fullname # Update the Email Address Policy Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase # Set the Mailbox database of the customer to use the public folder database you created $maildb = Get-MailboxDataBase | Select-String $fullname echo $maildb if ($maildb -match "sg") # if there is a database for the fullname value then { echo "not making the DB" } else { if ($typeofcustomer -match "3") # and if the type of customer is 3 (premium) { echo "making the DB" # this customer must be premium! good for them!! $i = 1 for( $i=0; $i -lt 50; $i++ ) # for each count 1 to 50 { $maildb = Get-MailboxDataBase | Select-String $fullname echo $maildb if ($maildb -match "sg") # Check for a database { echo "database located" } # if database is found then do nothing else { new-storagegroup sg$i # creating 50 storage groups new-mailboxdatabase -StorageGroup $MailboxServer\\sg$i -Name $fullname -EdbFilePath $LogFilePath + '\\' + $fullname.edb # make a database on the server - we need to add incrementation on servername here.. mount-database -Identity "CN=$fullname,CN=sg$i,CN=InformationStore,CN=$MailboxServer,$AdminName" # mount the database $i++ # increase the storage group by 1 } } Set-MailboxDatabase -Identity $fullname -PublicFolderDatabase $PublicFolderDatabase # set the public folder } else { echo "customer is a basic or standard customer so we are going to not create a DB" Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase } }
PowerShellCorpus/PoshCode/ISE-Lines.ps1
ISE-Lines.ps1
#requires -version 2.0 ## ISE-Lines module v 1.0 ## DEVELOPED FOR CTP3 ## See comments for each function for changes ... ############################################################################################################## ## Provides Line cmdlets for working with ISE ## Duplicate-Line - Duplicates current line ## Conflate-Line - Conflates current and next line ## MoveUp-Line - Moves current line up ## MoveDown-Line - Moves current line down ## Delete-TrailingBlanks - Deletes trailing blanks in the whole script ############################################################################################################## ## Duplicate-Line ############################################################################################################## ## Duplicates current line ############################################################################################################## function Duplicate-Line { $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") $line = $text[$caretLine -1] $newText = $text[0..($caretLine -1)] $newText += $line $newText += $text[$caretLine..($text.Count -1)] $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, $caretColumn) } ## Conflate-Line ############################################################################################################## ## Conflates current and next line ############################################################################################################## function Conflate-Line { $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") if ( $caretLine -ne $text.Count ) { $line = $text[$caretLine -1] + $text[$caretLine] -replace ("`r", "") $newText = @() if ( $caretLine -gt 1 ) { $newText = $text[0..($caretLine -2)] } $newText += $line $newText += $text[($caretLine +1)..($text.Count -1)] $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, $caretColumn) } } ## MoveUp-Line ############################################################################################################## ## Moves current line up ############################################################################################################## function MoveUp-Line { $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine if ( $caretLine -ne 1 ) { $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") $line = $text[$caretLine -1] $lineBefore = $text[$caretLine -2] $newText = @() if ( $caretLine -gt 2 ) { $newText = $text[0..($caretLine -3)] } $newText += $line $newText += $lineBefore if ( $caretLine -ne $text.Count ) { $newText += $text[$caretLine..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine - 1, $caretColumn) } } ## MoveDown-Line ############################################################################################################## ## Moves current line down ############################################################################################################## function MoveDown-Line { $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $caretColumn = $editor.CaretColumn $text = $editor.Text.Split("`n") if ( $caretLine -ne $text.Count ) { $line = $text[$caretLine -1] $lineAfter = $text[$caretLine] $newText = @() if ( $caretLine -ne 1 ) { $newText = $text[0..($caretLine -2)] } $newText += $lineAfter $newText += $line if ( $caretLine -lt $text.Count -1 ) { $newText += $text[($caretLine +1)..($text.Count -1)] } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine +1, $caretColumn) } } ## Delete-TrailingBlanks ############################################################################################################## ## Deletes trailing blanks in the whole script ############################################################################################################## function Delete-TrailingBlanks { $editor = $psISE.CurrentOpenedFile.Editor $caretLine = $editor.CaretLine $newText = @() foreach ( $line in $editor.Text.Split("`n") ) { $newText += $line -replace ("\\s+$", "") } $editor.Text = [String]::Join("`n", $newText) $editor.SetCaretPosition($caretLine, 1) } ############################################################################################################## ## Inserts a submenu Lines to ISE's Custum Menu ## Inserts command Duplicate Line to submenu Lines ## Inserts command Conflate Line Selected to submenu Lines ## Inserts command Move Up Line to submenu Lines ## Inserts command Move Down Line to submenu Lines ## Inserts command Delete Trailing Blanks to submenu Lines ############################################################################################################## if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "Line" } ) ) { $lineMenu = $psISE.CustomMenu.Submenus.Add("_Lines", $null, $null) $null = $lineMenu.Submenus.Add("Duplicate Line", {Duplicate-Line}, "Ctrl+Alt+D") $null = $lineMenu.Submenus.Add("Conflate Line", {Conflate-Line}, "Ctrl+Alt+J") $null = $lineMenu.Submenus.Add("Move Up Line", {MoveUp-Line}, "Ctrl+Shift+Up") $null = $lineMenu.Submenus.Add("Move Down Line", {MoveDown-Line}, "Ctrl+Shift+Down") $null = $lineMenu.Submenus.Add("Delete Trailing Blanks", {Delete-TrailingBlanks}, "Ctrl+Shift+Del") }
PowerShellCorpus/PoshCode/createSiteFromTemplate.ps1
createSiteFromTemplate.ps1
# Load the template $url = "http://spf" # where template base $namesite = "Good Site" #name new site title $targeturl = "goodsite" #name url new site # find id = viewAlltemplate $templateID = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}" #$templateID = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}#kolam" $site= new-Object Microsoft.SharePoint.SPSite($url ) # 1049 - russian, 1033 -english $loc= [System.Int32]::Parse(1049) # have list template with Russian localization $templates= $site.GetWebTemplates($loc) #Write-Host "templates = " $templates # view all templates in table - # this for find id custom template for installing foreach ($child in $templates){ write-host $child.Name " " $child.Title} # &#1058;&#1077;&#1086;&#1088;&#1077;&#1090;&#1080;&#1095;&#1077;&#1089;&#1082;&#1080; - &#1074;&#1099;&#1089;&#1074;&#1086;&#1073;&#1086;&#1078;&#1076;&#1072;&#1077;&#1090; &#1088;&#1077;&#1089;&#1091;&#1088;&#1089;&#1099; $site.Dispose() #look in the Output for the right one, and copy the Template Name #create a new-SPWeb $web = New-SPWeb -Url http://spf/$targeturl -Name "$namesite" -UseParentTopNav -AddToTopNav -UniquePermissions #-Template ""{E6BD7EFF-8336-4975-BA22-2256970781E2}#SubWebTemplate" # Another option is to create the New-SPWeb without the #-template argument. Then you can apply the custom template # by following line: $web.ApplyWebTemplate($templateID)
PowerShellCorpus/PoshCode/RunSSIS.ps1
RunSSIS.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Executes a SQL Server Integrations Services package for both server and file system storage types. ### Optionally Resets a Package Configuration connection string named "SSISCONFIG" to new server location. ### Also includes optional processing of external configuration file. ### </Description> ### <Usage> ### -------------------------- EXAMPLE 1 -------------------------- ### ./RunSSIS.ps1 -path Z002_SQL1\\sqlpsx -serverName 'Z002\\SQL1' ### ### This command will execute package sqlpsx on the server Z002\\SQL1 ### ### -------------------------- EXAMPLE 2 -------------------------- ### ./RunSSIS.ps1 -path Z002_SQL1\\sqlpsx -serverName 'Z002\\SQL1' -SSISCONFIG 'Z002\\SQL1' ### ### This command will execute as in Example 1 and using SSISCONFIG on Z002\\SQL1 regardless of the SSISCONFIG location defined in the package ### ### -------------------------- EXAMPLE 3 -------------------------- ### ./RunSSIS.ps1 -path Z002_SQL1\\sqlpsx -serverName Z002\\SQL1 -configFile 'C:\\SSISConfig\\sqlpsx.xml' ### ### This command will execute the package as in Example 1 and process and configuration file ### ### -------------------------- EXAMPLE 4 -------------------------- ### ./RunSSIS.ps1 -path 'C:\\SSIS\\sqlpsx.dtsx' ### ### This command will execute the package sqlpsx.dtsx located on the file system ### ### -------------------------- EXAMPLE 5 -------------------------- ### ./RunSSIS.ps1 -path 'C:\\SSIS\\sqlpsx.dtsx -nolog ### ### This command will execute the package sqlpsx.dtsx located on the file system and skip Windows Event logging ### ### </Usage> ### </Script> # --------------------------------------------------------------------------- param($path=$(throw 'path is required.'), $serverName, $configFile, $SSISCONFIG, [switch]$nolog) # Note: SSIS is NOT backwards compatible. At the beginning of the script you’ll need to comment/uncomment the specific assembly # to load 2005 or 2008. Default of the script is set to 2005 [reflection.assembly]::Load("Microsoft.SqlServer.ManagedDTS, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") > $null #[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft SQL Server\\90\\SDK\\Assemblies\\Microsoft.SQLServer.ManagedDTS.dll") > $null #[reflection.assembly]::Load("Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91") > $null #[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft SQL Server\\100\\SDK\\Assemblies\\Microsoft.SQLServer.ManagedDTS.dll") > $null #[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ManagedDTS") > $null ####################### function New-ISApplication { new-object ("Microsoft.SqlServer.Dts.Runtime.Application") } #New-ISApplication ####################### function Test-ISPath { param([string]$path=$(throw 'path is required.'), [string]$serverName=$(throw 'serverName is required.'), [string]$pathType='Any') #If serverName contains instance i.e. server\\instance, convert to just servername: $serverName = $serverName -replace "\\\\.*" #Note: Don't specify instance name $app = New-ISApplication switch ($pathType) { 'Package' { trap { $false; continue } $app.ExistsOnDtsServer($path,$serverName) } 'Folder' { trap { $false; continue } $app.FolderExistsOnDtsServer($path,$serverName) } 'Any' { $p=Test-ISPath $path $serverName 'Package'; $f=Test-ISPath $path $serverName 'Folder'; [bool]$($p -bor $f)} default { throw 'pathType must be Package, Folder, or Any' } } } #Test-ISPath ####################### function Get-ISPackage { param([string]$path, [string]$serverName) #If serverName contains instance i.e. server\\instance, convert to just servername: $serverName = $serverName -replace "\\\\.*" $app = New-ISApplication #SQL Server Store if ($path -and $serverName) { if (Test-ISPath $path $serverName 'Package') { $app.LoadFromDtsServer($path, $serverName, $null) } else { Write-Error "Package $path does not exist on server $serverName" } } #File Store elseif ($path -and !$serverName) { if (Test-Path -literalPath $path) { $app.LoadPackage($path, $null) } else { Write-Error "Package $path does not exist" } } else { throw 'You must specify a file path or package store path and server name' } } #Get-ISPackage ####################### function Set-ISConnectionString { param($package=$(throw 'package is required.'), $connectionInfo=$(throw 'value is required.')) foreach ($i in $connectionInfo.GetEnumerator()) { $name = $($i.Key); $value = $($i.Value); Write-Verbose "Set-ISConnectionString name:$name value:$value " $connectionManager = $package.connections | where {$_.Name -eq "$name"} Write-Verbose "Set-ISConnectionString connString1:$($connectionManager.ConnectionString)" if ($connectionManager) { $connString = $connectionManager.ConnectionString Write-Verbose "Set-ISConnectionString connString:$connString" $connString -match "^Data Source=(?<server>[^;]+);" > $null $newConnString = $connString -replace $($matches.server -replace "\\\\","\\\\"),$value Write-Verbose "Set-ISConnectionString newConnString:$newConnString" if ($newConnString) { $connectionManager.ConnectionString = $newConnString } } } } #Set-ISConnectionString ####################### #MAIN Write-Verbose "$MyInvocation.ScriptName path:$path serverName:$serverName configFile:$configFile SSISCONFIG:$SSISCONFIG nolog:$nolog.IsPresent" if (!($nolog.IsPresent)) { $log = Get-EventLog -List | Where-Object { $_.Log -eq "Application" } $log.Source = $MyInvocation.ScriptName $log.WriteEntry("Starting:$path",'Information') } $package = Get-ISPackage $path $serverName if ($package) { if ($SSISCONFIG) { Set-ISConnectionString $package @{SSISCONFIG=$SSISCONFIG} } if ($configFile) { $package.ImportConfigurationFile("$configFile") } #$connectionManager = $package.connections | where {$_.Name -eq "SSISCONFIG"} #$connString = $connectionManager.ConnectionString #Write-Verbose "***connString:$connString" $package.Execute() if ($?) { if (!($nolog.IsPresent)) { $log.WriteEntry("Completed:$path",'Information') } } else { if (!($nolog.IsPresent)) { $log.WriteEntry("Abend:$path:$Error[0]",'Error') } } } else { if (!($nolog.IsPresent)) { $log.WriteEntry("Abort:$path:$Error[0]",'Error') } throw ('CannotLoadPackage') } #MAIN #######################
PowerShellCorpus/PoshCode/Test Ora Proc Wrapper 1.ps1
Test Ora Proc Wrapper 1.ps1
# this is a testcase for http://code.google.com/p/poshcodegen/ # a project for generating PowerShell function wrappers around stored procedure call, and more. # Here we show how to return a resultsets (aka ref cursors) from an Orcale stored procedures using ADO.NET with PowerShell # by the way it tell the verion of the orcale Products you are running # Bernd Kriszio http://pauerschell.blogspot.com/ # Set your connection string (somthing like the following line) outside this function # $con_ora = "Data Source=your-tns;User Id=scott;Password=tiger;Integrated Security=no" [System.Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess") [System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") function noparm_recordset () { #Set up .NET code for calling stored proc $connection = New-Object System.Data.OracleClient.OracleConnection($con_ora) $command = New-Object System.Data.OracleClient.OracleCommand('noparm_recordset', $connection) $command.CommandType = [System.Data.CommandType]::StoredProcedure #Set up Stored Proc parameters #$command.Parameters.Add("ReturnValue", [Data.SqlDBType]::int) | out-null #$command.Parameters["ReturnValue"].Direction = [System.Data.ParameterDirection]::ReturnValue #$command.Parameters.Add("RC_1", [System.Data.OracleClient.OracleType]::Cursor) | out-null $command.Parameters.Add("RC_1", [Data.OracleClient.OracleType]::Cursor) | out-null $command.Parameters["RC_1"].Direction = [System.Data.ParameterDirection]::Output #Run $connection.Open() | out-null $adapter = New-Object System.Data.OracleClient.OracleDataAdapter $command $dataset = New-Object System.Data.DataSet [void] $adapter.Fill($dataSet) #$command.ExecuteNonQuery() $connection.Close() | out-null $CommandOutput = New-Object PSObject $CommandOutput | Add-Member -Name Tables -Value $dataSet.Tables -MemberType NoteProperty #Set output parameters #$CommandOutput | Add-Member -Name ReturnValue -Value $command.Parameters["ReturnValue"].Value -MemberType NoteProperty #Close the connection and return the output object return $CommandOutput } (noparm_recordset).tables[0] <# -- code of the testprocedure create or replace procedure noparm_recordset ( rc_1 in out SYS_REFCURSOR ) as begin Open rc_1 for SELECT * FROM product_component_version ; end; / -- Test call using SQL*Plus var r refcursor exec noparm_recordset(:r) print r #>
PowerShellCorpus/PoshCode/Start-Demo 3.3.ps1
Start-Demo 3.3.ps1
## Start-Demo.ps1 ################################################################################################## @@## This is an overhaul of Jeffrey Snover's original Start-Demo script by Joel "Jaykul" Bennett ## ## I've switched it to using ReadKey instead of ReadLine (you don't have to hit Enter each time) ## As a result, I've changed the names and keys for a lot of the operations, so that they make ## sense with only a single letter to tell them apart (sorry if you had them memorized). ## ## I've also been adding features as I come across needs for them, and you'll contribute your ## improvements back to the PowerShell Script repository as well. ################################################################################################## ## Revision History (version 3.3) ## 3.3 - Added: Added a "Clear Screen" option ## - Added: Added a "Rewind" function (which I'm not using much) ## 3.2 - Fixed: Put back the trap { continue; } ## 3.1 - Fixed: No Output when invoking Get-Member (and other cmdlets like it???) ## 3.0 - Fixed: Commands which set a variable, like: $files = ls ## - Fixed: Default action doesn't continue ## - Changed: Use ReadKey instead of ReadLine ## - Changed: Modified the option prompts (sorry if you had them memorized) ## - Changed: Various time and duration strings have better formatting ## - Enhance: Colors are settable: prompt, command, comment ## - Added: NoPauseAfterExecute switch removes the extra pause ## If you set this, the next command will be displayed immediately ## - Added: Auto Execute mode (FullAuto switch) runs the rest of the script ## at an automatic speed set by the AutoSpeed parameter (or manually) ## - Added: Automatically append an empty line to the end of the demo script ## so you have a chance to "go back" after the last line of you demo ################################################################################################## ## param( $file=".\\demo.txt", [int]$command=0, [System.ConsoleColor]$promptColor="Yellow", [System.ConsoleColor]$commandColor="White", [System.ConsoleColor]$commentColor="Green", [switch]$FullAuto, [int]$AutoSpeed = 3, [switch]$NoPauseAfterExecute ) $RawUI = $Host.UI.RawUI $hostWidth = $RawUI.BufferSize.Width # A function for reading in a character function Read-Char() { $_OldColor = $RawUI.ForeGroundColor $RawUI.ForeGroundColor = "Red" $inChar=$RawUI.ReadKey("IncludeKeyUp") # loop until they press a character, so Shift or Ctrl, etc don't terminate us while($_input.Character -eq 0){ $inChar=$RawUI.ReadKey("IncludeKeyUp") } $RawUI.ForeGroundColor = $_OldColor return $inChar.Character } function Rewind($lines, $index, $steps = 1) { $started = $index; $index -= $steps; while(($index -ge 0) -and ($lines[$index].Trim(" `t").StartsWith("#")) { $index-- } if( $index -lt 0 ) { $index = $started } return $index } $file = Resolve-Path $file while(-not(Test-Path $file)) { $file = Read-Host "Please enter the path of your demo script (Crtl+C to cancel)" $file = Resolve-Path $file } Clear-Host $_lines = Get-Content $file # Append an extra (do nothing) line on the end so we can still go back after the last line. $_lines += "Write-Host 'The End'" $_starttime = [DateTime]::now $FullAuto = $false Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth) Write-Host -nonew -back black -fore $promptColor @" <Demo Started :: $(split-path $file -leaf)>$(' ' * ($hostWidth -(18 + $(split-path $file -leaf).Length))) "@ Write-Host -nonew -back black -fore $promptColor "Press" Write-Host -nonew -back black -fore Red " ? " Write-Host -nonew -back black -fore $promptColor "for help.$(' ' * ($hostWidth -17))" Write-Host -nonew -back black -fore $promptColor $(" " * $hostWidth) # We use a FOR and an INDEX ($_i) instead of a FOREACH because # it is possible to start at a different location and/or jump # around in the order. for ($_i = $Command; $_i -lt $_lines.count; $_i++) { # Put the current command in the Window Title along with the demo duration $Dur = [DateTime]::Now - $_StartTime $RawUI.WindowTitle = "$(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s {3}" -f $dur.Hours, $dur.Minutes, $dur.Seconds, $($_Lines[$_i]) # Echo out the commmand to the console with a prompt as though it were real Write-Host -nonew -fore $promptColor "[$_i]PS> " if ($_lines[$_i].Trim(" ").StartsWith("#")) { Write-Host -fore $commentColor "$($_Lines[$_i]) " continue } else { Write-Host -nonew -fore $commandColor "$($_Lines[$_i]) " } if( $FullAuto ) { Start-Sleep $autoSpeed; $ch = [char]13 } else { $ch = Read-Char } switch($ch) { "?" { Write-Host -Fore $promptColor @" Running demo: $file (n) Next (p) Previous (q) Quit (s) Suspend (t) Timecheck (v) View $(split-path $file -leaf) (g) Go to line by number (f) Find lines by string (a) Auto Execute mode (c) Clear Screen "@ $_i-- # back a line, we're gonna step forward when we loop } "n" { # Next (do nothing) Write-Host -Fore $promptColor "<Skipping Line>" } "p" { # Previous Write-Host -Fore $promptColor "<Back one Line>" while ($_lines[--$_i].Trim(" ").StartsWith("#")){} $_i-- # back a line, we're gonna step forward when we loop } "x" { # EXECUTE (Go Faster) $AutoSpeed = [int](Read-Host "Pause (seconds)") $FullAuto = $true; Write-Host -Fore $promptColor "<eXecute Remaining Lines>" $_i-- # Repeat this line, and then just blow through the rest } "q" { # Quit Write-Host -Fore $promptColor "<Quiting demo>" $_i = $_lines.count; break; } "v" { # View Source $lines[0..($_i-1)] | Write-Host -Fore Yellow $lines[$_i] | Write-Host -Fore Green $lines[($_i+1)..$lines.Count] | Write-Host -Fore Yellow $_i-- # back a line, we're gonna step forward when we loop } "t" { # Time Check $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( "{3} -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s" -f $dur.Hours, $dur.Minutes, $dur.Seconds, ([DateTime]::Now.ToShortTimeString())) $_i-- # back a line, we're gonna step forward when we loop } "s" { # Suspend (Enter Nested Prompt) Write-Host -Fore $promptColor "<Suspending demo - type 'Exit' to resume>" $Host.EnterNestedPrompt() $_i-- # back a line, we're gonna step forward when we loop } "g" { # GoTo Line Number $i = [int](Read-Host "line number") if($i -le $_lines.Count) { if($i -gt 0) { # extra line back because we're gonna step forward when we loop $_i = Rewind $_lines $_i (($_i-$i)+1) } else { $_i = -1 # Start negative, because we step forward when we loop } } } "f" { # Find by pattern $match = $_lines | Select-String (Read-Host "search string") if($match -eq $null) { Write-Host -Fore Red "Can't find a matching line" } else { $match | % { Write-Host -Fore $promptColor $("[{0,2}] {1}" -f ($_.LineNumber - 1), $_.Line) } if($match.Count -lt 1) { $_i = $match.lineNumber - 2 # back a line, we're gonna step forward when we loop } else { $_i-- # back a line, we're gonna step forward when we loop } } } "c" { Clear-Host $_i-- # back a line, we're gonna step forward when we loop } "$([char]13)" { # on enter Write-Host trap [System.Exception] {Write-Error $_; continue;} Invoke-Expression ($_lines[$_i]) | out-default if(-not $NoPauseAfterExecute -and -not $FullAuto) { $null = $RawUI.ReadKey("NoEcho,IncludeKeyUp") # Pause after output for no apparent reason... ;) } } default { Write-Host -Fore Green "`nKey not recognized. Press ? for help, or ENTER to execute the command." $_i-- # back a line, we're gonna step forward when we loop } } } $dur = [DateTime]::Now - $_StartTime Write-Host -Fore $promptColor $( "<Demo Complete -- $(if($dur.Hours -gt 0){'{0}h '})$(if($dur.Minutes -gt 0){'{1}m '}){2}s>" -f $dur.Hours, $dur.Minutes, $dur.Seconds, [DateTime]::Now.ToLongTimeString()) Write-Host -Fore $promptColor $([DateTime]::now) Write-Host
PowerShellCorpus/PoshCode/Get-NewPassword.ps1
Get-NewPassword.ps1
#/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\ # # Script Name: Get-NewPassword.ps1 # Title: Random Password Generator # Version: 1.0 # Author: johnwcannon at gmail dot com # Date: September 16th, 2010 # # Description: Password gerneration function based upon code # originally posted on PoshCode.org by Sean Kearney # # Usage: Without any arguments, Get-NewPassword # generates an 8 character password with # upper, lower, and numeric characters. # It can accept 2 options, the first is # password length (up to 94) and the other # is complexity (1 to 4). The complexity # Levels are: # 1 - Lowercase characters only # 2 - Lower and Uppercase characters # 3 - Upper, Lower and Numeric (default) # 4 - Upper, Lower, Numeric, and Special chars # *Passwords generated do NOT reuse characters # and attempt to avoid creating repeating series # of characters, like abc or 123 #/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\ function global:Get-NewPassword([int]$PasswordLength, [int]$Complexity) { #Perform some (very) basic input sanitation on the variables (possibly) getting passed if ($PasswordLength -ne 0) { if ($PasswordLength -gt 94) { Write-Host "That's a long password you requested! There aren't enough unique characters to make a password that long." Return } if ($PasswordLength -lt 1) { Write-Host $PasswordLength Write-Host "You have entered an invalid password length." Return } } if ($Complexity -ne 0) { if (($Complexity -lt 1) -or ($Complexity -gt 4)) { Write-Host "You entered an invalid complexity value!" Return } } # Password length can be from 1 to 94, but defaults to 8 if no value is passed If ($PasswordLength -eq 0) { $PasswordLength=8 } #Set a default complexity level to 3 if one is not specified If ($Complexity -eq 0) { $Complexity=3 } if (($Complexity -eq 3) -and ($PasswordLength -gt 62)) { Write-Host "You have requested a password that has more characters than the `ncomplexity you chose. Try a complexity of 4 next time" Return } if (($Complexity -eq 2) -and ($PasswordLength -gt 52)) { Write-Host "You have requested a password that has more characters than the `ncomplexity you chose. Try a complexity of 3 or 4 next time" Return } if (($Complexity -eq 1) -and ($PasswordLength -gt 26)) { Write-Host "You have requested a password that has more characters than the `ncomplexity you chose. Try a complexity of 2, 3 or 4 next time" Return } # Declare arrays holding the decimal equivalents of the ascii characters $uppercasedec = 65..90 $lowercasedec = 97..122 $numeraldec = 48..57 #There are 4 ranges of special characters $specialchardec = 33..47 $specialchardec1 = 58..64 $specialchardec2 = 91..96 $specialchardec3 = 123..126 # Complexity can be from 1 - 4 with the results being # 1 - Pure lowercase Ascii # 2 - Mix Uppercase and Lowercase Ascii # 3 - Ascii Upper/Lower with Numbers # 4 - Ascii Upper/Lower with Numbers and Special Characters #Build an array of the complexity specified if($Complexity -eq 1) { $passchars += $lowercasedec } if($Complexity -eq 2) { $passchars += $lowercasedec + $uppercasedec } if($Complexity -eq 3) { $passchars += $lowercasedec + $uppercasedec + $numeraldec } if($Complexity -eq 4) { $passchars += $lowercasedec + $uppercasedec + $numeraldec + ` $specialchardec + $specialchardec1 + $specialchardec2 + $specialchardec3 } #Here is the loop that generates a character until the requested #password length is reached Foreach ($counter in 1..$PasswordLength) { $lastchar = $null #We pluck out a random character from the character set chosen $tempchar = ($passchars | Get-Random) #We asign a last character chosen variable to prevent repeating patterns like abc or 123 $lastchar = $tempchar #If statement to check if character is adjacent to last character used #and checks to make sure that there aren't only two characters left in #the set that might create an infinite loop if they are actually adjacent If (($lastchar -eq ($tempchar + 1)) -or ($lastchar -eq ($tempchar - 1)) -and ($passchars.count -gt 2)) { #Let's pluck out a new random character since the last one was adjacent $tempchar = ($passchars | Get-Random) #Reset the $lastchar variable so it can be tested again $lastchar = $tempchar } #Now that we have verified that the character isn't adjacent to #the last character we pulled, we need to remove it from the array $passchars = ($passchars | Where-Object {$_ -ne $tempchar}) #Now we build the password and convert the decimal to ASCII $NewPassword=$NewPassword+[char]($tempchar) } # When we are done, we return the completed password # back to the calling party Return $NewPassword }
PowerShellCorpus/PoshCode/814ade13-24cf-4b85-beea-d9492ddd8e1e.ps1
814ade13-24cf-4b85-beea-d9492ddd8e1e.ps1
$DriveLetter = "D:" $MaxShrink = 0.30 # 0.30 equals 30% $MinShrink = 0.20 # 0.20 equals 20% $FileLocation = $env:Temp $FileName4DiskPart = "Shrink.txt" $DiskDrive = GWMI -CL Win32_LogicalDisk | Where {$_.DeviceId -Eq "$DriveLetter"} $DriveSize = ($DiskDrive.Size /1GB) $DriveSize = [int]$DriveSize $DesiredShrink = [int]($DriveSize * $MaxShrink) $MinimumShrink = [int]($DriveSize * $MinShrink) #Write-Host DiskSize $DriveSize GB #Write-Host DesiredShrink $DesiredShrink GB #Write-Host MinimumShrink $MinimumShrink GB Write "Select volume $DriveLetter" |Out-file $FileLocation\\$FileName4DiskPart -encoding ASCII Write "shrink desired=$DesiredShrink minimum=$MinimumShrink" |Out-file $FileLocation\\$FileName4DiskPart -append -encoding ASCII &cmd " /c diskpart" " /s $FileLocation\\$FileName4DiskPart"
PowerShellCorpus/PoshCode/Set Logfile length.ps1
Set Logfile length.ps1
################################################################################ # Set-FileLines.ps1 # This script will maintain the PS Transcript file, or any text file, at a fixed # length and can be used to prevent such files from becoming too large, with the # option of removing any blank lines. Defaults to 10000 lines and can be placed # in $profile. # Setting lines to 0 will just remove any blank lines from the file and, in this # case, the -Blanks switch is not necessary. # Examples: # Set-FileLines 1500 c:\\Scripts\\Logfile.txt # Set-FileLines 0 c:\\scripts\\anyfile.txt # Set-FileLines 3000 -Blanks # The author can be contacted via www.SeaStarDevelopmet.Bravehost.com ################################################################################ Param ([int] $lines = 10000, [String]$file = "$pwd\\Transcript.txt", [Switch]$blanks) If ($file -notlike "*.txt") { [System.Media.SystemSounds]::Hand.Play() Write-Error "This script can only process .txt files" Exit 1 } If (!(Test-Path $file)) { [System.Media.SystemSounds]::Hand.Play() Write-Error "File $file does not exist" Exit 1 } [int]$count = 0 [int]$blankLines = 0 $errorActionPreference = 'SilentlyContinue' $content = (Get-Content $file) If ($lines -eq 0) { #Input 0 lines to have just blank lines removed. [int]$extra = 1 [int]$count = 1 [switch]$blanks = $true #Otherwise no blanks will be deleted below. } Else { $fileLength = ($content | Measure-Object -line) [int]$extra = $fileLength.Lines - $lines #The number of lines to remove. } If ($extra -gt 0) { $tempfile = [IO.Path]::GetTempFileName() Write-Output "Starting maintenance on file <$file>" $content | ForEach-Object { $count += 1 If($count -gt $extra) { #Ignore the first $extra lines. If (($blanks) -and ($_ -match '^\\s*$')) { #Skip blank lines. $blankLines++ } Else { $_ | Out-File $tempfile -Append -Force #Create new file. } } } If ($file -like "*transcript.txt") { Stop-Transcript | Out-Null } Remove-Item $file Move-Item $tempfile -Destination $file If ($lines -eq 0) { #Only interested in blank lines here. $tag = "$blankLines blank lines removed." } ElseIf ($blanks) { $tag = "$extra lines removed (+ $blankLines blank)." } Else { #Not interested in blank lines. $tag = "$extra lines removed." } If ($file -like "*transcript.txt") { Start-Transcript -append -path $file -force | Out-Null } Write-Output "Maintenance of file completed: $tag" } $ErrorActionPreference = 'Continue'
PowerShellCorpus/PoshCode/Async SQL Backup .ps1
Async SQL Backup .ps1
$backuppath = "\\\\server\\sqlbackups\\" $alertaddress = "jrich523@domain.com" $smtp = "smtp.domain.com" $retaindays = 14 $hname = (gwmi win32_computersystem).name $errorstate = 0 $body =@() $backups = @() $conns = @() $completed = @{} [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null $dt = get-date -format "MMddyy" $Instances = Get-Item "HKLM:\\software\\microsoft\\microsoft sql server\\instance names\\sql" foreach($InstanceName in $Instances.property) { $InstancePath = $Instances.GetValue($InstanceName) if(Test-Path ("HKLM:\\software\\microsoft\\microsoft sql server\\" + $InstancePath + "\\cluster")) { #is cluster $ServerName = (gp ("HKLM:\\software\\microsoft\\microsoft sql server\\" + $InstancePath + "\\cluster")).ClusterName } else #not cluster { $ServerName = $hname } if($InstanceName -eq "MSSQLSERVER") {#default Instance $InstConn = $ServerName } else {#named instance $InstConn = $ServerName + "\\" + $InstanceName } $sql = New-Object Microsoft.SqlServer.management.Smo.Server $InstConn $backuppath += $sql.name + "\\" $backuppath += $sql | ?{$_.instancename -ne "" -and $_.instancename -ne "MSSQLSERVER"} | %{$_.instancename + "\\"} $dbs = $sql.databases | ? {!$_.isSystemObject} #change to full recovery if set to simple. #$dbs |?{$_.recoverymodel -eq [microsoft.sqlserver.management.smo.recoverymodel]::simple} | %{$_.recoverymodel = [microsoft.sqlserver.management.smo.recoverymodel]::Full;$_.alter()} $dbs | %{$completed[$_.name] = 0} #completed status foreach ($db in $dbs) { $path = $backuppath + $db.name + "\\" if(!(Test-Path $path)){mkdir $path | Out-Null} $conn = New-Object Microsoft.SqlServer.management.Smo.Server $InstConn $conn.ConnectionContext.StatementTimeout = 0 $bk = new-object microsoft.sqlserver.management.smo.backup $bk.BackupSetDescription = "fullbackup of $($db.name) on $(get-date)" $bk.BackupSetName = "full" $bk.database = $db.name $bk.Devices.AddDevice("$backuppath$($db.name)\\$($db.name)-$dt.bak",'File') $backups += $bk $index = $backups.length -1 Register-ObjectEvent -InputObject $backups[$index] -EventName "Complete" -SourceIdentifier $db.name -MessageData "$($db.name)-$index" | Out-Null Register-ObjectEvent -InputObject $backups[$index] -EventName "Information" -SourceIdentifier "info-$($db.name)" -MessageData "$($db.name)-$index" | out-null $conns += $conn $backups[$index].SqlBackupAsync($conns[$index]) } } #### due to issue with completed trigger, another timer is being run to monitor the states of each backup. $timer = New-Object timers.Timer $timer.interval = 300000 #10 min $action = { $global:backups | ?{$_.asyncstatus.executionstatus -ne "InProgress"}|?{$global:completed.($_.database) -eq 0}|%{$global:completed.($_.database) = 1;$global:body += "timer caught: $($_.database)";"timer kicked off: $($_.database)"} New-Event -SourceIdentifier timer } Register-ObjectEvent -InputObject $timer -Action $action -SourceIdentifier timercheck -EventName elapsed $timer.start() ##wait for complete while(($completed.values | measure -sum).sum -lt $backups.length){ wait-event | Tee-Object -variable theevent | Remove-Event if($theevent.sourceIdentifier -ne "timer") { $msg = $theevent.sourceeventargs.error.message $db,$index = $theevent.messagedata.split('-') $status = $theevent.sourceargs[0].asyncstatus.executionstatus if($completed.$db -ne 1) { switch ($status){ "Succeeded" { $completed.$db = 1 $body += "$db successfully" break;} "Failed" { $body += "$db FAILED: $msg" $completed.$db, $errorstate = 1 break;} "InProgress"{ break;} "Inactive" { break;} } } } } if($errorstate -eq 1){$subject = "DBBK: Failure on $hname"} else {$subject = "DBBK: Success on $hname"} Send-MailMessage -Subject $subject -BodyAsHtml ([string]::join("<br>",$body)) -From $alertaddress -To $alertaddress -SmtpServer $smtp #cleanup $backups | %{$_.devices[0].name} | Split-Path | gci -Recurse | ? {!$_.PSIsContainer -and $_.lastWriteTime -lt [dateTime]::today.addDays(-1 * $retaindays)} | ri -force
PowerShellCorpus/PoshCode/New-CodeSigningCert.ps1
New-CodeSigningCert.ps1
## New-CodeSigningCert.ps1 ######################################################################################################################## ## Does the setup needed to self-sign PowerShell scripts ... ## Generates a "test" self-signed root Certificate Authority ## And then generates a code-signing certificate (and signs it with the CA certificate) ## OPTIONALLY (specify -import or -importall) imports the certificates to the store(s) ######################################################################################################################## ## NOTE: Uses OpenSSL (because it's xcopy redistributable -- wake up Microsoft) ## In order for this to work you should KEEP the script in the folder with OpenSsl.exe ## Also, it is VERY important that you properly provide passwords and the locale data... ## You can obviously reorder the parameters however you like, and hard-code some of the values in the parameters, but ## you need to make sure that if you use this to generate multiple certificates, that you preserve all of the certs ## and keep track of all your passwords so you don't lock yourself out of any of them. ######################################################################################################################## ## Usage: ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" Jaykul@HuddledMasses.org HuddledMasses.org Mystery Rochester "New York" US -importall -OpenSSLLocation C:\\Users\\Joel\\Documents\\WindowsPowershell\\PoshCerts\\bin -CAPassword MyCleverRootPassword -CodeSignPassword EvenMoreCleverPasswords ## ## If I hard-coded the company/dept/etc ... I could use this to generate certs for all my devs: ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" FakeEmail@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword MarksPassword ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" FakeEmail2@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword JessesPassword ## ## For the signed scripts to work, I just have to -import on the devices where the scripts need to run: ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" -import ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" -import ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -import ## ## On the developers' workstations, I need to use Get-PfxCertificate to sign, or else run -importall ## That will load the codesigning cert in their "my" store, and will only require the password for the initial import ## ## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -importall -CodeSignPassword MyCodeSignPassword ######################################################################################################################## ## History ## 1.0 - Initial public release ## 1.1 - Bug fix release to make it easier to use... ## 1.2 - Bug fix to get the ORG and COMMON NAME set correctly -- Major whoops! ## Param( $CertStorageLocation = (join-path (split-path $Profile) "Certs"), $UserName = (Read-Host "User name") , $email , $company , $department , $city , $state , $country , $RootCAName = "Self-Signed-Root-CA" , $CodeSignName = "$UserName Code-Signing" , $alias = "PoshCert", [string]$keyBits = 4096, [string]$days = 365, [string]$daysCA = (365 * 5), [switch]$forceNew = $false, [switch]$importall = $false, [switch]$import = ($false -or $importall), ## we ask you to specify the CA password and your codesign password ## You can leave these null when importing on end-user desktops $CAPassword = $null, $CodeSignPassword = $null, ## You really shouldn't pass these unless you know what you're doing $OpenSSLLocation = $null, $RootCAPassword = $Null, $CodeSignCertPassword = $null ) function Get-UserEmail { if(!$script:email) { $script:email = (Read-Host "Email address") } return $script:email } function Get-RootCAPassword { if(!$script:RootCAPassword) { if(!$script:CAPassword) { $script:CAPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Root CA Password")).GetNetworkCredential().Password) } ## Then down here we calculate large passwords to actually use: ## This works as long as you keep the same company name and root ca name $script:RootCAPassword = [Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CaPassword)), ([Text.Encoding]::UTF8.GetBytes("$company$RootCAName")), "SHA1", 5).GetBytes(64) ) } return $script:RootCAPassword } function Get-CodeSignPassword { if(!$script:CodeSignCertPassword) { if(!$script:CodeSignPassword) { $script:CodeSignPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Code Signing Password")).GetNetworkCredential().Password) } ## This works as long as you keep the same PFX password and email address $script:CodeSignCertPassword = ([Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CodeSignPassword)), ([Text.Encoding]::UTF8.GetBytes((Get-UserEmail))), "SHA1", 5).GetBytes(64) )) } return $script:CodeSignCertPassword } function Get-SslConfig { Param ( $keyBits, $Country = (Read-Host "Country (2-Letter code)"), $State = (Read-Host "State (Full Name, no intials)"), $city = (Read-Host "City"), $company = (Read-Host "Company Name (or Web URL)"), $orgUnit = (Read-Host "Department (team, group, family)"), $CommonName, $email = (Read-Host "Email Address") ) @" # OpenSSL example configuration file for BATCH certificate generation # This definition stops the following lines choking if HOME isn't defined. HOME = . RANDFILE = $($ENV::HOME)/.rnd # To use this configuration with the "-extfile" option of the "openssl x509" utility # name here the section containing the X.509v3 extensions to use: #extensions = code_sign #################################################################### [ req ] default_bits = {0} default_keyfile = privkey.pem distinguished_name = req_distinguished_name #attributes = req_attributes x509_extensions = v3_ca # The extentions to add to the self signed cert # req_extensions = v3_ca # Other extensions to add to a certificate request? ## Passwords for private keys could be specified here, instead of on the commandline # input_password = secret # output_password = secret ## Set the permitted string types... ## Some software crashes on BMPStrings or UTF8Strings, so we'll stick with string_mask = nombstr [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = {1} countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = {2} localityName = Locality Name (eg, city) localityName_default = {3} 0.organizationName = Organization Name (eg, company) 0.organizationName_default = {4} # we can do this but it is not usually needed #1.organizationName = Second Organization Name (eg, company) #1.organizationName_default = World Wide Web Pty Ltd organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = {5} commonName = Common Name (eg, YOUR name) commonName_default = {6} commonName_max = 64 emailAddress = Email Address emailAddress_default = {7} emailAddress_max = 64 # SET-ex3 = SET extension number 3 # [ req_attributes ] # challengePassword = A challenge password # challengePassword_min = 4 # challengePassword_max = 20 # unstructuredName = An optional company name [ v3_ca ] ## Extensions for a typical CA ## PKIX recommendations: subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always ## PKIX suggests we should include email address in subject alt name # subjectAltName=email:copy ## But really they want it *only* there or the certs are "deprecated" # subjectAltName=email:move ## And the issuer details # issuerAltName=issuer:copy ## This is what PKIX recommends basicConstraints = critical,CA:true ## some broken software chokes on critical extensions, so you could do this instead. #basicConstraints = CA:true ## For a normal CA certificate you would want to specify this. ## But it will cause problems for our self-signed certificate. # keyUsage = cRLSign, keyCertSign ## You might want the netscape-compatible stuff too # nsCertType = sslCA, emailCA [ code_sign ] # These extensions are added when we get a code_signing cert ## PKIX recommendations: subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer ## PKIX suggests we should include email address in subject alt name # subjectAltName=email:copy ## But really they want it *only* there or the certs are "deprecated" # subjectAltName=email:move ## And the issuer details # issuerAltName=issuer:copy # This goes against PKIX guidelines but some CAs do it and some software # requires this to avoid interpreting an end user certificate as a CA. basicConstraints=CA:FALSE # If nsCertType is omitted, the certificate can be used for anything *except* object signing. # We just want to allow everything including object signing: nsCertType = server, client, email, objsign # This is the vital bit for code-signing extendedKeyUsage = critical, serverAuth,clientAuth,codeSigning # This is typical in keyUsage for a client certificate. keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment # This will be displayed in Netscape's comment listbox. nsComment = "OpenSSL Generated Certificate" [ crl_ext ] # CRL extensions. # Only issuerAltName and authorityKeyIdentifier make any sense in a CRL. # issuerAltName=issuer:copy authorityKeyIdentifier=keyid:always,issuer:always "@ -f $keyBits,$Country,$State,$city,$company,$orgUnit,$CommonName,$email } if(!$OpenSSLLocation) { ## You should be running the script from the OpenSsl folder $OpenSSLLocation = Split-Path $MyInvocation.MyCommand.Path Write-Debug "OpenSSL: $OpenSSLLocation" } if( Test-Path $OpenSslLocation ) { ## The OpenSslLoction needs to actually have OpenSsl in it ... $files = ls (Join-Path $OpenSSLLocation "*.[de][lx][el]") -include libeay32.dll,ssleay32.dll,OpenSSL.exe # libssl32.dll, if($files.count -lt 3) { THROW "You need to configure a location where OpenSSL can be run from" } } else { THROW "You need to configure a location where OpenSSL can be run from" } ## Don't touch these [string]$SslCnfPath = (join-path (Convert-Path $CertStorageLocation) PoshOpenSSL.config) New-Alias OpenSsl (join-path $OpenSSLLocation OpenSSL.exe) if( !(Test-Path $CertStorageLocation) ) { New-Item -type directory -path $CertStorageLocation | Push-Location $forceNew = $true } else { Push-Location $CertStorageLocation } Write-Debug "SslCnfPath: $SslCnfPath" Write-Debug "OpenSsl: $((get-alias OpenSsl).Definition)" ## Process the CSR and generate a pfx file if($forceNew -or (@(Test-Path "$CodeSignName.crt","$CodeSignName.pfx") -contains $false)) { ## Generate the private code-signing key and a certificate signing request (csr) if($forceNew -or (@(Test-Path "$CodeSignName.key","$CodeSignName.csr") -contains $false)) { ## Generate the private root CA key and convert it into a self-signed certificate (crt) if($forceNew -or (@(Test-Path "$RootCAName.key","$RootCAName.crt") -contains $false)) { ## Change configuration before -batch processing root key $CommonName = "$company Certificate Authority" $orgUnit = "$department Certificate Authority" $email = Get-UserEmail Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file OpenSsl genrsa -out "$RootCAName.key" -des3 -passout pass:$(Get-RootCAPassword) $keyBits OpenSsl req -new -x509 -days $daysCA -key "$RootCAName.key" -out "$RootCAName.crt" -passin pass:$(Get-RootCAPassword) -config $SslCnfPath -batch } ## Change configuration before -batch processing code-signing key $CommonName = "$UserName" $orgUnit = "$department" $email = Get-UserEmail Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file OpenSsl genrsa -out "$CodeSignName.key" -des3 -passout pass:$(Get-CodeSignPassword) $keyBits OpenSsl req -new -key "$CodeSignName.key" -out "$CodeSignName.csr" -passin pass:$(Get-CodeSignPassword) -config $SslCnfPath -batch } ## Use the root CA key to process the CSR and sign the code-signing key in one step... OpenSsl x509 -req -days $days -in "$CodeSignName.csr" -CA "$RootCAName.crt" -CAcreateserial -CAkey "$RootCAName.key" -out "$CodeSignName.crt" -setalias $alias -extfile $SslCnfPath -extensions code_sign -passin pass:$(Get-RootCAPassword) ## Combine the signed certificate and the private key into a single file and specify a new password for it ... OpenSsl pkcs12 -export -out "$CodeSignName.pfx" -inkey "$CodeSignName.key" -in "$CodeSignName.crt" -passin pass:$(Get-CodeSignPassword) -passout pass:$script:CodeSignPassword } Pop-Location if($import) { ## Now we need to import the certificates to the computer so we can use them... ## Sadly, the PowerShell Certificate Provider is read-only, so we need to do this by hand trap { if($_.Exception.GetBaseException() -is [UnauthorizedAccessException]) { write-error "Cannot import certificates as 'Root CA' or 'Trusted Publisher' except in an elevated console." continue } } ## In order to be able to use scripts signed by these certs ## The root cert that signed the code-signing certs must be loaded into the "Root" store $lm = new-object System.Security.Cryptography.X509certificates.X509Store "root", "LocalMachine" $lm.Open("ReadWrite") $lm.Add( (Get-PfxCertificate "$CertStorageLocation\\$RootCAName.crt") ) if($?) { Write-Host "Successfully imported root certificate to trusted root store" -fore green } $lm.Close() ## In order to avoid the "untrusted publisher" prompt ## The public code-signing cert must be loaded into the "TrustedPublishers" store $tp = new-object System.Security.Cryptography.X509certificates.X509Store "TrustedPublisher", "LocalMachine" $tp.Open("ReadWrite") $tp.Add( (Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.crt") ) if($?) { Write-Host "Successfully imported code-signing certificate to trusted publishers store" -fore green } $tp.Close() if($importall) { ## It's a good practice to go ahead and put our private certificates in "OUR" store too ### Otherwise we have to load it each time from the pfx file using Get-PfxCertificate ##### $cert = Get-PfxCertificate "$CodeSignName.pfx" ##### Set-AuthenticodeSignature -Cert $cert -File Test-Script.ps1 $my = new-object System.Security.Cryptography.X509certificates.X509Store "My", "CurrentUser" $my.Open( "ReadWrite" ) Get-CodeSignPassword $my.Add((Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.pfx")) #$script:CodeSignPassword, $DefaultStorage) if($?) { Write-Host "Successfully imported code-signing certificate to 'my' store" -fore yellow } $my.Close() } } # SIG # Begin signature block # MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUunVl0UTZlvAjOS219sL9EUT4 # EE6gggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL # Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw # Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ # KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx # OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l # dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk # bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs # IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y # ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM # +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ # qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ # /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX # IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05 # 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7 # tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8 # xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx # gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs # VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG # fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1 # JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH # Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG # A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF # BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB # DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF # AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2 # bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q # V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha # vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg # oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1 # jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7 # iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp # Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz # y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp # JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0 # u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB # ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH # EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo # MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE # AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0 # eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo # OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ # KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB # gjcCARUwIwYJKoZIhvcNAQkEMRYEFGPa+3yKeAOuG8MGktIPE98U9IQyMA0GCSqG # SIb3DQEBAQUABIICACukiWmmkw/T3q/IukaKIIO4/jJLng9v52P60RViKwJn7TOZ # C6Qcov2zO8/LBm8oIlY+kQil8MXqA3+5D7TGtFfYpyzoUh+Nwks1C9KAMWeRBKAL # b3H6CVX0H5nRh9PLa2a4WxbYHM6IxCOa/Z8clH4veAZbs5Zq5mtjLV14u8PszAYM # 4P/H0sXHMZYb9nj0vKjsZdxOlM0g6JHqUszE40tND/5dFuzdr3Tyu/aC6/j/ZFGZ # jdyaM88kE88qAU9Bs2M18LsSUJx6GsdlXwDD4eCBRH59+QtAnQZB4HUL5KkF53DG # J0WtRuI+wWmeMU9nNtDMQgSGJev0LVEJ2Ui+UsVA+RvWH04VCBrzlXi2TLzS9bCQ # 5Fo/t/czCbC4m/WrXQyYNDoHtI/fXE2ctSPq2QQaDF9Bu65MuMGzWa3iFSFmq0uA # nYivtHSlgyqhPBBmu8fspePkye7PzYoH2Gpykp17R5fBx+rQriKjTkZcGNdAGdQY # j7SEC93e0KjtZRQA+ABxmVacmNrO6NGbMN2Zd8Pheham1T38V3aWjKvq2d94iUfh # dgqvWhSu6zw0yE/NaJPTKnixN0j+up/Y7jSO9Cytvl4TNWJkFjDp+u0exl4s6eQ5 # cspbWHwWyYWyg7e0YaclbL7mPygvjxQDWOWgMN9cddvHCq8fiq6VPNTJqeLB # SIG # End signature block
PowerShellCorpus/PoshCode/Get-Scope_3.ps1
Get-Scope_3.ps1
function Get-Scope { #.Synopsis # Determine the scope of execution (are you in a module? how many scope layers deep are you?) #.Parameter Invocation # In order to correctly determine the scope, this function requires that you pass in the $MyInvocation variable when you call it. #.Parameter ToHost # If you just want to *see* the value in the console to debug something, you can pass this switch (and optionally, set the foreground/background colors) #.Parameter Foreground # The Foreground color of host output #.Parameter Background # The Background color of host output #.Example # $scope = . Get-Scope $MyInvocation # # Description # ----------- # Call Get-Scope and store the output so you can test if you're in module scope, etc. #.Example # . Get-Scope $MyInvocation -ToHost Magenta DarkBlue # # Description # ----------- # Call Get-Scope and write the output to host, specifying the foreground and background colors [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$false)] [System.Management.Automation.InvocationInfo]$Invocation = $((Get-Variable -scope 1 'MyInvocation').Value) , [Parameter(ParameterSetName="Debugging")] [Switch]$ToHost , [Parameter(Position=1,ParameterSetName="Debugging")] [ConsoleColor]$Foreground = "Cyan" , [Parameter(Position=2,ParameterSetName="Debugging")] [ConsoleColor]$Background = "Black" ) end { function Get-ScopeDepth { trap { continue } $depth = 0 do { Set-Variable scope_test -Value $depth -Scope ($depth++) } while($?) return $depth - 1 } $depth = . Get-ScopeDepth $callstack = Get-PSCallStack $IsGlobal = 0 -eq (Get-Variable scope_test -Scope global).Value $IsScript = 0 -eq (. Get-Variable scope_test -Scope script).Value Remove-Variable scope_test $PSScope = New-Object PSObject -Property @{ Module = $Invocation.MyCommand.Module IsModuleScope = [bool]$Invocation.MyCommand.Module IsGlobalScope = $IsGlobal ScopeDepth = $depth PipelinePosition = $Invocation.PipelinePosition PipelineLength = $Invocation.PipelineLength StackDepth = $callstack.Count - 1 Invocation = $Invocation CallStack = $callstack } if($ToHost) { &{ $PSScope, $PSScope.Invocation | Out-String } | Write-Host -Foreground $Foreground -Background $Background } else { $PSScope } } }
PowerShellCorpus/PoshCode/FindNewVirtualMachines_1.ps1
FindNewVirtualMachines_1.ps1
#requires -pssnapin VMware.Vimautomation.Core Param( [int] $LastDays ) Process { $EventFilterSpecByTime = New-Object VMware.Vim.EventFilterSpecByTime If ($LastDays) { $EventFilterSpecByTime.BeginTime = (get-date).AddDays(-$($LastDays)) } $EventFilterSpec = New-Object VMware.Vim.EventFilterSpec $EventFilterSpec.Time = $EventFilterSpecByTime $EventFilterSpec.DisableFullMessage = $False $EventFilterSpec.Type = "VmCreatedEvent","VmDeployedEvent","VmClonedEvent","VmDiscoveredEvent","VmRegisteredEvent" $EventManager = Get-View EventManager $NewVmTasks = $EventManager.QueryEvents($EventFilterSpec) Foreach ($Task in $NewVmTasks) { # If VM was deployed from a template then record which template. If ($Task.Template -and ($Task.SrcTemplate.Vm)) { $srcTemplate = Get-View $Task.SrcTemplate.Vm -Property name | Select -ExpandProperty Name } Else { $srcTemplate = $null } write-output ""|Select-Object @{ Name="Name" Expression={$Task.Vm.name} }, @{ Name="Created" Expression={$Task.CreatedTime} }, @{ Name="UserName" Expression={$Task.UserName} }, @{ Name="Type" Expression={$Task.gettype().name} }, @{ Name="Template" Expression={$srcTemplate} } } }
PowerShellCorpus/PoshCode/vProfiles.ps1
vProfiles.ps1
# # vProfiles V1 # By Alan Renouf # http://virtu-al.net # #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.3.0 # Generated On: 27/06/2009 9:17 PM # Generated By: Alan ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null #endregion #region Generated Form Objects $vProfiles = New-Object System.Windows.Forms.Form $label3 = New-Object System.Windows.Forms.Label $label2 = New-Object System.Windows.Forms.Label $Disconnect = New-Object System.Windows.Forms.Button $Connect = New-Object System.Windows.Forms.Button $OutputWin = New-Object System.Windows.Forms.TextBox $CopyNetwork = New-Object System.Windows.Forms.Button $NewHost = New-Object System.Windows.Forms.ListBox $BaseHost = New-Object System.Windows.Forms.ListBox $label1 = New-Object System.Windows.Forms.Label $VCSRV = New-Object System.Windows.Forms.TextBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $Disconnect_OnClick= { Disconnect-VIServer $ConVISRV -Confirm:$false $Disconnect.Enabled = $false $CopyNetwork.Enabled = $false $OutputWin.Text += "`r`nDisconnect Successful" $vProfiles.Refresh() } $handler_NewHost_SelectedIndexChanged= { #TODO: Place custom script here } $handler_button3_Click= { $OutputWin.Text += "`r`nConnecting to $($Basehost.SelectedItem)" $vProfiles.Refresh() $CBASEHost = Get-VMHost -Name ($Basehost.SelectedItem) $OutputWin.Text += "`r`nConnecting to $($Newhost.SelectedItem)" $vProfiles.Refresh() $CNEWHost = Get-VMHost -Name ($NewHost.SelectedItem) $OutputWin.Text += "`r`nRetrieving Virtual Switches" $vProfiles.Refresh() $CBASEHost | Get-VirtualSwitch | Foreach { If (($CNEWHost | Get-VirtualSwitch -Name $_.Name -ErrorAction SilentlyContinue) -eq $null){ $vSwitch = $_ $OutputWin.Text += "`r`nCreating Virtual Switch $($_.Name)" $vProfiles.Refresh() #$NewSwitch = $CNEWHost | New-VirtualSwitch -Name $_.Name -NumPorts $_.NumPorts -Mtu $_.Mtu } $_ | Get-VirtualPortGroup | Foreach { If (($CNEWHost | Get-VirtualPortGroup -Name $_.Name -ErrorAction SilentlyContinue) -eq $null){ $OutputWin.Text += "`r`n..Creating Portgroup $($_.Name) on $($vSwitch.Name)" $vProfiles.Refresh() #$NewPortGroup = $CNEWHost | Get-VirtualSwitch -Name $vSwitch | New-VirtualPortGroup -Name $_.Name -VLanId $_.VLanID } } } $OutputWin.Text += "`r`n-- Configuration Completed --" $vProfiles.Refresh() } $handler_label1_Click= { #TODO: Place custom script here } $handler_listBox1_SelectedIndexChanged= { #TODO: Place custom script here } $handler_button1_Click= { If ($VCSRV.Text -eq "") {$OutputWin.Text = "Please Specify a VC Server above"} Else { $OutputWin.Text = "Connecting to $($VCSRV.Text)" $vProfiles.Refresh() $ConVISRV = Connect-VIServer $VCSRV.Text If ($ConVISRV.IsConnected -eq $true) { $OutputWin.Text += "`r`nConnection Successful" $vProfiles.Refresh() $Disconnect.Enabled = $true $CopyNetwork.Enabled = $true Foreach ($EsxHost in (Get-VMHost)) { $BaseHost.Items.Add("$($EsxHost.Name)")|Out-Null $NewHost.Items.Add("$($EsxHost.Name)")|Out-Null } } Else { $OutputWin.Text += "`r`nConnection Un-Successful - Please try again." $vProfiles.Refresh() } } } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $vProfiles.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 563 $System_Drawing_Size.Height = 503 $vProfiles.MaximumSize = $System_Drawing_Size $vProfiles.AutoSize = $True $vProfiles.Text = 'vProfiles' $vProfiles.ShowInTaskbar = $False $vProfiles.MaximizeBox = $False $vProfiles.Name = 'vProfiles' $vProfiles.SizeGripStyle = 2 $vProfiles.ShowIcon = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 563 $System_Drawing_Size.Height = 503 $vProfiles.MinimumSize = $System_Drawing_Size $vProfiles.StartPosition = 1 $vProfiles.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 547 $System_Drawing_Size.Height = 465 $vProfiles.ClientSize = $System_Drawing_Size $label3.TabIndex = 11 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 13 $label3.Size = $System_Drawing_Size $label3.Text = 'Destination:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 271 $System_Drawing_Point.Y = 43 $label3.Location = $System_Drawing_Point $label3.DataBindings.DefaultDataSourceUpdateMode = 0 $label3.Name = 'label3' $label3.add_Click($handler_label3_Click) $vProfiles.Controls.Add($label3) $label2.TabIndex = 10 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 13 $label2.Size = $System_Drawing_Size $label2.Text = 'Source:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 24 $System_Drawing_Point.Y = 43 $label2.Location = $System_Drawing_Point $label2.DataBindings.DefaultDataSourceUpdateMode = 0 $label2.Name = 'label2' $vProfiles.Controls.Add($label2) $Disconnect.TabIndex = 9 $Disconnect.Name = 'Disconnect' $Disconnect.Enabled = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $Disconnect.Size = $System_Drawing_Size $Disconnect.UseVisualStyleBackColor = $True $Disconnect.Text = 'Disconnect' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 442 $System_Drawing_Point.Y = 10 $Disconnect.Location = $System_Drawing_Point $Disconnect.DataBindings.DefaultDataSourceUpdateMode = 0 $Disconnect.add_Click($Disconnect_OnClick) $vProfiles.Controls.Add($Disconnect) $Connect.TabIndex = 8 $Connect.Name = 'Connect' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $Connect.Size = $System_Drawing_Size $Connect.UseVisualStyleBackColor = $True $Connect.Text = 'Connect' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 360 $System_Drawing_Point.Y = 10 $Connect.Location = $System_Drawing_Point $Connect.DataBindings.DefaultDataSourceUpdateMode = 0 $Connect.add_Click($handler_button1_Click) $vProfiles.Controls.Add($Connect) $OutputWin.Multiline = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 491 $System_Drawing_Size.Height = 264 $OutputWin.Size = $System_Drawing_Size $OutputWin.DataBindings.DefaultDataSourceUpdateMode = 0 $OutputWin.AcceptsReturn = $True $OutputWin.ScrollBars = 2 $OutputWin.Name = 'OutputWin' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 24 $System_Drawing_Point.Y = 189 $OutputWin.Location = $System_Drawing_Point $OutputWin.Enabled = $False $OutputWin.TabIndex = 7 $vProfiles.Controls.Add($OutputWin) $CopyNetwork.TabIndex = 6 $CopyNetwork.Name = 'CopyNetwork' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 179 $System_Drawing_Size.Height = 23 $CopyNetwork.Size = $System_Drawing_Size $CopyNetwork.UseVisualStyleBackColor = $True $CopyNetwork.Enabled = $false $CopyNetwork.Text = 'Copy vSwitches and PortGroups' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 175 $System_Drawing_Point.Y = 160 $CopyNetwork.Location = $System_Drawing_Point $CopyNetwork.DataBindings.DefaultDataSourceUpdateMode = 0 $CopyNetwork.add_Click($handler_button3_Click) $vProfiles.Controls.Add($CopyNetwork) $NewHost.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 244 $System_Drawing_Size.Height = 95 $NewHost.Size = $System_Drawing_Size $NewHost.DataBindings.DefaultDataSourceUpdateMode = 0 $NewHost.ScrollAlwaysVisible = $True $NewHost.Name = 'NewHost' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 271 $System_Drawing_Point.Y = 59 $NewHost.Location = $System_Drawing_Point $NewHost.TabIndex = 5 $NewHost.add_SelectedIndexChanged($handler_NewHost_SelectedIndexChanged) $vProfiles.Controls.Add($NewHost) $BaseHost.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 241 $System_Drawing_Size.Height = 95 $BaseHost.Size = $System_Drawing_Size $BaseHost.DataBindings.DefaultDataSourceUpdateMode = 0 $BaseHost.ScrollAlwaysVisible = $True $BaseHost.Name = 'BaseHost' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 24 $System_Drawing_Point.Y = 59 $BaseHost.Location = $System_Drawing_Point $BaseHost.TabIndex = 4 $BaseHost.add_SelectedIndexChanged($handler_listBox1_SelectedIndexChanged) $vProfiles.Controls.Add($BaseHost) $label1.TabIndex = 1 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 86 $System_Drawing_Size.Height = 23 $label1.Size = $System_Drawing_Size $label1.Text = 'Virtual Center:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 34 $System_Drawing_Point.Y = 15 $label1.Location = $System_Drawing_Point $label1.DataBindings.DefaultDataSourceUpdateMode = 0 $label1.Name = 'label1' $label1.add_Click($handler_label1_Click) $vProfiles.Controls.Add($label1) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 228 $System_Drawing_Size.Height = 20 $VCSRV.Size = $System_Drawing_Size $VCSRV.DataBindings.DefaultDataSourceUpdateMode = 0 $VCSRV.Name = 'VCSRV' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 126 $System_Drawing_Point.Y = 12 $VCSRV.Location = $System_Drawing_Point $VCSRV.TabIndex = 0 $vProfiles.Controls.Add($VCSRV) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $vProfiles.WindowState #Init the OnLoad event to correct the initial state of the form $vProfiles.add_Load($OnLoadForm_StateCorrection) #Show the Form $vProfiles.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/Autoload (beta).ps1
Autoload (beta).ps1
#Requires -Version 2.0 ## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time. ## To use: ## 1) Create a function. To be 100% compatible, it should specify pipeline arguments ## For example: <# function Skip-Object { param( [int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $InputObject ) begin { if($Last) { $Queue = new-object System.Collections.Queue $Last } $e = $every; $UpTo++; $u = 0 } process { $InputObject | where { --$First -lt 0 } | foreach { if($Last) { $Queue.EnQueue($_) if($Queue.Count -gt $Last) { $Queue.DeQueue() } } else { $_ } } | foreach { if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo } } | foreach { if($every -and (--$e -le 0)) { $e = $every } else { $_ } } } } #> ## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1) ## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile) ## 4) Dot-source this file, or include it as part of your profile ## 5) Add one line to your profile (or on the commandline): <# autoload Skip-Object #> ## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it. ## Now, you can just use the function: ## 1..10 | Skip-Object -first 2 -upto 2 function autoload { [CmdletBinding()] param( [Parameter(Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Name ) begin { $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } function global:Autoloaded { [CmdletBinding()]Param() DYNAMICPARAM { Write-Verbose "Autoloaded DynamicParam: $($MyInvocation.InvocationName)" ## Determine the Type name based on the alias used to invoke us ## Store the parameter set for use in the function later... $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary # $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript $externalScript = $ExecutionContext.InvokeCommand.GetCommand( $MyInvocation.InvocationName, [System.Management.Automation.CommandTypes]::ExternalScript ) $parserrors = $null $prev = $null $script = $externalScript.ScriptContents [System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) [Array]::Reverse($tokens) ForEach($token in $tokens) { if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $MyInvocation.InvocationName ) { $script = $script.Insert( $prev.Start, "global:" ) } $prev = $token } Invoke-Expression $script | out-null $command = $ExecutionContext.InvokeCommand.GetCommand( $MyInvocation.InvocationName, [System.Management.Automation.CommandTypes]::Function ) if(!$command) { throw "Something went wrong autoloading the $($MyInvocation.InvocationName) function. Function definition doesn't exist in script: $($externalScript.Path)" } foreach( $pkv in $command.Parameters.GetEnumerator() ){ $parameter = $pkv.Value if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue } $param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes) $paramdictionary.Add($pkv.Key, $param) } return $paramdictionary }#DynamicParam begin { ## Determine the Type name based on the alias used to invoke us Write-Verbose "Autoloaded Begin: $($MyInvocation.InvocationName)" Remove-Item Alias::$($MyInvocation.InvocationName) $command = $ExecutionContext.InvokeCommand.GetCommand( $MyInvocation.InvocationName, [System.Management.Automation.CommandTypes]::Function ) $scriptCmd = {& $command @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($true) } process { Write-Verbose "Autoloaded Process: $($MyInvocation.InvocationName) ($_)" try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } Write-Verbose "Autoloaded End: $($MyInvocation.InvocationName)" } }#AutoLoaded } process { foreach($function in $Name) { Write-Verbose "Set-Alias $function Autoloaded -Scope global" Set-Alias $function Autoloaded -Scope global } } }
PowerShellCorpus/PoshCode/Script-Proc_2.sql.ps1
Script-Proc_2.sql.ps1
#Copyright (c) 2011 Justin Dearing # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE. # The authoritative version is https://github.com/justaprogrammer/PowerShellScripts/blob/master/Script-Proc.ps1. # If you have a change I'd love to know about it to consider merging it into github. param( [Parameter(Mandatory=$true,HelpMessage='The name of the stored procedure or user defined function we wish to script')] [string] $ProcedureName, [string] $Path = "$($ProcedureName).sql", [string] $ConnectionString = 'Data Source=.\\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;' ); try { [System.Data.SqlClient.SqlConnection] $cn = New-Object System.Data.SqlClient.SqlConnection (,$ConnectionString); $cn.Open() > $null; $cmd = $cn.CreateCommand(); $cmd.CommandType = [System.Data.CommandType]::StoredProcedure; $cmd.CommandText = 'sp_helptext'; $cmd.Parameters.AddWithValue('@objname', $ProcedureName) > $null; [System.Data.IDataReader] $rdr = $cmd.ExecuteReader(); [string] $sproc_text = ''; while ($rdr.Read()) { $sproc_text += $rdr[0]; } $rdr.Close(); $sproc_text | Out-File -FilePath $Path; } finally { if ($cmd -ne $null) { $cmd.Dispose(); } if ($cn -ne $null) { $cn.Dispose(); } }
PowerShellCorpus/PoshCode/PoshCode ISE Addon_2.ps1
PoshCode ISE Addon_2.ps1
if (!(Get-Module WPK)) {Import-Module -global WPK} if (!(Get-Module PoshCode)) {Import-Module -global PoshCode} Function Get-PoshCodePreferences { if (Get-Item $global:xmlPath -ErrorAction SilentlyContinue) { try { $pcPreferences = Import-Clixml -Path $global:xmlPath $global:PCSyntax = $pcPreferences.Syntax $global:PCExpiry = $pcPreferences.Expiry $global:PCAuthor = $pcPreferences.Author } catch { Write-Host "Import-CliXml failed with following error" return } } else { $global:PCSyntax = "posh" $global:PCExpiry = "forever" $global:PCAuthor = "$($env:USERNAME)" } } Function Save-PoshCodePreferences { param($syntax, $expiry, $author) $pcPreferences = New-Object PSObject $pcPreferences | Add-Member -MemberType NoteProperty -Name "Syntax" -Value $syntax $pcPreferences | Add-Member -MemberType NoteProperty -Name "Expiry" -Value $expiry $pcPreferences | Add-Member -MemberType NoteProperty -Name "Author" -Value $author try { Export-Clixml -InputObject $pcPreferences -Path $global:xmlPath -Force } catch { Write-Host "Export-Clixml; failed with the following error" Write-Host $error[0].InnerException return } [system.Windows.Forms.MessageBox]::show('Your preferences have been saved') } function Show-PoshCodeGUI { Get-PoshCodePreferences New-Window -Title "PoshCode addon" -WindowStartupLocation CenterScreen -Width 836 -Height 477 -Show -ResizeMode NoResize -On_Loaded { $txtPasteCode = $Window | Get-ChildControl txtPasteCode $cmbSyntax = $Window | Get-ChildControl cmbSyntax $cmbExpiry = $Window | Get-ChildControl cmbExpiry $txtTitle = $window | Get-ChildControl txtTitle $txtDescription = $window | Get-ChildControl txtDescription $txtAuthor = $window | Get-ChildControl txtAuthor $btnSavePref = $window | Get-ChildControl btnSavePref $btnSubmit = $window | Get-ChildControl btnSubmit } { New-Grid { New-TextBox -Name txtPasteCode -Margin "12,12,0,0" -Height 258 -Width 800 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:SelectedText ` -IsReadOnly -VerticalScrollBarVisibility "Auto" -HorizontalScrollBarVisibility "Auto" New-Label -Name lblLang -Margin "12,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Scripting Language" -FontWeight "Bold" New-ComboBox -Name cmbSyntax -Margin "175,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:cmbSyntaxOptions -SelectedIndex $global:cmbSyntaxOptions.IndexOf($global:PCSyntax) New-Label -Name lblExpiry -Margin "12,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Keep" -FontWeight "Bold" New-ComboBox -Name cmbExpiry -Margin "175,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Items $global:Expiry -SelectedIndex $global:Expiry.IndexOf($global:PCExpiry) New-Label -Name lblTitle -Margin "450,281,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Title" -FontWeight "Bold" New-TextBox -Name txtTitle -Margin "570,285,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Label -Name lblAuthor -Margin "450,321,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Author" -FontWeight "Bold" New-TextBox -Name txtAuthor -Margin "570,324,0,0" -Height 23 -Width 192 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Text $global:PCAuthor New-Label -Name lblDescription -Margin "12,361,0,0" -Height 28 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Description" -FontWeight "Bold" New-TextBox -Name txtDescription -Margin "175,361,0,0" -Height 35 -Width 590 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" New-Button -Name btnSavePref -Margin "280,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Save Preferences" -On_Click { Save-PoshCodePreferences -Syntax $cmbSyntax.SelectedItem -Expiry $cmbExpiry.SelectedItem -Author $txtAuthor.Text } New-Button -Name btnSubmit -Margin "410,400,0,0" -Height 23 -Width 110 ` -HorizontalAlignment "Left" -VerticalAlignment "Top" -Content "Submit to PoshCode" -On_Click { $returnUri = $global:SelectedText | New-PoshCode -title $txtTitle.Text ` -description $txtDescription.Text -Author $txtAuthor.Text ` -keep $cmbExpiry.SelectedItem -Language $cmbSyntax.SelectedItem if ($returnUri) { [System.Diagnostics.Process]::Start($returnUri) $window.Close() } else { [system.Windows.Forms.MessageBox]::show('Error occured while uploading to PoshCode') $window.Close() } } } } } [System.Collections.ArrayList]$global:cmbSyntaxOptions = "posh","text","vbnet","xml","asp","bash","csharp" [System.Collections.ArrayList]$global:Expiry = "forever","day","month" $global:xmlPath = $("$env:APPDATA\\PoshCodePrefs.xml") if ($host.Name –eq 'Windows PowerShell ISE Host') { $scriptBlock = { if (($psISE.CurrentFile.Editor.SelectedText -ne "")) { $global:SelectedText = $psISE.CurrentFile.Editor.SelectedText } elseif (($psISE.CurrentFile.Editor.Text -ne "")) { $global:SelectedText = $psISE.CurrentFile.Editor.Text } else { [system.Windows.Forms.MessageBox]::show('There is nothing to upload. Select some text or open a script') return } Show-PoshCodeGUI } $submenus = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus $menuExists = $false foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to Posh_Code") { $menuExists = $true } } if (!$menuExists) { $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Send To Posh_Code",$ScriptBlock,"CTRL+ALT+C") } $ExecutionContext.SessionState.Module.OnRemove = { foreach ($menuItem in $subMenus) { if ($menuItem.DisplayName -eq "Send to PPosh_Code") { $submenus.Remove($menuItem) return } } } } else { Write-Host "This module is meant for either ISE or PGSE" return } Export-ModuleMember -Function * -Variable *